repo_id
stringclasses
875 values
size
int64
974
38.9k
file_path
stringlengths
10
308
content
stringlengths
974
38.9k
googleapis/google-cloud-java
37,603
java-vertexai/google-cloud-vertexai/src/main/java/com/google/cloud/vertexai/api/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.vertexai.api.stub; import static com.google.cloud.vertexai.api.PredictionServiceClient.ListLocationsPagedResponse; import com.google.api.HttpBody; 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.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.location.GetLocationRequest; import com.google.cloud.location.ListLocationsRequest; import com.google.cloud.location.ListLocationsResponse; import com.google.cloud.location.Location; import com.google.cloud.vertexai.api.DirectPredictRequest; import com.google.cloud.vertexai.api.DirectPredictResponse; import com.google.cloud.vertexai.api.DirectRawPredictRequest; import com.google.cloud.vertexai.api.DirectRawPredictResponse; import com.google.cloud.vertexai.api.ExplainRequest; import com.google.cloud.vertexai.api.ExplainResponse; import com.google.cloud.vertexai.api.GenerateContentRequest; import com.google.cloud.vertexai.api.GenerateContentResponse; import com.google.cloud.vertexai.api.PredictRequest; import com.google.cloud.vertexai.api.PredictResponse; import com.google.cloud.vertexai.api.RawPredictRequest; import com.google.cloud.vertexai.api.StreamDirectPredictRequest; import com.google.cloud.vertexai.api.StreamDirectPredictResponse; import com.google.cloud.vertexai.api.StreamDirectRawPredictRequest; import com.google.cloud.vertexai.api.StreamDirectRawPredictResponse; import com.google.cloud.vertexai.api.StreamRawPredictRequest; import com.google.cloud.vertexai.api.StreamingPredictRequest; import com.google.cloud.vertexai.api.StreamingPredictResponse; import com.google.cloud.vertexai.api.StreamingRawPredictRequest; import com.google.cloud.vertexai.api.StreamingRawPredictResponse; 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); } if (getTransportChannelProvider() .getTransportName() .equals(HttpJsonTransportChannel.getHttpJsonTransportName())) { return HttpJsonPredictionServiceStub.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 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(PredictionServiceStubSettings.class)) .setTransportToken( GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); } public static ApiClientHeaderProvider.Builder defaultHttpJsonApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken( "gapic", GaxProperties.getLibraryVersion(PredictionServiceStubSettings.class)) .setTransportToken( GaxHttpJsonProperties.getHttpJsonTokenName(), GaxHttpJsonProperties.getHttpJsonVersion()); } public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return PredictionServiceStubSettings.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 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 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 .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); } } }
apache/hive
37,437
ql/src/java/org/apache/hadoop/hive/ql/exec/vector/mapjoin/VectorMapJoinOuterGenerateResultOperator.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.exec.vector.mapjoin; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.hive.ql.CompilationOpContext; import org.apache.hadoop.hive.ql.exec.JoinUtil; import org.apache.hadoop.hive.ql.exec.persistence.MapJoinTableContainer; import org.apache.hadoop.hive.ql.exec.vector.BytesColumnVector; import org.apache.hadoop.hive.ql.exec.vector.ColumnVector; import org.apache.hadoop.hive.ql.exec.vector.LongColumnVector; import org.apache.hadoop.hive.ql.exec.vector.VectorizationContext; import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch; import org.apache.hadoop.hive.ql.exec.vector.expressions.VectorExpression; import org.apache.hadoop.hive.ql.exec.vector.mapjoin.hashtable.VectorMapJoinBytesHashMap; import org.apache.hadoop.hive.ql.exec.vector.mapjoin.hashtable.VectorMapJoinHashMap; import org.apache.hadoop.hive.ql.exec.vector.mapjoin.hashtable.VectorMapJoinHashMapResult; import org.apache.hadoop.hive.ql.exec.vector.mapjoin.hashtable.VectorMapJoinHashTableResult; import org.apache.hadoop.hive.ql.exec.vector.mapjoin.hashtable.VectorMapJoinLongHashMap; import org.apache.hadoop.hive.ql.exec.vector.mapjoin.hashtable.VectorMapJoinNonMatchedIterator; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.plan.OperatorDesc; import org.apache.hadoop.hive.ql.plan.VectorDesc; import org.apache.hadoop.hive.serde2.WriteBuffers.ByteSegmentRef; /** * This class has methods for generating vectorized join results for outer joins. * * The big difference between inner joins and outer joins is the treatment of null and non-matching * keys. * * Inner joins ignore null keys. Outer joins include big table rows with null keys in the result. * * (Left non-full) outer joins include big table rows that do not match the small table. Small * table columns for non-matches will be NULL. * * Another important difference is filtering. For outer joins to include the necessary rows, * filtering must be done after the hash table lookup. That is because filtering does not * eliminate rows, but changes them from match to non-matching rows. They will still appear in * the join result. * * One vector outer join optimization is referencing bytes outer keys. When a bytes key appears * in the small table results area, instead of copying the bytes key we reference the big table key. * Bytes column vectors allow a by reference entry to bytes. It is safe to do a by reference * since it is within the same row. * * Outer join uses a hash map since small table columns can be included in the join result. */ public abstract class VectorMapJoinOuterGenerateResultOperator extends VectorMapJoinGenerateResultOperator { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(VectorMapJoinOuterGenerateResultOperator.class.getName()); //--------------------------------------------------------------------------- // Outer join specific members. // // An array of hash map results so we can do lookups on the whole batch before output result // generation. protected transient VectorMapJoinHashMapResult hashMapResults[]; // Pre-allocated member for remembering the big table's selected array at the beginning of // the process method before applying any filter. For outer join we need to remember which // rows did not match since they will appear the in outer join result with NULLs for the // small table. protected transient int[] inputSelected; // Pre-allocated member for storing the (physical) batch index of matching row (single- or // multi-small-table-valued) indexes during a process call. protected transient int[] allMatches; /* * Pre-allocated members for storing information equal key series for small-table matches. * * ~HashMapResultIndices * Index into the hashMapResults array for the match. * ~AllMatchIndices * (Logical) indices into allMatches to the first row of a match of a * possible series of duplicate keys. * ~IsSingleValue * Whether there is 1 or multiple small table values. * ~DuplicateCounts * The duplicate count for each matched key. * */ protected transient int[] equalKeySeriesHashMapResultIndices; protected transient int[] equalKeySeriesAllMatchIndices; protected transient boolean[] equalKeySeriesIsSingleValue; protected transient int[] equalKeySeriesDuplicateCounts; // Pre-allocated member for storing the (physical) batch index of rows that need to be spilled. protected transient int[] spills; // Pre-allocated member for storing index into the hashSetResults for each spilled row. protected transient int[] spillHashMapResultIndices; // Pre-allocated member for storing any non-spills, non-matches, or merged row indexes during a // process method call. protected transient int[] nonSpills; protected transient int[] noMatchs; protected transient int[] merged; /** Kryo ctor. */ protected VectorMapJoinOuterGenerateResultOperator() { super(); } public VectorMapJoinOuterGenerateResultOperator(CompilationOpContext ctx) { super(ctx); } public VectorMapJoinOuterGenerateResultOperator(CompilationOpContext ctx, OperatorDesc conf, VectorizationContext vContext, VectorDesc vectorDesc) throws HiveException { super(ctx, conf, vContext, vectorDesc); } /* * Setup our outer join specific members. */ protected void commonSetup() throws HiveException { super.commonSetup(); // Outer join specific. VectorMapJoinHashMap baseHashMap = (VectorMapJoinHashMap) vectorMapJoinHashTable; hashMapResults = new VectorMapJoinHashMapResult[VectorizedRowBatch.DEFAULT_SIZE]; for (int i = 0; i < hashMapResults.length; i++) { hashMapResults[i] = baseHashMap.createHashMapResult(); } inputSelected = new int[VectorizedRowBatch.DEFAULT_SIZE]; allMatches = new int[VectorizedRowBatch.DEFAULT_SIZE]; equalKeySeriesHashMapResultIndices = new int[VectorizedRowBatch.DEFAULT_SIZE]; equalKeySeriesAllMatchIndices = new int[VectorizedRowBatch.DEFAULT_SIZE]; equalKeySeriesIsSingleValue = new boolean[VectorizedRowBatch.DEFAULT_SIZE]; equalKeySeriesDuplicateCounts = new int[VectorizedRowBatch.DEFAULT_SIZE]; spills = new int[VectorizedRowBatch.DEFAULT_SIZE]; spillHashMapResultIndices = new int[VectorizedRowBatch.DEFAULT_SIZE]; nonSpills = new int[VectorizedRowBatch.DEFAULT_SIZE]; noMatchs = new int[VectorizedRowBatch.DEFAULT_SIZE]; merged = new int[VectorizedRowBatch.DEFAULT_SIZE]; matchTracker = null; } //----------------------------------------------------------------------------------------------- /* * Outer join (hash map). */ /** * Do the per-batch setup for an outer join. */ protected void outerPerBatchSetup(VectorizedRowBatch batch) { // For join operators that can generate small table results, reset their // (target) scratch columns. for (int column : outerSmallTableKeyColumnMap) { ColumnVector bigTableOuterKeyColumn = batch.cols[column]; bigTableOuterKeyColumn.reset(); } for (int column : smallTableValueColumnMap) { ColumnVector smallTableColumn = batch.cols[column]; smallTableColumn.reset(); } } /** * Apply the value expression to rows in the (original) input selected array. * * @param batch * The vectorized row batch. * @param inputSelectedInUse * Whether the (original) input batch is selectedInUse. * @param inputLogicalSize * The (original) input batch size. */ private void doValueExprOnInputSelected(VectorizedRowBatch batch, boolean inputSelectedInUse, int inputLogicalSize) throws HiveException { int saveBatchSize = batch.size; int[] saveSelected = batch.selected; boolean saveSelectedInUse = batch.selectedInUse; batch.size = inputLogicalSize; batch.selected = inputSelected; batch.selectedInUse = inputSelectedInUse; if (bigTableValueExpressions != null) { for(VectorExpression ve: bigTableValueExpressions) { ve.evaluate(batch); } } batch.size = saveBatchSize; batch.selected = saveSelected; batch.selectedInUse = saveSelectedInUse; } /** * Apply the value expression to rows specified by a selected array. * * @param batch * The vectorized row batch. * @param selected * The (physical) batch indices to apply the expression to. * @param size * The size of selected. */ private void doValueExpr(VectorizedRowBatch batch, int[] selected, int size) throws HiveException { int saveBatchSize = batch.size; int[] saveSelected = batch.selected; boolean saveSelectedInUse = batch.selectedInUse; batch.size = size; batch.selected = selected; batch.selectedInUse = true; if (bigTableValueExpressions != null) { for(VectorExpression ve: bigTableValueExpressions) { ve.evaluate(batch); } } batch.size = saveBatchSize; batch.selected = saveSelected; batch.selectedInUse = saveSelectedInUse; } /** * Remove (subtract) members from the input selected array and produce the results into * a difference array. * * @param inputSelectedInUse * Whether the (original) input batch is selectedInUse. * @param inputLogicalSize * The (original) input batch size. * @param remove * The indices to remove. They must all be present in input selected array. * @param removeSize * The size of remove. * @param difference * The resulting difference -- the input selected array indices not in the * remove array. * @return * The resulting size of the difference array. * @throws HiveException */ private int subtractFromInputSelected(boolean inputSelectedInUse, int inputLogicalSize, int[] remove, int removeSize, int[] difference) throws HiveException { // if (!verifyMonotonicallyIncreasing(remove, removeSize)) { // throw new HiveException("remove is not in sort order and unique"); // } int differenceCount = 0; // Determine which rows are left. int removeIndex = 0; if (inputSelectedInUse) { for (int i = 0; i < inputLogicalSize; i++) { int candidateIndex = inputSelected[i]; if (removeIndex < removeSize && candidateIndex == remove[removeIndex]) { removeIndex++; } else { difference[differenceCount++] = candidateIndex; } } } else { for (int candidateIndex = 0; candidateIndex < inputLogicalSize; candidateIndex++) { if (removeIndex < removeSize && candidateIndex == remove[removeIndex]) { removeIndex++; } else { difference[differenceCount++] = candidateIndex; } } } if (removeIndex != removeSize) { throw new HiveException("Not all batch indices removed"); } // if (!verifyMonotonicallyIncreasing(difference, differenceCount)) { // throw new HiveException("difference is not in sort order and unique"); // } return differenceCount; } /** * Remove (subtract) members from an array and produce the results into * a difference array. * @param all * The selected array containing all members. * @param allSize * The size of all. * @param remove * The indices to remove. They must all be present in input selected array. * @param removeSize * The size of remove. * @param difference * The resulting difference -- the all array indices not in the * remove array. * @return * The resulting size of the difference array. * @throws HiveException */ private int subtract(int[] all, int allSize, int[] remove, int removeSize, int[] difference) throws HiveException { // if (!verifyMonotonicallyIncreasing(remove, removeSize)) { // throw new HiveException("remove is not in sort order and unique"); // } int differenceCount = 0; // Determine which rows are left. int removeIndex = 0; for (int i = 0; i < allSize; i++) { int candidateIndex = all[i]; if (removeIndex < removeSize && candidateIndex == remove[removeIndex]) { removeIndex++; } else { difference[differenceCount++] = candidateIndex; } } if (removeIndex != removeSize) { throw new HiveException("Not all batch indices removed"); } return differenceCount; } /** * Sort merge two select arrays so the resulting array is ordered by (batch) index. * * @param selected1 * @param selected1Count * @param selected2 * @param selected2Count * @param sortMerged * The resulting sort merge of selected1 and selected2. * @return * The resulting size of the sortMerged array. * @throws HiveException */ private int sortMerge(int[] selected1, int selected1Count, int[] selected2, int selected2Count, int[] sortMerged) throws HiveException { // if (!verifyMonotonicallyIncreasing(selected1, selected1Count)) { // throw new HiveException("selected1 is not in sort order and unique"); // } // if (!verifyMonotonicallyIncreasing(selected2, selected2Count)) { // throw new HiveException("selected1 is not in sort order and unique"); // } int sortMergeCount = 0; int selected1Index = 0; int selected2Index = 0; for (int i = 0; i < selected1Count + selected2Count; i++) { if (selected1Index < selected1Count && selected2Index < selected2Count) { if (selected1[selected1Index] < selected2[selected2Index]) { sortMerged[sortMergeCount++] = selected1[selected1Index++]; } else { sortMerged[sortMergeCount++] = selected2[selected2Index++]; } } else if (selected1Index < selected1Count) { sortMerged[sortMergeCount++] = selected1[selected1Index++]; } else { sortMerged[sortMergeCount++] = selected2[selected2Index++]; } } // if (!verifyMonotonicallyIncreasing(sortMerged, sortMergeCount)) { // throw new HiveException("sortMerged is not in sort order and unique"); // } return sortMergeCount; } /** * Generate the outer join output results for one vectorized row batch. * * @param batch * The big table batch with any matching and any non matching rows both as * selected in use. * @param allMatchCount * Number of matches in allMatches. * @param equalKeySeriesCount * Number of single value matches. * @param atLeastOneNonMatch * Whether at least one row was a non-match. * @param inputSelectedInUse * A copy of the batch's selectedInUse flag on input to the process method. * @param inputLogicalSize * The batch's size on input to the process method. * @param spillCount * Number of spills in spills. * @param hashMapResultCount * Number of entries in hashMapResults. */ public void finishOuter(VectorizedRowBatch batch, int allMatchCount, int equalKeySeriesCount, boolean atLeastOneNonMatch, boolean inputSelectedInUse, int inputLogicalSize, int spillCount, int hashMapResultCount) throws IOException, HiveException { // Get rid of spills before we start modifying the batch. if (spillCount > 0) { spillHashMapBatch(batch, (VectorMapJoinHashTableResult[]) hashMapResults, spills, spillHashMapResultIndices, spillCount); } int noMatchCount = 0; if (spillCount > 0) { // Subtract the spills to get all match and non-match rows. int nonSpillCount = subtractFromInputSelected( inputSelectedInUse, inputLogicalSize, spills, spillCount, nonSpills); if (LOG.isDebugEnabled()) { LOG.debug("finishOuter spillCount > 0" + " nonSpills " + intArrayToRangesString(nonSpills, nonSpillCount)); } // Big table value expressions apply to ALL matching and non-matching rows. if (bigTableValueExpressions != null) { doValueExpr(batch, nonSpills, nonSpillCount); } if (atLeastOneNonMatch) { noMatchCount = subtract(nonSpills, nonSpillCount, allMatches, allMatchCount, noMatchs); if (LOG.isDebugEnabled()) { LOG.debug("finishOuter spillCount > 0" + " noMatchs " + intArrayToRangesString(noMatchs, noMatchCount)); } } } else { // Run value expressions over original (whole) input batch. doValueExprOnInputSelected(batch, inputSelectedInUse, inputLogicalSize); if (atLeastOneNonMatch) { noMatchCount = subtractFromInputSelected( inputSelectedInUse, inputLogicalSize, allMatches, allMatchCount, noMatchs); if (LOG.isDebugEnabled()) { LOG.debug("finishOuter spillCount == 0" + " noMatchs " + intArrayToRangesString(noMatchs, noMatchCount)); } } } // When we generate results into the overflow batch, we may still end up with fewer rows // in the big table batch. So, nulSel and the batch's selected array will be rebuilt with // just the big table rows that need to be forwarded, minus any rows processed with the // overflow batch. if (allMatchCount > 0) { int numSel = 0; for (int i = 0; i < equalKeySeriesCount; i++) { int hashMapResultIndex = equalKeySeriesHashMapResultIndices[i]; VectorMapJoinHashMapResult hashMapResult = hashMapResults[hashMapResultIndex]; int allMatchesIndex = equalKeySeriesAllMatchIndices[i]; boolean isSingleValue = equalKeySeriesIsSingleValue[i]; int duplicateCount = equalKeySeriesDuplicateCounts[i]; if (isSingleValue) { numSel = generateHashMapResultSingleValue( batch, hashMapResult, allMatches, allMatchesIndex, duplicateCount, numSel); } else { generateHashMapResultMultiValue( batch, hashMapResult, allMatches, allMatchesIndex, duplicateCount); } } // The number of single value rows that were generated in the big table batch. batch.size = numSel; batch.selectedInUse = true; if (LOG.isDebugEnabled()) { LOG.debug("finishOuter allMatchCount > 0" + " batch.selected " + intArrayToRangesString(batch.selected, batch.size)); } } else { batch.size = 0; } if (noMatchCount > 0) { if (batch.size > 0) { generateOuterNulls(batch, noMatchs, noMatchCount); // Merge noMatchs and (match) selected. int mergeCount = sortMerge( noMatchs, noMatchCount, batch.selected, batch.size, merged); if (LOG.isDebugEnabled()) { LOG.debug("finishOuter noMatchCount > 0 && batch.size > 0" + " merged " + intArrayToRangesString(merged, mergeCount)); } System.arraycopy(merged, 0, batch.selected, 0, mergeCount); batch.size = mergeCount; batch.selectedInUse = true; } else { // We can use the whole batch for output of no matches. generateOuterNullsRepeatedAll(batch); System.arraycopy(noMatchs, 0, batch.selected, 0, noMatchCount); batch.size = noMatchCount; batch.selectedInUse = true; if (LOG.isDebugEnabled()) { LOG.debug("finishOuter noMatchCount > 0 && batch.size == 0" + " batch.selected " + intArrayToRangesString(batch.selected, batch.size)); } } } } /** * Generate the non matching outer join output results for one vectorized row batch. * * For each non matching row specified by parameter, generate nulls for the small table results. * * @param batch * The big table batch with any matching and any non matching rows both as * selected in use. * @param noMatchs * A subset of the rows of the batch that are non matches. * @param noMatchSize * Number of non matches in noMatchs. */ protected void generateOuterNulls(VectorizedRowBatch batch, int[] noMatchs, int noMatchSize) throws IOException, HiveException { // Set null information in the small table results area. for (int i = 0; i < noMatchSize; i++) { int batchIndex = noMatchs[i]; // Mark any scratch small table scratch columns that would normally receive a copy of the // key as null, too. // for (int column : outerSmallTableKeyColumnMap) { ColumnVector colVector = batch.cols[column]; colVector.noNulls = false; colVector.isNull[batchIndex] = true; } // Small table values are set to null. for (int column : smallTableValueColumnMap) { ColumnVector colVector = batch.cols[column]; colVector.noNulls = false; colVector.isNull[batchIndex] = true; } } } /** * Generate the outer join output results for one vectorized row batch with a repeated key. * * Any filter expressions will apply now since hash map lookup for outer join is complete. * * @param batch * The big table batch with any matching and any non matching rows both as * selected in use. * @param joinResult * The hash map lookup result for the repeated key. * @param hashMapResult * The array of all hash map results for the batch. * @param someRowsFilteredOut * Whether some rows of the repeated key batch were knocked out by the filter. * @param inputSelectedInUse * A copy of the batch's selectedInUse flag on input to the process method. * @param inputLogicalSize * The batch's size on input to the process method. */ public void finishOuterRepeated(VectorizedRowBatch batch, JoinUtil.JoinResult joinResult, VectorMapJoinHashMapResult hashMapResult, boolean someRowsFilteredOut, boolean inputSelectedInUse, int inputLogicalSize) throws IOException, HiveException { // LOG.debug("finishOuterRepeated batch #" + batchCounter + " " + joinResult.name() + " batch.size " + batch.size + " someRowsFilteredOut " + someRowsFilteredOut); switch (joinResult) { case MATCH: // Rows we looked up as one repeated key are a match. But filtered out rows // need to be generated as non-matches, too. if (someRowsFilteredOut) { // For the filtered out rows that didn't (logically) get looked up in the hash table, // we need to generate no match results for those too... // Run value expressions over original (whole) input batch. doValueExprOnInputSelected(batch, inputSelectedInUse, inputLogicalSize); // Now calculate which rows were filtered out (they are logically no matches). // Determine which rows are non matches by determining the delta between inputSelected and // (current) batch selected. int noMatchCount = subtractFromInputSelected( inputSelectedInUse, inputLogicalSize, batch.selected, batch.size, noMatchs); generateOuterNulls(batch, noMatchs, noMatchCount); // Now generate the matchs. Single small table values will be put into the big table // batch and come back in matchs. Any multiple small table value results will go into // the overflow batch. generateHashMapResultRepeatedAll(batch, hashMapResult); // Merge noMatchs and (match) selected. int mergeCount = sortMerge( noMatchs, noMatchCount, batch.selected, batch.size, merged); System.arraycopy(merged, 0, batch.selected, 0, mergeCount); batch.size = mergeCount; batch.selectedInUse = true; } else { // Just run our value expressions over input batch. if (bigTableValueExpressions != null) { for(VectorExpression ve: bigTableValueExpressions) { ve.evaluate(batch); } } generateHashMapResultRepeatedAll(batch, hashMapResult); } break; case SPILL: // Rows we looked up as one repeated key need to spill. But filtered out rows // need to be generated as non-matches, too. spillBatchRepeated(batch, (VectorMapJoinHashTableResult) hashMapResult); // After using selected to generate spills, generate non-matches, if any. if (someRowsFilteredOut) { // Determine which rows are non matches by determining the delta between inputSelected and // (current) batch selected. int noMatchCount = subtractFromInputSelected( inputSelectedInUse, inputLogicalSize, batch.selected, batch.size, noMatchs); System.arraycopy(noMatchs, 0, batch.selected, 0, noMatchCount); batch.size = noMatchCount; batch.selectedInUse = true; generateOuterNullsRepeatedAll(batch); } else { batch.size = 0; } break; case NOMATCH: if (someRowsFilteredOut) { // When the repeated no match is due to filtering, we need to restore the // selected information. if (inputSelectedInUse) { System.arraycopy(inputSelected, 0, batch.selected, 0, inputLogicalSize); } batch.selectedInUse = inputSelectedInUse; batch.size = inputLogicalSize; } // Run our value expressions over whole batch. if (bigTableValueExpressions != null) { for(VectorExpression ve: bigTableValueExpressions) { ve.evaluate(batch); } } generateOuterNullsRepeatedAll(batch); break; } } /** * Generate the non-match outer join output results for the whole repeating vectorized * row batch. * * Each row will get nulls for all small table values. * * @param batch * The big table batch. */ protected void generateOuterNullsRepeatedAll(VectorizedRowBatch batch) throws HiveException { // Mark any scratch small table scratch columns that would normally receive a copy of the // key as null, too. // for (int column : outerSmallTableKeyColumnMap) { ColumnVector colVector = batch.cols[column]; colVector.noNulls = false; colVector.isNull[0] = true; colVector.isRepeating = true; } for (int column : smallTableValueColumnMap) { ColumnVector colVector = batch.cols[column]; colVector.noNulls = false; colVector.isNull[0] = true; colVector.isRepeating = true; } } private void markBigTableColumnsAsNullRepeating() { /* * For non-match FULL OUTER Small Table results, the Big Table columns are all NULL. */ for (int column : bigTableRetainColumnMap) { ColumnVector colVector = overflowBatch.cols[column]; colVector.isRepeating = true; colVector.noNulls = false; colVector.isNull[0] = true; } } /* * For FULL OUTER MapJoin, find the non matched Small Table keys and values and odd them to the * join output result. */ @Override protected void generateFullOuterSmallTableNoMatches(byte smallTablePos, MapJoinTableContainer substituteSmallTable) throws HiveException { /* * For dynamic partition hash join, both the Big Table and Small Table are partitioned (sent) * to the Reducer using the key hash code. So, we can generate the non-match Small Table * results locally. * * Scan the Small Table for keys that didn't match and generate the non-matchs into the * overflowBatch. */ /* * If there were no matched keys sent, we need to do our common initialization. */ if (needCommonSetup) { // Our one time process method initialization. commonSetup(); needCommonSetup = false; } if (needHashTableSetup) { // Setup our hash table specialization. It will be the first time the process // method is called, or after a Hybrid Grace reload. hashTableSetup(); needHashTableSetup = false; } /* * To support fancy NULL repeating columns, let's flush the overflowBatch if it has anything. */ if (overflowBatch.size > 0) { forwardOverflow(); } markBigTableColumnsAsNullRepeating(); switch (hashTableKeyType) { case BOOLEAN: case BYTE: case SHORT: case INT: case LONG: generateFullOuterLongKeySmallTableNoMatches(); break; case STRING: generateFullOuterStringKeySmallTableNoMatches(); break; case MULTI_KEY: generateFullOuterMultiKeySmallTableNoMatches(); break; default: throw new RuntimeException("Unexpected hash table key type " + hashTableKeyType); } } /* * For FULL OUTER MapJoin, find the non matched Small Table Long keys and values and odd them to * the join output result. */ protected void generateFullOuterLongKeySmallTableNoMatches() throws HiveException { final LongColumnVector singleSmallTableKeyOutputColumnVector; if (allSmallTableKeyColumnIncluded[0]) { singleSmallTableKeyOutputColumnVector = (LongColumnVector) overflowBatch.cols[allSmallTableKeyColumnNums[0]]; } else { singleSmallTableKeyOutputColumnVector = null; } VectorMapJoinLongHashMap hashMap = (VectorMapJoinLongHashMap) vectorMapJoinHashTable; VectorMapJoinNonMatchedIterator nonMatchedIterator = hashMap.createNonMatchedIterator(matchTracker); nonMatchedIterator.init(); while (nonMatchedIterator.findNextNonMatched()) { final long longKey; boolean isKeyNull = !nonMatchedIterator.readNonMatchedLongKey(); if (!isKeyNull) { longKey = nonMatchedIterator.getNonMatchedLongKey(); } else { longKey = 0; } VectorMapJoinHashMapResult hashMapResult = nonMatchedIterator.getNonMatchedHashMapResult(); ByteSegmentRef byteSegmentRef = hashMapResult.first(); while (byteSegmentRef != null) { // NOTE: Big Table result columns were marked repeating NULL already. if (singleSmallTableKeyOutputColumnVector != null) { if (isKeyNull) { singleSmallTableKeyOutputColumnVector.isNull[overflowBatch.size] = true; singleSmallTableKeyOutputColumnVector.noNulls = false; } else { singleSmallTableKeyOutputColumnVector.vector[overflowBatch.size] = longKey; singleSmallTableKeyOutputColumnVector.isNull[overflowBatch.size] = false; } } if (smallTableValueVectorDeserializeRow != null) { doSmallTableValueDeserializeRow(overflowBatch, overflowBatch.size, byteSegmentRef, hashMapResult); } overflowBatch.size++; if (overflowBatch.size == overflowBatch.DEFAULT_SIZE) { forwardOverflow(); markBigTableColumnsAsNullRepeating(); } byteSegmentRef = hashMapResult.next(); } } } private void doSmallTableKeyDeserializeRow(VectorizedRowBatch batch, int batchIndex, byte[] keyBytes, int keyOffset, int keyLength) throws HiveException { smallTableKeyOuterVectorDeserializeRow.setBytes(keyBytes, keyOffset, keyLength); try { // Our hash tables are immutable. We can safely do by reference STRING, CHAR/VARCHAR, etc. smallTableKeyOuterVectorDeserializeRow.deserializeByRef(batch, batchIndex); } catch (Exception e) { throw new HiveException( "\nDeserializeRead detail: " + smallTableKeyOuterVectorDeserializeRow.getDetailedReadPositionString(), e); } } /* * For FULL OUTER MapJoin, find the non matched Small Table Multi-Keys and values and odd them to * the join output result. */ protected void generateFullOuterMultiKeySmallTableNoMatches() throws HiveException { VectorMapJoinBytesHashMap hashMap = (VectorMapJoinBytesHashMap) vectorMapJoinHashTable; VectorMapJoinNonMatchedIterator nonMatchedIterator = hashMap.createNonMatchedIterator(matchTracker); nonMatchedIterator.init(); while (nonMatchedIterator.findNextNonMatched()) { nonMatchedIterator.readNonMatchedBytesKey(); byte[] keyBytes = nonMatchedIterator.getNonMatchedBytes(); final int keyOffset = nonMatchedIterator.getNonMatchedBytesOffset(); final int keyLength = nonMatchedIterator.getNonMatchedBytesLength(); VectorMapJoinHashMapResult hashMapResult = nonMatchedIterator.getNonMatchedHashMapResult(); ByteSegmentRef byteSegmentRef = hashMapResult.first(); while (byteSegmentRef != null) { // NOTE: Big Table result columns were marked repeating NULL already. if (smallTableKeyOuterVectorDeserializeRow != null) { doSmallTableKeyDeserializeRow(overflowBatch, overflowBatch.size, keyBytes, keyOffset, keyLength); } if (smallTableValueVectorDeserializeRow != null) { doSmallTableValueDeserializeRow(overflowBatch, overflowBatch.size, byteSegmentRef, hashMapResult); } overflowBatch.size++; if (overflowBatch.size == overflowBatch.DEFAULT_SIZE) { forwardOverflow(); markBigTableColumnsAsNullRepeating(); } byteSegmentRef = hashMapResult.next(); } } // NOTE: We don't have to deal with FULL OUTER All-NULL key values like we do for single-column // LONG and STRING because we do store them in the hash map... } /* * For FULL OUTER MapJoin, find the non matched Small Table String keys and values and odd them to * the join output result. */ protected void generateFullOuterStringKeySmallTableNoMatches() throws HiveException { final BytesColumnVector singleSmallTableKeyOutputColumnVector; if (allSmallTableKeyColumnIncluded[0]) { singleSmallTableKeyOutputColumnVector = (BytesColumnVector) overflowBatch.cols[allSmallTableKeyColumnNums[0]]; } else { singleSmallTableKeyOutputColumnVector = null; } VectorMapJoinBytesHashMap hashMap = (VectorMapJoinBytesHashMap) vectorMapJoinHashTable; VectorMapJoinNonMatchedIterator nonMatchedIterator = hashMap.createNonMatchedIterator(matchTracker); nonMatchedIterator.init(); while (nonMatchedIterator.findNextNonMatched()) { final byte[] keyBytes; final int keyOffset; final int keyLength; boolean isKeyNull = !nonMatchedIterator.readNonMatchedBytesKey(); if (!isKeyNull) { keyBytes = nonMatchedIterator.getNonMatchedBytes(); keyOffset = nonMatchedIterator.getNonMatchedBytesOffset(); keyLength = nonMatchedIterator.getNonMatchedBytesLength(); } else { keyBytes = null; keyOffset = 0; keyLength = 0; } VectorMapJoinHashMapResult hashMapResult = nonMatchedIterator.getNonMatchedHashMapResult(); ByteSegmentRef byteSegmentRef = hashMapResult.first(); while (byteSegmentRef != null) { // NOTE: Big Table result columns were marked repeating NULL already. if (singleSmallTableKeyOutputColumnVector != null) { if (isKeyNull) { singleSmallTableKeyOutputColumnVector.isNull[overflowBatch.size] = true; singleSmallTableKeyOutputColumnVector.noNulls = false; } else { singleSmallTableKeyOutputColumnVector.setVal( overflowBatch.size, keyBytes, keyOffset, keyLength); singleSmallTableKeyOutputColumnVector.isNull[overflowBatch.size] = false; } } if (smallTableValueVectorDeserializeRow != null) { doSmallTableValueDeserializeRow(overflowBatch, overflowBatch.size, byteSegmentRef, hashMapResult); } overflowBatch.size++; if (overflowBatch.size == overflowBatch.DEFAULT_SIZE) { forwardOverflow(); markBigTableColumnsAsNullRepeating(); } byteSegmentRef = hashMapResult.next(); } } } protected void fullOuterHashTableSetup() { // Always track key matches for FULL OUTER. matchTracker = vectorMapJoinHashTable.createMatchTracker(); } protected void fullOuterIntersectHashTableSetup() { matchTracker = vectorMapJoinHashTable.createMatchTracker(); } }
oracle/graal
37,212
truffle/src/com.oracle.truffle.api.dsl.test/src/com/oracle/truffle/api/dsl/test/CachedTest.java
/* * Copyright (c) 2015, 2023, 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 com.oracle.truffle.api.dsl.test.TestHelper.assertionsEnabled; import static com.oracle.truffle.api.dsl.test.TestHelper.createCallTarget; import static com.oracle.truffle.api.dsl.test.TestHelper.createNode; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Field; import org.junit.Assert; import org.junit.Test; import com.oracle.truffle.api.CallTarget; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.GenerateUncached; import com.oracle.truffle.api.dsl.Idempotent; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.NodeChildren; import com.oracle.truffle.api.dsl.NodeField; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.dsl.TypeSystemReference; import com.oracle.truffle.api.dsl.UnsupportedSpecializationException; import com.oracle.truffle.api.dsl.test.CachedTestFactory.BoundCacheFactory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.BoundCacheOverflowFactory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.CacheDimensions1Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.CacheDimensions2Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.CacheNodeWithReplaceFactory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ChildrenAdoption1Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ChildrenAdoption2Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ChildrenAdoption3Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ChildrenAdoption4Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ChildrenAdoption5Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ChildrenAdoption6Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ChildrenAdoption7Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ChildrenNoAdoption1Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ChildrenNoAdoption2Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ChildrenNoAdoption3Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ChildrenNoAdoption4Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ChildrenNoAdoption5Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ChildrenNoAdoption6Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.NullChildAdoptionNodeGen; import com.oracle.truffle.api.dsl.test.CachedTestFactory.NullLiteralNodeGen; import com.oracle.truffle.api.dsl.test.CachedTestFactory.ProfileNodeGen; import com.oracle.truffle.api.dsl.test.CachedTestFactory.TestBoundCacheOverflowContainsFactory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.TestCacheFieldFactory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.TestCacheMethodFactory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.TestCacheNodeFieldFactory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.TestCachesOrder2Factory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.TestCachesOrderFactory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.TestCodeGenerationPosNegGuardNodeGen; import com.oracle.truffle.api.dsl.test.CachedTestFactory.TestGuardWithCachedAndDynamicParameterFactory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.TestGuardWithJustCachedParameterFactory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.TestMultipleCachesFactory; import com.oracle.truffle.api.dsl.test.CachedTestFactory.UnboundCacheFactory; import com.oracle.truffle.api.dsl.test.TypeSystemTest.ValueNode; import com.oracle.truffle.api.dsl.test.examples.ExampleTypes; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.NodeInterface; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.profiles.ConditionProfile; import com.oracle.truffle.api.profiles.LoopConditionProfile; @SuppressWarnings({"truffle-inlining", "truffle-neverdefault", "truffle-sharing", "unused"}) public class CachedTest { @Test public void testUnboundCache() { CallTarget root = createCallTarget(UnboundCacheFactory.getInstance()); assertEquals(42, root.call(42)); assertEquals(42, root.call(43)); assertEquals(42, root.call(44)); } @NodeChild static class UnboundCache extends ValueNode { @Specialization static int do1(int value, @Cached("value") int cachedValue) { return cachedValue; } } @Test public void testBoundCache() { CallTarget root = createCallTarget(BoundCacheFactory.getInstance()); assertEquals(42, root.call(42)); assertEquals(43, root.call(43)); assertEquals(44, root.call(44)); try { root.call(45); fail(); } catch (UnsupportedSpecializationException e) { } } @NodeChild static class BoundCache extends ValueNode { @Specialization(guards = "value == cachedValue", limit = "3") static int do1(int value, @Cached("value") int cachedValue) { return cachedValue; } } @Test public void testBoundCacheOverflow() { CallTarget root = createCallTarget(BoundCacheOverflowFactory.getInstance()); assertEquals(42, root.call(42)); assertEquals(43, root.call(43)); assertEquals(-1, root.call(44)); assertEquals(42, root.call(42)); assertEquals(43, root.call(43)); assertEquals(-1, root.call(44)); } @NodeChild static class BoundCacheOverflow extends ValueNode { @Specialization(guards = "value == cachedValue", limit = "2") static int do1(int value, @Cached("value") int cachedValue) { return cachedValue; } @Specialization static int do2(int value) { return -1; } } @Test public void testBoundCacheOverflowContains() { CallTarget root = createCallTarget(TestBoundCacheOverflowContainsFactory.getInstance()); assertEquals(42, root.call(42)); assertEquals(43, root.call(43)); assertEquals(-1, root.call(44)); assertEquals(-1, root.call(42)); assertEquals(-1, root.call(43)); assertEquals(-1, root.call(44)); } @NodeChild static class TestBoundCacheOverflowContains extends ValueNode { @Specialization(guards = "value == cachedValue", limit = "2") static int do1(int value, @Cached("value") int cachedValue) { return cachedValue; } @Specialization(replaces = "do1") static int do2(int value) { return -1; } } @Test public void testCacheField() { CallTarget root = createCallTarget(TestCacheFieldFactory.getInstance()); assertEquals(3, root.call(42)); assertEquals(3, root.call(43)); } @NodeChild static class TestCacheField extends ValueNode { protected int field = 3; @Specialization() static int do1(int value, @Cached("field") int cachedValue) { return cachedValue; } } @Test public void testCacheNodeField() { CallTarget root = createCallTarget(TestCacheNodeFieldFactory.getInstance(), 21); assertEquals(21, root.call(42)); assertEquals(21, root.call(43)); } @NodeChild @NodeField(name = "field", type = int.class) static class TestCacheNodeField extends ValueNode { @Specialization static int do1(int value, @Cached("field") int cachedValue) { return cachedValue; } } @Test public void testCacheNodeWithReplace() { CallTarget root = createCallTarget(CacheNodeWithReplaceFactory.getInstance()); assertEquals(42, root.call(41)); assertEquals(42, root.call(40)); assertEquals(42, root.call(39)); } @NodeChild static class CacheNodeWithReplace extends ValueNode { @Specialization static int do1(int value, @Cached("new()") NodeSubClass cachedNode) { return cachedNode.execute(value); } } public static class NodeSubClass extends Node { private int increment = 1; public int execute(int value) { final NodeSubClass replaced = doReplace(); replaced.increment = increment + 1; return value + increment; } @CompilerDirectives.TruffleBoundary private NodeSubClass doReplace() { return replace(new NodeSubClass()); } } @Test public void testCacheMethod() { TestCacheMethod.invocations = 0; CallTarget root = createCallTarget(TestCacheMethodFactory.getInstance()); assertEquals(42, root.call(42)); assertEquals(42, root.call(43)); assertEquals(42, root.call(44)); assertEquals(1, TestCacheMethod.invocations); } @NodeChild static class TestCacheMethod extends ValueNode { static int invocations = 0; @Specialization static int do1(int value, @Cached("someMethod(value)") int cachedValue) { return cachedValue; } static int someMethod(int value) { invocations++; return value; } } @Test public void testGuardWithJustCachedParameter() { TestGuardWithJustCachedParameter.invocations = 0; CallTarget root = createCallTarget(TestGuardWithJustCachedParameterFactory.getInstance()); assertEquals(42, root.call(42)); assertEquals(42, root.call(43)); assertEquals(42, root.call(44)); if (assertionsEnabled() && !isCompileImmediately()) { Assert.assertTrue(TestGuardWithJustCachedParameter.invocations >= 3); } else { assertEquals(1, TestGuardWithJustCachedParameter.invocations); } } @NodeChild static class TestGuardWithJustCachedParameter extends ValueNode { static int invocations = 0; @Specialization(guards = "someMethod(cachedValue)") static int do1(int value, @Cached("value") int cachedValue) { return cachedValue; } @Idempotent static boolean someMethod(int value) { invocations++; return true; } } private static boolean isCompileImmediately() { CallTarget target = new RootNode(null) { @Override public Object execute(VirtualFrame frame) { return CompilerDirectives.inCompiledCode(); } }.getCallTarget(); return (boolean) target.call(); } @Test public void testGuardWithCachedAndDynamicParameter() { TestGuardWithCachedAndDynamicParameter.cachedMethodInvocations = 0; TestGuardWithCachedAndDynamicParameter.dynamicMethodInvocations = 0; CallTarget root = createCallTarget(TestGuardWithCachedAndDynamicParameterFactory.getInstance()); assertEquals(42, root.call(42)); assertEquals(42, root.call(43)); assertEquals(42, root.call(44)); // guards with just cached parameters are just invoked on the slow path if (assertionsEnabled() && !isCompileImmediately()) { Assert.assertTrue(TestGuardWithCachedAndDynamicParameter.cachedMethodInvocations >= 3); } else { assertEquals(1, TestGuardWithCachedAndDynamicParameter.cachedMethodInvocations); } Assert.assertTrue(TestGuardWithCachedAndDynamicParameter.dynamicMethodInvocations >= 3); } @NodeChild static class TestGuardWithCachedAndDynamicParameter extends ValueNode { static int cachedMethodInvocations = 0; static int dynamicMethodInvocations = 0; @Specialization(guards = {"dynamicMethod(value)", "cachedMethod(cachedValue)"}) static int do1(int value, @Cached("value") int cachedValue) { return cachedValue; } @Idempotent static boolean cachedMethod(int value) { cachedMethodInvocations++; return true; } static boolean dynamicMethod(int value) { dynamicMethodInvocations++; return true; } } /* * Node should not produce any warnings in isIdentical of the generated code. Unnecessary casts * were generated for isIdentical on the fast path. */ @NodeChildren({@NodeChild, @NodeChild}) static class RegressionTestWarningInIsIdentical extends ValueNode { @Specialization(guards = {"cachedName == name"}, limit = "3") protected Object directAccess(String receiver, String name, // @Cached("name") String cachedName, // @Cached("create(receiver, name)") Object callHandle) { return receiver; } protected static Object create(String receiver, String name) { return receiver; } } @NodeChild static class TestMultipleCaches extends ValueNode { @Specialization static int do1(int value, @Cached("value") int cachedValue1, @Cached("value") int cachedValue2) { return cachedValue1 + cachedValue2; } } @Test public void testMultipleCaches() { CallTarget root = createCallTarget(TestMultipleCachesFactory.getInstance()); assertEquals(42, root.call(21)); assertEquals(42, root.call(22)); assertEquals(42, root.call(23)); } @NodeChild static class TestCachedWithProfile extends ValueNode { @Specialization static int do1(int value, @Cached MySubClass mySubclass) { return 42; } } public static class MyClass { public static MyClass create() { return new MyClass(); } } public static class MySubClass extends MyClass { public static MySubClass create() { return new MySubClass(); } } @NodeChild static class TestCachesOrder extends ValueNode { @Specialization(guards = "boundByGuard != 0") static int do1(int value, // @Cached("get(value)") int intermediateValue, // @Cached("transform(intermediateValue)") int boundByGuard, // @Cached("new()") Object notBoundByGuards) { return intermediateValue; } protected int get(int i) { return i * 2; } protected int transform(int i) { return i * 3; } } @Test public void testCachesOrder() { CallTarget root = createCallTarget(TestCachesOrderFactory.getInstance()); assertEquals(42, root.call(21)); assertEquals(42, root.call(22)); assertEquals(42, root.call(23)); } @NodeChild static class TestCachesOrder2 extends ValueNode { @Specialization(guards = "cachedValue == value", limit = "3") static int do1(int value, // @Cached("value") int cachedValue, @Cached("get(cachedValue)") int intermediateValue, // @Cached("transform(intermediateValue)") int boundByGuard, // @Cached("new()") Object notBoundByGuards) { return intermediateValue; } protected int get(int i) { return i * 2; } protected int transform(int i) { return i * 3; } } @Test public void testCachesOrder2() { CallTarget root = createCallTarget(TestCachesOrder2Factory.getInstance()); assertEquals(42, root.call(21)); assertEquals(44, root.call(22)); assertEquals(46, root.call(23)); } @TypeSystemReference(ExampleTypes.class) abstract static class TestCodeGenerationPosNegGuard extends Node { public abstract int execute(Object execute); @Specialization(guards = "guard(value)") static int do0(int value) { return value; } @Specialization(guards = {"!guard(value)", "value != cachedValue"}, limit = "3") static int do1(int value, @Cached("get(value)") int cachedValue) { return cachedValue; } protected static boolean guard(int i) { return i == 0; } protected int get(int i) { return i * 2; } } @Test public void testCodeGenerationPosNegGuard() { TestCodeGenerationPosNegGuard root = TestCodeGenerationPosNegGuardNodeGen.create(); assertEquals(0, root.execute(0)); assertEquals(2, root.execute(1)); assertEquals(4, root.execute(2)); } @NodeChild static class CacheDimensions1 extends ValueNode { @Specialization(guards = "value == cachedValue", limit = "3") static int[] do1(int[] value, // @Cached(value = "value", dimensions = 1) int[] cachedValue) { return cachedValue; } } @Test public void testCacheDimension1() throws NoSuchFieldException, SecurityException { CacheDimensions1 node = TestHelper.createNode(CacheDimensions1Factory.getInstance(), false); Field field = node.getClass().getDeclaredField("do1_cache"); field.setAccessible(true); Field cachedField = field.getType().getDeclaredField("cachedValue_"); cachedField.setAccessible(true); assertEquals(1, cachedField.getAnnotation(CompilationFinal.class).dimensions()); } @NodeChild static class CacheDimensions2 extends ValueNode { @Specialization static int[] do1(int[] value, // @Cached(value = "value", dimensions = 1) int[] cachedValue) { return cachedValue; } } @Test public void testCacheDimension2() throws NoSuchFieldException, SecurityException { CacheDimensions2 node = TestHelper.createNode(CacheDimensions2Factory.getInstance(), false); Field cachedField = node.getClass().getDeclaredField("cachedValue_"); cachedField.setAccessible(true); assertEquals(1, cachedField.getAnnotation(CompilationFinal.class).dimensions()); } abstract static class NullChildAdoption extends Node { abstract Object execute(Object value); @Specialization static int do1(int value, // @Cached(value = "createNode()", neverDefault = false) Node cachedValue) { return value; } static Node createNode() { return null; } } @Test public void testNullChildAdoption() throws NoSuchFieldException, SecurityException { NullChildAdoption node; node = NullChildAdoptionNodeGen.create(); // we should be able to return null from nodes. node.execute(42); } @NodeChild abstract static class ChildrenAdoption1 extends ValueNode { abstract NodeInterface[] execute(Object value); @Specialization(guards = "value == cachedValue", limit = "3") static NodeInterface[] do1(NodeInterface[] value, @Cached("value") NodeInterface[] cachedValue) { return cachedValue; } } @NodeChild abstract static class ChildrenAdoption2 extends ValueNode { abstract NodeInterface execute(Object value); @Specialization(guards = "value == cachedValue", limit = "3") static NodeInterface do1(NodeInterface value, @Cached("value") NodeInterface cachedValue) { return cachedValue; } } @NodeChild abstract static class ChildrenAdoption3 extends ValueNode { abstract Node[] execute(Object value); @Specialization(guards = "value == cachedValue", limit = "3") static Node[] do1(Node[] value, @Cached("value") Node[] cachedValue) { return cachedValue; } } @NodeChild abstract static class ChildrenAdoption4 extends ValueNode { abstract Node execute(Object value); @Specialization(guards = "value == cachedValue", limit = "3") static Node do1(Node value, @Cached("value") Node cachedValue) { return cachedValue; } } @NodeChild abstract static class ChildrenAdoption5 extends ValueNode { abstract Node[] execute(Object value); @Specialization static Node[] do1(Node value, @Cached("createChildren(value)") Node[] cachedValue) { return cachedValue; } protected static Node[] createChildren(Node value) { return new Node[]{value}; } } @NodeChild abstract static class ChildrenAdoption6 extends ValueNode { abstract NodeInterface execute(Node value); @Specialization static NodeInterface do1(Node value, @Cached("createChild(value)") NodeInterface cachedValue) { return cachedValue; } protected static NodeInterface createChild(Node node) { return node; } } @NodeChild abstract static class ChildrenAdoption7 extends ValueNode { abstract NodeInterface[] execute(Object value); @Specialization static NodeInterface[] do1(Node value, @Cached("createChildren(value)") NodeInterface[] cachedValue) { return cachedValue; } protected static NodeInterface[] createChildren(Node value) { return new Node[]{value}; } } @Test public void testChildrenAdoption1() { ChildrenAdoption1 root = createNode(ChildrenAdoption1Factory.getInstance(), false); Node[] children = new Node[]{new ValueNode()}; root.execute(children); Assert.assertTrue(hasParent(root, children[0])); } @Test public void testChildrenAdoption2() { ChildrenAdoption2 root = createNode(ChildrenAdoption2Factory.getInstance(), false); Node child = new ValueNode(); root.execute(child); root.adoptChildren(); Assert.assertTrue(hasParent(root, child)); } @Test public void testChildrenAdoption3() { ChildrenAdoption3 root = createNode(ChildrenAdoption3Factory.getInstance(), false); Node[] children = new Node[]{new ValueNode()}; root.execute(children); Assert.assertTrue(hasParent(root, children[0])); } @Test public void testChildrenAdoption4() { ChildrenAdoption4 root = createNode(ChildrenAdoption4Factory.getInstance(), false); Node child = new ValueNode(); root.execute(child); Assert.assertTrue(hasParent(root, child)); } @Test public void testChildrenAdoption5() { ChildrenAdoption5 root = createNode(ChildrenAdoption5Factory.getInstance(), false); Node child = new ValueNode(); root.execute(child); Assert.assertTrue(hasParent(root, child)); } @Test public void testChildrenAdoption6() { ChildrenAdoption6 root = createNode(ChildrenAdoption6Factory.getInstance(), false); Node child = new ValueNode(); root.execute(child); Assert.assertTrue(hasParent(root, child)); } @Test public void testChildrenAdoption7() { ChildrenAdoption7 root = createNode(ChildrenAdoption7Factory.getInstance(), false); Node child = new ValueNode(); root.execute(child); Assert.assertTrue(hasParent(root, child)); } @NodeChild static class ConstantValueNode extends Node { @Idempotent public int execute() { return 1; } } @NodeChild abstract static class ChildrenNoAdoption1 extends ValueNode { abstract NodeInterface execute(Object value); @Specialization(guards = "value == cachedValue", limit = "3") static NodeInterface do1(NodeInterface value, @Cached(value = "value", adopt = false) NodeInterface cachedValue) { return cachedValue; } } @NodeChild abstract static class ChildrenNoAdoption2 extends ValueNode { abstract NodeInterface[] execute(Object value); @Specialization(guards = "value == cachedValue", limit = "3") static NodeInterface[] do1(NodeInterface[] value, @Cached(value = "value", adopt = false, dimensions = 1) NodeInterface[] cachedValue) { return cachedValue; } } @NodeChild abstract static class ChildrenNoAdoption3 extends ValueNode { abstract NodeInterface[] execute(Object value); @Specialization static NodeInterface[] do1(Node value, @Cached(value = "createChildren(value)", adopt = false, dimensions = 1) NodeInterface[] cachedValue) { return cachedValue; } protected static NodeInterface[] createChildren(Node value) { return new Node[]{value}; } } @NodeChild abstract static class ChildrenNoAdoption4 extends ValueNode { abstract Node execute(Object value); @Specialization(guards = "value == cachedValue", limit = "3") static Node do1(Node value, @Cached(value = "value", adopt = false) Node cachedValue) { return cachedValue; } } @NodeChild abstract static class ChildrenNoAdoption5 extends ValueNode { abstract Node[] execute(Object value); @Specialization static Node[] do1(Node value, @Cached(value = "createChildren(value)", adopt = false, dimensions = 1) Node[] cachedValue) { return cachedValue; } protected static Node[] createChildren(Node value) { return new Node[]{value}; } } // Case where a no-adopt cached node is executed in the guards. @NodeChild abstract static class ChildrenNoAdoption6 extends ValueNode { abstract Node execute(Object value); @Specialization(guards = "cachedValue.execute() == 1") static Node do1(ConstantValueNode value, @Cached(value = "value", adopt = false) ConstantValueNode cachedValue) { return cachedValue; } } @Test public void testChildrenNoAdoption1() { ChildrenNoAdoption1 root = createNode(ChildrenNoAdoption1Factory.getInstance(), false); Node child = new ValueNode(); root.execute(child); root.adoptChildren(); assertFalse(hasParent(root, child)); } @Test public void testChildrenNoAdoption2() { ChildrenNoAdoption2 root = createNode(ChildrenNoAdoption2Factory.getInstance(), false); Node[] children = new Node[]{new ValueNode()}; root.execute(children); assertFalse(hasParent(root, children[0])); } @Test public void testChildrenNoAdoption3() { ChildrenNoAdoption3 root = createNode(ChildrenNoAdoption3Factory.getInstance(), false); Node child = new ValueNode(); root.execute(child); assertFalse(hasParent(root, child)); } @Test public void testChildrenNoAdoption4() { ChildrenNoAdoption4 root = createNode(ChildrenNoAdoption4Factory.getInstance(), false); Node child = new ValueNode(); root.execute(child); assertFalse(hasParent(root, child)); } @Test public void testChildrenNoAdoption5() { ChildrenNoAdoption5 root = createNode(ChildrenNoAdoption5Factory.getInstance(), false); Node child = new ValueNode(); root.execute(child); assertFalse(hasParent(root, child)); } @Test public void testChildrenNoAdoption6() { ChildrenNoAdoption6 root = createNode(ChildrenNoAdoption6Factory.getInstance(), false); ConstantValueNode child = new ConstantValueNode(); root.execute(child); assertFalse(hasParent(root, child)); } @GenerateUncached abstract static class NullLiteralNode extends Node { abstract Object execute(Object value); @Specialization static Object do1(String value, @Cached(value = "null", uncached = "null") Object cachedValue) { return cachedValue; } protected static Object createChildren() { return null; } } @Test public void testNullLiteral() { assertNull(NullLiteralNodeGen.create().execute("")); assertNull(NullLiteralNodeGen.getUncached().execute("")); } @GenerateUncached abstract static class ProfileNode extends Node { abstract Object execute(Object value); @Specialization static ConditionProfile do1(String value, // @Cached(inline = false) ConditionProfile conditionProfile) { return conditionProfile; } @Specialization static LoopConditionProfile do1(int value, // @Cached LoopConditionProfile loopProfile) { return loopProfile; } } @Test public void testConditionProfileLoopConditionProfile() { final Object conditionProfile = ProfileNodeGen.getUncached().execute(""); assertTrue(conditionProfile instanceof ConditionProfile); assertFalse(conditionProfile instanceof LoopConditionProfile); assertTrue(ProfileNodeGen.getUncached().execute(0) instanceof LoopConditionProfile); } private static boolean hasParent(Node parent, Node node) { Node current = node != null ? node.getParent() : null; while (current != null) { if (current == parent) { return true; } current = current.getParent(); } return false; } @NodeChild static class CacheDimensionsError1 extends ValueNode { @Specialization(guards = "value == cachedValue", limit = "3") static int[] do1(int[] value, // @ExpectError("The cached dimensions attribute must be specified for array types.") @Cached("value") int[] cachedValue) { return cachedValue; } } @NodeChild static class CacheDimensionsError2 extends ValueNode { @Specialization(guards = "value == cachedValue") static Node[] do1(Node[] value, // @ExpectError("The dimensions attribute has no affect for the type Node[].") @Cached(value = "value", dimensions = 1) Node[] cachedValue) { return cachedValue; } } @NodeChild static class CacheDimensionsError3 extends ValueNode { @Specialization(guards = "value == cachedValue") static NodeInterface[] do1(NodeInterface[] value, // @ExpectError("The dimensions attribute has no affect for the type NodeInterface[].") @Cached(value = "value", dimensions = 1) NodeInterface[] cachedValue) { return cachedValue; } } @NodeChild static class CachedError1 extends ValueNode { @Specialization static int do1(int value, @ExpectError("Incompatible return type int. The expression type must be equal to the parameter type short.")// @Cached("value") short cachedValue) { return value; } } @NodeChild static class CachedError2 extends ValueNode { // caches are not allowed to make backward references @Specialization static int do1(int value, @ExpectError("The initializer expression of parameter 'cachedValue1' binds uninitialized parameter 'cachedValue2. Reorder the parameters to resolve the problem.") @Cached("cachedValue2") int cachedValue1, @Cached("value") int cachedValue2) { return cachedValue1 + cachedValue2; } } @NodeChild static class CachedError3 extends ValueNode { // cyclic dependency between cached expressions @Specialization static int do1(int value, @ExpectError("The initializer expression of parameter 'cachedValue1' binds uninitialized parameter 'cachedValue2. Reorder the parameters to resolve the problem.") @Cached("cachedValue2") int cachedValue1, @Cached("cachedValue1") int cachedValue2) { return cachedValue1 + cachedValue2; } } @NodeChild static class CachedError4 extends ValueNode { // adopting not a Node @Specialization static int do1(int value, @ExpectError("Type 'int' is neither a NodeInterface type, nor an array of NodeInterface types and therefore it can not be adopted. Remove the adopt attribute to resolve this.") // @Cached(value = "value", adopt = true) int cachedValue) { return cachedValue; } } @NodeChild static class CachedError5 extends ValueNode { // adopting not a Node @Specialization static Class<?> do1(Class<?> value, @ExpectError("Type 'java.lang.Class<?>' is neither a NodeInterface type, nor an array of NodeInterface types and therefore it can not be adopted. Remove the adopt attribute to resolve this.") // @Cached(value = "value", adopt = false) Class<?> cachedValue) { return cachedValue; } } @NodeChild abstract static class CachedError6 extends ValueNode { // dimensions are missing when not adopting @Specialization static NodeInterface[] do1(NodeInterface[] value, @ExpectError("The cached dimensions attribute must be specified for array types.") // @Cached(value = "value", adopt = false) NodeInterface[] cachedValue) { return cachedValue; } } @NodeChild abstract static class CachedError7 extends ValueNode { // dimensions are missing when not adopting @Specialization static Node[] do1(Node[] value, @ExpectError("The cached dimensions attribute must be specified for array types.") // @Cached(value = "value", adopt = false) Node[] cachedValue) { return cachedValue; } } record TestRecord(boolean foo) { } @NodeChild abstract static class CachedRecord extends ValueNode { protected static TestRecord getRecord() { return null; } // ensure that ElementUtils.elementEquals accepts records @Specialization static int do1(int x, @Cached("getRecord().foo()") boolean cached) { return 0; } @Specialization static int do1(double x, @Cached("getRecord().foo()") boolean cached) { return 0; } } }
googleapis/google-cloud-java
37,170
java-orchestration-airflow/proto-google-cloud-orchestration-airflow-v1beta1/src/main/java/com/google/cloud/orchestration/airflow/service/v1beta1/UserWorkloadsConfigMap.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/orchestration/airflow/service/v1beta1/environments.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.orchestration.airflow.service.v1beta1; /** * * * <pre> * User workloads ConfigMap used by Airflow tasks that run with Kubernetes * executor or KubernetesPodOperator. * </pre> * * Protobuf type {@code google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap} */ public final class UserWorkloadsConfigMap extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap) UserWorkloadsConfigMapOrBuilder { private static final long serialVersionUID = 0L; // Use UserWorkloadsConfigMap.newBuilder() to construct. private UserWorkloadsConfigMap(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UserWorkloadsConfigMap() { name_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UserWorkloadsConfigMap(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.orchestration.airflow.service.v1beta1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1beta1_UserWorkloadsConfigMap_descriptor; } @SuppressWarnings({"rawtypes"}) @java.lang.Override protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 2: return internalGetData(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.orchestration.airflow.service.v1beta1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1beta1_UserWorkloadsConfigMap_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap.class, com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap.Builder .class); } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Identifier. The resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Identifier. The resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DATA_FIELD_NUMBER = 2; private static final class DataDefaultEntryHolder { static final com.google.protobuf.MapEntry<java.lang.String, java.lang.String> defaultEntry = com.google.protobuf.MapEntry.<java.lang.String, java.lang.String>newDefaultInstance( com.google.cloud.orchestration.airflow.service.v1beta1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1beta1_UserWorkloadsConfigMap_DataEntry_descriptor, com.google.protobuf.WireFormat.FieldType.STRING, "", com.google.protobuf.WireFormat.FieldType.STRING, ""); } @SuppressWarnings("serial") private com.google.protobuf.MapField<java.lang.String, java.lang.String> data_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetData() { if (data_ == null) { return com.google.protobuf.MapField.emptyMapField(DataDefaultEntryHolder.defaultEntry); } return data_; } public int getDataCount() { return internalGetData().getMap().size(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public boolean containsData(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetData().getMap().containsKey(key); } /** Use {@link #getDataMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getData() { return getDataMap(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getDataMap() { return internalGetData().getMap(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public /* nullable */ java.lang.String getDataOrDefault( java.lang.String key, /* nullable */ java.lang.String defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetData().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.lang.String getDataOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetData().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( output, internalGetData(), DataDefaultEntryHolder.defaultEntry, 2); getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } for (java.util.Map.Entry<java.lang.String, java.lang.String> entry : internalGetData().getMap().entrySet()) { com.google.protobuf.MapEntry<java.lang.String, java.lang.String> data__ = DataDefaultEntryHolder.defaultEntry .newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, data__); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap)) { return super.equals(obj); } com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap other = (com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap) obj; if (!getName().equals(other.getName())) return false; if (!internalGetData().equals(other.internalGetData())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); if (!internalGetData().getMap().isEmpty()) { hash = (37 * hash) + DATA_FIELD_NUMBER; hash = (53 * hash) + internalGetData().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * User workloads ConfigMap used by Airflow tasks that run with Kubernetes * executor or KubernetesPodOperator. * </pre> * * Protobuf type {@code google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap) com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMapOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.orchestration.airflow.service.v1beta1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1beta1_UserWorkloadsConfigMap_descriptor; } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 2: return internalGetData(); default: throw new RuntimeException("Invalid map field number: " + number); } } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMutableMapFieldReflection( int number) { switch (number) { case 2: return internalGetMutableData(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.orchestration.airflow.service.v1beta1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1beta1_UserWorkloadsConfigMap_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap.class, com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap.Builder .class); } // Construct using // com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; internalGetMutableData().clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.orchestration.airflow.service.v1beta1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1beta1_UserWorkloadsConfigMap_descriptor; } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap getDefaultInstanceForType() { return com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap .getDefaultInstance(); } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap build() { com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap buildPartial() { com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap result = new com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.data_ = internalGetData(); result.data_.makeImmutable(); } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap) { return mergeFrom( (com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap other) { if (other == com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap .getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } internalGetMutableData().mergeFrom(other.internalGetData()); bitField0_ |= 0x00000002; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { com.google.protobuf.MapEntry<java.lang.String, java.lang.String> data__ = input.readMessage( DataDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); internalGetMutableData().getMutableMap().put(data__.getKey(), data__.getValue()); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Identifier. The resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Identifier. The resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Identifier. The resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Identifier. The resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Identifier. The resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.MapField<java.lang.String, java.lang.String> data_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetData() { if (data_ == null) { return com.google.protobuf.MapField.emptyMapField(DataDefaultEntryHolder.defaultEntry); } return data_; } private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetMutableData() { if (data_ == null) { data_ = com.google.protobuf.MapField.newMapField(DataDefaultEntryHolder.defaultEntry); } if (!data_.isMutable()) { data_ = data_.copy(); } bitField0_ |= 0x00000002; onChanged(); return data_; } public int getDataCount() { return internalGetData().getMap().size(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public boolean containsData(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetData().getMap().containsKey(key); } /** Use {@link #getDataMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getData() { return getDataMap(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getDataMap() { return internalGetData().getMap(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public /* nullable */ java.lang.String getDataOrDefault( java.lang.String key, /* nullable */ java.lang.String defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetData().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.lang.String getDataOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetData().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public Builder clearData() { bitField0_ = (bitField0_ & ~0x00000002); internalGetMutableData().getMutableMap().clear(); return this; } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder removeData(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } internalGetMutableData().getMutableMap().remove(key); return this; } /** Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getMutableData() { bitField0_ |= 0x00000002; return internalGetMutableData().getMutableMap(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder putData(java.lang.String key, java.lang.String value) { if (key == null) { throw new NullPointerException("map key"); } if (value == null) { throw new NullPointerException("map value"); } internalGetMutableData().getMutableMap().put(key, value); bitField0_ |= 0x00000002; return this; } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder putAllData(java.util.Map<java.lang.String, java.lang.String> values) { internalGetMutableData().getMutableMap().putAll(values); bitField0_ |= 0x00000002; return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap) } // @@protoc_insertion_point(class_scope:google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap) private static final com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap(); } public static com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UserWorkloadsConfigMap> PARSER = new com.google.protobuf.AbstractParser<UserWorkloadsConfigMap>() { @java.lang.Override public UserWorkloadsConfigMap parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<UserWorkloadsConfigMap> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UserWorkloadsConfigMap> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1beta1.UserWorkloadsConfigMap getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,571
java-appengine-admin/grpc-google-cloud-appengine-admin-v1/src/main/java/com/google/appengine/v1/ApplicationsGrpc.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.appengine.v1; import static io.grpc.MethodDescriptor.generateFullMethodName; /** * * * <pre> * Manages App Engine applications. * </pre> */ @javax.annotation.Generated( value = "by gRPC proto compiler", comments = "Source: google/appengine/v1/appengine.proto") @io.grpc.stub.annotations.GrpcGenerated public final class ApplicationsGrpc { private ApplicationsGrpc() {} public static final java.lang.String SERVICE_NAME = "google.appengine.v1.Applications"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor< com.google.appengine.v1.GetApplicationRequest, com.google.appengine.v1.Application> getGetApplicationMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetApplication", requestType = com.google.appengine.v1.GetApplicationRequest.class, responseType = com.google.appengine.v1.Application.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.appengine.v1.GetApplicationRequest, com.google.appengine.v1.Application> getGetApplicationMethod() { io.grpc.MethodDescriptor< com.google.appengine.v1.GetApplicationRequest, com.google.appengine.v1.Application> getGetApplicationMethod; if ((getGetApplicationMethod = ApplicationsGrpc.getGetApplicationMethod) == null) { synchronized (ApplicationsGrpc.class) { if ((getGetApplicationMethod = ApplicationsGrpc.getGetApplicationMethod) == null) { ApplicationsGrpc.getGetApplicationMethod = getGetApplicationMethod = io.grpc.MethodDescriptor .<com.google.appengine.v1.GetApplicationRequest, com.google.appengine.v1.Application> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetApplication")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.appengine.v1.GetApplicationRequest.getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.appengine.v1.Application.getDefaultInstance())) .setSchemaDescriptor( new ApplicationsMethodDescriptorSupplier("GetApplication")) .build(); } } } return getGetApplicationMethod; } private static volatile io.grpc.MethodDescriptor< com.google.appengine.v1.CreateApplicationRequest, com.google.longrunning.Operation> getCreateApplicationMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "CreateApplication", requestType = com.google.appengine.v1.CreateApplicationRequest.class, responseType = com.google.longrunning.Operation.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.appengine.v1.CreateApplicationRequest, com.google.longrunning.Operation> getCreateApplicationMethod() { io.grpc.MethodDescriptor< com.google.appengine.v1.CreateApplicationRequest, com.google.longrunning.Operation> getCreateApplicationMethod; if ((getCreateApplicationMethod = ApplicationsGrpc.getCreateApplicationMethod) == null) { synchronized (ApplicationsGrpc.class) { if ((getCreateApplicationMethod = ApplicationsGrpc.getCreateApplicationMethod) == null) { ApplicationsGrpc.getCreateApplicationMethod = getCreateApplicationMethod = io.grpc.MethodDescriptor .<com.google.appengine.v1.CreateApplicationRequest, com.google.longrunning.Operation> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "CreateApplication")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.appengine.v1.CreateApplicationRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.Operation.getDefaultInstance())) .setSchemaDescriptor( new ApplicationsMethodDescriptorSupplier("CreateApplication")) .build(); } } } return getCreateApplicationMethod; } private static volatile io.grpc.MethodDescriptor< com.google.appengine.v1.UpdateApplicationRequest, com.google.longrunning.Operation> getUpdateApplicationMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "UpdateApplication", requestType = com.google.appengine.v1.UpdateApplicationRequest.class, responseType = com.google.longrunning.Operation.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.appengine.v1.UpdateApplicationRequest, com.google.longrunning.Operation> getUpdateApplicationMethod() { io.grpc.MethodDescriptor< com.google.appengine.v1.UpdateApplicationRequest, com.google.longrunning.Operation> getUpdateApplicationMethod; if ((getUpdateApplicationMethod = ApplicationsGrpc.getUpdateApplicationMethod) == null) { synchronized (ApplicationsGrpc.class) { if ((getUpdateApplicationMethod = ApplicationsGrpc.getUpdateApplicationMethod) == null) { ApplicationsGrpc.getUpdateApplicationMethod = getUpdateApplicationMethod = io.grpc.MethodDescriptor .<com.google.appengine.v1.UpdateApplicationRequest, com.google.longrunning.Operation> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "UpdateApplication")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.appengine.v1.UpdateApplicationRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.Operation.getDefaultInstance())) .setSchemaDescriptor( new ApplicationsMethodDescriptorSupplier("UpdateApplication")) .build(); } } } return getUpdateApplicationMethod; } private static volatile io.grpc.MethodDescriptor< com.google.appengine.v1.RepairApplicationRequest, com.google.longrunning.Operation> getRepairApplicationMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "RepairApplication", requestType = com.google.appengine.v1.RepairApplicationRequest.class, responseType = com.google.longrunning.Operation.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.appengine.v1.RepairApplicationRequest, com.google.longrunning.Operation> getRepairApplicationMethod() { io.grpc.MethodDescriptor< com.google.appengine.v1.RepairApplicationRequest, com.google.longrunning.Operation> getRepairApplicationMethod; if ((getRepairApplicationMethod = ApplicationsGrpc.getRepairApplicationMethod) == null) { synchronized (ApplicationsGrpc.class) { if ((getRepairApplicationMethod = ApplicationsGrpc.getRepairApplicationMethod) == null) { ApplicationsGrpc.getRepairApplicationMethod = getRepairApplicationMethod = io.grpc.MethodDescriptor .<com.google.appengine.v1.RepairApplicationRequest, com.google.longrunning.Operation> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "RepairApplication")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.appengine.v1.RepairApplicationRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.Operation.getDefaultInstance())) .setSchemaDescriptor( new ApplicationsMethodDescriptorSupplier("RepairApplication")) .build(); } } } return getRepairApplicationMethod; } /** Creates a new async stub that supports all call types for the service */ public static ApplicationsStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<ApplicationsStub> factory = new io.grpc.stub.AbstractStub.StubFactory<ApplicationsStub>() { @java.lang.Override public ApplicationsStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ApplicationsStub(channel, callOptions); } }; return ApplicationsStub.newStub(factory, channel); } /** Creates a new blocking-style stub that supports all types of calls on the service */ public static ApplicationsBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<ApplicationsBlockingV2Stub> factory = new io.grpc.stub.AbstractStub.StubFactory<ApplicationsBlockingV2Stub>() { @java.lang.Override public ApplicationsBlockingV2Stub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ApplicationsBlockingV2Stub(channel, callOptions); } }; return ApplicationsBlockingV2Stub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static ApplicationsBlockingStub newBlockingStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<ApplicationsBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<ApplicationsBlockingStub>() { @java.lang.Override public ApplicationsBlockingStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ApplicationsBlockingStub(channel, callOptions); } }; return ApplicationsBlockingStub.newStub(factory, channel); } /** Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static ApplicationsFutureStub newFutureStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<ApplicationsFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<ApplicationsFutureStub>() { @java.lang.Override public ApplicationsFutureStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ApplicationsFutureStub(channel, callOptions); } }; return ApplicationsFutureStub.newStub(factory, channel); } /** * * * <pre> * Manages App Engine applications. * </pre> */ public interface AsyncService { /** * * * <pre> * Gets information about an application. * </pre> */ default void getApplication( com.google.appengine.v1.GetApplicationRequest request, io.grpc.stub.StreamObserver<com.google.appengine.v1.Application> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getGetApplicationMethod(), responseObserver); } /** * * * <pre> * Creates an App Engine application for a Google Cloud Platform project. * Required fields: * * `id` - The ID of the target Cloud Platform project. * * *location* - The [region](https://cloud.google.com/appengine/docs/locations) where you want the App Engine application located. * For more information about App Engine applications, see [Managing Projects, Applications, and Billing](https://cloud.google.com/appengine/docs/standard/python/console/). * </pre> */ default void createApplication( com.google.appengine.v1.CreateApplicationRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getCreateApplicationMethod(), responseObserver); } /** * * * <pre> * Updates the specified Application resource. * You can update the following fields: * * `auth_domain` - Google authentication domain for controlling user access to the application. * * `default_cookie_expiration` - Cookie expiration policy for the application. * * `iap` - Identity-Aware Proxy properties for the application. * </pre> */ default void updateApplication( com.google.appengine.v1.UpdateApplicationRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getUpdateApplicationMethod(), responseObserver); } /** * * * <pre> * Recreates the required App Engine features for the specified App Engine * application, for example a Cloud Storage bucket or App Engine service * account. * Use this method if you receive an error message about a missing feature, * for example, *Error retrieving the App Engine service account*. * If you have deleted your App Engine service account, this will * not be able to recreate it. Instead, you should attempt to use the * IAM undelete API if possible at https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D . * If the deletion was recent, the numeric ID can be found in the Cloud * Console Activity Log. * </pre> */ default void repairApplication( com.google.appengine.v1.RepairApplicationRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getRepairApplicationMethod(), responseObserver); } } /** * Base class for the server implementation of the service Applications. * * <pre> * Manages App Engine applications. * </pre> */ public abstract static class ApplicationsImplBase implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return ApplicationsGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service Applications. * * <pre> * Manages App Engine applications. * </pre> */ public static final class ApplicationsStub extends io.grpc.stub.AbstractAsyncStub<ApplicationsStub> { private ApplicationsStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ApplicationsStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ApplicationsStub(channel, callOptions); } /** * * * <pre> * Gets information about an application. * </pre> */ public void getApplication( com.google.appengine.v1.GetApplicationRequest request, io.grpc.stub.StreamObserver<com.google.appengine.v1.Application> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetApplicationMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Creates an App Engine application for a Google Cloud Platform project. * Required fields: * * `id` - The ID of the target Cloud Platform project. * * *location* - The [region](https://cloud.google.com/appengine/docs/locations) where you want the App Engine application located. * For more information about App Engine applications, see [Managing Projects, Applications, and Billing](https://cloud.google.com/appengine/docs/standard/python/console/). * </pre> */ public void createApplication( com.google.appengine.v1.CreateApplicationRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getCreateApplicationMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Updates the specified Application resource. * You can update the following fields: * * `auth_domain` - Google authentication domain for controlling user access to the application. * * `default_cookie_expiration` - Cookie expiration policy for the application. * * `iap` - Identity-Aware Proxy properties for the application. * </pre> */ public void updateApplication( com.google.appengine.v1.UpdateApplicationRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getUpdateApplicationMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Recreates the required App Engine features for the specified App Engine * application, for example a Cloud Storage bucket or App Engine service * account. * Use this method if you receive an error message about a missing feature, * for example, *Error retrieving the App Engine service account*. * If you have deleted your App Engine service account, this will * not be able to recreate it. Instead, you should attempt to use the * IAM undelete API if possible at https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D . * If the deletion was recent, the numeric ID can be found in the Cloud * Console Activity Log. * </pre> */ public void repairApplication( com.google.appengine.v1.RepairApplicationRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getRepairApplicationMethod(), getCallOptions()), request, responseObserver); } } /** * A stub to allow clients to do synchronous rpc calls to service Applications. * * <pre> * Manages App Engine applications. * </pre> */ public static final class ApplicationsBlockingV2Stub extends io.grpc.stub.AbstractBlockingStub<ApplicationsBlockingV2Stub> { private ApplicationsBlockingV2Stub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ApplicationsBlockingV2Stub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ApplicationsBlockingV2Stub(channel, callOptions); } /** * * * <pre> * Gets information about an application. * </pre> */ public com.google.appengine.v1.Application getApplication( com.google.appengine.v1.GetApplicationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetApplicationMethod(), getCallOptions(), request); } /** * * * <pre> * Creates an App Engine application for a Google Cloud Platform project. * Required fields: * * `id` - The ID of the target Cloud Platform project. * * *location* - The [region](https://cloud.google.com/appengine/docs/locations) where you want the App Engine application located. * For more information about App Engine applications, see [Managing Projects, Applications, and Billing](https://cloud.google.com/appengine/docs/standard/python/console/). * </pre> */ public com.google.longrunning.Operation createApplication( com.google.appengine.v1.CreateApplicationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateApplicationMethod(), getCallOptions(), request); } /** * * * <pre> * Updates the specified Application resource. * You can update the following fields: * * `auth_domain` - Google authentication domain for controlling user access to the application. * * `default_cookie_expiration` - Cookie expiration policy for the application. * * `iap` - Identity-Aware Proxy properties for the application. * </pre> */ public com.google.longrunning.Operation updateApplication( com.google.appengine.v1.UpdateApplicationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getUpdateApplicationMethod(), getCallOptions(), request); } /** * * * <pre> * Recreates the required App Engine features for the specified App Engine * application, for example a Cloud Storage bucket or App Engine service * account. * Use this method if you receive an error message about a missing feature, * for example, *Error retrieving the App Engine service account*. * If you have deleted your App Engine service account, this will * not be able to recreate it. Instead, you should attempt to use the * IAM undelete API if possible at https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D . * If the deletion was recent, the numeric ID can be found in the Cloud * Console Activity Log. * </pre> */ public com.google.longrunning.Operation repairApplication( com.google.appengine.v1.RepairApplicationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getRepairApplicationMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do limited synchronous rpc calls to service Applications. * * <pre> * Manages App Engine applications. * </pre> */ public static final class ApplicationsBlockingStub extends io.grpc.stub.AbstractBlockingStub<ApplicationsBlockingStub> { private ApplicationsBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ApplicationsBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ApplicationsBlockingStub(channel, callOptions); } /** * * * <pre> * Gets information about an application. * </pre> */ public com.google.appengine.v1.Application getApplication( com.google.appengine.v1.GetApplicationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetApplicationMethod(), getCallOptions(), request); } /** * * * <pre> * Creates an App Engine application for a Google Cloud Platform project. * Required fields: * * `id` - The ID of the target Cloud Platform project. * * *location* - The [region](https://cloud.google.com/appengine/docs/locations) where you want the App Engine application located. * For more information about App Engine applications, see [Managing Projects, Applications, and Billing](https://cloud.google.com/appengine/docs/standard/python/console/). * </pre> */ public com.google.longrunning.Operation createApplication( com.google.appengine.v1.CreateApplicationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateApplicationMethod(), getCallOptions(), request); } /** * * * <pre> * Updates the specified Application resource. * You can update the following fields: * * `auth_domain` - Google authentication domain for controlling user access to the application. * * `default_cookie_expiration` - Cookie expiration policy for the application. * * `iap` - Identity-Aware Proxy properties for the application. * </pre> */ public com.google.longrunning.Operation updateApplication( com.google.appengine.v1.UpdateApplicationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getUpdateApplicationMethod(), getCallOptions(), request); } /** * * * <pre> * Recreates the required App Engine features for the specified App Engine * application, for example a Cloud Storage bucket or App Engine service * account. * Use this method if you receive an error message about a missing feature, * for example, *Error retrieving the App Engine service account*. * If you have deleted your App Engine service account, this will * not be able to recreate it. Instead, you should attempt to use the * IAM undelete API if possible at https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D . * If the deletion was recent, the numeric ID can be found in the Cloud * Console Activity Log. * </pre> */ public com.google.longrunning.Operation repairApplication( com.google.appengine.v1.RepairApplicationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getRepairApplicationMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do ListenableFuture-style rpc calls to service Applications. * * <pre> * Manages App Engine applications. * </pre> */ public static final class ApplicationsFutureStub extends io.grpc.stub.AbstractFutureStub<ApplicationsFutureStub> { private ApplicationsFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ApplicationsFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ApplicationsFutureStub(channel, callOptions); } /** * * * <pre> * Gets information about an application. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.appengine.v1.Application> getApplication(com.google.appengine.v1.GetApplicationRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetApplicationMethod(), getCallOptions()), request); } /** * * * <pre> * Creates an App Engine application for a Google Cloud Platform project. * Required fields: * * `id` - The ID of the target Cloud Platform project. * * *location* - The [region](https://cloud.google.com/appengine/docs/locations) where you want the App Engine application located. * For more information about App Engine applications, see [Managing Projects, Applications, and Billing](https://cloud.google.com/appengine/docs/standard/python/console/). * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation> createApplication(com.google.appengine.v1.CreateApplicationRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getCreateApplicationMethod(), getCallOptions()), request); } /** * * * <pre> * Updates the specified Application resource. * You can update the following fields: * * `auth_domain` - Google authentication domain for controlling user access to the application. * * `default_cookie_expiration` - Cookie expiration policy for the application. * * `iap` - Identity-Aware Proxy properties for the application. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation> updateApplication(com.google.appengine.v1.UpdateApplicationRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getUpdateApplicationMethod(), getCallOptions()), request); } /** * * * <pre> * Recreates the required App Engine features for the specified App Engine * application, for example a Cloud Storage bucket or App Engine service * account. * Use this method if you receive an error message about a missing feature, * for example, *Error retrieving the App Engine service account*. * If you have deleted your App Engine service account, this will * not be able to recreate it. Instead, you should attempt to use the * IAM undelete API if possible at https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D . * If the deletion was recent, the numeric ID can be found in the Cloud * Console Activity Log. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation> repairApplication(com.google.appengine.v1.RepairApplicationRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getRepairApplicationMethod(), getCallOptions()), request); } } private static final int METHODID_GET_APPLICATION = 0; private static final int METHODID_CREATE_APPLICATION = 1; private static final int METHODID_UPDATE_APPLICATION = 2; private static final int METHODID_REPAIR_APPLICATION = 3; 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_GET_APPLICATION: serviceImpl.getApplication( (com.google.appengine.v1.GetApplicationRequest) request, (io.grpc.stub.StreamObserver<com.google.appengine.v1.Application>) responseObserver); break; case METHODID_CREATE_APPLICATION: serviceImpl.createApplication( (com.google.appengine.v1.CreateApplicationRequest) request, (io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) responseObserver); break; case METHODID_UPDATE_APPLICATION: serviceImpl.updateApplication( (com.google.appengine.v1.UpdateApplicationRequest) request, (io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) responseObserver); break; case METHODID_REPAIR_APPLICATION: serviceImpl.repairApplication( (com.google.appengine.v1.RepairApplicationRequest) request, (io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) 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( getGetApplicationMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.appengine.v1.GetApplicationRequest, com.google.appengine.v1.Application>(service, METHODID_GET_APPLICATION))) .addMethod( getCreateApplicationMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.appengine.v1.CreateApplicationRequest, com.google.longrunning.Operation>(service, METHODID_CREATE_APPLICATION))) .addMethod( getUpdateApplicationMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.appengine.v1.UpdateApplicationRequest, com.google.longrunning.Operation>(service, METHODID_UPDATE_APPLICATION))) .addMethod( getRepairApplicationMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.appengine.v1.RepairApplicationRequest, com.google.longrunning.Operation>(service, METHODID_REPAIR_APPLICATION))) .build(); } private abstract static class ApplicationsBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { ApplicationsBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return com.google.appengine.v1.AppengineProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("Applications"); } } private static final class ApplicationsFileDescriptorSupplier extends ApplicationsBaseDescriptorSupplier { ApplicationsFileDescriptorSupplier() {} } private static final class ApplicationsMethodDescriptorSupplier extends ApplicationsBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final java.lang.String methodName; ApplicationsMethodDescriptorSupplier(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 (ApplicationsGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new ApplicationsFileDescriptorSupplier()) .addMethod(getGetApplicationMethod()) .addMethod(getCreateApplicationMethod()) .addMethod(getUpdateApplicationMethod()) .addMethod(getRepairApplicationMethod()) .build(); } } } return result; } }
apache/ignite-3
37,268
modules/table/src/integrationTest/java/org/apache/ignite/internal/table/ItRecordBinaryViewApiTest.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.table; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.ignite.internal.schema.Column; import org.apache.ignite.internal.schema.InvalidTypeException; import org.apache.ignite.internal.schema.SchemaDescriptor; import org.apache.ignite.internal.schema.SchemaMismatchException; import org.apache.ignite.internal.testframework.IgniteTestUtils; import org.apache.ignite.internal.type.NativeTypes; import org.apache.ignite.lang.ErrorGroups.Client; import org.apache.ignite.lang.IgniteException; import org.apache.ignite.lang.MarshallerException; import org.apache.ignite.lang.util.IgniteNameUtils; import org.apache.ignite.table.RecordView; import org.apache.ignite.table.Tuple; import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; /** * Integration tests for binary record view API. */ @SuppressWarnings("ClassEscapesDefinedScope") public class ItRecordBinaryViewApiTest extends ItRecordViewApiBaseTest { private static final String TABLE_NAME_API_TEST = "test_api"; private static final String TABLE_NAME_API_TEST_QUOTED = "\"#%\"\"$\\@?!^.[table1]\""; private static final String TABLE_NAME_WITH_DEFAULT_VALUES = "test_defaults"; private static final String TABLE_NAME_FOR_SCHEMA_VALIDATION = "test_schema"; private static final String TABLE_COMPOUND_KEY = "test_tuple_compound_key"; private static final String TABLE_TYPE_MISMATCH = "test_type_mismatch"; private static final String TABLE_STRING_TYPE_MATCH = "test_string_type_match"; private static final String TABLE_BYTE_TYPE_MATCH = "test_byte_type_match"; private Map<String, TestTableDefinition> schemaAwareTestTables; @BeforeAll void createTables() { Column[] valueColumns = {new Column("VAL", NativeTypes.INT64, true)}; TestTableDefinition testApiTable1 = new TestTableDefinition(TABLE_NAME_API_TEST, DEFAULT_KEY, valueColumns, true); TestTableDefinition testApiTable2 = new TestTableDefinition( TABLE_NAME_API_TEST_QUOTED, new Column[]{new Column("_-#$%/\"\"\\@?!^.[key]", NativeTypes.INT64, false)}, new Column[]{new Column("_-#$%/\"\"\\@?!^.[val]", NativeTypes.INT64, true)}, true ); List<TestTableDefinition> tablesToCreate = List.of( testApiTable1, testApiTable2, new TestTableDefinition( TABLE_COMPOUND_KEY, new Column[]{ new Column("ID", NativeTypes.INT64, false), new Column("AFFID", NativeTypes.INT64, false) }, valueColumns ), new TestTableDefinition( TABLE_TYPE_MISMATCH, DEFAULT_KEY, new Column[]{ new Column("VALSTRING", NativeTypes.stringOf(3), true), new Column("VALBYTES", NativeTypes.blobOf(3), true) } ), new TestTableDefinition( TABLE_STRING_TYPE_MATCH, DEFAULT_KEY, new Column[]{new Column("VALSTRING", NativeTypes.stringOf(3), true)} ), new TestTableDefinition( TABLE_BYTE_TYPE_MATCH, DEFAULT_KEY, new Column[]{ new Column("VALUNLIMITED", NativeTypes.BYTES, true), new Column("VALLIMITED", NativeTypes.blobOf(2), true) } ), new TestTableDefinition( TABLE_NAME_FOR_SCHEMA_VALIDATION, DEFAULT_KEY, new Column[]{ new Column("VAL", NativeTypes.INT64, true), new Column("STR", NativeTypes.stringOf(3), true), new Column("BLOB", NativeTypes.blobOf(3), true) } ) ); createTables(tablesToCreate); TestTableDefinition testApiTable3 = new TestTableDefinition( TABLE_NAME_WITH_DEFAULT_VALUES, DEFAULT_KEY, new Column[]{ new Column("VAL", NativeTypes.INT64, true), new Column("STR", NativeTypes.stringOf(3), true), new Column("BLOB", NativeTypes.blobOf(3), true) } ); sql("CREATE TABLE " + testApiTable3.name + " (" + "ID BIGINT PRIMARY KEY, " + "VAL BIGINT DEFAULT 28, " + "STR VARCHAR(3) DEFAULT 'ABC', " + "BLOB VARBINARY(3) DEFAULT X'000102'" + ")"); schemaAwareTestTables = Map.of( testApiTable1.name, testApiTable1, testApiTable2.name, testApiTable2, testApiTable3.name, testApiTable3 ); } @ParameterizedTest @MethodSource("apiTestCases") public void upsert(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); Tuple tuple = Tuple.create().set(keyName, 1L).set(valName, 11L); Tuple newTuple = Tuple.create().set(keyName, 1L).set(valName, 22L); Tuple nonExistedTuple = Tuple.create().set(keyName, 2L); assertNull(tbl.get(null, Tuple.create().set(keyName, 1L))); // Insert new tuple. tbl.upsert(null, tuple); assertEqualsRows(testCase.schema(), tuple, tbl.get(null, Tuple.create().set(keyName, 1L))); // Update exited row. tbl.upsert(null, newTuple); assertEqualsRows(testCase.schema(), newTuple, tbl.get(null, Tuple.create().set(keyName, 1L))); assertNull(tbl.get(null, nonExistedTuple)); } @ParameterizedTest @MethodSource("apiTestCases") public void getAndUpsert(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); Tuple tuple = Tuple.create().set(keyName, 1L).set(valName, 11L); Tuple newTuple = Tuple.create().set(keyName, 1L).set(valName, 22L); assertNull(tbl.get(null, Tuple.create().set(keyName, 1L))); // Insert new tuple. assertNull(tbl.getAndUpsert(null, tuple)); assertEqualsRows(testCase.schema(), tuple, tbl.get(null, Tuple.create().set(keyName, 1L))); // Update exited row. assertEqualsRows(testCase.schema(), tuple, tbl.getAndUpsert(null, newTuple)); assertEqualsRows(testCase.schema(), newTuple, tbl.get(null, Tuple.create().set(keyName, 1L))); } @ParameterizedTest @MethodSource("apiTestCases") public void remove(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); tbl.upsert(null, Tuple.create().set(keyName, 1L).set(valName, 11L)); Tuple keyTuple = Tuple.create().set(keyName, 1L); // Delete not existed keyTuple. assertFalse(tbl.delete(null, Tuple.create().set(keyName, 2L))); // Delete existed keyTuple. assertTrue(tbl.delete(null, keyTuple)); assertNull(tbl.get(null, keyTuple)); // Delete already deleted keyTuple. assertFalse(tbl.delete(null, keyTuple)); } @ParameterizedTest @MethodSource("apiTestCases") public void removeExact(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); Tuple keyTuple = Tuple.create().set(keyName, 1L); Tuple tuple = Tuple.create().set(keyName, 1L).set(valName, 11L); Tuple tuple2 = Tuple.create().set(keyName, 1L).set(valName, 22L); Tuple nonExistedTuple = Tuple.create().set(keyName, 2L).set(valName, 22L); tbl.insert(null, tuple); assertEqualsRows(testCase.schema(), tuple, tbl.get(null, keyTuple)); // Fails to delete not existed tuple. assertFalse(tbl.deleteExact(null, nonExistedTuple)); assertEqualsRows(testCase.schema(), tuple, tbl.get(null, keyTuple)); // Fails to delete tuple with unexpected value. assertFalse(tbl.deleteExact(null, tuple2)); assertEqualsRows(testCase.schema(), tuple, tbl.get(null, keyTuple)); assertFalse(tbl.deleteExact(null, keyTuple)); assertEqualsRows(testCase.schema(), tuple, tbl.get(null, keyTuple)); // Delete tuple with expected value. assertTrue(tbl.deleteExact(null, tuple)); assertNull(tbl.get(null, keyTuple)); // Once again. assertFalse(tbl.deleteExact(null, tuple)); assertNull(tbl.get(null, keyTuple)); // Insert new. tbl.insert(null, tuple2); assertEqualsRows(testCase.schema(), tuple2, tbl.get(null, keyTuple)); // Delete tuple with expected value. assertTrue(tbl.deleteExact(null, tuple2)); assertNull(tbl.get(null, keyTuple)); } @ParameterizedTest @MethodSource("apiTestCases") public void replace(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); Tuple keyTuple = Tuple.create().set(keyName, 1L); Tuple tuple = Tuple.create().set(keyName, 1L).set(valName, 11L); Tuple tuple2 = Tuple.create().set(keyName, 1L).set(valName, 22L); assertNull(tbl.get(null, keyTuple)); // Ignore replace operation for non-existed row. assertFalse(tbl.replace(null, tuple)); assertNull(tbl.get(null, keyTuple)); // Insert row. tbl.insert(null, tuple); // Replace existed row. assertTrue(tbl.replace(null, tuple2)); assertEqualsRows(testCase.schema(), tuple2, tbl.get(null, keyTuple)); } @ParameterizedTest @MethodSource("apiTestCases") public void replaceExact(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); Tuple keyTuple = Tuple.create().set(keyName, 1L); Tuple tuple = Tuple.create().set(keyName, 1L).set(valName, 11L); Tuple tuple2 = Tuple.create().set(keyName, 1L).set(valName, 22L); assertNull(tbl.get(null, keyTuple)); // Ignore replace operation for non-existed row. assertFalse(tbl.replace(null, tuple)); assertNull(tbl.get(null, keyTuple)); // Insert row. assertTrue(tbl.insert(null, tuple)); // Replace existed row. assertTrue(tbl.replace(null, tuple, tuple2)); assertEqualsRows(testCase.schema(), tuple2, tbl.get(null, Tuple.create().set(keyName, 1L))); } @ParameterizedTest @MethodSource("schemaValidationTestCases") public void validateSchema(BinTestCase testCase) { sql("DELETE FROM " + TABLE_NAME_FOR_SCHEMA_VALIDATION); RecordView<Tuple> tbl = testCase.view(); Tuple keyTuple0 = Tuple.create().set("id", 0).set("id1", 0); Tuple keyTuple1 = Tuple.create().set("id1", 0); Tuple tuple0 = Tuple.create().set("id", 1L).set("str", "qweqweqwe").set("val", 11L); Tuple tuple1 = Tuple.create().set("id", 1L).set("blob", new byte[]{0, 1, 2, 3}).set("val", 22L); testCase.checkValueTypeDoesNotMatchError(() -> tbl.get(null, keyTuple0)); testCase.checkMissedKeyColumnError(() -> tbl.get(null, keyTuple1)); testCase.checkKeyColumnContainsExtraColumns(() -> tbl.get(null, Tuple.create().set("id", 1L).set("val", 1L))); String strTooLongErr = "Value too long [column='STR', type=STRING(3)]"; String byteArrayTooLongErr = "Value too long [column='BLOB', type=BYTE_ARRAY(3)]"; testCase.checkInvalidTypeError(() -> tbl.replace(null, tuple0), strTooLongErr); testCase.checkInvalidTypeError(() -> tbl.replace(null, tuple1), byteArrayTooLongErr); testCase.checkInvalidTypeError(() -> tbl.insert(null, tuple0), strTooLongErr); testCase.checkInvalidTypeError(() -> tbl.insert(null, tuple1), byteArrayTooLongErr); testCase.checkInvalidTypeError(() -> tbl.replace(null, tuple0), strTooLongErr); testCase.checkInvalidTypeError(() -> tbl.replace(null, tuple1), byteArrayTooLongErr); } @ParameterizedTest @MethodSource("defaultValueTestCases") public void defaultValues(BinApiTestCase testCase) { sql("DELETE FROM " + TABLE_NAME_WITH_DEFAULT_VALUES); RecordView<Tuple> tbl = testCase.view(); Tuple keyTuple0 = Tuple.create().set("id", 0L); Tuple keyTuple1 = Tuple.create().set("id", 1L); Tuple tuple0 = Tuple.create().set("id", 0L); Tuple tupleExpected0 = Tuple.create().set("id", 0L).set("val", 28L).set("str", "ABC").set("blob", new byte[]{0, 1, 2}); Tuple tuple1 = Tuple.create().set("id", 1L).set("val", null).set("str", null).set("blob", null); tbl.insert(null, tuple0); tbl.insert(null, tuple1); assertEqualsRows(testCase.schema(), tupleExpected0, tbl.get(null, keyTuple0)); assertEqualsRows(testCase.schema(), tuple1, tbl.get(null, keyTuple1)); } @ParameterizedTest @MethodSource("apiTestCases") public void getAll(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); Tuple rec1 = Tuple.create().set(keyName, 1L).set(valName, 11L); Tuple rec3 = Tuple.create().set(keyName, 3L).set(valName, 33L); testCase.checkNullKeyRecsError(() -> tbl.getAll(null, null)); testCase.checkNullKeyError(() -> tbl.getAll(null, Arrays.asList(rec1, null))); testCase.checkNullRecsError(() -> tbl.upsertAll(null, null)); testCase.checkNullRecError(() -> tbl.upsertAll(null, Arrays.asList(rec1, null))); tbl.upsertAll(null, List.of(rec1, rec3)); Collection<Tuple> res = tbl.getAll( null, List.of( Tuple.create().set(keyName, 1L), Tuple.create().set(keyName, 2L), Tuple.create().set(keyName, 3L) )); assertThat(res, Matchers.contains(rec1, null, rec3)); } @ParameterizedTest @MethodSource("apiTestCases") public void contains(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); final long keyId = 1L; Tuple rec = Tuple.create() .set(keyName, keyId) .set(valName, 11L); Tuple keyRec = Tuple.create() .set(keyName, keyId); tbl.insert(null, rec); assertTrue(tbl.contains(null, keyRec)); assertFalse(tbl.contains(null, Tuple.create().set(keyName, -1L))); tbl.delete(null, keyRec); assertFalse(tbl.contains(null, keyRec)); Tuple nullValRec = Tuple.create().set(keyName, 1L).set(valName, null); tbl.insert(null, nullValRec); assertTrue(tbl.contains(null, keyRec)); } @ParameterizedTest @MethodSource("apiTestCases") public void containsAll(BinApiTestCase testCase) { RecordView<Tuple> recordView = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); long firstKey = 101L; Tuple firstKeyTuple = Tuple.create() .set(keyName, firstKey); Tuple firstValTuple = Tuple.create() .set(keyName, firstKey) .set(valName, 201L); long secondKey = 102L; Tuple secondKeyTuple = Tuple.create() .set(keyName, secondKey); Tuple secondValTuple = Tuple.create() .set(keyName, secondKey) .set(valName, 202L); long thirdKey = 103L; Tuple thirdKeyTuple = Tuple.create() .set(keyName, thirdKey); Tuple thirdValTuple = Tuple.create() .set(keyName, thirdKey) .set(valName, 203L); testCase.checkNullRecsError(() -> recordView.insertAll(null, null)); testCase.checkNullRecError(() -> recordView.insertAll(null, Arrays.asList(firstKeyTuple, null))); List<Tuple> recs = List.of(firstValTuple, secondValTuple, thirdValTuple); recordView.insertAll(null, recs); testCase.checkNullKeysError(() -> recordView.containsAll(null, null)); testCase.checkNullKeyError(() -> recordView.containsAll(null, Arrays.asList(firstKeyTuple, null, thirdKeyTuple))); assertTrue(recordView.containsAll(null, List.of())); assertTrue(recordView.containsAll(null, List.of(firstKeyTuple))); assertTrue(recordView.containsAll(null, List.of(firstKeyTuple, secondKeyTuple, thirdKeyTuple))); long missedKey = 0L; Tuple missedKeyTuple = Tuple.create() .set(keyName, missedKey); assertFalse(recordView.containsAll(null, List.of(missedKeyTuple))); assertFalse(recordView.containsAll(null, List.of(firstKeyTuple, secondKeyTuple, missedKeyTuple))); } @ParameterizedTest @MethodSource("apiTestCases") public void upsertAllAfterInsertAll(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); Tuple rec1 = Tuple.create().set(keyName, 1L).set(valName, 11L); Tuple rec3 = Tuple.create().set(keyName, 3L).set(valName, 33L); tbl.insertAll(null, List.of(rec1, rec3)); Collection<Tuple> res = tbl.getAll( null, List.of( Tuple.create().set(keyName, 1L), Tuple.create().set(keyName, 2L), Tuple.create().set(keyName, 3L) )); assertThat(res, Matchers.contains(rec1, null, rec3)); Tuple upRec1 = Tuple.create().set(keyName, 1L).set(valName, 112L); Tuple rec2 = Tuple.create().set(keyName, 2L).set(valName, 22L); Tuple upRec3 = Tuple.create().set(keyName, 3L).set(valName, 332L); tbl.upsertAll(null, List.of(upRec1, rec2, upRec3)); res = tbl.getAll( null, List.of( Tuple.create().set(keyName, 1L), Tuple.create().set(keyName, 2L), Tuple.create().set(keyName, 3L) )); assertThat(res, Matchers.contains(upRec1, rec2, upRec3)); } @ParameterizedTest @MethodSource("apiTestCases") public void deleteVsDeleteExact(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); Tuple rec = Tuple.create().set(keyName, 1L).set(valName, 11L); Tuple recReplace = Tuple.create().set(keyName, 1L).set(valName, 12L); tbl.insert(null, rec); tbl.upsert(null, recReplace); assertFalse(tbl.deleteExact(null, rec)); assertTrue(tbl.deleteExact(null, recReplace)); tbl.upsert(null, recReplace); assertTrue(tbl.delete(null, Tuple.create().set(keyName, 1L))); assertNull(tbl.get(null, Tuple.create().set(keyName, 1L))); } @ParameterizedTest @MethodSource("apiTestCases") public void getAndReplace(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); long val = 0; tbl.insert(null, Tuple.create().set(keyName, 1L).set(valName, val)); for (int i = 1; i < 10; i++) { val = i; assertEquals( val - 1, tbl.getAndReplace(null, Tuple.create().set(keyName, 1L).set(valName, val)) .longValue(1) ); } } @ParameterizedTest @MethodSource("apiTestCases") public void getAndDelete(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); Tuple tuple = Tuple.create().set(keyName, 1L).set(valName, 1L); tbl.insert(null, tuple); Tuple removedTuple = tbl.getAndDelete(null, Tuple.create().set(keyName, 1L)); assertEquals(tuple, removedTuple); assertNull(tbl.getAndDelete(null, Tuple.create().set(keyName, 1L))); } @ParameterizedTest @MethodSource("apiTestCases") public void deleteAll(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); Tuple tuple1 = Tuple.create().set(keyName, 1L).set(valName, 11L); Tuple tuple2 = Tuple.create().set(keyName, 2L).set(valName, 22L); Tuple tuple3 = Tuple.create().set(keyName, 3L).set(valName, 33L); tbl.insertAll(null, List.of(tuple1, tuple2, tuple3)); Collection<Tuple> current = tbl.getAll( null, List.of( Tuple.create().set(keyName, 1L), Tuple.create().set(keyName, 2L), Tuple.create().set(keyName, 3L) )); assertEquals(3, current.size()); assertTrue(current.contains(tuple1)); assertTrue(current.contains(tuple2)); assertTrue(current.contains(tuple3)); Collection<Tuple> notRemovedTuples = tbl.deleteAll( null, List.of( Tuple.create().set(keyName, 1L), Tuple.create().set(keyName, 3L), Tuple.create().set(keyName, 4L) ) ); assertEquals(1, notRemovedTuples.size()); assertTrue(notRemovedTuples.contains(Tuple.create().set(keyName, 4L))); current = tbl.getAll( null, List.of( Tuple.create().set(keyName, 1L), Tuple.create().set(keyName, 2L), Tuple.create().set(keyName, 3L) )); assertThat(current, Matchers.contains(null, tuple2, null)); } @ParameterizedTest @MethodSource("apiTestCases") public void deleteExact(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); Tuple tuple1 = Tuple.create().set(keyName, 1L).set(valName, 11L); Tuple tuple2 = Tuple.create().set(keyName, 2L).set(valName, 22L); Tuple tuple3 = Tuple.create().set(keyName, 3L).set(valName, 33L); tbl.insertAll(null, List.of(tuple1, tuple2, tuple3)); Collection<Tuple> current = tbl.getAll( null, List.of( Tuple.create().set(keyName, 1L), Tuple.create().set(keyName, 2L), Tuple.create().set(keyName, 3L) )); assertEquals(3, current.size()); assertTrue(current.contains(tuple1)); assertTrue(current.contains(tuple2)); assertTrue(current.contains(tuple3)); Tuple tuple3Upsert = Tuple.create().set(keyName, 3L).set(valName, 44L); tbl.upsert(null, tuple3Upsert); Tuple tuple4NotExists = Tuple.create().set(keyName, 4L).set(valName, 55L); Collection<Tuple> notRemovedTuples = tbl.deleteAllExact(null, List.of(tuple1, tuple2, tuple3, tuple4NotExists)); assertEquals(2, notRemovedTuples.size()); assertTrue(notRemovedTuples.contains(tuple3)); assertTrue(notRemovedTuples.contains(tuple4NotExists)); current = tbl.getAll( null, List.of( Tuple.create().set(keyName, 1L), Tuple.create().set(keyName, 2L), Tuple.create().set(keyName, 3L) )); assertThat(current, Matchers.contains(null, null, tuple3Upsert)); } @ParameterizedTest @MethodSource("apiTestCases") public void getAndReplaceVsGetAndUpsert(BinApiTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); String keyName = testCase.keyColumnName(0); String valName = testCase.valColumnName(0); Tuple tuple1 = Tuple.create().set(keyName, 1L).set(valName, 11L); assertNull(tbl.getAndUpsert(null, tuple1)); Tuple tuple = tbl.get(null, Tuple.create().set(keyName, 1L)); assertNotNull(tuple); assertEquals(tuple, tuple1); assertTrue(tbl.deleteExact(null, tuple)); assertNull(tbl.getAndReplace(null, tuple)); assertNull(tbl.get(null, Tuple.create().set(keyName, 1L))); } @ParameterizedTest @MethodSource("compoundPkTestCases") void schemaMismatch(BinTestCase testCase) { RecordView<Tuple> recordView = testCase.view(); // TODO https://issues.apache.org/jira/browse/IGNITE-21793 Thin client must throw exception if (!testCase.thin) { testCase.checkSchemaMismatchError( () -> recordView.get(null, Tuple.create().set("id", 0L).set("affId", 1L).set("val", 0L)), "Key tuple contains extra columns: [VAL]" ); } testCase.checkSchemaMismatchError( () -> recordView.get(null, Tuple.create().set("id", 0L)), "Missed key column: AFFID" ); } @ParameterizedTest @MethodSource("typeMismatchTestCases") public void typeMismatch(BinTestCase testCase) { RecordView<Tuple> tbl = testCase.view(); // Check not-nullable column. testCase.checkSchemaMismatchError( () -> tbl.insert(null, Tuple.create().set("id", null)), "Column 'ID' does not allow NULLs" ); testCase.checkInvalidTypeError( () -> tbl.insert(null, Tuple.create().set("id", 0L).set("valString", "qweqwe")), "Value too long [column='VALSTRING', type=STRING(3)]" ); testCase.checkInvalidTypeError( () -> tbl.insert(null, Tuple.create().set("id", 0L).set("valBytes", new byte[]{0, 1, 2, 3})), "Value too long [column='VALBYTES', type=BYTE_ARRAY(3)]" ); } @ParameterizedTest @MethodSource("stringTypeMatchTestCases") public void stringTypeMatch(BinTestCase testCase) { try { RecordView<Tuple> view = testCase.view(); Tuple tuple = Tuple.create().set("id", 1L); view.insert(null, tuple.set("valString", "qwe")); view.insert(null, tuple.set("valString", "qw")); view.insert(null, tuple.set("valString", "q")); view.insert(null, tuple.set("valString", "")); view.insert(null, tuple.set("valString", null)); // Check string 3 char length and 9 bytes. view.insert(null, tuple.set("valString", "我是谁")); testCase.checkInvalidTypeError(() -> view.insert(null, tuple.set("valString", "我是谁我")), "Value too long [column='VALSTRING', type=STRING(3)]"); } finally { sql("DELETE FROM " + TABLE_STRING_TYPE_MATCH); } } @ParameterizedTest @MethodSource("byteTypeMatchTestCases") public void bytesTypeMatch(BinTestCase testCase) { try { RecordView<Tuple> recordView = testCase.view(); Tuple tuple = Tuple.create().set("id", 1L); recordView.insert(null, tuple.set("valUnlimited", null)); recordView.insert(null, tuple.set("valLimited", null)); recordView.insert(null, tuple.set("valUnlimited", new byte[2])); recordView.insert(null, tuple.set("valLimited", new byte[2])); recordView.insert(null, tuple.set("valUnlimited", new byte[3])); testCase.checkInvalidTypeError( () -> recordView.insert(null, tuple.set("valLimited", new byte[3])), "Value too long [column='VALLIMITED', type=BYTE_ARRAY(2)]" ); } finally { sql("DELETE FROM " + TABLE_BYTE_TYPE_MATCH); } } /** * Check tuples equality. * * @param expected Expected tuple. * @param actual Actual tuple. */ private static void assertEqualsRows(SchemaDescriptor schema, Tuple expected, Tuple actual) { assertEqualsKeys(schema, expected, actual); assertEqualsValues(schema, expected, actual); assertTrue(Tuple.equals(expected, actual)); } /** * Check key columns equality. * * @param schema Schema. * @param expected Expected tuple. * @param actual Actual tuple. */ private static void assertEqualsKeys(SchemaDescriptor schema, Tuple expected, Tuple actual) { int nonNullKey = 0; for (int i = 0; i < schema.keyColumns().size(); i++) { Column col = schema.keyColumns().get(i); Object val1 = expected.value(IgniteNameUtils.quoteIfNeeded(col.name())); Object val2 = actual.value(IgniteNameUtils.quoteIfNeeded(col.name())); assertEquals(val1, val2, "Value columns equality check failed: " + col); if (col.positionInKey() != -1 && val1 != null) { nonNullKey++; } } assertTrue(nonNullKey > 0, "At least one non-null key column must exist."); } private List<Arguments> apiTestCases() { List<Arguments> args1 = generateRecordViewTestArguments(TABLE_NAME_API_TEST, Tuple.class); List<Arguments> args2 = generateRecordViewTestArguments(TABLE_NAME_API_TEST_QUOTED, Tuple.class, " (quoted names)"); args1.addAll(args2); return args1; } private List<Arguments> schemaValidationTestCases() { return generateRecordViewTestArguments(TABLE_NAME_FOR_SCHEMA_VALIDATION, Tuple.class); } private List<Arguments> defaultValueTestCases() { return generateRecordViewTestArguments(TABLE_NAME_WITH_DEFAULT_VALUES, Tuple.class); } private List<Arguments> compoundPkTestCases() { return generateRecordViewTestArguments(TABLE_COMPOUND_KEY, Tuple.class); } private List<Arguments> typeMismatchTestCases() { return generateRecordViewTestArguments(TABLE_TYPE_MISMATCH, Tuple.class); } private List<Arguments> stringTypeMatchTestCases() { return generateRecordViewTestArguments(TABLE_STRING_TYPE_MATCH, Tuple.class); } private List<Arguments> byteTypeMatchTestCases() { return generateRecordViewTestArguments(TABLE_BYTE_TYPE_MATCH, Tuple.class); } @Override TestCaseFactory getFactory(String name) { return new TestCaseFactory(name) { @Override <V> TestCase<V> create(boolean async, boolean thin, Class<V> recordClass) { RecordView<Tuple> view = thin ? client.tables().table(tableName).recordView() : CLUSTER.aliveNode().tables().table(tableName).recordView(); if (async) { view = new AsyncApiRecordViewAdapter<>(view); } if (schemaAwareTestTables.containsKey(name)) { return (TestCase<V>) new BinApiTestCase(async, thin, view, schemaAwareTestTables.get(name)); } return (TestCase<V>) new BinTestCase(async, thin, view); } }; } static class BinTestCase extends TestCase<Tuple> { BinTestCase(boolean async, boolean thin, RecordView<Tuple> view) { super(async, thin, view); } void checkValueTypeDoesNotMatchError(Executable run) { String expectedMessage = "Value type does not match [column='ID', expected=INT64, actual=INT32]"; if (thin) { IgniteException ex = (IgniteException) IgniteTestUtils.assertThrows(IgniteException.class, run, expectedMessage); assertThat(ex.code(), is(Client.PROTOCOL_ERR)); } else { //noinspection ThrowableNotThrown IgniteTestUtils.assertThrowsWithCause(run::execute, SchemaMismatchException.class, expectedMessage); } } @SuppressWarnings("ThrowableNotThrown") void checkMissedKeyColumnError(Executable run) { String expectedMessage = "Missed key column: ID"; if (thin) { IgniteTestUtils.assertThrows(MarshallerException.class, run, expectedMessage); } else { IgniteTestUtils.assertThrowsWithCause(run::execute, SchemaMismatchException.class, expectedMessage); } } @SuppressWarnings("ThrowableNotThrown") void checkInvalidTypeError(Executable run, String expectedMessage) { if (thin) { IgniteTestUtils.assertThrows(MarshallerException.class, run, expectedMessage); } else { IgniteTestUtils.assertThrowsWithCause(run::execute, InvalidTypeException.class, expectedMessage); } } @SuppressWarnings("ThrowableNotThrown") void checkKeyColumnContainsExtraColumns(Executable run) { // TODO https://issues.apache.org/jira/browse/IGNITE-21793 Thin client must also throw exception if (!thin) { IgniteTestUtils.assertThrowsWithCause(run::execute, SchemaMismatchException.class, "Key tuple contains extra columns: [VAL]"); } } @SuppressWarnings("ThrowableNotThrown") void checkSchemaMismatchError(Executable run, String expectedMessage) { if (thin) { IgniteTestUtils.assertThrows(IgniteException.class, run, expectedMessage); } else { IgniteTestUtils.assertThrowsWithCause(run::execute, SchemaMismatchException.class, expectedMessage); } } } static class BinApiTestCase extends BinTestCase { final List<String> keyColumns; final List<String> valueColumns; final SchemaDescriptor schema; String keyColumnName(int index) { return keyColumns.get(index); } String valColumnName(int index) { return valueColumns.get(index); } public SchemaDescriptor schema() { return schema; } BinApiTestCase(boolean async, boolean thin, RecordView<Tuple> view, TestTableDefinition tableDefinition) { super(async, thin, view); this.keyColumns = quoteOrLowercaseNames(tableDefinition.schemaDescriptor.keyColumns()); this.valueColumns = quoteOrLowercaseNames(tableDefinition.schemaDescriptor.valueColumns()); this.schema = tableDefinition.schemaDescriptor; } } }
apache/impala
37,539
fe/src/main/java/org/apache/impala/catalog/FeFsTable.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.impala.catalog; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeMap; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.SQLForeignKey; import org.apache.hadoop.hive.metastore.api.SQLPrimaryKey; import org.apache.impala.analysis.Expr; import org.apache.impala.analysis.LiteralExpr; import org.apache.impala.analysis.PartitionKeyValue; import org.apache.impala.common.AnalysisException; import org.apache.impala.common.FileSystemUtil; import org.apache.impala.common.PrintUtils; import org.apache.impala.fb.FbFileBlock; import org.apache.impala.service.BackendConfig; import org.apache.impala.thrift.TColumn; import org.apache.impala.thrift.TNetworkAddress; import org.apache.impala.thrift.TPartitionKeyValue; import org.apache.impala.thrift.TResultSet; import org.apache.impala.thrift.TResultSetMetadata; import org.apache.impala.thrift.TSortingOrder; import org.apache.impala.thrift.TTableStats; import org.apache.impala.util.HdfsCachingUtil; import org.apache.impala.util.ListMap; import org.apache.impala.util.TAccessLevelUtil; import org.apache.impala.util.TResultRowBuilder; import org.apache.thrift.TException; /** * Frontend interface for interacting with a filesystem-backed table. * * TODO(vercegovac): various method names and comments in this interface refer * to HDFS where they should be more generically "Fs". */ public interface FeFsTable extends FeTable { /** hive's default value for table property 'serialization.null.format' */ public static final String DEFAULT_NULL_COLUMN_VALUE = "\\N"; // Caching this configuration object makes calls to getFileSystem much quicker // (saves ~50ms on a standard plan) // TODO(henry): confirm that this is thread safe - cursory inspection of the class // and its usage in getFileSystem suggests it should be. public static final Configuration CONF = new Configuration(); // Internal table property that specifies the number of files in the table. public static final String NUM_FILES = "numFiles"; // Internal table property that specifies the total size of the table. public static final String TOTAL_SIZE = "totalSize"; // FS table specific metrics public static final String NUM_FILES_METRIC = "num-files"; public static final String NUM_BLOCKS_METRIC = "num-blocks"; public static final String TOTAL_FILE_BYTES_METRIC = "total-file-size-bytes"; public static final String MEMORY_ESTIMATE_METRIC = "memory-estimate-bytes"; // Internal table property that specifies the number of erasure coded files in the // table. public static final String NUM_ERASURE_CODED_FILES = "numFilesErasureCoded"; // Average memory requirements (in bytes) for storing a file descriptor. public static final long PER_FD_MEM_USAGE_BYTES = 500; // Average memory requirements (in bytes) for storing a block. public static final long PER_BLOCK_MEM_USAGE_BYTES = 150; // Represents a set of storage-related statistics aggregated at the table or partition // level. public final static class FileMetadataStats { // Number of files in a table/partition. public long numFiles = 0; // Number of blocks in a table/partition. public long numBlocks = 0; // Total size (in bytes) of all files in a table/partition. public long totalFileBytes = 0; public FileMetadataStats() {} /** * This constructor allows third party extensions to instantiate a FileMetadataStats * with a List of FileDescriptor's. */ public FileMetadataStats(List<FileDescriptor> fds) { for (FileDescriptor fd : fds) { accumulate(fd); } } // Initializes the values of the storage stats. public void init() { numFiles = 0; numBlocks = 0; totalFileBytes = 0; } public void set(FileMetadataStats stats) { numFiles = stats.numFiles; numBlocks = stats.numBlocks; totalFileBytes = stats.totalFileBytes; } public void merge(FileMetadataStats other) { numFiles += other.numFiles; numBlocks += other.numBlocks; totalFileBytes += other.totalFileBytes; } public void remove(FileMetadataStats other) { numFiles -= other.numFiles; numBlocks -= other.numBlocks; totalFileBytes -= other.totalFileBytes; } // Accumulate the statistics of the fd into this FileMetadataStats. public void accumulate(FileDescriptor fd) { numBlocks += fd.getNumFileBlocks(); totalFileBytes += fd.getFileLength(); ++numFiles; } } /** * @return true if the table and all its partitions reside at locations which * support caching (e.g. HDFS). */ public boolean isCacheable(); /** * @return true if the table resides at a location which supports caching * (e.g. HDFS). */ public boolean isLocationCacheable(); /** * @return true if this table is marked as cached */ boolean isMarkedCached(); /* * Returns the storage location (HDFS path) of this table. */ public String getLocation(); /** * @return the value Hive is configured to use for NULL partition key values. * * TODO(todd): this is an HMS-wide setting, rather than a per-table setting. * Perhaps this should move to the FeCatalog interface? */ public String getNullPartitionKeyValue(); /** * @return the base HDFS directory where files of this table are stored. */ public String getHdfsBaseDir(); /** * @return the FsType where files of this table are stored. */ public FileSystemUtil.FsType getFsType(); /** * @return the total number of bytes stored for this table. */ long getTotalHdfsBytes(); /** * @return true if this table's schema as stored in the HMS has been overridden * by an Avro schema. */ boolean usesAvroSchemaOverride(); /** * @return the set of file formats that the partitions in this table use. * This API is only used by the TableSink to write out partitions. It * should not be used for scanning. */ public Set<HdfsFileFormat> getFileFormats(); /** * Return true if the table's base directory may be written to, in order to * create new partitions, or insert into the default partition in the case of * an unpartitioned table. */ public boolean hasWriteAccessToBaseDir(); /** * Return some location found without write access for this table, useful * in error messages about insufficient permissions to insert into a table. * * In case multiple locations are missing write access, the particular * location returned is implementation-defined. * * Returns null if all partitions have write access. */ public String getFirstLocationWithoutWriteAccess(); /** * @return all partitions of this table */ Collection<? extends PrunablePartition> getPartitions(); /** * @return identifiers for all partitions in this table */ public Set<Long> getPartitionIds(); /** * Returns the map from partition identifier to prunable partition. */ Map<Long, ? extends PrunablePartition> getPartitionMap(); /** * @param col the index of the target partitioning column * @return a map from value to a set of partitions for which column 'col' * has that value. */ TreeMap<LiteralExpr, Set<Long>> getPartitionValueMap(int col); /** * @return the set of partitions which have a null value for column * index 'colIdx'. */ Set<Long> getNullPartitionIds(int colIdx); /** * Convenience method to load exactly one partition from a table. */ default FeFsPartition loadPartition(long partitionId) { Collection<? extends FeFsPartition> partCol = loadPartitions( Collections.singleton(partitionId)); if (partCol.size() != 1) { throw new AssertionError(String.format( "expected exactly one result fetching partition ID %s from table %s " + "(got %s)", partitionId, getFullName(), partCol.size())); } return Iterables.getOnlyElement(partCol); } /** * Returns the full partition objects for the given partition IDs, which must * have been obtained by prior calls to the above methods. * @throws IllegalArgumentException if any partition ID does not exist */ List<? extends FeFsPartition> loadPartitions(Collection<Long> ids); /** * Load all partitions from the table. */ default Collection<? extends FeFsPartition> loadAllPartitions() { return loadPartitions(getPartitionIds()); } /** * @return whether it is a Hive ACID table. */ default boolean isHiveAcid() { return false; } default FileSystem getFileSystem() throws CatalogException { FileSystem tableFs; try { tableFs = (new Path(getLocation())).getFileSystem(CONF); } catch (IOException e) { throw new CatalogException("Invalid table path for table: " + getFullName(), e); } return tableFs; } public static FileSystem getFileSystem(Path filePath) throws CatalogException { FileSystem tableFs; try { tableFs = filePath.getFileSystem(CONF); } catch (IOException e) { throw new CatalogException("Invalid path: " + filePath.toString(), e); } return tableFs; } /** * @return List of primary keys column names, useful for toSqlUtils. In local * catalog mode, this causes load of constraints. */ default List<String> getPrimaryKeyColumnNames() throws TException { List<String> primaryKeyColNames = new ArrayList<>(); List<SQLPrimaryKey> primaryKeys = getSqlConstraints().getPrimaryKeys(); if (!primaryKeys.isEmpty()) { primaryKeys.stream().forEach(p -> primaryKeyColNames.add(p.getColumn_name())); } return primaryKeyColNames; } /** * Returns true if the table is partitioned, false otherwise. */ default boolean isPartitioned() { return getMetaStoreTable().getPartitionKeysSize() > 0; } /** * Get foreign keys information as strings. Useful for toSqlUtils. * @return List of strings of the form "(col1, col2,..) REFERENCES [pk_db].pk_table * (colA, colB,..)". In local catalog mode, this causes load of constraints. */ default List<String> getForeignKeysSql() throws TException{ List<String> foreignKeysSql = new ArrayList<>(); // Iterate through foreign keys list. This list may contain multiple foreign keys // and each foreign key may contain multiple columns. The outerloop collects // information common to a foreign key (pk table information). The inner // loop collects column information. List<SQLForeignKey> foreignKeys = getSqlConstraints().getForeignKeys(); for (int i = 0; i < foreignKeys.size(); i++) { String pkTableDb = foreignKeys.get(i).getPktable_db(); String pkTableName = foreignKeys.get(i).getPktable_name(); List<String> pkList = new ArrayList<>(); List<String> fkList = new ArrayList<>(); StringBuilder sb = new StringBuilder(); sb.append("("); for (; i < foreignKeys.size(); i++) { fkList.add(foreignKeys.get(i).getFkcolumn_name()); pkList.add(foreignKeys.get(i).getPkcolumn_name()); // Foreign keys for a table can consist of multiple columns, they are represented // as different SQLForeignKey structures. A key_seq is used to stitch together // the entire sequence that forms the foreign key. Hence, we bail out of inner // loop if the key_seq of the next SQLForeignKey is 1. if (i + 1 < foreignKeys.size() && foreignKeys.get(i + 1).getKey_seq() == 1) { break; } } Joiner.on(", ").appendTo(sb, fkList).append(") "); sb.append("REFERENCES "); if (pkTableDb != null) sb.append(pkTableDb + "."); sb.append(pkTableName + "("); Joiner.on(", ").appendTo(sb, pkList).append(")"); foreignKeysSql.add(sb.toString()); } return foreignKeysSql; } /** * Parses and returns the value of the 'skip.header.line.count' table property. If the * value is not set for the table, returns 0. If parsing fails or a value < 0 is found, * the error parameter is updated to contain an error message. */ default int parseSkipHeaderLineCount(StringBuilder error) { org.apache.hadoop.hive.metastore.api.Table msTbl = getMetaStoreTable(); if (msTbl == null || !msTbl.getParameters().containsKey( FeFsTable.Utils.TBL_PROP_SKIP_HEADER_LINE_COUNT)) { return 0; } return Utils.parseSkipHeaderLineCount(msTbl.getParameters(), error); } /** * @return the index of hosts that store replicas of blocks of this table. */ ListMap<TNetworkAddress> getHostIndex(); /** * Check if 'col_name' appears in the list of sort-by columns by searching the * 'sort.columns' table property and return the index in the list if so. Return * -1 otherwise. */ default int getSortByColumnIndex(String col_name) { // Get the names of all sort by columns (specified in the SORT BY clause in // CREATE TABLE DDL) from TBLPROPERTIES. Map<String, String> parameters = getMetaStoreTable().getParameters(); if (parameters == null) return -1; String sort_by_columns_string = parameters.get("sort.columns"); if (sort_by_columns_string == null) return -1; String[] sort_by_columns = sort_by_columns_string.split(","); if (sort_by_columns == null) return -1; for (int i = 0; i < sort_by_columns.length; i++) { if (sort_by_columns[i].equals(col_name)) return i; } return -1; } /** * Check if 'col_name' names the leading sort-by column. */ default boolean isLeadingSortByColumn(String col_name) { return getSortByColumnIndex(col_name) == 0; } /** * Check if 'col_name' appears in the list of sort-by columns. */ default boolean isSortByColumn(String col_name) { return getSortByColumnIndex(col_name) >= 0; } /** * Return the sort order for the sort by columns if exists. Return null otherwise. */ default TSortingOrder getSortOrderForSortByColumn() { Map<String, String> parameters = getMetaStoreTable().getParameters(); if (parameters == null) return null; String sortOrder = parameters.get("sort.order"); if (sortOrder == null) return null; if (sortOrder.equals("LEXICAL")) return TSortingOrder.LEXICAL; if (sortOrder.equals("ZORDER")) return TSortingOrder.ZORDER; return null; } /** * Return true if the sort order for the sort by columns is lexical. Return false * otherwise. */ default boolean IsLexicalSortByColumn() { TSortingOrder sortOrder = getSortOrderForSortByColumn(); if (sortOrder == null) return false; return sortOrder == TSortingOrder.LEXICAL; } /** * @return statistics on this table as a tabular result set. Used for the * SHOW TABLE STATS statement. The schema of the returned TResultSet is set * inside this method. */ default TResultSet getTableStats() { TResultSet result = new TResultSet(); TResultSetMetadata resultSchema = new TResultSetMetadata(); result.setSchema(resultSchema); for (int i = 0; i < getNumClusteringCols(); ++i) { // Add the partition-key values as strings for simplicity. Column partCol = getColumns().get(i); TColumn colDesc = new TColumn(partCol.getName(), Type.STRING.toThrift()); resultSchema.addToColumns(colDesc); } boolean statsExtrap = Utils.isStatsExtrapolationEnabled(this); resultSchema.addToColumns(new TColumn("#Rows", Type.BIGINT.toThrift())); if (statsExtrap) { resultSchema.addToColumns(new TColumn("Extrap #Rows", Type.BIGINT.toThrift())); } resultSchema.addToColumns(new TColumn("#Files", Type.BIGINT.toThrift())); resultSchema.addToColumns(new TColumn("Size", Type.STRING.toThrift())); resultSchema.addToColumns(new TColumn("Bytes Cached", Type.STRING.toThrift())); resultSchema.addToColumns(new TColumn("Cache Replication", Type.STRING.toThrift())); resultSchema.addToColumns(new TColumn("Format", Type.STRING.toThrift())); resultSchema.addToColumns(new TColumn("Incremental stats", Type.STRING.toThrift())); resultSchema.addToColumns(new TColumn("Location", Type.STRING.toThrift())); resultSchema.addToColumns(new TColumn("EC Policy", Type.STRING.toThrift())); // Pretty print partitions and their stats. List<FeFsPartition> orderedPartitions = new ArrayList<>(loadAllPartitions()); orderedPartitions.sort(HdfsPartition.KV_COMPARATOR); long totalCachedBytes = 0L; long totalBytes = 0L; long totalNumFiles = 0L; for (FeFsPartition p: orderedPartitions) { long numFiles = p.getNumFileDescriptors(); long size = p.getSize(); totalNumFiles += numFiles; totalBytes += size; TResultRowBuilder rowBuilder = new TResultRowBuilder(); // Add the partition-key values (as strings for simplicity). for (LiteralExpr expr: p.getPartitionValues()) { rowBuilder.add(expr.getStringValue()); } // Add rows, extrapolated rows, files, bytes, cache stats, and file format. rowBuilder.add(p.getNumRows()); // Compute and report the extrapolated row count because the set of files could // have changed since we last computed stats for this partition. We also follow // this policy during scan-cardinality estimation. if (statsExtrap) { rowBuilder.add(Utils.getExtrapolatedNumRows(this, size)); } rowBuilder.add(numFiles).addBytes(size); if (!p.isMarkedCached()) { // Helps to differentiate partitions that have 0B cached versus partitions // that are not marked as cached. rowBuilder.add("NOT CACHED"); rowBuilder.add("NOT CACHED"); } else { // Calculate the number the number of bytes that are cached. long cachedBytes = 0L; for (FileDescriptor fd: p.getFileDescriptors()) { int numBlocks = fd.getNumFileBlocks(); for (int i = 0; i < numBlocks; ++i) { FbFileBlock block = fd.getFbFileBlock(i); if (FileBlock.hasCachedReplica(block)) { cachedBytes += FileBlock.getLength(block); } } } totalCachedBytes += cachedBytes; rowBuilder.addBytes(cachedBytes); // Extract cache replication factor from the parameters of the table // if the table is not partitioned or directly from the partition. Short rep = HdfsCachingUtil.getCachedCacheReplication( getNumClusteringCols() == 0 ? p.getTable().getMetaStoreTable().getParameters() : p.getParameters()); rowBuilder.add(rep.toString()); } rowBuilder.add(p.getFileFormat().toString()); rowBuilder.add(String.valueOf(p.hasIncrementalStats())); rowBuilder.add(p.getLocation()); rowBuilder.add(FileSystemUtil.getErasureCodingPolicy(p.getLocationPath())); result.addToRows(rowBuilder.get()); } // For partitioned tables add a summary row at the bottom. if (getNumClusteringCols() > 0) { TResultRowBuilder rowBuilder = new TResultRowBuilder(); int numEmptyCells = getNumClusteringCols() - 1; rowBuilder.add("Total"); for (int i = 0; i < numEmptyCells; ++i) { rowBuilder.add(""); } // Total rows, extrapolated rows, files, bytes, cache stats. // Leave format empty. rowBuilder.add(getNumRows()); // Compute and report the extrapolated row count because the set of files could // have changed since we last computed stats for this partition. We also follow // this policy during scan-cardinality estimation. if (statsExtrap) { rowBuilder.add(Utils.getExtrapolatedNumRows(this, getTotalHdfsBytes())); } rowBuilder.add(totalNumFiles) .addBytes(totalBytes) .addBytes(totalCachedBytes).add("").add("").add("").add("").add(""); result.addToRows(rowBuilder.get()); } return result; } default Map<Long, List<FileDescriptor>> getFilesSample( long percentBytes, long minSampleBytes, long randomSeed) { return Utils.getFilesSample(this, loadAllPartitions(), percentBytes, minSampleBytes, randomSeed); } /** * Utility functions for operating on FeFsTable. When we move fully to Java 8, * these can become default methods of the interface. */ abstract class Utils { // Table property key for skip.header.line.count public static final String TBL_PROP_SKIP_HEADER_LINE_COUNT = "skip.header.line.count"; /** * Returns true if stats extrapolation is enabled for this table, false otherwise. * Reconciles the Impalad-wide --enable_stats_extrapolation flag and the * TBL_PROP_ENABLE_STATS_EXTRAPOLATION table property */ public static boolean isStatsExtrapolationEnabled(FeFsTable table) { org.apache.hadoop.hive.metastore.api.Table msTbl = table.getMetaStoreTable(); String propVal = msTbl.getParameters().get( HdfsTable.TBL_PROP_ENABLE_STATS_EXTRAPOLATION); if (propVal == null) return BackendConfig.INSTANCE.isStatsExtrapolationEnabled(); return Boolean.parseBoolean(propVal); } /** * Returns true if the file contents within a partition should be recursively listed. * Reconciles the Impalad-wide --recursively_list_partitions and the * TBL_PROP_DISABLE_RECURSIVE_LISTING table property */ public static boolean shouldRecursivelyListPartitions(FeFsTable table) { org.apache.hadoop.hive.metastore.api.Table msTbl = table.getMetaStoreTable(); String propVal = msTbl.getParameters().get( HdfsTable.TBL_PROP_DISABLE_RECURSIVE_LISTING); if (propVal == null) return BackendConfig.INSTANCE.recursivelyListPartitions(); // TODO(todd): we should detect if this flag is set on an ACID table and // give some kind of error (we _must_ recursively list such tables) return !Boolean.parseBoolean(propVal); } /** * Returns an estimated row count for the given number of file bytes. The row count is * extrapolated using the table-level row count and file bytes statistics. * Returns zero only if the given file bytes is zero. * Returns -1 if: * - stats extrapolation has been disabled * - the given file bytes statistic is negative * - the row count or the file byte statistic is missing * - the file bytes statistic is zero or negative * - the row count statistic is zero and the file bytes is non-zero * Otherwise, returns a value >= 1. */ public static long getExtrapolatedNumRows(FeFsTable table, long fileBytes) { if (!isStatsExtrapolationEnabled(table)) return -1; if (fileBytes == 0) return 0; if (fileBytes < 0) return -1; TTableStats tableStats = table.getTTableStats(); if (tableStats.num_rows < 0 || tableStats.total_file_bytes <= 0) return -1; if (tableStats.num_rows == 0 && tableStats.total_file_bytes != 0) return -1; double rowsPerByte = tableStats.num_rows / (double) tableStats.total_file_bytes; double extrapolatedNumRows = fileBytes * rowsPerByte; return (long) Math.max(1, Math.round(extrapolatedNumRows)); } /** * Get file info for the given set of partitions, or all partitions if * partitionSet is null. * * @return partition file info, ordered by partition */ public static TResultSet getFiles(FeFsTable table, List<List<TPartitionKeyValue>> partitionSet) { TResultSet result = new TResultSet(); TResultSetMetadata resultSchema = new TResultSetMetadata(); result.setSchema(resultSchema); resultSchema.addToColumns(new TColumn("Path", Type.STRING.toThrift())); resultSchema.addToColumns(new TColumn("Size", Type.STRING.toThrift())); resultSchema.addToColumns(new TColumn("Partition", Type.STRING.toThrift())); resultSchema.addToColumns(new TColumn("EC Policy", Type.STRING.toThrift())); result.setRows(new ArrayList<>()); if (table instanceof FeIcebergTable) { return FeIcebergTable.Utils.getIcebergTableFiles((FeIcebergTable) table, result); } List<? extends FeFsPartition> orderedPartitions; if (partitionSet == null) { orderedPartitions = Lists.newArrayList(table.loadAllPartitions()); } else { // Get a list of HdfsPartition objects for the given partition set. orderedPartitions = getPartitionsFromPartitionSet(table, partitionSet); } Collections.sort(orderedPartitions, HdfsPartition.KV_COMPARATOR); for (FeFsPartition p: orderedPartitions) { List<FileDescriptor> orderedFds = Lists.newArrayList(p.getFileDescriptors()); Collections.sort(orderedFds); for (FileDescriptor fd: orderedFds) { TResultRowBuilder rowBuilder = new TResultRowBuilder(); String absPath = fd.getAbsolutePath(p.getLocation()); rowBuilder.add(absPath); rowBuilder.add(PrintUtils.printBytes(fd.getFileLength())); rowBuilder.add(p.getPartitionName()); rowBuilder.add(FileSystemUtil.getErasureCodingPolicy(new Path(absPath))); result.addToRows(rowBuilder.get()); } } return result; } /** * Selects a random sample of files from the given list of partitions such that the * sum of file sizes is at least 'percentBytes' percent of the total number of bytes * in those partitions and at least 'minSampleBytes'. The sample is returned as a map * from partition id to a list of file descriptors selected from that partition. * * This function allocates memory proportional to the number of files in 'inputParts'. * Its implementation tries to minimize the constant factor and object generation. * The given 'randomSeed' is used for random number generation. * The 'percentBytes' parameter must be between 0 and 100. * * TODO(IMPALA-9883): Fix this for full ACID tables. */ public static Map<Long, List<FileDescriptor>> getFilesSample(FeFsTable table, Collection<? extends FeFsPartition> inputParts, long percentBytes, long minSampleBytes, long randomSeed) { Preconditions.checkState(percentBytes >= 0 && percentBytes <= 100); Preconditions.checkState(minSampleBytes >= 0); long totalNumFiles = 0; for (FeFsPartition part : inputParts) { totalNumFiles += part.getNumFileDescriptors(); } // Conservative max size for Java arrays. The actual maximum varies // from JVM version and sometimes between configurations. final long JVM_MAX_ARRAY_SIZE = Integer.MAX_VALUE - 10; if (totalNumFiles > JVM_MAX_ARRAY_SIZE) { throw new IllegalStateException(String.format( "Too many files to generate a table sample of table %s. " + "Sample requested over %s files, but a maximum of %s files are supported.", table.getTableName().toString(), totalNumFiles, JVM_MAX_ARRAY_SIZE)); } // Ensure a consistent ordering of files for repeatable runs. The files within a // partition are already ordered based on how they are loaded in the catalog. List<FeFsPartition> orderedParts = Lists.newArrayList(inputParts); Collections.sort(orderedParts, HdfsPartition.KV_COMPARATOR); // fileIdxs contains indexes into the file descriptor lists of all inputParts // parts[i] contains the partition corresponding to fileIdxs[i] // fileIdxs[i] is an index into the file descriptor list of the partition parts[i] // The purpose of these arrays is to efficiently avoid selecting the same file // multiple times during the sampling, regardless of the sample percent. // We purposely avoid generating objects proportional to the number of files. int[] fileIdxs = new int[(int)totalNumFiles]; FeFsPartition[] parts = new FeFsPartition[(int)totalNumFiles]; int idx = 0; long totalBytes = 0; for (FeFsPartition part: orderedParts) { totalBytes += part.getSize(); int numFds = part.getNumFileDescriptors(); for (int fileIdx = 0; fileIdx < numFds; ++fileIdx) { fileIdxs[idx] = fileIdx; parts[idx] = part; ++idx; } } if (idx != totalNumFiles) { throw new AssertionError("partition file counts changed during iteration"); } int numFilesRemaining = idx; double fracPercentBytes = (double) percentBytes / 100; long targetBytes = (long) Math.round(totalBytes * fracPercentBytes); targetBytes = Math.max(targetBytes, minSampleBytes); // Randomly select files until targetBytes has been reached or all files have been // selected. Random rnd = new Random(randomSeed); long selectedBytes = 0; Map<Long, List<FileDescriptor>> result = new HashMap<>(); while (selectedBytes < targetBytes && numFilesRemaining > 0) { int selectedIdx = Math.abs(rnd.nextInt()) % numFilesRemaining; FeFsPartition part = parts[selectedIdx]; Long partId = Long.valueOf(part.getId()); List<FileDescriptor> sampleFileIdxs = result.computeIfAbsent( partId, id -> Lists.newArrayList()); FileDescriptor fd = part.getFileDescriptors().get(fileIdxs[selectedIdx]); sampleFileIdxs.add(fd); selectedBytes += fd.getFileLength(); // Avoid selecting the same file multiple times. fileIdxs[selectedIdx] = fileIdxs[numFilesRemaining - 1]; parts[selectedIdx] = parts[numFilesRemaining - 1]; --numFilesRemaining; } return result; } /** * Get and load the specified partitions from the table. */ public static List<? extends FeFsPartition> getPartitionsFromPartitionSet( FeFsTable table, List<List<TPartitionKeyValue>> partitionSet) { List<Long> partitionIds = new ArrayList<>(); for (List<TPartitionKeyValue> kv : partitionSet) { PrunablePartition partition = getPartitionFromThriftPartitionSpec(table, kv); if (partition != null) partitionIds.add(partition.getId()); } return table.loadPartitions(partitionIds); } /** * Get the specified partition from the table, or null if no such partition * exists. */ public static PrunablePartition getPartitionFromThriftPartitionSpec( FeFsTable table, List<TPartitionKeyValue> partitionSpec) { // First, build a list of the partition values to search for in the same order they // are defined in the table. List<String> targetValues = new ArrayList<>(); Set<String> keys = new HashSet<>(); for (FieldSchema fs: table.getMetaStoreTable().getPartitionKeys()) { for (TPartitionKeyValue kv: partitionSpec) { if (fs.getName().equalsIgnoreCase(kv.getName())) { targetValues.add(kv.getValue()); // Same key was specified twice if (!keys.add(kv.getName().toLowerCase())) { return null; } } } } // Make sure the number of values match up and that some values were found. if (targetValues.size() == 0 || (targetValues.size() != table.getMetaStoreTable().getPartitionKeysSize())) { return null; } // Search through all the partitions and check if their partition key values // match the values being searched for. for (PrunablePartition partition: table.getPartitions()) { List<LiteralExpr> partitionValues = partition.getPartitionValues(); Preconditions.checkState(partitionValues.size() == targetValues.size(), "Partition values not match in table %s: %s != %s", table.getFullName(), partitionValues.size(), targetValues.size()); boolean matchFound = true; for (int i = 0; i < targetValues.size(); ++i) { String value; if (Expr.IS_NULL_LITERAL.apply(partitionValues.get(i))) { value = table.getNullPartitionKeyValue(); } else { value = partitionValues.get(i).getStringValue(); Preconditions.checkNotNull(value, "Got null string from non-null partition value of table %s: i=%s", table.getFullName(), i); // See IMPALA-252: we deliberately map empty strings on to // NULL when they're in partition columns. This is for // backwards compatibility with Hive, and is clearly broken. if (value.isEmpty()) value = table.getNullPartitionKeyValue(); } if (!targetValues.get(i).equals(value)) { matchFound = false; break; } } if (matchFound) return partition; } return null; } /** * Check that the Impala user has write access to the given target table. * If 'partitionKeyValues' is null, the user should have write access to all * partitions (or to the table directory itself in the case of unpartitioned * tables). Otherwise, the user only needs write access to the specific partition. * * @throws AnalysisException if write access is not available */ public static void checkWriteAccess(FeFsTable table, List<PartitionKeyValue> partitionKeyValues, String operationType) throws AnalysisException { String noWriteAccessErrorMsg = String.format("Unable to %s into " + "target table (%s) because Impala does not have WRITE access to HDFS " + "location: ", operationType, table.getFullName()); PrunablePartition existingTargetPartition = null; if (partitionKeyValues != null) { existingTargetPartition = HdfsTable.getPartition(table, partitionKeyValues); // This could be null in the case that we are writing to a specific partition that // has not been created yet. } if (existingTargetPartition != null) { FeFsPartition partition = table.loadPartition(existingTargetPartition.getId()); String location = partition.getLocation(); if (!TAccessLevelUtil.impliesWriteAccess(partition.getAccessLevel())) { throw new AnalysisException(noWriteAccessErrorMsg + location); } } else if (partitionKeyValues != null) { // Writing into a table with a specific partition specified which doesn't // exist yet. In this case, we need write access to the top-level // table location in order to create a new partition. if (!table.hasWriteAccessToBaseDir()) { throw new AnalysisException(noWriteAccessErrorMsg + table.getHdfsBaseDir()); } } else { // No explicit partition was specified. Need to ensure that write access is // available to all partitions as well as the base dir. String badPath = table.getFirstLocationWithoutWriteAccess(); if (badPath != null) { throw new AnalysisException(noWriteAccessErrorMsg + badPath); } } } /** * Parses and returns the value of the 'skip.header.line.count' table property. The * caller must ensure that the property is contained in the 'tblProperties' map. If * parsing fails or a value < 0 is found, the error parameter is updated to contain an * error message. */ public static int parseSkipHeaderLineCount(Map<String, String> tblProperties, StringBuilder error) { Preconditions.checkState(tblProperties != null); Preconditions.checkState( tblProperties.containsKey(TBL_PROP_SKIP_HEADER_LINE_COUNT)); // Try to parse. String string_value = tblProperties.get(TBL_PROP_SKIP_HEADER_LINE_COUNT); int skipHeaderLineCount = 0; String error_msg = String.format("Invalid value for table property %s: %s (value " + "must be an integer >= 0)", TBL_PROP_SKIP_HEADER_LINE_COUNT, string_value); try { skipHeaderLineCount = Integer.parseInt(string_value); } catch (NumberFormatException exc) { error.append(error_msg); } if (skipHeaderLineCount < 0) error.append(error_msg); return skipHeaderLineCount; } } }
apache/kafka
37,105
clients/src/main/java/org/apache/kafka/common/protocol/types/Type.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.common.protocol.types; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.record.BaseRecords; import org.apache.kafka.common.record.MemoryRecords; import org.apache.kafka.common.utils.ByteUtils; import org.apache.kafka.common.utils.Utils; import java.nio.ByteBuffer; import java.util.Optional; /** * A serializable type */ public abstract class Type { /** * Write the typed object to the buffer * * @throws SchemaException If the object is not valid for its type */ public abstract void write(ByteBuffer buffer, Object o); /** * Read the typed object from the buffer * Please remember to do size validation before creating the container (ex: array) for the following data * * @throws SchemaException If the object is not valid for its type */ public abstract Object read(ByteBuffer buffer); /** * Validate the object. If succeeded return its typed object. * * @throws SchemaException If validation failed */ public abstract Object validate(Object o); /** * Return the size of the object in bytes */ public abstract int sizeOf(Object o); /** * Check if the type supports null values * @return whether or not null is a valid value for the type implementation */ public boolean isNullable() { return false; } /** * If the type is an array, return the type of the array elements. Otherwise, return empty. */ public Optional<Type> arrayElementType() { return Optional.empty(); } /** * Returns true if the type is an array. */ public final boolean isArray() { return arrayElementType().isPresent(); } /** * A Type that can return its description for documentation purposes. */ public abstract static class DocumentedType extends Type { /** * Short name of the type to identify it in documentation; * @return the name of the type */ public abstract String typeName(); /** * Documentation of the Type. * * @return details about valid values, representation */ public abstract String documentation(); @Override public String toString() { return typeName(); } } /** * The Boolean type represents a boolean value in a byte by using * the value of 0 to represent false, and 1 to represent true. * * If for some reason a value that is not 0 or 1 is read, * then any non-zero value will return true. */ public static final DocumentedType BOOLEAN = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { if ((Boolean) o) buffer.put((byte) 1); else buffer.put((byte) 0); } @Override public Object read(ByteBuffer buffer) { byte value = buffer.get(); return value != 0; } @Override public int sizeOf(Object o) { return 1; } @Override public String typeName() { return "BOOLEAN"; } @Override public Boolean validate(Object item) { if (item instanceof Boolean) return (Boolean) item; else throw new SchemaException(item + " is not a Boolean."); } @Override public String documentation() { return "Represents a boolean value in a byte. " + "Values 0 and 1 are used to represent false and true respectively. " + "When reading a boolean value, any non-zero value is considered true."; } }; public static final DocumentedType INT8 = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { buffer.put((Byte) o); } @Override public Object read(ByteBuffer buffer) { return buffer.get(); } @Override public int sizeOf(Object o) { return 1; } @Override public String typeName() { return "INT8"; } @Override public Byte validate(Object item) { if (item instanceof Byte) return (Byte) item; else throw new SchemaException(item + " is not a Byte."); } @Override public String documentation() { return "Represents an integer between -2<sup>7</sup> and 2<sup>7</sup>-1 inclusive."; } }; public static final DocumentedType INT16 = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { buffer.putShort((Short) o); } @Override public Object read(ByteBuffer buffer) { return buffer.getShort(); } @Override public int sizeOf(Object o) { return 2; } @Override public String typeName() { return "INT16"; } @Override public Short validate(Object item) { if (item instanceof Short) return (Short) item; else throw new SchemaException(item + " is not a Short."); } @Override public String documentation() { return "Represents an integer between -2<sup>15</sup> and 2<sup>15</sup>-1 inclusive. " + "The values are encoded using two bytes in network byte order (big-endian)."; } }; public static final DocumentedType UINT16 = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { Integer value = (Integer) o; buffer.putShort((short) value.intValue()); } @Override public Object read(ByteBuffer buffer) { short value = buffer.getShort(); return Short.toUnsignedInt(value); } @Override public int sizeOf(Object o) { return 2; } @Override public String typeName() { return "UINT16"; } @Override public Integer validate(Object item) { if (item instanceof Integer) return (Integer) item; else throw new SchemaException(item + " is not an a Integer (encoding an unsigned short)"); } @Override public String documentation() { return "Represents an integer between 0 and 65535 inclusive. " + "The values are encoded using two bytes in network byte order (big-endian)."; } }; public static final DocumentedType INT32 = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { buffer.putInt((Integer) o); } @Override public Object read(ByteBuffer buffer) { return buffer.getInt(); } @Override public int sizeOf(Object o) { return 4; } @Override public String typeName() { return "INT32"; } @Override public Integer validate(Object item) { if (item instanceof Integer) return (Integer) item; else throw new SchemaException(item + " is not an Integer."); } @Override public String documentation() { return "Represents an integer between -2<sup>31</sup> and 2<sup>31</sup>-1 inclusive. " + "The values are encoded using four bytes in network byte order (big-endian)."; } }; public static final DocumentedType UNSIGNED_INT32 = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { ByteUtils.writeUnsignedInt(buffer, (long) o); } @Override public Object read(ByteBuffer buffer) { return ByteUtils.readUnsignedInt(buffer); } @Override public int sizeOf(Object o) { return 4; } @Override public String typeName() { return "UINT32"; } @Override public Long validate(Object item) { if (item instanceof Long) return (Long) item; else throw new SchemaException(item + " is not an a Long (encoding an unsigned integer)."); } @Override public String documentation() { return "Represents an integer between 0 and 2<sup>32</sup>-1 inclusive. " + "The values are encoded using four bytes in network byte order (big-endian)."; } }; public static final DocumentedType INT64 = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { buffer.putLong((Long) o); } @Override public Object read(ByteBuffer buffer) { return buffer.getLong(); } @Override public int sizeOf(Object o) { return 8; } @Override public String typeName() { return "INT64"; } @Override public Long validate(Object item) { if (item instanceof Long) return (Long) item; else throw new SchemaException(item + " is not a Long."); } @Override public String documentation() { return "Represents an integer between -2<sup>63</sup> and 2<sup>63</sup>-1 inclusive. " + "The values are encoded using eight bytes in network byte order (big-endian)."; } }; public static final DocumentedType UUID = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { final Uuid uuid = (Uuid) o; buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); } @Override public Object read(ByteBuffer buffer) { return new Uuid(buffer.getLong(), buffer.getLong()); } @Override public int sizeOf(Object o) { return 16; } @Override public String typeName() { return "UUID"; } @Override public Uuid validate(Object item) { if (item instanceof Uuid) return (Uuid) item; else throw new SchemaException(item + " is not a Uuid."); } @Override public String documentation() { return "Represents a type 4 immutable universally unique identifier (Uuid). " + "The values are encoded using sixteen bytes in network byte order (big-endian)."; } }; public static final DocumentedType FLOAT64 = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { ByteUtils.writeDouble((Double) o, buffer); } @Override public Object read(ByteBuffer buffer) { return ByteUtils.readDouble(buffer); } @Override public int sizeOf(Object o) { return 8; } @Override public String typeName() { return "FLOAT64"; } @Override public Double validate(Object item) { if (item instanceof Double) return (Double) item; else throw new SchemaException(item + " is not a Double."); } @Override public String documentation() { return "Represents a double-precision 64-bit format IEEE 754 value. " + "The values are encoded using eight bytes in network byte order (big-endian)."; } }; public static final DocumentedType STRING = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { byte[] bytes = Utils.utf8((String) o); if (bytes.length > Short.MAX_VALUE) throw new SchemaException("String length " + bytes.length + " is larger than the maximum string length."); buffer.putShort((short) bytes.length); buffer.put(bytes); } @Override public String read(ByteBuffer buffer) { short length = buffer.getShort(); if (length < 0) throw new SchemaException("String length " + length + " cannot be negative"); if (length > buffer.remaining()) throw new SchemaException("Error reading string of length " + length + ", only " + buffer.remaining() + " bytes available"); String result = Utils.utf8(buffer, length); buffer.position(buffer.position() + length); return result; } @Override public int sizeOf(Object o) { return 2 + Utils.utf8Length((String) o); } @Override public String typeName() { return "STRING"; } @Override public String validate(Object item) { if (item instanceof String) return (String) item; else throw new SchemaException(item + " is not a String."); } @Override public String documentation() { return "Represents a sequence of characters. First the length N is given as an " + INT16 + ". Then N bytes follow which are the UTF-8 encoding of the character sequence. " + "Length must not be negative."; } }; public static final DocumentedType COMPACT_STRING = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { byte[] bytes = Utils.utf8((String) o); if (bytes.length > Short.MAX_VALUE) throw new SchemaException("String length " + bytes.length + " is larger than the maximum string length."); ByteUtils.writeUnsignedVarint(bytes.length + 1, buffer); buffer.put(bytes); } @Override public String read(ByteBuffer buffer) { int length = ByteUtils.readUnsignedVarint(buffer) - 1; if (length < 0) throw new SchemaException("String length " + length + " cannot be negative"); if (length > Short.MAX_VALUE) throw new SchemaException("String length " + length + " is larger than the maximum string length."); if (length > buffer.remaining()) throw new SchemaException("Error reading string of length " + length + ", only " + buffer.remaining() + " bytes available"); String result = Utils.utf8(buffer, length); buffer.position(buffer.position() + length); return result; } @Override public int sizeOf(Object o) { int length = Utils.utf8Length((String) o); return ByteUtils.sizeOfUnsignedVarint(length + 1) + length; } @Override public String typeName() { return "COMPACT_STRING"; } @Override public String validate(Object item) { if (item instanceof String) return (String) item; else throw new SchemaException(item + " is not a String."); } @Override public String documentation() { return "Represents a sequence of characters. First the length N + 1 is given as an UNSIGNED_VARINT " + ". Then N bytes follow which are the UTF-8 encoding of the character sequence."; } }; public static final DocumentedType NULLABLE_STRING = new DocumentedType() { @Override public boolean isNullable() { return true; } @Override public void write(ByteBuffer buffer, Object o) { if (o == null) { buffer.putShort((short) -1); return; } byte[] bytes = Utils.utf8((String) o); if (bytes.length > Short.MAX_VALUE) throw new SchemaException("String length " + bytes.length + " is larger than the maximum string length."); buffer.putShort((short) bytes.length); buffer.put(bytes); } @Override public String read(ByteBuffer buffer) { short length = buffer.getShort(); if (length < 0) return null; if (length > buffer.remaining()) throw new SchemaException("Error reading string of length " + length + ", only " + buffer.remaining() + " bytes available"); String result = Utils.utf8(buffer, length); buffer.position(buffer.position() + length); return result; } @Override public int sizeOf(Object o) { if (o == null) return 2; return 2 + Utils.utf8Length((String) o); } @Override public String typeName() { return "NULLABLE_STRING"; } @Override public String validate(Object item) { if (item == null) return null; if (item instanceof String) return (String) item; else throw new SchemaException(item + " is not a String."); } @Override public String documentation() { return "Represents a sequence of characters or null. For non-null strings, first the length N is given as an " + INT16 + ". Then N bytes follow which are the UTF-8 encoding of the character sequence. " + "A null value is encoded with length of -1 and there are no following bytes."; } }; public static final DocumentedType COMPACT_NULLABLE_STRING = new DocumentedType() { @Override public boolean isNullable() { return true; } @Override public void write(ByteBuffer buffer, Object o) { if (o == null) { ByteUtils.writeUnsignedVarint(0, buffer); } else { byte[] bytes = Utils.utf8((String) o); if (bytes.length > Short.MAX_VALUE) throw new SchemaException("String length " + bytes.length + " is larger than the maximum string length."); ByteUtils.writeUnsignedVarint(bytes.length + 1, buffer); buffer.put(bytes); } } @Override public String read(ByteBuffer buffer) { int length = ByteUtils.readUnsignedVarint(buffer) - 1; if (length < 0) { return null; } else if (length > Short.MAX_VALUE) { throw new SchemaException("String length " + length + " is larger than the maximum string length."); } else if (length > buffer.remaining()) { throw new SchemaException("Error reading string of length " + length + ", only " + buffer.remaining() + " bytes available"); } else { String result = Utils.utf8(buffer, length); buffer.position(buffer.position() + length); return result; } } @Override public int sizeOf(Object o) { if (o == null) { return 1; } int length = Utils.utf8Length((String) o); return ByteUtils.sizeOfUnsignedVarint(length + 1) + length; } @Override public String typeName() { return "COMPACT_NULLABLE_STRING"; } @Override public String validate(Object item) { if (item == null) { return null; } else if (item instanceof String) { return (String) item; } else { throw new SchemaException(item + " is not a String."); } } @Override public String documentation() { return "Represents a sequence of characters. First the length N + 1 is given as an UNSIGNED_VARINT " + ". Then N bytes follow which are the UTF-8 encoding of the character sequence. " + "A null string is represented with a length of 0."; } }; public static final DocumentedType BYTES = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { ByteBuffer arg = (ByteBuffer) o; int pos = arg.position(); buffer.putInt(arg.remaining()); buffer.put(arg); arg.position(pos); } @Override public Object read(ByteBuffer buffer) { int size = buffer.getInt(); if (size < 0) throw new SchemaException("Bytes size " + size + " cannot be negative"); if (size > buffer.remaining()) throw new SchemaException("Error reading bytes of size " + size + ", only " + buffer.remaining() + " bytes available"); int limit = buffer.limit(); int newPosition = buffer.position() + size; buffer.limit(newPosition); ByteBuffer val = buffer.slice(); buffer.limit(limit); buffer.position(newPosition); return val; } @Override public int sizeOf(Object o) { ByteBuffer buffer = (ByteBuffer) o; return 4 + buffer.remaining(); } @Override public String typeName() { return "BYTES"; } @Override public ByteBuffer validate(Object item) { if (item instanceof ByteBuffer) return (ByteBuffer) item; else throw new SchemaException(item + " is not a java.nio.ByteBuffer."); } @Override public String documentation() { return "Represents a raw sequence of bytes. First the length N is given as an " + INT32 + ". Then N bytes follow."; } }; public static final DocumentedType COMPACT_BYTES = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { ByteBuffer arg = (ByteBuffer) o; int pos = arg.position(); ByteUtils.writeUnsignedVarint(arg.remaining() + 1, buffer); buffer.put(arg); arg.position(pos); } @Override public Object read(ByteBuffer buffer) { int size = ByteUtils.readUnsignedVarint(buffer) - 1; if (size < 0) throw new SchemaException("Bytes size " + size + " cannot be negative"); if (size > buffer.remaining()) throw new SchemaException("Error reading bytes of size " + size + ", only " + buffer.remaining() + " bytes available"); int limit = buffer.limit(); int newPosition = buffer.position() + size; buffer.limit(newPosition); ByteBuffer val = buffer.slice(); buffer.limit(limit); buffer.position(newPosition); return val; } @Override public int sizeOf(Object o) { ByteBuffer buffer = (ByteBuffer) o; int remaining = buffer.remaining(); return ByteUtils.sizeOfUnsignedVarint(remaining + 1) + remaining; } @Override public String typeName() { return "COMPACT_BYTES"; } @Override public ByteBuffer validate(Object item) { if (item instanceof ByteBuffer) return (ByteBuffer) item; else throw new SchemaException(item + " is not a java.nio.ByteBuffer."); } @Override public String documentation() { return "Represents a raw sequence of bytes. First the length N+1 is given as an UNSIGNED_VARINT." + "Then N bytes follow."; } }; public static final DocumentedType NULLABLE_BYTES = new DocumentedType() { @Override public boolean isNullable() { return true; } @Override public void write(ByteBuffer buffer, Object o) { if (o == null) { buffer.putInt(-1); return; } ByteBuffer arg = (ByteBuffer) o; int pos = arg.position(); buffer.putInt(arg.remaining()); buffer.put(arg); arg.position(pos); } @Override public Object read(ByteBuffer buffer) { int size = buffer.getInt(); if (size < 0) return null; if (size > buffer.remaining()) throw new SchemaException("Error reading bytes of size " + size + ", only " + buffer.remaining() + " bytes available"); int limit = buffer.limit(); int newPosition = buffer.position() + size; buffer.limit(newPosition); ByteBuffer val = buffer.slice(); buffer.limit(limit); buffer.position(newPosition); return val; } @Override public int sizeOf(Object o) { if (o == null) return 4; ByteBuffer buffer = (ByteBuffer) o; return 4 + buffer.remaining(); } @Override public String typeName() { return "NULLABLE_BYTES"; } @Override public ByteBuffer validate(Object item) { if (item == null) return null; if (item instanceof ByteBuffer) return (ByteBuffer) item; throw new SchemaException(item + " is not a java.nio.ByteBuffer."); } @Override public String documentation() { return "Represents a raw sequence of bytes or null. For non-null values, first the length N is given as an " + INT32 + ". Then N bytes follow. A null value is encoded with length of -1 and there are no following bytes."; } }; public static final DocumentedType COMPACT_NULLABLE_BYTES = new DocumentedType() { @Override public boolean isNullable() { return true; } @Override public void write(ByteBuffer buffer, Object o) { if (o == null) { ByteUtils.writeUnsignedVarint(0, buffer); } else { ByteBuffer arg = (ByteBuffer) o; int pos = arg.position(); ByteUtils.writeUnsignedVarint(arg.remaining() + 1, buffer); buffer.put(arg); arg.position(pos); } } @Override public Object read(ByteBuffer buffer) { int size = ByteUtils.readUnsignedVarint(buffer) - 1; if (size < 0) return null; if (size > buffer.remaining()) throw new SchemaException("Error reading bytes of size " + size + ", only " + buffer.remaining() + " bytes available"); int limit = buffer.limit(); int newPosition = buffer.position() + size; buffer.limit(newPosition); ByteBuffer val = buffer.slice(); buffer.limit(limit); buffer.position(newPosition); return val; } @Override public int sizeOf(Object o) { if (o == null) { return 1; } ByteBuffer buffer = (ByteBuffer) o; int remaining = buffer.remaining(); return ByteUtils.sizeOfUnsignedVarint(remaining + 1) + remaining; } @Override public String typeName() { return "COMPACT_NULLABLE_BYTES"; } @Override public ByteBuffer validate(Object item) { if (item == null) return null; if (item instanceof ByteBuffer) return (ByteBuffer) item; throw new SchemaException(item + " is not a java.nio.ByteBuffer."); } @Override public String documentation() { return "Represents a raw sequence of bytes. First the length N+1 is given as an UNSIGNED_VARINT." + "Then N bytes follow. A null object is represented with a length of 0."; } }; public static final DocumentedType COMPACT_RECORDS = new DocumentedType() { @Override public boolean isNullable() { return true; } @Override public void write(ByteBuffer buffer, Object o) { if (o == null) { COMPACT_NULLABLE_BYTES.write(buffer, null); } else if (o instanceof MemoryRecords) { MemoryRecords records = (MemoryRecords) o; COMPACT_NULLABLE_BYTES.write(buffer, records.buffer().duplicate()); } else { throw new IllegalArgumentException("Unexpected record type: " + o.getClass()); } } @Override public MemoryRecords read(ByteBuffer buffer) { ByteBuffer recordsBuffer = (ByteBuffer) COMPACT_NULLABLE_BYTES.read(buffer); if (recordsBuffer == null) { return null; } else { return MemoryRecords.readableRecords(recordsBuffer); } } @Override public int sizeOf(Object o) { if (o == null) { return 1; } BaseRecords records = (BaseRecords) o; int recordsSize = records.sizeInBytes(); return ByteUtils.sizeOfUnsignedVarint(recordsSize + 1) + recordsSize; } @Override public String typeName() { return "COMPACT_RECORDS"; } @Override public BaseRecords validate(Object item) { if (item == null) return null; if (item instanceof BaseRecords) return (BaseRecords) item; throw new SchemaException(item + " is not an instance of " + BaseRecords.class.getName()); } @Override public String documentation() { return "Represents a sequence of Kafka records as " + COMPACT_NULLABLE_BYTES + ". " + "For a detailed description of records see " + "<a href=\"/documentation/#messageformat\">Message Sets</a>."; } }; public static final DocumentedType RECORDS = new DocumentedType() { @Override public boolean isNullable() { return true; } @Override public void write(ByteBuffer buffer, Object o) { if (o == null) { NULLABLE_BYTES.write(buffer, null); } else if (o instanceof MemoryRecords) { MemoryRecords records = (MemoryRecords) o; NULLABLE_BYTES.write(buffer, records.buffer().duplicate()); } else { throw new IllegalArgumentException("Unexpected record type: " + o.getClass()); } } @Override public MemoryRecords read(ByteBuffer buffer) { ByteBuffer recordsBuffer = (ByteBuffer) NULLABLE_BYTES.read(buffer); if (recordsBuffer == null) { return null; } else { return MemoryRecords.readableRecords(recordsBuffer); } } @Override public int sizeOf(Object o) { if (o == null) return 4; BaseRecords records = (BaseRecords) o; return 4 + records.sizeInBytes(); } @Override public String typeName() { return "RECORDS"; } @Override public BaseRecords validate(Object item) { if (item == null) return null; if (item instanceof BaseRecords) return (BaseRecords) item; throw new SchemaException(item + " is not an instance of " + BaseRecords.class.getName()); } @Override public String documentation() { return "Represents a sequence of Kafka records as " + NULLABLE_BYTES + ". " + "For a detailed description of records see " + "<a href=\"/documentation/#messageformat\">Message Sets</a>."; } }; public static final DocumentedType VARINT = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { ByteUtils.writeVarint((Integer) o, buffer); } @Override public Integer read(ByteBuffer buffer) { return ByteUtils.readVarint(buffer); } @Override public Integer validate(Object item) { if (item instanceof Integer) return (Integer) item; throw new SchemaException(item + " is not an integer"); } public String typeName() { return "VARINT"; } @Override public int sizeOf(Object o) { return ByteUtils.sizeOfVarint((Integer) o); } @Override public String documentation() { return "Represents an integer between -2<sup>31</sup> and 2<sup>31</sup>-1 inclusive. " + "Encoding follows the variable-length zig-zag encoding from " + " <a href=\"https://code.google.com/apis/protocolbuffers/docs/encoding.html\"> Google Protocol Buffers</a>."; } }; public static final DocumentedType VARLONG = new DocumentedType() { @Override public void write(ByteBuffer buffer, Object o) { ByteUtils.writeVarlong((Long) o, buffer); } @Override public Long read(ByteBuffer buffer) { return ByteUtils.readVarlong(buffer); } @Override public Long validate(Object item) { if (item instanceof Long) return (Long) item; throw new SchemaException(item + " is not a long"); } public String typeName() { return "VARLONG"; } @Override public int sizeOf(Object o) { return ByteUtils.sizeOfVarlong((Long) o); } @Override public String documentation() { return "Represents an integer between -2<sup>63</sup> and 2<sup>63</sup>-1 inclusive. " + "Encoding follows the variable-length zig-zag encoding from " + " <a href=\"https://code.google.com/apis/protocolbuffers/docs/encoding.html\"> Google Protocol Buffers</a>."; } }; private static String toHtml() { DocumentedType[] types = { BOOLEAN, INT8, INT16, INT32, INT64, UINT16, UNSIGNED_INT32, VARINT, VARLONG, UUID, FLOAT64, STRING, COMPACT_STRING, NULLABLE_STRING, COMPACT_NULLABLE_STRING, BYTES, COMPACT_BYTES, NULLABLE_BYTES, COMPACT_NULLABLE_BYTES, RECORDS, COMPACT_RECORDS, new ArrayOf(STRING), new CompactArrayOf(COMPACT_STRING)}; final StringBuilder b = new StringBuilder(); b.append("<table class=\"data-table\"><tbody>\n"); b.append("<tr>"); b.append("<th>Type</th>\n"); b.append("<th>Description</th>\n"); b.append("</tr>\n"); for (DocumentedType type : types) { b.append("<tr>"); b.append("<td>"); b.append(type.typeName()); b.append("</td>"); b.append("<td>"); b.append(type.documentation()); b.append("</td>"); b.append("</tr>\n"); } b.append("</tbody></table>\n"); return b.toString(); } public static void main(String[] args) { System.out.println(toHtml()); } }
google/j2objc
37,442
jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/HttpURLConnection.java
/* * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.net; import java.io.InputStream; import java.io.IOException; import java.security.Permission; import java.util.Date; // Android-changed: top-level documentation substantially changed/rewritten. /** * A URLConnection with support for HTTP-specific features. See * <A HREF="http://www.w3.org/pub/WWW/Protocols/"> the spec </A> for * details. * <p> * * <p>Uses of this class follow a pattern: * <ol> * <li>Obtain a new {@code HttpURLConnection} by calling {@link * URL#openConnection() URL.openConnection()} and casting the result to * {@code HttpURLConnection}. * <li>Prepare the request. The primary property of a request is its URI. * Request headers may also include metadata such as credentials, preferred * content types, and session cookies. * <li>Optionally upload a request body. Instances must be configured with * {@link #setDoOutput(boolean) setDoOutput(true)} if they include a * request body. Transmit data by writing to the stream returned by {@link * #getOutputStream()}. * <li>Read the response. Response headers typically include metadata such as * the response body's content type and length, modified dates and session * cookies. The response body may be read from the stream returned by {@link * #getInputStream()}. If the response has no body, that method returns an * empty stream. * <li>Disconnect. Once the response body has been read, the {@code * HttpURLConnection} should be closed by calling {@link #disconnect()}. * Disconnecting releases the resources held by a connection so they may * be closed or reused. * </ol> * * <p>For example, to retrieve the webpage at {@code http://www.android.com/}: * <pre> {@code * URL url = new URL("http://www.android.com/"); * HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); * try { * InputStream in = new BufferedInputStream(urlConnection.getInputStream()); * readStream(in); * } finally { * urlConnection.disconnect(); * } * }</pre> * * <h3>Secure Communication with HTTPS</h3> * Calling {@link URL#openConnection()} on a URL with the "https" * scheme will return an {@code HttpsURLConnection}, which allows for * overriding the default {@link javax.net.ssl.HostnameVerifier * HostnameVerifier} and {@link javax.net.ssl.SSLSocketFactory * SSLSocketFactory}. An application-supplied {@code SSLSocketFactory} * created from an {@link javax.net.ssl.SSLContext SSLContext} can * provide a custom {@link javax.net.ssl.X509TrustManager * X509TrustManager} for verifying certificate chains and a custom * {@link javax.net.ssl.X509KeyManager X509KeyManager} for supplying * client certificates. See {@link javax.net.ssl.HttpsURLConnection * HttpsURLConnection} for more details. * * <h3>Response Handling</h3> * {@code HttpURLConnection} will follow up to five HTTP redirects. It will * follow redirects from one origin server to another. This implementation * doesn't follow redirects from HTTPS to HTTP or vice versa. * * <p>If the HTTP response indicates that an error occurred, {@link * #getInputStream()} will throw an {@link IOException}. Use {@link * #getErrorStream()} to read the error response. The headers can be read in * the normal way using {@link #getHeaderFields()}, * * <h3>Posting Content</h3> * To upload data to a web server, configure the connection for output using * {@link #setDoOutput(boolean) setDoOutput(true)}. * * <p>For best performance, you should call either {@link * #setFixedLengthStreamingMode(int)} when the body length is known in advance, * or {@link #setChunkedStreamingMode(int)} when it is not. Otherwise {@code * HttpURLConnection} will be forced to buffer the complete request body in * memory before it is transmitted, wasting (and possibly exhausting) heap and * increasing latency. * * <p>For example, to perform an upload: <pre> {@code * HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); * try { * urlConnection.setDoOutput(true); * urlConnection.setChunkedStreamingMode(0); * * OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); * writeStream(out); * * InputStream in = new BufferedInputStream(urlConnection.getInputStream()); * readStream(in); * } finally { * urlConnection.disconnect(); * } * }</pre> * * <h3>Performance</h3> * The input and output streams returned by this class are <strong>not * buffered</strong>. Most callers should wrap the returned streams with {@link * java.io.BufferedInputStream BufferedInputStream} or {@link * java.io.BufferedOutputStream BufferedOutputStream}. Callers that do only bulk * reads or writes may omit buffering. * * <p>When transferring large amounts of data to or from a server, use streams * to limit how much data is in memory at once. Unless you need the entire * body to be in memory at once, process it as a stream (rather than storing * the complete body as a single byte array or string). * * <p>To reduce latency, this class may reuse the same underlying {@code Socket} * for multiple request/response pairs. As a result, HTTP connections may be * held open longer than necessary. Calls to {@link #disconnect()} may return * the socket to a pool of connected sockets. * * <p>By default, this implementation of {@code HttpURLConnection} requests that * servers use gzip compression and it automatically decompresses the data for * callers of {@link #getInputStream()}. The Content-Encoding and Content-Length * response headers are cleared in this case. Gzip compression can be disabled by * setting the acceptable encodings in the request header: <pre> {@code * urlConnection.setRequestProperty("Accept-Encoding", "identity"); * }</pre> * * <p>Setting the Accept-Encoding request header explicitly disables automatic * decompression and leaves the response headers intact; callers must handle * decompression as needed, according to the Content-Encoding header of the * response. * * <p>{@link #getContentLength()} returns the number of bytes transmitted and * cannot be used to predict how many bytes can be read from * {@link #getInputStream()} for compressed streams. Instead, read that stream * until it is exhausted, i.e. when {@link InputStream#read} returns -1. * * <h3>Handling Network Sign-On</h3> * Some Wi-Fi networks block Internet access until the user clicks through a * sign-on page. Such sign-on pages are typically presented by using HTTP * redirects. You can use {@link #getURL()} to test if your connection has been * unexpectedly redirected. This check is not valid until <strong>after</strong> * the response headers have been received, which you can trigger by calling * {@link #getHeaderFields()} or {@link #getInputStream()}. For example, to * check that a response was not redirected to an unexpected host: * <pre> {@code * HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); * try { * InputStream in = new BufferedInputStream(urlConnection.getInputStream()); * if (!url.getHost().equals(urlConnection.getURL().getHost())) { * // we were redirected! Kick the user out to the browser to sign on? * } * ... * } finally { * urlConnection.disconnect(); * } * }</pre> * * <h3>HTTP Authentication</h3> * {@code HttpURLConnection} supports <a * href="http://www.ietf.org/rfc/rfc2617">HTTP basic authentication</a>. Use * {@link Authenticator} to set the VM-wide authentication handler: * <pre> {@code * Authenticator.setDefault(new Authenticator() { * protected PasswordAuthentication getPasswordAuthentication() { * return new PasswordAuthentication(username, password.toCharArray()); * } * }); * }</pre> * Unless paired with HTTPS, this is <strong>not</strong> a secure mechanism for * user authentication. In particular, the username, password, request and * response are all transmitted over the network without encryption. * * <h3>Sessions with Cookies</h3> * To establish and maintain a potentially long-lived session between client * and server, {@code HttpURLConnection} includes an extensible cookie manager. * Enable VM-wide cookie management using {@link CookieHandler} and {@link * CookieManager}: <pre> {@code * CookieManager cookieManager = new CookieManager(); * CookieHandler.setDefault(cookieManager); * }</pre> * By default, {@code CookieManager} accepts cookies from the <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec1.html">origin * server</a> only. Two other policies are included: {@link * CookiePolicy#ACCEPT_ALL} and {@link CookiePolicy#ACCEPT_NONE}. Implement * {@link CookiePolicy} to define a custom policy. * * <p>The default {@code CookieManager} keeps all accepted cookies in memory. It * will forget these cookies when the VM exits. Implement {@link CookieStore} to * define a custom cookie store. * * <p>In addition to the cookies set by HTTP responses, you may set cookies * programmatically. To be included in HTTP request headers, cookies must have * the domain and path properties set. * * <p>By default, new instances of {@code HttpCookie} work only with servers * that support <a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a> * cookies. Many web servers support only the older specification, <a * href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a>. For compatibility * with the most web servers, set the cookie version to 0. * * <p>For example, to receive {@code www.twitter.com} in French: <pre> {@code * HttpCookie cookie = new HttpCookie("lang", "fr"); * cookie.setDomain("twitter.com"); * cookie.setPath("/"); * cookie.setVersion(0); * cookieManager.getCookieStore().add(new URI("http://twitter.com/"), cookie); * }</pre> * * <h3>HTTP Methods</h3> * <p>{@code HttpURLConnection} uses the {@code GET} method by default. It will * use {@code POST} if {@link #setDoOutput setDoOutput(true)} has been called. * Other HTTP methods ({@code OPTIONS}, {@code HEAD}, {@code PUT}, {@code * DELETE} and {@code TRACE}) can be used with {@link #setRequestMethod}. * * <h3>Proxies</h3> * By default, this class will connect directly to the <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec1.html">origin * server</a>. It can also connect via an {@link Proxy.Type#HTTP HTTP} or {@link * Proxy.Type#SOCKS SOCKS} proxy. To use a proxy, use {@link * URL#openConnection(Proxy) URL.openConnection(Proxy)} when creating the * connection. * * <h3>IPv6 Support</h3> * <p>This class includes transparent support for IPv6. For hosts with both IPv4 * and IPv6 addresses, it will attempt to connect to each of a host's addresses * until a connection is established. * * <h3>Response Caching</h3> * Android 4.0 (Ice Cream Sandwich, API level 15) includes a response cache. See * {@code android.net.http.HttpResponseCache} for instructions on enabling HTTP * caching in your application. * * <h3>Avoiding Bugs In Earlier Releases</h3> * Prior to Android 2.2 (Froyo), this class had some frustrating bugs. In * particular, calling {@code close()} on a readable {@code InputStream} could * <a href="http://code.google.com/p/android/issues/detail?id=2939">poison the * connection pool</a>. Work around this by disabling connection pooling: * <pre> {@code * private void disableConnectionReuseIfNecessary() { * // Work around pre-Froyo bugs in HTTP connection reuse. * if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) { * System.setProperty("http.keepAlive", "false"); * } * }}</pre> * * <p>Each instance of {@code HttpURLConnection} may be used for one * request/response pair. Instances of this class are not thread safe. * * @see java.net.HttpURLConnection#disconnect() * @since JDK1.1 */ abstract public class HttpURLConnection extends URLConnection { /* instance variables */ /** * The HTTP method (GET,POST,PUT,etc.). */ protected String method = "GET"; /** * The chunk-length when using chunked encoding streaming mode for output. * A value of {@code -1} means chunked encoding is disabled for output. * @since 1.5 */ protected int chunkLength = -1; /** * The fixed content-length when using fixed-length streaming mode. * A value of {@code -1} means fixed-length streaming mode is disabled * for output. * * <P> <B>NOTE:</B> {@link #fixedContentLengthLong} is recommended instead * of this field, as it allows larger content lengths to be set. * * @since 1.5 */ protected int fixedContentLength = -1; /** * The fixed content-length when using fixed-length streaming mode. * A value of {@code -1} means fixed-length streaming mode is disabled * for output. * * @since 1.7 */ protected long fixedContentLengthLong = -1; /** * Returns the key for the {@code n}<sup>th</sup> header field. * Some implementations may treat the {@code 0}<sup>th</sup> * header field as special, i.e. as the status line returned by the HTTP * server. In this case, {@link #getHeaderField(int) getHeaderField(0)} returns the status * line, but {@code getHeaderFieldKey(0)} returns null. * * @param n an index, where n >=0. * @return the key for the {@code n}<sup>th</sup> header field, * or {@code null} if the key does not exist. */ public String getHeaderFieldKey (int n) { return null; } /** * This method is used to enable streaming of a HTTP request body * without internal buffering, when the content length is known in * advance. * <p> * An exception will be thrown if the application * attempts to write more data than the indicated * content-length, or if the application closes the OutputStream * before writing the indicated amount. * <p> * When output streaming is enabled, authentication * and redirection cannot be handled automatically. * A HttpRetryException will be thrown when reading * the response if authentication or redirection are required. * This exception can be queried for the details of the error. * <p> * This method must be called before the URLConnection is connected. * <p> * <B>NOTE:</B> {@link #setFixedLengthStreamingMode(long)} is recommended * instead of this method as it allows larger content lengths to be set. * * @param contentLength The number of bytes which will be written * to the OutputStream. * * @throws IllegalStateException if URLConnection is already connected * or if a different streaming mode is already enabled. * * @throws IllegalArgumentException if a content length less than * zero is specified. * * @see #setChunkedStreamingMode(int) * @since 1.5 */ public void setFixedLengthStreamingMode (int contentLength) { if (connected) { throw new IllegalStateException ("Already connected"); } if (chunkLength != -1) { throw new IllegalStateException ("Chunked encoding streaming mode set"); } if (contentLength < 0) { throw new IllegalArgumentException ("invalid content length"); } fixedContentLength = contentLength; } /** * This method is used to enable streaming of a HTTP request body * without internal buffering, when the content length is known in * advance. * * <P> An exception will be thrown if the application attempts to write * more data than the indicated content-length, or if the application * closes the OutputStream before writing the indicated amount. * * <P> When output streaming is enabled, authentication and redirection * cannot be handled automatically. A {@linkplain HttpRetryException} will * be thrown when reading the response if authentication or redirection * are required. This exception can be queried for the details of the * error. * * <P> This method must be called before the URLConnection is connected. * * <P> The content length set by invoking this method takes precedence * over any value set by {@link #setFixedLengthStreamingMode(int)}. * * @param contentLength * The number of bytes which will be written to the OutputStream. * * @throws IllegalStateException * if URLConnection is already connected or if a different * streaming mode is already enabled. * * @throws IllegalArgumentException * if a content length less than zero is specified. * * @since 1.7 */ public void setFixedLengthStreamingMode(long contentLength) { if (connected) { throw new IllegalStateException("Already connected"); } if (chunkLength != -1) { throw new IllegalStateException( "Chunked encoding streaming mode set"); } if (contentLength < 0) { throw new IllegalArgumentException("invalid content length"); } fixedContentLengthLong = contentLength; } /* Default chunk size (including chunk header) if not specified; * we want to keep this in sync with the one defined in * sun.net.www.http.ChunkedOutputStream */ private static final int DEFAULT_CHUNK_SIZE = 4096; /** * This method is used to enable streaming of a HTTP request body * without internal buffering, when the content length is <b>not</b> * known in advance. In this mode, chunked transfer encoding * is used to send the request body. Note, not all HTTP servers * support this mode. * <p> * When output streaming is enabled, authentication * and redirection cannot be handled automatically. * A HttpRetryException will be thrown when reading * the response if authentication or redirection are required. * This exception can be queried for the details of the error. * <p> * This method must be called before the URLConnection is connected. * * @param chunklen The number of bytes to write in each chunk. * If chunklen is less than or equal to zero, a default * value will be used. * * @throws IllegalStateException if URLConnection is already connected * or if a different streaming mode is already enabled. * * @see #setFixedLengthStreamingMode(int) * @since 1.5 */ public void setChunkedStreamingMode (int chunklen) { if (connected) { throw new IllegalStateException ("Can't set streaming mode: already connected"); } if (fixedContentLength != -1 || fixedContentLengthLong != -1) { throw new IllegalStateException ("Fixed length streaming mode set"); } chunkLength = chunklen <=0? DEFAULT_CHUNK_SIZE : chunklen; } /** * Returns the value for the {@code n}<sup>th</sup> header field. * Some implementations may treat the {@code 0}<sup>th</sup> * header field as special, i.e. as the status line returned by the HTTP * server. * <p> * This method can be used in conjunction with the * {@link #getHeaderFieldKey getHeaderFieldKey} method to iterate through all * the headers in the message. * * @param n an index, where n>=0. * @return the value of the {@code n}<sup>th</sup> header field, * or {@code null} if the value does not exist. * @see java.net.HttpURLConnection#getHeaderFieldKey(int) */ public String getHeaderField(int n) { return null; } /** * An {@code int} representing the three digit HTTP Status-Code. * <ul> * <li> 1xx: Informational * <li> 2xx: Success * <li> 3xx: Redirection * <li> 4xx: Client Error * <li> 5xx: Server Error * </ul> */ protected int responseCode = -1; /** * The HTTP response message. */ protected String responseMessage = null; /* static variables */ /* do we automatically follow redirects? The default is true. */ private static boolean followRedirects = true; /** * If {@code true}, the protocol will automatically follow redirects. * If {@code false}, the protocol will not automatically follow * redirects. * <p> * This field is set by the {@code setInstanceFollowRedirects} * method. Its value is returned by the {@code getInstanceFollowRedirects} * method. * <p> * Its default value is based on the value of the static followRedirects * at HttpURLConnection construction time. * * @see java.net.HttpURLConnection#setInstanceFollowRedirects(boolean) * @see java.net.HttpURLConnection#getInstanceFollowRedirects() * @see java.net.HttpURLConnection#setFollowRedirects(boolean) */ protected boolean instanceFollowRedirects = followRedirects; /* valid HTTP methods */ private static final String[] methods = { "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE" }; /** * Constructor for the HttpURLConnection. * @param u the URL */ protected HttpURLConnection (URL u) { super(u); } /** * Sets whether HTTP redirects (requests with response code 3xx) should * be automatically followed by this class. True by default. Applets * cannot change this variable. * <p> * If there is a security manager, this method first calls * the security manager's {@code checkSetFactory} method * to ensure the operation is allowed. * This could result in a SecurityException. * * @param set a {@code boolean} indicating whether or not * to follow HTTP redirects. * @exception SecurityException if a security manager exists and its * {@code checkSetFactory} method doesn't * allow the operation. * @see SecurityManager#checkSetFactory * @see #getFollowRedirects() */ public static void setFollowRedirects(boolean set) { // SecurityManager sec = System.getSecurityManager(); // if (sec != null) { // // seems to be the best check here... // sec.checkSetFactory(); // } followRedirects = set; } /** * Returns a {@code boolean} indicating * whether or not HTTP redirects (3xx) should * be automatically followed. * * @return {@code true} if HTTP redirects should * be automatically followed, {@code false} if not. * @see #setFollowRedirects(boolean) */ public static boolean getFollowRedirects() { return followRedirects; } /** * Sets whether HTTP redirects (requests with response code 3xx) should * be automatically followed by this {@code HttpURLConnection} * instance. * <p> * The default value comes from followRedirects, which defaults to * true. * * @param followRedirects a {@code boolean} indicating * whether or not to follow HTTP redirects. * * @see java.net.HttpURLConnection#instanceFollowRedirects * @see #getInstanceFollowRedirects * @since 1.3 */ public void setInstanceFollowRedirects(boolean followRedirects) { instanceFollowRedirects = followRedirects; } /** * Returns the value of this {@code HttpURLConnection}'s * {@code instanceFollowRedirects} field. * * @return the value of this {@code HttpURLConnection}'s * {@code instanceFollowRedirects} field. * @see java.net.HttpURLConnection#instanceFollowRedirects * @see #setInstanceFollowRedirects(boolean) * @since 1.3 */ public boolean getInstanceFollowRedirects() { return instanceFollowRedirects; } /** * Set the method for the URL request, one of: * <UL> * <LI>GET * <LI>POST * <LI>HEAD * <LI>OPTIONS * <LI>PUT * <LI>DELETE * <LI>TRACE * </UL> are legal, subject to protocol restrictions. The default * method is GET. * * @param method the HTTP method * @exception ProtocolException if the method cannot be reset or if * the requested method isn't valid for HTTP. * @exception SecurityException if a security manager is set and the * method is "TRACE", but the "allowHttpTrace" * NetPermission is not granted. * @see #getRequestMethod() */ public void setRequestMethod(String method) throws ProtocolException { if (connected) { throw new ProtocolException("Can't reset method: already connected"); } // This restriction will prevent people from using this class to // experiment w/ new HTTP methods using java. But it should // be placed for security - the request String could be // arbitrarily long. for (int i = 0; i < methods.length; i++) { if (methods[i].equals(method)) { // if (method.equals("TRACE")) { // SecurityManager s = System.getSecurityManager(); // if (s != null) { // s.checkPermission(new NetPermission("allowHttpTrace")); // } // } this.method = method; return; } } throw new ProtocolException("Invalid HTTP method: " + method); } /** * Get the request method. * @return the HTTP request method * @see #setRequestMethod(java.lang.String) */ public String getRequestMethod() { return method; } /** * Gets the status code from an HTTP response message. * For example, in the case of the following status lines: * <PRE> * HTTP/1.0 200 OK * HTTP/1.0 401 Unauthorized * </PRE> * It will return 200 and 401 respectively. * Returns -1 if no code can be discerned * from the response (i.e., the response is not valid HTTP). * @throws IOException if an error occurred connecting to the server. * @return the HTTP Status-Code, or -1 */ public int getResponseCode() throws IOException { /* * We're got the response code already */ if (responseCode != -1) { return responseCode; } /* * Ensure that we have connected to the server. Record * exception as we need to re-throw it if there isn't * a status line. */ Exception exc = null; try { getInputStream(); } catch (Exception e) { exc = e; } /* * If we can't a status-line then re-throw any exception * that getInputStream threw. */ String statusLine = getHeaderField(0); if (statusLine == null) { if (exc != null) { if (exc instanceof RuntimeException) throw (RuntimeException)exc; else throw (IOException)exc; } return -1; } /* * Examine the status-line - should be formatted as per * section 6.1 of RFC 2616 :- * * Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase * * If status line can't be parsed return -1. */ if (statusLine.startsWith("HTTP/1.")) { int codePos = statusLine.indexOf(' '); if (codePos > 0) { int phrasePos = statusLine.indexOf(' ', codePos+1); if (phrasePos > 0 && phrasePos < statusLine.length()) { responseMessage = statusLine.substring(phrasePos+1); } // deviation from RFC 2616 - don't reject status line // if SP Reason-Phrase is not included. if (phrasePos < 0) phrasePos = statusLine.length(); try { responseCode = Integer.parseInt (statusLine.substring(codePos+1, phrasePos)); return responseCode; } catch (NumberFormatException e) { } } } return -1; } /** * Gets the HTTP response message, if any, returned along with the * response code from a server. From responses like: * <PRE> * HTTP/1.0 200 OK * HTTP/1.0 404 Not Found * </PRE> * Extracts the Strings "OK" and "Not Found" respectively. * Returns null if none could be discerned from the responses * (the result was not valid HTTP). * @throws IOException if an error occurred connecting to the server. * @return the HTTP response message, or {@code null} */ public String getResponseMessage() throws IOException { getResponseCode(); return responseMessage; } @SuppressWarnings("deprecation") public long getHeaderFieldDate(String name, long Default) { String dateString = getHeaderField(name); try { if (dateString.indexOf("GMT") == -1) { dateString = dateString+" GMT"; } return Date.parse(dateString); } catch (Exception e) { } return Default; } /** * Indicates that other requests to the server * are unlikely in the near future. Calling disconnect() * should not imply that this HttpURLConnection * instance can be reused for other requests. */ public abstract void disconnect(); /** * Indicates if the connection is going through a proxy. * @return a boolean indicating if the connection is * using a proxy. */ public abstract boolean usingProxy(); /** * Returns a {@link SocketPermission} object representing the * permission necessary to connect to the destination host and port. * * @exception IOException if an error occurs while computing * the permission. * * @return a {@code SocketPermission} object representing the * permission necessary to connect to the destination * host and port. */ public Permission getPermission() throws IOException { int port = url.getPort(); port = port < 0 ? 80 : port; String host = url.getHost() + ":" + port; Permission permission = new SocketPermission(host, "connect"); return permission; } /** * Returns the error stream if the connection failed * but the server sent useful data nonetheless. The * typical example is when an HTTP server responds * with a 404, which will cause a FileNotFoundException * to be thrown in connect, but the server sent an HTML * help page with suggestions as to what to do. * * <p>This method will not cause a connection to be initiated. If * the connection was not connected, or if the server did not have * an error while connecting or if the server had an error but * no error data was sent, this method will return null. This is * the default. * * @return an error stream if any, null if there have been no * errors, the connection is not connected or the server sent no * useful data. */ public InputStream getErrorStream() { return null; } /** * The response codes for HTTP, as of version 1.1. */ // REMIND: do we want all these?? // Others not here that we do want?? /* 2XX: generally "OK" */ /** * HTTP Status-Code 200: OK. */ public static final int HTTP_OK = 200; /** * HTTP Status-Code 201: Created. */ public static final int HTTP_CREATED = 201; /** * HTTP Status-Code 202: Accepted. */ public static final int HTTP_ACCEPTED = 202; /** * HTTP Status-Code 203: Non-Authoritative Information. */ public static final int HTTP_NOT_AUTHORITATIVE = 203; /** * HTTP Status-Code 204: No Content. */ public static final int HTTP_NO_CONTENT = 204; /** * HTTP Status-Code 205: Reset Content. */ public static final int HTTP_RESET = 205; /** * HTTP Status-Code 206: Partial Content. */ public static final int HTTP_PARTIAL = 206; /* 3XX: relocation/redirect */ /** * HTTP Status-Code 300: Multiple Choices. */ public static final int HTTP_MULT_CHOICE = 300; /** * HTTP Status-Code 301: Moved Permanently. */ public static final int HTTP_MOVED_PERM = 301; /** * HTTP Status-Code 302: Temporary Redirect. */ public static final int HTTP_MOVED_TEMP = 302; /** * HTTP Status-Code 303: See Other. */ public static final int HTTP_SEE_OTHER = 303; /** * HTTP Status-Code 304: Not Modified. */ public static final int HTTP_NOT_MODIFIED = 304; /** * HTTP Status-Code 305: Use Proxy. */ public static final int HTTP_USE_PROXY = 305; /* 4XX: client error */ /** * HTTP Status-Code 400: Bad Request. */ public static final int HTTP_BAD_REQUEST = 400; /** * HTTP Status-Code 401: Unauthorized. */ public static final int HTTP_UNAUTHORIZED = 401; /** * HTTP Status-Code 402: Payment Required. */ public static final int HTTP_PAYMENT_REQUIRED = 402; /** * HTTP Status-Code 403: Forbidden. */ public static final int HTTP_FORBIDDEN = 403; /** * HTTP Status-Code 404: Not Found. */ public static final int HTTP_NOT_FOUND = 404; /** * HTTP Status-Code 405: Method Not Allowed. */ public static final int HTTP_BAD_METHOD = 405; /** * HTTP Status-Code 406: Not Acceptable. */ public static final int HTTP_NOT_ACCEPTABLE = 406; /** * HTTP Status-Code 407: Proxy Authentication Required. */ public static final int HTTP_PROXY_AUTH = 407; /** * HTTP Status-Code 408: Request Time-Out. */ public static final int HTTP_CLIENT_TIMEOUT = 408; /** * HTTP Status-Code 409: Conflict. */ public static final int HTTP_CONFLICT = 409; /** * HTTP Status-Code 410: Gone. */ public static final int HTTP_GONE = 410; /** * HTTP Status-Code 411: Length Required. */ public static final int HTTP_LENGTH_REQUIRED = 411; /** * HTTP Status-Code 412: Precondition Failed. */ public static final int HTTP_PRECON_FAILED = 412; /** * HTTP Status-Code 413: Request Entity Too Large. */ public static final int HTTP_ENTITY_TOO_LARGE = 413; /** * HTTP Status-Code 414: Request-URI Too Large. */ public static final int HTTP_REQ_TOO_LONG = 414; /** * HTTP Status-Code 415: Unsupported Media Type. */ public static final int HTTP_UNSUPPORTED_TYPE = 415; /* 5XX: server error */ /** * HTTP Status-Code 500: Internal Server Error. * @deprecated it is misplaced and shouldn't have existed. */ @Deprecated public static final int HTTP_SERVER_ERROR = 500; /** * HTTP Status-Code 500: Internal Server Error. */ public static final int HTTP_INTERNAL_ERROR = 500; /** * HTTP Status-Code 501: Not Implemented. */ public static final int HTTP_NOT_IMPLEMENTED = 501; /** * HTTP Status-Code 502: Bad Gateway. */ public static final int HTTP_BAD_GATEWAY = 502; /** * HTTP Status-Code 503: Service Unavailable. */ public static final int HTTP_UNAVAILABLE = 503; /** * HTTP Status-Code 504: Gateway Timeout. */ public static final int HTTP_GATEWAY_TIMEOUT = 504; /** * HTTP Status-Code 505: HTTP Version Not Supported. */ public static final int HTTP_VERSION = 505; }
googleapis/google-cloud-java
37,191
java-orchestration-airflow/proto-google-cloud-orchestration-airflow-v1/src/main/java/com/google/cloud/orchestration/airflow/service/v1/ExecuteAirflowCommandResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/orchestration/airflow/service/v1/environments.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.orchestration.airflow.service.v1; /** * * * <pre> * Response to ExecuteAirflowCommandRequest. * </pre> * * Protobuf type {@code google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse} */ public final class ExecuteAirflowCommandResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse) ExecuteAirflowCommandResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ExecuteAirflowCommandResponse.newBuilder() to construct. private ExecuteAirflowCommandResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ExecuteAirflowCommandResponse() { executionId_ = ""; pod_ = ""; podNamespace_ = ""; error_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ExecuteAirflowCommandResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_ExecuteAirflowCommandResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_ExecuteAirflowCommandResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse.class, com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse.Builder .class); } public static final int EXECUTION_ID_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object executionId_ = ""; /** * * * <pre> * The unique ID of the command execution for polling. * </pre> * * <code>string execution_id = 1;</code> * * @return The executionId. */ @java.lang.Override public java.lang.String getExecutionId() { java.lang.Object ref = executionId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); executionId_ = s; return s; } } /** * * * <pre> * The unique ID of the command execution for polling. * </pre> * * <code>string execution_id = 1;</code> * * @return The bytes for executionId. */ @java.lang.Override public com.google.protobuf.ByteString getExecutionIdBytes() { java.lang.Object ref = executionId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); executionId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int POD_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object pod_ = ""; /** * * * <pre> * The name of the pod where the command is executed. * </pre> * * <code>string pod = 2;</code> * * @return The pod. */ @java.lang.Override public java.lang.String getPod() { java.lang.Object ref = pod_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pod_ = s; return s; } } /** * * * <pre> * The name of the pod where the command is executed. * </pre> * * <code>string pod = 2;</code> * * @return The bytes for pod. */ @java.lang.Override public com.google.protobuf.ByteString getPodBytes() { java.lang.Object ref = pod_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pod_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int POD_NAMESPACE_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object podNamespace_ = ""; /** * * * <pre> * The namespace of the pod where the command is executed. * </pre> * * <code>string pod_namespace = 3;</code> * * @return The podNamespace. */ @java.lang.Override public java.lang.String getPodNamespace() { java.lang.Object ref = podNamespace_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); podNamespace_ = s; return s; } } /** * * * <pre> * The namespace of the pod where the command is executed. * </pre> * * <code>string pod_namespace = 3;</code> * * @return The bytes for podNamespace. */ @java.lang.Override public com.google.protobuf.ByteString getPodNamespaceBytes() { java.lang.Object ref = podNamespace_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); podNamespace_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ERROR_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object error_ = ""; /** * * * <pre> * Error message. Empty if there was no error. * </pre> * * <code>string error = 4;</code> * * @return The error. */ @java.lang.Override public java.lang.String getError() { java.lang.Object ref = error_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); error_ = s; return s; } } /** * * * <pre> * Error message. Empty if there was no error. * </pre> * * <code>string error = 4;</code> * * @return The bytes for error. */ @java.lang.Override public com.google.protobuf.ByteString getErrorBytes() { java.lang.Object ref = error_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); error_ = 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(executionId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, executionId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pod_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, pod_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(podNamespace_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, podNamespace_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(error_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, error_); } 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(executionId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, executionId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pod_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, pod_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(podNamespace_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, podNamespace_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(error_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, error_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse)) { return super.equals(obj); } com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse other = (com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse) obj; if (!getExecutionId().equals(other.getExecutionId())) return false; if (!getPod().equals(other.getPod())) return false; if (!getPodNamespace().equals(other.getPodNamespace())) return false; if (!getError().equals(other.getError())) 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) + EXECUTION_ID_FIELD_NUMBER; hash = (53 * hash) + getExecutionId().hashCode(); hash = (37 * hash) + POD_FIELD_NUMBER; hash = (53 * hash) + getPod().hashCode(); hash = (37 * hash) + POD_NAMESPACE_FIELD_NUMBER; hash = (53 * hash) + getPodNamespace().hashCode(); hash = (37 * hash) + ERROR_FIELD_NUMBER; hash = (53 * hash) + getError().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse 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 to ExecuteAirflowCommandRequest. * </pre> * * Protobuf type {@code * google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse) com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_ExecuteAirflowCommandResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_ExecuteAirflowCommandResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse.class, com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse .Builder.class); } // Construct using // com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; executionId_ = ""; pod_ = ""; podNamespace_ = ""; error_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_ExecuteAirflowCommandResponse_descriptor; } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse getDefaultInstanceForType() { return com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse .getDefaultInstance(); } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse build() { com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse buildPartial() { com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse result = new com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.executionId_ = executionId_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pod_ = pod_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.podNamespace_ = podNamespace_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.error_ = error_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse) { return mergeFrom( (com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse other) { if (other == com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse .getDefaultInstance()) return this; if (!other.getExecutionId().isEmpty()) { executionId_ = other.executionId_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getPod().isEmpty()) { pod_ = other.pod_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getPodNamespace().isEmpty()) { podNamespace_ = other.podNamespace_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getError().isEmpty()) { error_ = other.error_; 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: { executionId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { pod_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { podNamespace_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { error_ = 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 executionId_ = ""; /** * * * <pre> * The unique ID of the command execution for polling. * </pre> * * <code>string execution_id = 1;</code> * * @return The executionId. */ public java.lang.String getExecutionId() { java.lang.Object ref = executionId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); executionId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The unique ID of the command execution for polling. * </pre> * * <code>string execution_id = 1;</code> * * @return The bytes for executionId. */ public com.google.protobuf.ByteString getExecutionIdBytes() { java.lang.Object ref = executionId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); executionId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The unique ID of the command execution for polling. * </pre> * * <code>string execution_id = 1;</code> * * @param value The executionId to set. * @return This builder for chaining. */ public Builder setExecutionId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } executionId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The unique ID of the command execution for polling. * </pre> * * <code>string execution_id = 1;</code> * * @return This builder for chaining. */ public Builder clearExecutionId() { executionId_ = getDefaultInstance().getExecutionId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * The unique ID of the command execution for polling. * </pre> * * <code>string execution_id = 1;</code> * * @param value The bytes for executionId to set. * @return This builder for chaining. */ public Builder setExecutionIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); executionId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object pod_ = ""; /** * * * <pre> * The name of the pod where the command is executed. * </pre> * * <code>string pod = 2;</code> * * @return The pod. */ public java.lang.String getPod() { java.lang.Object ref = pod_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pod_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The name of the pod where the command is executed. * </pre> * * <code>string pod = 2;</code> * * @return The bytes for pod. */ public com.google.protobuf.ByteString getPodBytes() { java.lang.Object ref = pod_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pod_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The name of the pod where the command is executed. * </pre> * * <code>string pod = 2;</code> * * @param value The pod to set. * @return This builder for chaining. */ public Builder setPod(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pod_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The name of the pod where the command is executed. * </pre> * * <code>string pod = 2;</code> * * @return This builder for chaining. */ public Builder clearPod() { pod_ = getDefaultInstance().getPod(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * The name of the pod where the command is executed. * </pre> * * <code>string pod = 2;</code> * * @param value The bytes for pod to set. * @return This builder for chaining. */ public Builder setPodBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pod_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object podNamespace_ = ""; /** * * * <pre> * The namespace of the pod where the command is executed. * </pre> * * <code>string pod_namespace = 3;</code> * * @return The podNamespace. */ public java.lang.String getPodNamespace() { java.lang.Object ref = podNamespace_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); podNamespace_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The namespace of the pod where the command is executed. * </pre> * * <code>string pod_namespace = 3;</code> * * @return The bytes for podNamespace. */ public com.google.protobuf.ByteString getPodNamespaceBytes() { java.lang.Object ref = podNamespace_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); podNamespace_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The namespace of the pod where the command is executed. * </pre> * * <code>string pod_namespace = 3;</code> * * @param value The podNamespace to set. * @return This builder for chaining. */ public Builder setPodNamespace(java.lang.String value) { if (value == null) { throw new NullPointerException(); } podNamespace_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The namespace of the pod where the command is executed. * </pre> * * <code>string pod_namespace = 3;</code> * * @return This builder for chaining. */ public Builder clearPodNamespace() { podNamespace_ = getDefaultInstance().getPodNamespace(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * The namespace of the pod where the command is executed. * </pre> * * <code>string pod_namespace = 3;</code> * * @param value The bytes for podNamespace to set. * @return This builder for chaining. */ public Builder setPodNamespaceBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); podNamespace_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object error_ = ""; /** * * * <pre> * Error message. Empty if there was no error. * </pre> * * <code>string error = 4;</code> * * @return The error. */ public java.lang.String getError() { java.lang.Object ref = error_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); error_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Error message. Empty if there was no error. * </pre> * * <code>string error = 4;</code> * * @return The bytes for error. */ public com.google.protobuf.ByteString getErrorBytes() { java.lang.Object ref = error_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); error_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Error message. Empty if there was no error. * </pre> * * <code>string error = 4;</code> * * @param value The error to set. * @return This builder for chaining. */ public Builder setError(java.lang.String value) { if (value == null) { throw new NullPointerException(); } error_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Error message. Empty if there was no error. * </pre> * * <code>string error = 4;</code> * * @return This builder for chaining. */ public Builder clearError() { error_ = getDefaultInstance().getError(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Error message. Empty if there was no error. * </pre> * * <code>string error = 4;</code> * * @param value The bytes for error to set. * @return This builder for chaining. */ public Builder setErrorBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); error_ = 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.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse) } // @@protoc_insertion_point(class_scope:google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse) private static final com.google.cloud.orchestration.airflow.service.v1 .ExecuteAirflowCommandResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse(); } public static com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ExecuteAirflowCommandResponse> PARSER = new com.google.protobuf.AbstractParser<ExecuteAirflowCommandResponse>() { @java.lang.Override public ExecuteAirflowCommandResponse 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<ExecuteAirflowCommandResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ExecuteAirflowCommandResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1.ExecuteAirflowCommandResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
openjdk/jdk8
37,349
jaxws/src/share/jaxws_classes/com/sun/tools/internal/xjc/Options.java
/* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tools.internal.xjc; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import com.sun.codemodel.internal.CodeWriter; import com.sun.codemodel.internal.JPackage; import com.sun.codemodel.internal.JResourceFile; import com.sun.codemodel.internal.writer.FileCodeWriter; import com.sun.codemodel.internal.writer.PrologCodeWriter; import com.sun.istack.internal.tools.DefaultAuthenticator; import com.sun.org.apache.xml.internal.resolver.CatalogManager; import com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver; import com.sun.tools.internal.xjc.api.ClassNameAllocator; import com.sun.tools.internal.xjc.api.SpecVersion; import com.sun.tools.internal.xjc.generator.bean.field.FieldRendererFactory; import com.sun.tools.internal.xjc.model.Model; import com.sun.tools.internal.xjc.reader.Util; import com.sun.xml.internal.bind.api.impl.NameConverter; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; /** * Global options. * * <p> * This class stores invocation configuration for XJC. * The configuration in this class should be abstract enough so that * it could be parsed from both command-line or Ant. */ public class Options { /** If "-debug" is specified. */ public boolean debugMode; /** If the "-verbose" option is specified. */ public boolean verbose; /** If the "-quiet" option is specified. */ public boolean quiet; /** If the -readOnly option is specified. */ public boolean readOnly; /** No file header comment (to be more friendly with diff.) */ public boolean noFileHeader; /** When on, fixes getter/setter generation to match the Bean Introspection API */ public boolean enableIntrospection; /** When on, generates content property for types with multiple xs:any derived elements (which is supposed to be correct behaviour) */ public boolean contentForWildcard; /** Encoding to be used by generated java sources, null for platform default. */ public String encoding; /** * If true XML security features when parsing XML documents will be disabled. * The default value is false. * * Boolean * @since 2.2.6 */ public boolean disableXmlSecurity; /** * Check the source schemas with extra scrutiny. * The exact meaning depends on the schema language. */ public boolean strictCheck =true; /** * If -explicit-annotation option is specified. * <p> * This generates code that works around issues specific to 1.4 runtime. */ public boolean runtime14 = false; /** * If true, try to resolve name conflicts automatically by assigning mechanical numbers. */ public boolean automaticNameConflictResolution = false; /** * strictly follow the compatibility rules and reject schemas that * contain features from App. E.2, use vendor binding extensions */ public static final int STRICT = 1; /** * loosely follow the compatibility rules and allow the use of vendor * binding extensions */ public static final int EXTENSION = 2; /** * this switch determines how carefully the compiler will follow * the compatibility rules in the spec. Either <code>STRICT</code> * or <code>EXTENSION</code>. */ public int compatibilityMode = STRICT; public boolean isExtensionMode() { return compatibilityMode==EXTENSION; } private static final Logger logger = com.sun.xml.internal.bind.Util.getClassLogger(); /** * Generates output for the specified version of the runtime. */ public SpecVersion target = SpecVersion.LATEST; public Options() { try { Class.forName("javax.xml.bind.JAXBPermission"); } catch (ClassNotFoundException cnfe) { target = SpecVersion.V2_1; } } /** * Target directory when producing files. * <p> * This field is not used when XJC is driven through the XJC API. * Plugins that need to generate extra files should do so by using * {@link JPackage#addResourceFile(JResourceFile)}. */ public File targetDir = new File("."); /** * Actually stores {@link CatalogResolver}, but the field * type is made to {@link EntityResolver} so that XJC can be * used even if resolver.jar is not available in the classpath. */ public EntityResolver entityResolver = null; /** * Type of input schema language. One of the <code>SCHEMA_XXX</code> * constants. */ private Language schemaLanguage = null; /** * The -p option that should control the default Java package that * will contain the generated code. Null if unspecified. */ public String defaultPackage = null; /** * Similar to the -p option, but this one works with a lower priority, * and customizations overrides this. Used by JAX-RPC. */ public String defaultPackage2 = null; /** * Input schema files as a list of {@link InputSource}s. */ private final List<InputSource> grammars = new ArrayList<InputSource>(); private final List<InputSource> bindFiles = new ArrayList<InputSource>(); // Proxy setting. private String proxyHost = null; private String proxyPort = null; public String proxyAuth = null; /** * {@link Plugin}s that are enabled in this compilation. */ public final List<Plugin> activePlugins = new ArrayList<Plugin>(); /** * All discovered {@link Plugin}s. * This is lazily parsed, so that we can take '-cp' option into account. * * @see #getAllPlugins() */ private List<Plugin> allPlugins; /** * Set of URIs that plug-ins recognize as extension bindings. */ public final Set<String> pluginURIs = new HashSet<String>(); /** * This allocator has the final say on deciding the class name. */ public ClassNameAllocator classNameAllocator; /** * This switch controls whether or not xjc will generate package level annotations */ public boolean packageLevelAnnotations = true; /** * This {@link FieldRendererFactory} determines how the fields are generated. */ private FieldRendererFactory fieldRendererFactory = new FieldRendererFactory(); /** * Used to detect if two {@link Plugin}s try to overwrite {@link #fieldRendererFactory}. */ private Plugin fieldRendererFactoryOwner = null; /** * If this is non-null, we use this {@link NameConverter} over the one * given in the schema/binding. */ private NameConverter nameConverter = null; /** * Used to detect if two {@link Plugin}s try to overwrite {@link #nameConverter}. */ private Plugin nameConverterOwner = null; /** * Gets the active {@link FieldRendererFactory} that shall be used to build {@link Model}. * * @return always non-null. */ public FieldRendererFactory getFieldRendererFactory() { return fieldRendererFactory; } /** * Sets the {@link FieldRendererFactory}. * * <p> * This method is for plugins to call to set a custom {@link FieldRendererFactory}. * * @param frf * The {@link FieldRendererFactory} to be installed. Must not be null. * @param owner * Identifies the plugin that owns this {@link FieldRendererFactory}. * When two {@link Plugin}s try to call this method, this allows XJC * to report it as a user-friendly error message. * * @throws BadCommandLineException * If a conflit happens, this exception carries a user-friendly error * message, indicating a conflict. */ public void setFieldRendererFactory(FieldRendererFactory frf, Plugin owner) throws BadCommandLineException { // since this method is for plugins, make it bit more fool-proof than usual if(frf==null) throw new IllegalArgumentException(); if(fieldRendererFactoryOwner!=null) { throw new BadCommandLineException( Messages.format(Messages.FIELD_RENDERER_CONFLICT, fieldRendererFactoryOwner.getOptionName(), owner.getOptionName() )); } this.fieldRendererFactoryOwner = owner; this.fieldRendererFactory = frf; } /** * Gets the active {@link NameConverter} that shall be used to build {@link Model}. * * @return can be null, in which case it's up to the binding. */ public NameConverter getNameConverter() { return nameConverter; } /** * Sets the {@link NameConverter}. * * <p> * This method is for plugins to call to set a custom {@link NameConverter}. * * @param nc * The {@link NameConverter} to be installed. Must not be null. * @param owner * Identifies the plugin that owns this {@link NameConverter}. * When two {@link Plugin}s try to call this method, this allows XJC * to report it as a user-friendly error message. * * @throws BadCommandLineException * If a conflit happens, this exception carries a user-friendly error * message, indicating a conflict. */ public void setNameConverter(NameConverter nc, Plugin owner) throws BadCommandLineException { // since this method is for plugins, make it bit more fool-proof than usual if(nc==null) throw new IllegalArgumentException(); if(nameConverter!=null) { throw new BadCommandLineException( Messages.format(Messages.NAME_CONVERTER_CONFLICT, nameConverterOwner.getOptionName(), owner.getOptionName() )); } this.nameConverterOwner = owner; this.nameConverter = nc; } /** * Gets all the {@link Plugin}s discovered so far. * * <p> * A plugins are enumerated when this method is called for the first time, * by taking {@link #classpaths} into account. That means * "-cp plugin.jar" has to come before you specify options to enable it. */ public List<Plugin> getAllPlugins() { if(allPlugins==null) { allPlugins = new ArrayList<Plugin>(); ClassLoader ucl = getUserClassLoader(SecureLoader.getClassClassLoader(getClass())); allPlugins.addAll(Arrays.asList(findServices(Plugin.class,ucl))); } return allPlugins; } public Language getSchemaLanguage() { if( schemaLanguage==null) schemaLanguage = guessSchemaLanguage(); return schemaLanguage; } public void setSchemaLanguage(Language _schemaLanguage) { this.schemaLanguage = _schemaLanguage; } /** Input schema files. */ public InputSource[] getGrammars() { return grammars.toArray(new InputSource[grammars.size()]); } /** * Adds a new input schema. */ public void addGrammar( InputSource is ) { grammars.add(absolutize(is)); } private InputSource fileToInputSource( File source ) { try { String url = source.toURL().toExternalForm(); return new InputSource(Util.escapeSpace(url)); } catch (MalformedURLException e) { return new InputSource(source.getPath()); } } public void addGrammar( File source ) { addGrammar(fileToInputSource(source)); } /** * Recursively scan directories and add all XSD files in it. */ public void addGrammarRecursive( File dir ) { addRecursive(dir,".xsd",grammars); } private void addRecursive( File dir, String suffix, List<InputSource> result ) { File[] files = dir.listFiles(); if(files==null) return; // work defensively for( File f : files ) { if(f.isDirectory()) addRecursive(f,suffix,result); else if(f.getPath().endsWith(suffix)) result.add(absolutize(fileToInputSource(f))); } } private InputSource absolutize(InputSource is) { // absolutize all the system IDs in the input, so that we can map system IDs to DOM trees. try { URL baseURL = new File(".").getCanonicalFile().toURL(); is.setSystemId( new URL(baseURL,is.getSystemId()).toExternalForm() ); } catch( IOException e ) { logger.log(Level.FINE, "{0}, {1}", new Object[]{is.getSystemId(), e.getLocalizedMessage()}); } return is; } /** Input external binding files. */ public InputSource[] getBindFiles() { return bindFiles.toArray(new InputSource[bindFiles.size()]); } /** * Adds a new binding file. */ public void addBindFile( InputSource is ) { bindFiles.add(absolutize(is)); } /** * Adds a new binding file. */ public void addBindFile( File bindFile ) { bindFiles.add(fileToInputSource(bindFile)); } /** * Recursively scan directories and add all ".xjb" files in it. */ public void addBindFileRecursive( File dir ) { addRecursive(dir,".xjb",bindFiles); } public final List<URL> classpaths = new ArrayList<URL>(); /** * Gets a classLoader that can load classes specified via the * -classpath option. */ public ClassLoader getUserClassLoader( ClassLoader parent ) { if (classpaths.isEmpty()) return parent; return new URLClassLoader( classpaths.toArray(new URL[classpaths.size()]),parent); } /** * Parses an option <code>args[i]</code> and return * the number of tokens consumed. * * @return * 0 if the argument is not understood. Returning 0 * will let the caller report an error. * @exception BadCommandLineException * If the callee wants to provide a custom message for an error. */ public int parseArgument( String[] args, int i ) throws BadCommandLineException { if (args[i].equals("-classpath") || args[i].equals("-cp")) { String a = requireArgument(args[i], args, ++i); for (String p : a.split(File.pathSeparator)) { File file = new File(p); try { classpaths.add(file.toURL()); } catch (MalformedURLException e) { throw new BadCommandLineException( Messages.format(Messages.NOT_A_VALID_FILENAME,file),e); } } return 2; } if (args[i].equals("-d")) { targetDir = new File(requireArgument("-d",args,++i)); if( !targetDir.exists() ) throw new BadCommandLineException( Messages.format(Messages.NON_EXISTENT_DIR,targetDir)); return 2; } if (args[i].equals("-readOnly")) { readOnly = true; return 1; } if (args[i].equals("-p")) { defaultPackage = requireArgument("-p",args,++i); if(defaultPackage.length()==0) { // user specified default package // there won't be any package to annotate, so disable them // automatically as a usability feature packageLevelAnnotations = false; } return 2; } if (args[i].equals("-debug")) { debugMode = true; verbose = true; return 1; } if (args[i].equals("-nv")) { strictCheck = false; return 1; } if( args[i].equals("-npa")) { packageLevelAnnotations = false; return 1; } if( args[i].equals("-no-header")) { noFileHeader = true; return 1; } if (args[i].equals("-verbose")) { verbose = true; return 1; } if (args[i].equals("-quiet")) { quiet = true; return 1; } if (args[i].equals("-XexplicitAnnotation")) { runtime14 = true; return 1; } if (args[i].equals("-enableIntrospection")) { enableIntrospection = true; return 1; } if (args[i].equals("-disableXmlSecurity")) { disableXmlSecurity = true; return 1; } if (args[i].equals("-contentForWildcard")) { contentForWildcard = true; return 1; } if (args[i].equals("-XautoNameResolution")) { automaticNameConflictResolution = true; return 1; } if (args[i].equals("-b")) { addFile(requireArgument("-b",args,++i),bindFiles,".xjb"); return 2; } if (args[i].equals("-dtd")) { schemaLanguage = Language.DTD; return 1; } if (args[i].equals("-relaxng")) { schemaLanguage = Language.RELAXNG; return 1; } if (args[i].equals("-relaxng-compact")) { schemaLanguage = Language.RELAXNG_COMPACT; return 1; } if (args[i].equals("-xmlschema")) { schemaLanguage = Language.XMLSCHEMA; return 1; } if (args[i].equals("-wsdl")) { schemaLanguage = Language.WSDL; return 1; } if (args[i].equals("-extension")) { compatibilityMode = EXTENSION; return 1; } if (args[i].equals("-target")) { String token = requireArgument("-target",args,++i); target = SpecVersion.parse(token); if(target==null) throw new BadCommandLineException(Messages.format(Messages.ILLEGAL_TARGET_VERSION,token)); return 2; } if (args[i].equals("-httpproxyfile")) { if (i == args.length - 1 || args[i + 1].startsWith("-")) { throw new BadCommandLineException( Messages.format(Messages.MISSING_PROXYFILE)); } File file = new File(args[++i]); if(!file.exists()) { throw new BadCommandLineException( Messages.format(Messages.NO_SUCH_FILE,file)); } try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); parseProxy(in.readLine()); in.close(); } catch (IOException e) { throw new BadCommandLineException( Messages.format(Messages.FAILED_TO_PARSE,file,e.getMessage()),e); } return 2; } if (args[i].equals("-httpproxy")) { if (i == args.length - 1 || args[i + 1].startsWith("-")) { throw new BadCommandLineException( Messages.format(Messages.MISSING_PROXY)); } parseProxy(args[++i]); return 2; } if (args[i].equals("-host")) { proxyHost = requireArgument("-host",args,++i); return 2; } if (args[i].equals("-port")) { proxyPort = requireArgument("-port",args,++i); return 2; } if( args[i].equals("-catalog") ) { // use Sun's "XML Entity and URI Resolvers" by Norman Walsh // to resolve external entities. // http://www.sun.com/xml/developers/resolver/ File catalogFile = new File(requireArgument("-catalog",args,++i)); try { addCatalog(catalogFile); } catch (IOException e) { throw new BadCommandLineException( Messages.format(Messages.FAILED_TO_PARSE,catalogFile,e.getMessage()),e); } return 2; } if( args[i].equals("-Xtest-class-name-allocator") ) { classNameAllocator = new ClassNameAllocator() { public String assignClassName(String packageName, String className) { System.out.printf("assignClassName(%s,%s)\n",packageName,className); return className+"_Type"; } }; return 1; } if (args[i].equals("-encoding")) { encoding = requireArgument("-encoding", args, ++i); try { if (!Charset.isSupported(encoding)) { throw new BadCommandLineException( Messages.format(Messages.UNSUPPORTED_ENCODING, encoding)); } } catch (IllegalCharsetNameException icne) { throw new BadCommandLineException( Messages.format(Messages.UNSUPPORTED_ENCODING, encoding)); } return 2; } // see if this is one of the extensions for( Plugin plugin : getAllPlugins() ) { try { if( ('-'+plugin.getOptionName()).equals(args[i]) ) { activePlugins.add(plugin); plugin.onActivated(this); pluginURIs.addAll(plugin.getCustomizationURIs()); // give the plugin a chance to parse arguments to this option. // this is new in 2.1, and due to the backward compatibility reason, // if plugin didn't understand it, we still return 1 to indicate // that this option is consumed. int r = plugin.parseArgument(this,args,i); if(r!=0) return r; else return 1; } int r = plugin.parseArgument(this,args,i); if(r!=0) return r; } catch (IOException e) { throw new BadCommandLineException(e.getMessage(),e); } } return 0; // unrecognized } private void parseProxy(String text) throws BadCommandLineException { int i = text.lastIndexOf('@'); int j = text.lastIndexOf(':'); if (i > 0) { proxyAuth = text.substring(0, i); if (j > i) { proxyHost = text.substring(i + 1, j); proxyPort = text.substring(j + 1); } else { proxyHost = text.substring(i + 1); proxyPort = "80"; } } else { //no auth info if (j < 0) { //no port proxyHost = text; proxyPort = "80"; } else { proxyHost = text.substring(0, j); proxyPort = text.substring(j + 1); } } try { Integer.valueOf(proxyPort); } catch (NumberFormatException e) { throw new BadCommandLineException(Messages.format(Messages.ILLEGAL_PROXY,text)); } } /** * Obtains an operand and reports an error if it's not there. */ public String requireArgument(String optionName, String[] args, int i) throws BadCommandLineException { if (i == args.length || args[i].startsWith("-")) { throw new BadCommandLineException( Messages.format(Messages.MISSING_OPERAND,optionName)); } return args[i]; } /** * Parses a token to a file (or a set of files) * and add them as {@link InputSource} to the specified list. * * @param suffix * If the given token is a directory name, we do a recusive search * and find all files that have the given suffix. */ private void addFile(String name, List<InputSource> target, String suffix) throws BadCommandLineException { Object src; try { src = Util.getFileOrURL(name); } catch (IOException e) { throw new BadCommandLineException( Messages.format(Messages.NOT_A_FILE_NOR_URL,name)); } if(src instanceof URL) { target.add(absolutize(new InputSource(Util.escapeSpace(((URL)src).toExternalForm())))); } else { File fsrc = (File)src; if(fsrc.isDirectory()) { addRecursive(fsrc,suffix,target); } else { target.add(absolutize(fileToInputSource(fsrc))); } } } /** * Adds a new catalog file. */ public void addCatalog(File catalogFile) throws IOException { if(entityResolver==null) { CatalogManager.getStaticManager().setIgnoreMissingProperties(true); entityResolver = new CatalogResolver(true); } ((CatalogResolver)entityResolver).getCatalog().parseCatalog(catalogFile.getPath()); } /** * Parses arguments and fill fields of this object. * * @exception BadCommandLineException * thrown when there's a problem in the command-line arguments */ public void parseArguments( String[] args ) throws BadCommandLineException { for (int i = 0; i < args.length; i++) { if(args[i].length()==0) throw new BadCommandLineException(); if (args[i].charAt(0) == '-') { int j = parseArgument(args,i); if(j==0) throw new BadCommandLineException( Messages.format(Messages.UNRECOGNIZED_PARAMETER, args[i])); i += (j-1); } else { if(args[i].endsWith(".jar")) scanEpisodeFile(new File(args[i])); else addFile(args[i],grammars,".xsd"); } } // configure proxy if (proxyHost != null || proxyPort != null) { if (proxyHost != null && proxyPort != null) { System.setProperty("http.proxyHost", proxyHost); System.setProperty("http.proxyPort", proxyPort); System.setProperty("https.proxyHost", proxyHost); System.setProperty("https.proxyPort", proxyPort); } else if (proxyHost == null) { throw new BadCommandLineException( Messages.format(Messages.MISSING_PROXYHOST)); } else { throw new BadCommandLineException( Messages.format(Messages.MISSING_PROXYPORT)); } if (proxyAuth != null) { DefaultAuthenticator.getAuthenticator().setProxyAuth(proxyAuth); } } if (grammars.isEmpty()) throw new BadCommandLineException( Messages.format(Messages.MISSING_GRAMMAR)); if( schemaLanguage==null ) schemaLanguage = guessSchemaLanguage(); // if(target==SpecVersion.V2_2 && !isExtensionMode()) // throw new BadCommandLineException( // "Currently 2.2 is still not finalized yet, so using it requires the -extension switch." + // "NOTE THAT 2.2 SPEC MAY CHANGE BEFORE IT BECOMES FINAL."); if(pluginLoadFailure!=null) throw new BadCommandLineException( Messages.format(Messages.PLUGIN_LOAD_FAILURE,pluginLoadFailure)); } /** * Finds the <tt>META-INF/sun-jaxb.episode</tt> file to add as a binding customization. */ public void scanEpisodeFile(File jar) throws BadCommandLineException { try { URLClassLoader ucl = new URLClassLoader(new URL[]{jar.toURL()}); Enumeration<URL> resources = ucl.findResources("META-INF/sun-jaxb.episode"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); addBindFile(new InputSource(url.toExternalForm())); } } catch (IOException e) { throw new BadCommandLineException( Messages.format(Messages.FAILED_TO_LOAD,jar,e.getMessage()), e); } } /** * Guesses the schema language. */ public Language guessSchemaLanguage() { // otherwise, use the file extension. // not a good solution, but very easy. if ((grammars != null) && (grammars.size() > 0)) { String name = grammars.get(0).getSystemId().toLowerCase(); if (name.endsWith(".rng")) return Language.RELAXNG; if (name.endsWith(".rnc")) return Language.RELAXNG_COMPACT; if (name.endsWith(".dtd")) return Language.DTD; if (name.endsWith(".wsdl")) return Language.WSDL; } // by default, assume XML Schema return Language.XMLSCHEMA; } /** * Creates a configured CodeWriter that produces files into the specified directory. */ public CodeWriter createCodeWriter() throws IOException { return createCodeWriter(new FileCodeWriter( targetDir, readOnly, encoding )); } /** * Creates a configured CodeWriter that produces files into the specified directory. */ public CodeWriter createCodeWriter( CodeWriter core ) { if(noFileHeader) return core; return new PrologCodeWriter( core,getPrologComment() ); } /** * Gets the string suitable to be used as the prolog comment baked into artifacts. * This is the string like "This file was generated by the JAXB RI on YYYY/mm/dd..." */ public String getPrologComment() { // generate format syntax: <date> 'at' <time> String format = Messages.format(Messages.DATE_FORMAT) + " '" + Messages.format(Messages.AT) + "' " + Messages.format(Messages.TIME_FORMAT); SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.ENGLISH); return Messages.format( Messages.FILE_PROLOG_COMMENT, dateFormat.format(new Date())); } /** * If a plugin failed to load, report. */ private static String pluginLoadFailure; /** * Looks for all "META-INF/services/[className]" files and * create one instance for each class name found inside this file. */ private static <T> T[] findServices( Class<T> clazz, ClassLoader classLoader ) { // if true, print debug output final boolean debug = com.sun.tools.internal.xjc.util.Util.getSystemProperty(Options.class,"findServices")!=null; // if we are running on Mustang or Dolphin, use ServiceLoader // so that we can take advantage of JSR-277 module system. try { Class<?> serviceLoader = Class.forName("java.util.ServiceLoader"); if(debug) System.out.println("Using java.util.ServiceLoader"); Iterable<T> itr = (Iterable<T>)serviceLoader.getMethod("load",Class.class,ClassLoader.class).invoke(null,clazz,classLoader); List<T> r = new ArrayList<T>(); for (T t : itr) r.add(t); return r.toArray((T[])Array.newInstance(clazz,r.size())); } catch (ClassNotFoundException e) { // fall through } catch (IllegalAccessException e) { Error x = new IllegalAccessError(); x.initCause(e); throw x; } catch (InvocationTargetException e) { Throwable x = e.getTargetException(); if (x instanceof RuntimeException) throw (RuntimeException) x; if (x instanceof Error) throw (Error) x; throw new Error(x); } catch (NoSuchMethodException e) { Error x = new NoSuchMethodError(); x.initCause(e); throw x; } String serviceId = "META-INF/services/" + clazz.getName(); // used to avoid creating the same instance twice Set<String> classNames = new HashSet<String>(); if(debug) { System.out.println("Looking for "+serviceId+" for add-ons"); } // try to find services in CLASSPATH try { Enumeration<URL> e = classLoader.getResources(serviceId); if(e==null) return (T[])Array.newInstance(clazz,0); ArrayList<T> a = new ArrayList<T>(); while(e.hasMoreElements()) { URL url = e.nextElement(); BufferedReader reader=null; if(debug) { System.out.println("Checking "+url+" for an add-on"); } try { reader = new BufferedReader(new InputStreamReader(url.openStream())); String impl; while((impl = reader.readLine())!=null ) { // try to instanciate the object impl = impl.trim(); if(classNames.add(impl)) { Class implClass = classLoader.loadClass(impl); if(!clazz.isAssignableFrom(implClass)) { pluginLoadFailure = impl+" is not a subclass of "+clazz+". Skipping"; if(debug) System.out.println(pluginLoadFailure); continue; } if(debug) { System.out.println("Attempting to instanciate "+impl); } a.add(clazz.cast(implClass.newInstance())); } } reader.close(); } catch( Exception ex ) { // let it go. StringWriter w = new StringWriter(); ex.printStackTrace(new PrintWriter(w)); pluginLoadFailure = w.toString(); if(debug) { System.out.println(pluginLoadFailure); } if( reader!=null ) { try { reader.close(); } catch( IOException ex2 ) { // ignore } } } } return a.toArray((T[])Array.newInstance(clazz,a.size())); } catch( Throwable e ) { // ignore any error StringWriter w = new StringWriter(); e.printStackTrace(new PrintWriter(w)); pluginLoadFailure = w.toString(); if(debug) { System.out.println(pluginLoadFailure); } return (T[])Array.newInstance(clazz,0); } } // this is a convenient place to expose the build version to xjc plugins public static String getBuildID() { return Messages.format(Messages.BUILD_ID); } public static String normalizeSystemId(String systemId) { try { systemId = new URI(systemId).normalize().toString(); } catch (URISyntaxException e) { // leave the system ID untouched. In my experience URI is often too strict } return systemId; } }
apache/derby
37,331
java/org.apache.derby.tests/org/apache/derbyTesting/system/oe/direct/Standard.java
/* * * Derby - Class org.apache.derbyTesting.system.oe.direct.Standard * * 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.derbyTesting.system.oe.direct; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.List; import org.apache.derbyTesting.system.oe.client.Display; import org.apache.derbyTesting.system.oe.client.Operations; import org.apache.derbyTesting.system.oe.model.Customer; import org.apache.derbyTesting.system.oe.model.District; import org.apache.derbyTesting.system.oe.model.Order; import org.apache.derbyTesting.system.oe.model.OrderLine; import org.apache.derbyTesting.system.oe.model.Warehouse; /** * Implement the transactions following the TPC-C specification * using client side prepared statements. Thus all the logic * is contained within this class. The client, through this * object, holds onto PreparedStatements for all the SQL * for its lifetime. * <P> * This standard implementation is based upon the sample * programs in the appendix of the TPC-C specification. * <P> * More specific direct (client side) implementations * could extend this class overriding methods as needed. * <P> * Object is single threaded so it re-uses objects * where possible to avoid the garbage collection * due to the application affecting the results * too much since the purpose of the framework * is to test Derby's performance. */ public class Standard extends StatementHelper implements Operations { /* * Objects for re-use within the transactions */ private final Customer customer = new Customer(); private final Warehouse warehouse = new Warehouse(); private final District district = new District(); private final Order order = new Order(); private final List<Object> nameList = new ArrayList<Object>(); /** * Create an instance of this implementation. * Connection will be set to non auto commit * mode and SERIZIALZABLE isolation. */ public Standard(Connection conn) throws SQLException { super(conn, false, Connection.TRANSACTION_SERIALIZABLE); } /** * Return an Operations implementation based upon * Standard with a single difference. In this implementation * the reset() executed after each PreparedStatement execute * does nothing. Sees if there is any performance impact * of explicitly closing each ResultSet and clearing the * parameters. * <P> * Each ResultSet will be closed implicitly either at commit * time or at the next execution of the same PreparedStatement object. */ public static Operations noReset(final Connection conn) throws SQLException { return new Standard(conn) { protected void reset(PreparedStatement ps) {} }; } /** * Stock Level transaction. * Described in section 2.8.2. * SQL based upon sample prgram in appendix A.5. */ public void stockLevel(Display display, Object displayData, short w, short d, int threshold) throws Exception { int isolation = conn.getTransactionIsolation(); int lowStock; try { try { conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); PreparedStatement sl1 = prepareStatement( "SELECT D_NEXT_O_ID FROM DISTRICT WHERE D_W_ID = ? AND D_ID = ?"); PreparedStatement sl2 = prepareStatement( "SELECT COUNT(DISTINCT(S_I_ID)) AS LOW_STOCK FROM ORDERLINE, STOCK " + "WHERE OL_W_ID = ? AND OL_D_ID = ? " + "AND OL_O_ID < ? AND OL_O_ID >= ? " + "AND S_W_ID = ? AND S_I_ID = OL_I_ID AND S_QUANTITY < ?"); sl1.setShort(1, w); sl1.setShort(2, d); sl2.setShort(1, w); sl2.setShort(2, d); sl2.setShort(5, w); sl2.setInt(6, threshold); ResultSet rs = sl1.executeQuery(); rs.next(); int nextOrder = rs.getInt("D_NEXT_O_ID"); reset(sl1); sl2.setInt(3, nextOrder); sl2.setInt(4, nextOrder - 20); rs = sl2.executeQuery(); rs.next(); lowStock = rs.getInt("LOW_STOCK"); reset(sl2); conn.commit(); } finally { conn.setTransactionIsolation(isolation); } } catch (SQLException sqle) { conn.rollback(); conn.setTransactionIsolation(isolation); throw sqle; } if (display != null) display.displayStockLevel(displayData, w, d, threshold, lowStock); } /** * Order status by customer last name. * Based up the example SQL queries in appendix A.3 */ public void orderStatus(Display display, Object displayData, short w, short d, String customerLast) throws Exception { PreparedStatement osCustomerByName = prepareStatement( "SELECT C_ID, C_BALANCE, C_FIRST, C_MIDDLE " + "FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_LAST = ? " + "ORDER BY C_FIRST"); try { osCustomerByName.setShort(1, w); osCustomerByName.setShort(2, d); osCustomerByName.setString(3, customerLast); ResultSet rs = osCustomerByName.executeQuery(); nameList.clear(); while (rs.next()) { Customer customer = new Customer(); customer.setWarehouse(w); customer.setDistrict(d); customer.setLast(customerLast); customer.setId(rs.getInt("C_ID")); customer.setBalance(rs.getString("C_BALANCE")); customer.setFirst(rs.getString("C_FIRST")); customer.setMiddle(rs.getString("C_MIDDLE")); nameList.add(customer); } reset(osCustomerByName); if (nameList.isEmpty()) throw new SQLException("Order Status by name - no matching customer " + customerLast); // Customer to use is midpoint (with round up) (see 2.6.2.2) int mid = nameList.size()/2; if (mid != 0) { if (nameList.size()%2 == 1) mid++; } Customer customer = (Customer) nameList.get(mid); nameList.clear(); getOrderStatusForCustomer(display, displayData, true, customer); } catch (SQLException e) { conn.rollback(); throw e; } } /** * Order status by customer identifier. * Based up the example SQL queries in appendix A.3 */ public void orderStatus(Display display, Object displayData, short w, short d, int c) throws Exception { PreparedStatement osCustomerById = prepareStatement( "SELECT C_BALANCE, C_FIRST, C_MIDDLE, C_LAST " + "FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?"); customer.clear(); customer.setWarehouse(w); customer.setDistrict(d); customer.setId(c); try { // Get the customer information osCustomerById.setShort(1, w); osCustomerById.setShort(2, d); osCustomerById.setInt(3, c); ResultSet rs = osCustomerById.executeQuery(); rs.next(); customer.setBalance(rs.getString("C_BALANCE")); customer.setFirst(rs.getString("C_FIRST")); customer.setMiddle(rs.getString("C_MIDDLE")); customer.setLast(rs.getString("C_LAST")); reset(osCustomerById); getOrderStatusForCustomer(display, displayData, false, customer); } catch (SQLException e) { conn.rollback(); throw e; } } /** * Fetch the order details having obtained the customer information * and display it. */ private void getOrderStatusForCustomer(Display display, Object displayData, boolean byName, Customer customer) throws Exception { PreparedStatement osLastOrderNumber = prepareStatement( "SELECT MAX(O_ID) AS LAST_ORDER FROM ORDERS " + "WHERE O_W_ID = ? AND O_D_ID = ? AND O_C_ID = ?"); PreparedStatement osOrderDetails = prepareStatement( "SELECT O_ENTRY_D, O_CARRIER_ID, O_OL_CNT " + "FROM ORDERS WHERE O_W_ID = ? AND O_D_ID = ? AND O_ID = ?"); PreparedStatement osOrderLineItems = prepareStatement( "SELECT OL_I_ID, OL_SUPPLY_W_ID, OL_QUANTITY, OL_AMOUNT, " + "OL_DELIVERY_D FROM ORDERLINE " + "WHERE OL_W_ID = ? AND OL_D_ID = ? AND OL_O_ID = ?"); order.clear(); order.setWarehouse(customer.getWarehouse()); order.setDistrict(customer.getDistrict()); // Find the most recent order number for this customer osLastOrderNumber.setShort(1, customer.getWarehouse()); osLastOrderNumber.setShort(2, customer.getDistrict()); osLastOrderNumber.setInt(3, customer.getId()); ResultSet rs = osLastOrderNumber.executeQuery(); rs.next(); order.setId(rs.getInt("LAST_ORDER")); reset(osLastOrderNumber); // Details for the order. osOrderDetails.setShort(1, customer.getWarehouse()); osOrderDetails.setShort(2, customer.getDistrict()); osOrderDetails.setInt(3, order.getId()); rs = osOrderDetails.executeQuery(); rs.next(); order.setEntry_d(rs.getTimestamp("O_ENTRY_D")); order.setCarrier_id((Integer) rs.getObject("O_CARRIER_ID")); order.setOl_cnt(rs.getInt("O_OL_CNT")); rs.close(); OrderLine[] lineItems = new OrderLine[order.getOl_cnt()]; osOrderLineItems.setShort(1, order.getWarehouse()); osOrderLineItems.setShort(2, order.getDistrict()); osOrderLineItems.setInt(3, order.getId()); rs = osOrderLineItems.executeQuery(); int oli = 0; while (rs.next()) { OrderLine ol = new OrderLine(); ol.setI_id(rs.getInt("OL_I_ID")); ol.setSupply_w_id(rs.getShort("OL_SUPPLY_W_ID")); ol.setQuantity(rs.getShort("OL_QUANTITY")); ol.setAmount(rs.getString("OL_AMOUNT")); ol.setDelivery_d( rs.getTimestamp("OL_DELIVERY_D")); lineItems[oli++] = ol; } rs.close(); conn.commit(); if (display != null) display.displayOrderStatus(displayData, byName, customer, order, lineItems); } /** * Payment by customer last name. * Section 2.5.2 * The CUSTOMER row will be fetched and then updated. * This is due to the need to select the specific customer * first based upon last name (which will actually fetch and * hence lock a number of customers). */ public void payment(Display display, Object displayData, short w, short d, short cw, short cd, String customerLast, String amount) throws Exception { PreparedStatement pyCustomerByName = prepareStatement( "SELECT C_ID " + "FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_LAST = ? " + "ORDER BY C_FIRST"); // Since so much data is needed for the payment transaction // from the customer we don't fill it in as we select the // correct customer. Instead we just fetch the identifier // and then execute a payment by identifier. try { pyCustomerByName.setShort(1, cw); pyCustomerByName.setShort(2, cd); pyCustomerByName.setString(3, customerLast); ResultSet rs = pyCustomerByName.executeQuery(); nameList.clear(); while (rs.next()) { nameList.add(rs.getObject("C_ID")); } reset(pyCustomerByName); if (nameList.isEmpty()) throw new SQLException("Payment by name - no matching customer " + customerLast); // Customer to use is midpoint (with round up) (see 2.5.2.2) int mid = nameList.size()/2; if (mid != 0) { if (nameList.size()%2 == 1) mid++; } int c = ((Integer) nameList.get(mid)).intValue(); paymentById(display, displayData, w, d, cw, cd, c, amount); } catch (SQLException e) { conn.rollback(); throw e; } if (display != null) ; } /** * Payment by customer identifier. * Section 2.5.2. * The CUSTOMER row is update and then fetched. * */ public void payment(Display display, Object displayData, short w, short d, short cw, short cd, int c, final String amount) throws Exception { try { paymentById(display, displayData, w, d, cw, cd, c, amount); } catch (SQLException e) { conn.rollback(); throw e; } if (display != null) ; } private void paymentById(Display display, Object displayData, short w, short d, short cw, short cd, int c, final String amount) throws Exception { PreparedStatement pyCustomerPayment = prepareStatement( "UPDATE CUSTOMER SET C_BALANCE = C_BALANCE - ?, " + "C_YTD_PAYMENT = C_YTD_PAYMENT + ?, " + "C_PAYMENT_CNT = C_PAYMENT_CNT + 1 " + "WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?"); PreparedStatement pyCustomerInfoId = prepareStatement( "SELECT C_FIRST, C_MIDDLE, C_LAST, C_BALANCE, " + "C_STREET_1, C_STREET_2, C_CITY, C_STATE, C_ZIP, " + "C_PHONE, C_SINCE, C_CREDIT, C_CREDIT_LIM, C_DISCOUNT " + "FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?"); PreparedStatement pyCustomerUpdateBadCredit = prepareStatement( "UPDATE CUSTOMER SET C_DATA = " + " BAD_CREDIT_DATA(C_DATA, ?, ?, C_W_ID, C_W_ID, C_ID, ?) " + "WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?"); PreparedStatement pyCustomerGetData = prepareStatement( "SELECT SUBSTR(C_DATA, 1, 200) AS C_DATA_200 " + "FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?"); PreparedStatement pyDistrictUpdate = prepareStatement( "UPDATE DISTRICT SET D_YTD = D_YTD + ? WHERE D_W_ID = ? AND D_ID = ?"); PreparedStatement pyDistrictInfo = prepareStatement( "SELECT D_NAME, D_STREET_1, D_STREET_2, D_CITY, D_STATE, D_ZIP FROM DISTRICT WHERE D_W_ID = ? AND D_ID = ? "); PreparedStatement pyWarehouseUpdate = prepareStatement( "UPDATE WAREHOUSE SET W_YTD = W_YTD + ? WHERE W_ID = ?"); PreparedStatement pyWarehouseInfo = prepareStatement( "SELECT W_NAME, W_STREET_1, W_STREET_2, W_CITY, W_STATE, W_ZIP " + "FROM WAREHOUSE WHERE W_ID = ?"); PreparedStatement pyHistory = prepareStatement( "INSERT INTO HISTORY(H_C_ID, H_C_D_ID, H_C_W_ID, H_D_ID, H_W_ID, " + "H_DATE, H_AMOUNT, H_DATA) " + "VALUES (?, ?, ?, ?, ?, CURRENT TIMESTAMP, ?, ?)"); Customer customer = new Customer(); customer.setWarehouse(cw); customer.setDistrict(cd); customer.setId(c); // Update the customer assuming that they have good credit pyCustomerPayment.setString(1, amount); pyCustomerPayment.setString(2, amount); pyCustomerPayment.setShort(3, cw); pyCustomerPayment.setShort(4, cd); pyCustomerPayment.setInt(5, c); pyCustomerPayment.executeUpdate(); // Get the customer information pyCustomerInfoId.setShort(1, cw); pyCustomerInfoId.setShort(2, cd); pyCustomerInfoId.setInt(3, c); ResultSet rs = pyCustomerInfoId.executeQuery(); rs.next(); customer.setFirst(rs.getString("C_FIRST")); customer.setMiddle(rs.getString("C_MIDDLE")); customer.setLast(rs.getString("C_LAST")); customer.setBalance(rs.getString("C_BALANCE")); customer.setAddress(getAddress(rs, "C_STREET_1")); customer.setPhone(rs.getString("C_PHONE")); customer.setSince(rs.getTimestamp("C_SINCE")); customer.setCredit(rs.getString("C_CREDIT")); customer.setCredit_lim(rs.getString("C_CREDIT_LIM")); customer.setDiscount(rs.getString("C_DISCOUNT")); reset(pyCustomerInfoId); // additional work for bad credit customers. if ("BC".equals(customer.getCredit())) { pyCustomerUpdateBadCredit.setShort(1, w); pyCustomerUpdateBadCredit.setShort(2, d); pyCustomerUpdateBadCredit.setString(3, amount); pyCustomerUpdateBadCredit.setShort(4, cw); pyCustomerUpdateBadCredit.setShort(5, cd); pyCustomerUpdateBadCredit.setInt(6, c); pyCustomerUpdateBadCredit.executeUpdate(); reset(pyCustomerUpdateBadCredit); // Need to display the first 200 characters // of C_DATA information if the customer has // bad credit. pyCustomerGetData.setShort(1, cw); pyCustomerGetData.setShort(2, cd); pyCustomerGetData.setInt(3, c); rs = pyCustomerGetData.executeQuery(); rs.next(); customer.setData(rs.getString("C_DATA_200")); reset(pyCustomerGetData); } district.clear(); district.setWarehouse(w); district.setId(d); // Update DISTRICT pyDistrictUpdate.setString(1, amount); pyDistrictUpdate.setShort(2, w); pyDistrictUpdate.setShort(3, d); pyDistrictUpdate.executeUpdate(); reset(pyDistrictUpdate); // Get the required information from DISTRICT pyDistrictInfo.setShort(1, w); pyDistrictInfo.setShort(2, d); rs = pyDistrictInfo.executeQuery(); rs.next(); district.setName(rs.getString("D_NAME")); district.setAddress(getAddress(rs, "D_STREET_1")); reset(pyDistrictInfo); warehouse.clear(); warehouse.setId(w); // Update WAREHOUSE pyWarehouseUpdate.setString(1, amount); pyWarehouseUpdate.setShort(2, w); pyWarehouseUpdate.executeUpdate(); reset(pyWarehouseUpdate); // Get the required information from WAREHOUSE pyWarehouseInfo.setShort(1, w); rs = pyWarehouseInfo.executeQuery(); rs.next(); warehouse.setName(rs.getString("W_NAME")); warehouse.setAddress(getAddress(rs, "W_STREET_1")); reset(pyWarehouseInfo); // Insert HISTORY row pyHistory.setInt(1, c); pyHistory.setShort(2, cd); pyHistory.setShort(3, cw); pyHistory.setShort(4, d); pyHistory.setShort(5, w); pyHistory.setString(6, amount); StringBuffer hData = new StringBuffer(24); hData.append(warehouse.getName()); hData.append(" "); hData.append(district.getName()); pyHistory.setString(7, hData.toString()); pyHistory.executeUpdate(); reset(pyHistory); conn.commit(); } private static final String[] STOCK_INFO = { "SELECT S_QUANTITY, S_DIST_01, S_DATA FROM STOCK WHERE S_I_ID = ? AND S_W_ID = ?", "SELECT S_QUANTITY, S_DIST_02, S_DATA FROM STOCK WHERE S_I_ID = ? AND S_W_ID = ?", "SELECT S_QUANTITY, S_DIST_03, S_DATA FROM STOCK WHERE S_I_ID = ? AND S_W_ID = ?", "SELECT S_QUANTITY, S_DIST_04, S_DATA FROM STOCK WHERE S_I_ID = ? AND S_W_ID = ?", "SELECT S_QUANTITY, S_DIST_05, S_DATA FROM STOCK WHERE S_I_ID = ? AND S_W_ID = ?", "SELECT S_QUANTITY, S_DIST_06, S_DATA FROM STOCK WHERE S_I_ID = ? AND S_W_ID = ?", "SELECT S_QUANTITY, S_DIST_07, S_DATA FROM STOCK WHERE S_I_ID = ? AND S_W_ID = ?", "SELECT S_QUANTITY, S_DIST_08, S_DATA FROM STOCK WHERE S_I_ID = ? AND S_W_ID = ?", "SELECT S_QUANTITY, S_DIST_09, S_DATA FROM STOCK WHERE S_I_ID = ? AND S_W_ID = ?", "SELECT S_QUANTITY, S_DIST_10, S_DATA FROM STOCK WHERE S_I_ID = ? AND S_W_ID = ?", }; public void newOrder(Display display, Object displayData, short w, short d, int c, int[] items, short[] quantities, short[] supplyW) throws Exception { // This transaction is subject to deadlocks since the // stock table is read and then updated, and multiple // stock items are read and updated in a random order. // to avoid the deadlocks, the items are sorted here. // If some engine did not require sorting then it could // provide a different implementation of this class with // the sort method a no-op. sortOrderItems(items, quantities, supplyW); try { // Get the warehouse tax PreparedStatement psWarehouseTax = prepareStatement( "SELECT W_TAX FROM WAREHOUSE WHERE W_ID = ?"); psWarehouseTax.setShort(1, w); ResultSet rs = psWarehouseTax.executeQuery(); rs.next(); BigDecimal warehouseTax = (BigDecimal) rs.getObject(1); reset(psWarehouseTax); // Get the district tax and order number including the update. PreparedStatement psDistrictUpdate = prepareStatement( "UPDATE DISTRICT SET D_NEXT_O_ID = D_NEXT_O_ID + 1 " + "WHERE D_W_ID = ? AND D_ID = ?"); psDistrictUpdate.setShort(1, w); psDistrictUpdate.setShort(2, d); psDistrictUpdate.executeUpdate(); reset(psDistrictUpdate); PreparedStatement psDistrict = prepareStatement( "SELECT D_NEXT_O_ID - 1, D_TAX " + "FROM DISTRICT WHERE D_W_ID = ? AND D_ID = ?"); psDistrict.setShort(1, w); psDistrict.setShort(2, d); rs = psDistrict.executeQuery(); rs.next(); int orderNumber = rs.getInt(1); BigDecimal districtTax = (BigDecimal) rs.getObject(2); reset(psDistrict); PreparedStatement psCustomer = prepareStatement( "SELECT C_LAST, C_DISCOUNT, C_CREDIT " + "FROM CUSTOMER WHERE C_W_ID = ? AND C_D_ID = ? AND C_ID = ?"); psCustomer.setShort(1, w); psCustomer.setShort(2, d); psCustomer.setInt(3, c); rs = psCustomer.executeQuery(); rs.next(); // TODO fetch data reset(psCustomer); // See if all the items are from the local warehouse. short allLocal = 1; for (int i = 0; i < supplyW.length; i++) { if (supplyW[i] != w) { allLocal = 0; break; } } PreparedStatement psOrder = prepareStatement( "INSERT INTO ORDERS VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP, NULL, ?, ?)"); psOrder.setInt(1, orderNumber); psOrder.setShort(2, d); psOrder.setShort(3, w); psOrder.setInt(4, c); psOrder.setShort(5, (short) items.length); psOrder.setShort(6, allLocal); psOrder.executeUpdate(); reset(psOrder); PreparedStatement psNewOrder = prepareStatement( "INSERT INTO NEWORDERS VALUES(?, ?, ?)"); psNewOrder.setInt(1, orderNumber); psNewOrder.setShort(2, d); psNewOrder.setShort(3, w); psNewOrder.executeUpdate(); reset(psNewOrder); /* * Now all the processing for the order line items. */ PreparedStatement psOrderLine = prepareStatement( "INSERT INTO ORDERLINE(OL_W_ID, OL_D_ID, OL_O_ID, OL_NUMBER, " + "OL_I_ID, OL_SUPPLY_W_ID, OL_QUANTITY, OL_AMOUNT, OL_DIST_INFO, " + "OL_DELIVERY_D) VALUES (?, ?, ?, ?, ?, ?, ?, " + "CAST (? AS DECIMAL(5,2)) * CAST (? AS SMALLINT), ?, NULL)"); // These are constant across the order items psOrderLine.setShort(1, w); psOrderLine.setShort(2, d); psOrderLine.setInt(3, orderNumber); PreparedStatement psItemPrice = prepareStatement( "SELECT I_PRICE, I_NAME, I_DATA FROM ITEM WHERE I_ID = ?"); PreparedStatement psStockUpdate = prepareStatement( "UPDATE STOCK SET S_ORDER_CNT = S_ORDER_CNT + 1, " + "S_YTD = S_YTD + ?, S_REMOTE_CNT = S_REMOTE_CNT + ?, " + "S_QUANTITY = ? WHERE S_I_ID = ? AND S_W_ID = ?"); for (int i = 0; i < items.length; i++) { // Item details psItemPrice.setInt(1, items[i]); rs = psItemPrice.executeQuery(); rs.next(); BigDecimal itemPrice = (BigDecimal) rs.getObject(1); String itemName = rs.getString(2); String itemData = rs.getString(3); rs.close(); // SELECT S_QUANTITY, S_DIST_XX, S_DATA FROM STOCK WHERE S_I_ID = ? AND S_W_ID = ? PreparedStatement psStockInfo = prepareStatement(STOCK_INFO[d-1]); psStockInfo.setInt(1, items[i]); psStockInfo.setShort(2, w); rs = psStockInfo.executeQuery(); rs.next(); int stockQuantity = rs.getInt(1); String stockDistInfo = rs.getString(2); String stockData = rs.getString(3); reset(psStockInfo); psStockUpdate.setInt(1, quantities[i]); psStockUpdate.setInt(2, w == supplyW[i] ? 0 : 1); if ((stockQuantity - quantities[i]) > 10) stockQuantity -= quantities[i]; else stockQuantity = (stockQuantity - quantities[i] + 91); psStockUpdate.setInt(3, stockQuantity); psStockUpdate.setInt(4, items[i]); psStockUpdate.setShort(5, w); psStockUpdate.executeUpdate(); psOrderLine.setShort(4, (short) (i + 1)); psOrderLine.setInt(5, items[i]); psOrderLine.setShort(6, supplyW[i]); psOrderLine.setShort(7, quantities[i]); psOrderLine.setObject(8, itemPrice, Types.DECIMAL); psOrderLine.setShort(9, quantities[i]); psOrderLine.setString(10, stockDistInfo); psOrderLine.executeUpdate(); } reset(psOrderLine); reset(psItemPrice); reset(psOrderLine); reset(psStockUpdate); // get the sum of the order. This is done as a select rather than // directly in this code so that all the DECIMAL arithmetic is made // using the SQL engine (since this is a test of Derby). // PreparedStatement psTotal = prepareStatement( "SELECT SUM(OL_AMOUNT) FROM ORDERLINE " + "WHERE OL_W_ID = ? AND OL_D_ID = ? AND OL_O_ID = ?"); psTotal.setShort(1, w); psTotal.setShort(2, d); psTotal.setInt(3, orderNumber); rs = psTotal.executeQuery(); rs.next(); BigDecimal orderTotal = (BigDecimal) rs.getObject(1); reset(psTotal); conn.commit(); } catch (SQLException e) { conn.rollback(); } } /** * Schedule a delivery using the database as the queuing * mechanism and the results file. * See delivery.sql. */ public void scheduleDelivery(Display display, Object displayData, short w, short carrier) throws Exception { PreparedStatement sdSchedule = prepareStatement( "INSERT INTO DELIVERY_REQUEST(DR_W_ID, DR_CARRIER_ID, DR_STATE) " + "VALUES(?, ?, 'Q')"); int isolation = conn.getTransactionIsolation(); try { conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); sdSchedule.setShort(1, w); sdSchedule.setShort(2, carrier); sdSchedule.executeUpdate(); reset(sdSchedule); conn.commit(); } finally { conn.setTransactionIsolation(isolation); } if (display != null) display.displayScheduleDelivery(displayData, w, carrier); } public void delivery() throws Exception { PreparedStatement dlFindOldestRequest = prepareStatement( "SELECT DR_ID, DR_W_ID, DR_CARRIER_ID FROM DELIVERY_REQUEST " + "WHERE DR_STATE = 'Q' ORDER BY DR_QUEUED"); dlFindOldestRequest.setMaxRows(1); PreparedStatement dlSetRequestState = prepareStatement( "UPDATE DELIVERY_REQUEST SET DR_STATE = ? " + "WHERE DR_ID = ?"); PreparedStatement dlCompleteDelivery = prepareStatement( "UPDATE DELIVERY_REQUEST SET DR_STATE = 'C', DR_COMPLETED = CURRENT TIMESTAMP " + "WHERE DR_ID = ?"); PreparedStatement dlFindOrderToDeliver = prepareStatement( "SELECT MIN(NO_O_ID) AS ORDER_TO_DELIVER FROM NEWORDERS " + "WHERE NO_W_ID = ? AND NO_D_ID = ?"); PreparedStatement dlDeleteNewOrder = prepareStatement( "DELETE FROM NEWORDERS WHERE NO_W_ID = ? AND NO_D_ID = ? AND NO_O_ID = ?"); PreparedStatement dlSetOrderCarrier = prepareStatement( "UPDATE ORDERS SET O_CARRIER_ID = ? " + "WHERE O_W_ID = ? AND O_D_ID = ? AND O_ID = ?"); PreparedStatement dlSetOrderlineDate = prepareStatement( "UPDATE ORDERLINE SET OL_DELIVERY_D = CURRENT TIMESTAMP " + "WHERE OL_W_ID = ? AND OL_D_ID = ? AND OL_O_ID = ?"); PreparedStatement dlUpdateCustomer = prepareStatement( "UPDATE CUSTOMER SET " + "C_BALANCE = (SELECT SUM(OL_AMOUNT) FROM ORDERLINE " + "WHERE OL_W_ID = ? AND OL_D_ID = ? AND OL_O_ID = ?), " + "C_DELIVERY_CNT = C_DELIVERY_CNT + 1 " + "WHERE C_W_ID = ? AND C_D_ID = ? AND " + "C_ID = (SELECT O_C_ID FROM ORDERS " + "WHERE O_W_ID = ? AND O_D_ID = ? AND O_ID = ?)"); PreparedStatement dlRecordDelivery = prepareStatement( "INSERT INTO DELIVERY_ORDERS(DO_DR_ID, DO_D_ID, DO_O_ID) " + "VALUES (?, ?, ?)"); // Find the most oldest queued order (FIFO) ResultSet rs = dlFindOldestRequest.executeQuery(); rs.next(); int request = rs.getInt("DR_ID"); short w = rs.getShort("DR_W_ID"); short carrier = rs.getShort("DR_CARRIER_ID"); reset(dlFindOldestRequest); // Mark it as in progress dlSetRequestState.setString(1, "I"); dlSetRequestState.setInt(2, request); dlSetRequestState.executeUpdate(); reset(dlSetRequestState); conn.commit(); // This parameter remains invariant over // the batch we will insert. dlRecordDelivery.setInt(1, request); // Process one row per-district for this warehouse for (short d = 1; d <= 10; d++) { dlRecordDelivery.setShort(2, d); // Get the oldest NEWORDERS for this district dlFindOrderToDeliver.setShort(1, w); dlFindOrderToDeliver.setShort(2, d); rs = dlFindOrderToDeliver.executeQuery(); rs.next(); int order = rs.getInt("ORDER_TO_DELIVER"); if (rs.wasNull()) { // No orders to deliver dlRecordDelivery.setNull(3, Types.INTEGER); dlRecordDelivery.addBatch(); } reset(dlFindOrderToDeliver); // Delete the NEWORDERS row dlDeleteNewOrder.setShort(1, w); dlDeleteNewOrder.setShort(2, d); dlDeleteNewOrder.setInt(3, order); dlDeleteNewOrder.executeUpdate(); reset(dlDeleteNewOrder); // Set the carrier in ORDERS dlSetOrderCarrier.setShort(1, carrier); dlSetOrderCarrier.setShort(2, w); dlSetOrderCarrier.setShort(3, d); dlSetOrderCarrier.setInt(4, order); dlSetOrderCarrier.executeUpdate(); reset(dlSetOrderCarrier); // Update ORDERLINE with the delivery date dlSetOrderlineDate.setShort(1, w); dlSetOrderlineDate.setShort(2, d); dlSetOrderlineDate.setInt(3, order); dlSetOrderlineDate.executeUpdate(); reset(dlSetOrderlineDate); dlUpdateCustomer.setShort(1, w); dlUpdateCustomer.setShort(2, d); dlUpdateCustomer.setInt(3, order); dlUpdateCustomer.setShort(4, w); dlUpdateCustomer.setShort(5, d); dlUpdateCustomer.setShort(6, w); dlUpdateCustomer.setShort(7, d); dlUpdateCustomer.setInt(8, order); dlUpdateCustomer.executeUpdate(); reset(dlUpdateCustomer); conn.commit(); dlRecordDelivery.setInt(3, order); dlRecordDelivery.addBatch(); } // Record the delivery including the timestamp // 90% are meant to complete within 80 seconds // of them being queued. dlRecordDelivery.executeBatch(); reset(dlRecordDelivery); dlCompleteDelivery.setInt(1, request); dlCompleteDelivery.executeUpdate(); reset(dlCompleteDelivery); conn.commit(); } public void sortOrderItems(int[] items, short[] quantities, short[] supplyW) { OrderItem4Sort[] list = new OrderItem4Sort[items.length]; for (int i = 0; i < items.length; i++) { list[i] = new OrderItem4Sort(items[i], quantities[i], supplyW[i]); } java.util.Arrays.sort(list); for (int i = 0; i < items.length; i++) { items[i] = list[i].i; quantities[i] = list[i].q; supplyW[i] = list[i].w; } } } class OrderItem4Sort implements Comparable { final int i; final short q; final short w; OrderItem4Sort(int i, short q, short w) { this.i = i; this.q = q; this.w = w; } public int compareTo(Object o) { OrderItem4Sort oo = (OrderItem4Sort) o; if (w < oo.w) return -1; if (w > oo.w) return 1; if (i < oo.i) return -1; if (i > oo.i) return 1; return 0; } }
google/j2objc
37,291
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ImmutableCollections.java
/* * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /* J2ObjC removed import jdk.internal.vm.annotation.Stable; */ import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; /** * Container class for immutable collections. Not part of the public API. * Mainly for namespace management and shared infrastructure. * * Serial warnings are suppressed throughout because all implementation * classes use a serial proxy and thus have no need to declare serialVersionUID. */ @SuppressWarnings("serial") class ImmutableCollections { /** * A "salt" value used for randomizing iteration order. This is initialized once * and stays constant for the lifetime of the JVM. It need not be truly random, but * it needs to vary sufficiently from one run to the next so that iteration order * will vary between JVM runs. */ static final int SALT; static { long nt = System.nanoTime(); SALT = (int)((nt >>> 32) ^ nt); } /** No instances. */ private ImmutableCollections() { } /** * The reciprocal of load factor. Given a number of elements * to store, multiply by this factor to get the table size. */ static final int EXPAND_FACTOR = 2; static UnsupportedOperationException uoe() { return new UnsupportedOperationException(); } static abstract class AbstractImmutableCollection<E> extends AbstractCollection<E> { // all mutating methods throw UnsupportedOperationException @Override public boolean add(E e) { throw uoe(); } @Override public boolean addAll(Collection<? extends E> c) { throw uoe(); } @Override public void clear() { throw uoe(); } @Override public boolean remove(Object o) { throw uoe(); } @Override public boolean removeAll(Collection<?> c) { throw uoe(); } @Override public boolean removeIf(Predicate<? super E> filter) { throw uoe(); } @Override public boolean retainAll(Collection<?> c) { throw uoe(); } } // ---------- List Implementations ---------- // make a copy, short-circuiting based on implementation class @SuppressWarnings("unchecked") static <E> List<E> listCopy(Collection<? extends E> coll) { if (coll instanceof AbstractImmutableList && coll.getClass() != SubList.class) { return (List<E>)coll; } else { return (List<E>)List.of(coll.toArray()); } } @SuppressWarnings("unchecked") static <E> List<E> emptyList() { return (List<E>) ListN.EMPTY_LIST; } static abstract class AbstractImmutableList<E> extends AbstractImmutableCollection<E> implements List<E>, RandomAccess { // all mutating methods throw UnsupportedOperationException @Override public void add(int index, E element) { throw uoe(); } @Override public boolean addAll(int index, Collection<? extends E> c) { throw uoe(); } @Override public E remove(int index) { throw uoe(); } @Override public void replaceAll(UnaryOperator<E> operator) { throw uoe(); } @Override public E set(int index, E element) { throw uoe(); } @Override public void sort(Comparator<? super E> c) { throw uoe(); } @Override public List<E> subList(int fromIndex, int toIndex) { int size = size(); subListRangeCheck(fromIndex, toIndex, size); return SubList.fromList(this, fromIndex, toIndex); } static void subListRangeCheck(int fromIndex, int toIndex, int size) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > size) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } @Override public Iterator<E> iterator() { return new ListItr<E>(this, size()); } @Override public ListIterator<E> listIterator() { return listIterator(0); } @Override public ListIterator<E> listIterator(final int index) { int size = size(); if (index < 0 || index > size) { throw outOfBounds(index); } return new ListItr<E>(this, size, index); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof List)) { return false; } Iterator<?> oit = ((List<?>) o).iterator(); for (int i = 0, s = size(); i < s; i++) { if (!oit.hasNext() || !get(i).equals(oit.next())) { return false; } } return !oit.hasNext(); } @Override public int indexOf(Object o) { Objects.requireNonNull(o); for (int i = 0, s = size(); i < s; i++) { if (o.equals(get(i))) { return i; } } return -1; } @Override public int lastIndexOf(Object o) { Objects.requireNonNull(o); for (int i = size() - 1; i >= 0; i--) { if (o.equals(get(i))) { return i; } } return -1; } @Override public int hashCode() { int hash = 1; for (int i = 0, s = size(); i < s; i++) { hash = 31 * hash + get(i).hashCode(); } return hash; } @Override public boolean contains(Object o) { return indexOf(o) >= 0; } IndexOutOfBoundsException outOfBounds(int index) { return new IndexOutOfBoundsException("Index: " + index + " Size: " + size()); } } static final class ListItr<E> implements ListIterator<E> { /* J2ObjC removed @Stable */ private final List<E> list; /* J2ObjC removed @Stable */ private final int size; /* J2ObjC removed @Stable */ private final boolean isListIterator; private int cursor; ListItr(List<E> list, int size) { this.list = list; this.size = size; this.cursor = 0; isListIterator = false; } ListItr(List<E> list, int size, int index) { this.list = list; this.size = size; this.cursor = index; isListIterator = true; } public boolean hasNext() { return cursor != size; } public E next() { try { int i = cursor; E next = list.get(i); cursor = i + 1; return next; } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } public void remove() { throw uoe(); } public boolean hasPrevious() { if (!isListIterator) { throw uoe(); } return cursor != 0; } public E previous() { if (!isListIterator) { throw uoe(); } try { int i = cursor - 1; E previous = list.get(i); cursor = i; return previous; } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } public int nextIndex() { if (!isListIterator) { throw uoe(); } return cursor; } public int previousIndex() { if (!isListIterator) { throw uoe(); } return cursor - 1; } public void set(E e) { throw uoe(); } public void add(E e) { throw uoe(); } } static final class SubList<E> extends AbstractImmutableList<E> implements RandomAccess { /* J2ObjC removed @Stable */ private final List<E> root; /* J2ObjC removed @Stable */ private final int offset; /* J2ObjC removed @Stable */ private final int size; private SubList(List<E> root, int offset, int size) { this.root = root; this.offset = offset; this.size = size; } /** * Constructs a sublist of another SubList. */ static <E> SubList<E> fromSubList(SubList<E> parent, int fromIndex, int toIndex) { return new SubList<>(parent.root, parent.offset + fromIndex, toIndex - fromIndex); } /** * Constructs a sublist of an arbitrary AbstractImmutableList, which is * not a SubList itself. */ static <E> SubList<E> fromList(List<E> list, int fromIndex, int toIndex) { return new SubList<>(list, fromIndex, toIndex - fromIndex); } public E get(int index) { Objects.checkIndex(index, size); return root.get(offset + index); } public int size() { return size; } public Iterator<E> iterator() { return new ListItr<>(this, size()); } public ListIterator<E> listIterator(int index) { rangeCheck(index); return new ListItr<>(this, size(), index); } public List<E> subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return SubList.fromSubList(this, fromIndex, toIndex); } private void rangeCheck(int index) { if (index < 0 || index > size) { throw outOfBounds(index); } } } static final class List12<E> extends AbstractImmutableList<E> implements Serializable { /* J2ObjC removed @Stable */ private final E e0; /* J2ObjC removed @Stable */ private final E e1; List12(E e0) { this.e0 = Objects.requireNonNull(e0); this.e1 = null; } List12(E e0, E e1) { this.e0 = Objects.requireNonNull(e0); this.e1 = Objects.requireNonNull(e1); } @Override public int size() { return e1 != null ? 2 : 1; } @Override public E get(int index) { if (index == 0) { return e0; } else if (index == 1 && e1 != null) { return e1; } throw outOfBounds(index); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { throw new InvalidObjectException("not serial proxy"); } private Object writeReplace() { if (e1 == null) { return new CollSer(CollSer.IMM_LIST, e0); } else { return new CollSer(CollSer.IMM_LIST, e0, e1); } } } static final class ListN<E> extends AbstractImmutableList<E> implements Serializable { // EMPTY_LIST may be initialized from the CDS archive. static /* @Stable */ List<?> EMPTY_LIST; static { // Android-removed: CDS is not supported. // VM.initializeFromArchive(ListN.class); if (EMPTY_LIST == null) { EMPTY_LIST = new ListN<>(); } } /* J2ObjC removed @Stable */ private final E[] elements; @SafeVarargs ListN(E... input) { // copy and check manually to avoid TOCTOU @SuppressWarnings("unchecked") E[] tmp = (E[])new Object[input.length]; // implicit nullcheck of input for (int i = 0; i < input.length; i++) { tmp[i] = Objects.requireNonNull(input[i]); } elements = tmp; } @Override public boolean isEmpty() { return size() == 0; } @Override public int size() { return elements.length; } @Override public E get(int index) { return elements[index]; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { throw new InvalidObjectException("not serial proxy"); } private Object writeReplace() { return new CollSer(CollSer.IMM_LIST, elements); } } // ---------- Set Implementations ---------- static abstract class AbstractImmutableSet<E> extends AbstractImmutableCollection<E> implements Set<E> { @Override public boolean equals(Object o) { if (o == this) { return true; } else if (!(o instanceof Set)) { return false; } Collection<?> c = (Collection<?>) o; if (c.size() != size()) { return false; } for (Object e : c) { if (e == null || !contains(e)) { return false; } } return true; } @Override public abstract int hashCode(); } @SuppressWarnings("unchecked") static <E> Set<E> emptySet() { return (Set<E>) SetN.EMPTY_SET; } static final class Set12<E> extends AbstractImmutableSet<E> implements Serializable { /* J2ObjC removed @Stable */ final E e0; /* J2ObjC removed @Stable */ final E e1; Set12(E e0) { this.e0 = Objects.requireNonNull(e0); this.e1 = null; } Set12(E e0, E e1) { if (e0.equals(Objects.requireNonNull(e1))) { // implicit nullcheck of e0 throw new IllegalArgumentException("duplicate element: " + e0); } this.e0 = e0; this.e1 = e1; } @Override public int size() { return (e1 == null) ? 1 : 2; } @Override public boolean contains(Object o) { return o.equals(e0) || o.equals(e1); // implicit nullcheck of o } @Override public int hashCode() { return e0.hashCode() + (e1 == null ? 0 : e1.hashCode()); } @Override public Iterator<E> iterator() { return new Iterator<>() { private int idx = size(); @Override public boolean hasNext() { return idx > 0; } @Override public E next() { if (idx == 1) { idx = 0; return SALT >= 0 || e1 == null ? e0 : e1; } else if (idx == 2) { idx = 1; return SALT >= 0 ? e1 : e0; } else { throw new NoSuchElementException(); } } }; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { throw new InvalidObjectException("not serial proxy"); } private Object writeReplace() { if (e1 == null) { return new CollSer(CollSer.IMM_SET, e0); } else { return new CollSer(CollSer.IMM_SET, e0, e1); } } } /** * An array-based Set implementation. The element array must be strictly * larger than the size (the number of contained elements) so that at * least one null is always present. * @param <E> the element type */ static final class SetN<E> extends AbstractImmutableSet<E> implements Serializable { // EMPTY_SET may be initialized from the CDS archive. static /* @Stable */ Set<?> EMPTY_SET; static { // Android-removed: CDS is not supported. // VM.initializeFromArchive(SetN.class); if (EMPTY_SET == null) { EMPTY_SET = new SetN<>(); } } /* J2ObjC removed @Stable */ final E[] elements; /* J2ObjC removed @Stable */ final int size; @SafeVarargs @SuppressWarnings("unchecked") SetN(E... input) { size = input.length; // implicit nullcheck of input elements = (E[])new Object[EXPAND_FACTOR * input.length]; for (int i = 0; i < input.length; i++) { E e = input[i]; int idx = probe(e); // implicit nullcheck of e if (idx >= 0) { throw new IllegalArgumentException("duplicate element: " + e); } else { elements[-(idx + 1)] = e; } } } @Override public int size() { return size; } @Override public boolean contains(Object o) { Objects.requireNonNull(o); return size > 0 && probe(o) >= 0; } private final class SetNIterator implements Iterator<E> { private int remaining; private int idx; SetNIterator() { remaining = size(); if (remaining > 0) { idx = Math.floorMod(SALT, elements.length); } } @Override public boolean hasNext() { return remaining > 0; } private int nextIndex() { int idx = this.idx; if (SALT >= 0) { if (++idx >= elements.length) { idx = 0; } } else { if (--idx < 0) { idx = elements.length - 1; } } return this.idx = idx; } @Override public E next() { if (hasNext()) { E element; // skip null elements while ((element = elements[nextIndex()]) == null) {} remaining--; return element; } else { throw new NoSuchElementException(); } } } @Override public Iterator<E> iterator() { return new SetNIterator(); } @Override public int hashCode() { int h = 0; for (E e : elements) { if (e != null) { h += e.hashCode(); } } return h; } // returns index at which element is present; or if absent, // (-i - 1) where i is location where element should be inserted. // Callers are relying on this method to perform an implicit nullcheck // of pe private int probe(Object pe) { int idx = Math.floorMod(pe.hashCode(), elements.length); while (true) { E ee = elements[idx]; if (ee == null) { return -idx - 1; } else if (pe.equals(ee)) { return idx; } else if (++idx == elements.length) { idx = 0; } } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { throw new InvalidObjectException("not serial proxy"); } private Object writeReplace() { Object[] array = new Object[size]; int dest = 0; for (Object o : elements) { if (o != null) { array[dest++] = o; } } return new CollSer(CollSer.IMM_SET, array); } } // ---------- Map Implementations ---------- @SuppressWarnings("unchecked") static <K,V> Map<K,V> emptyMap() { return (Map<K,V>) MapN.EMPTY_MAP; } abstract static class AbstractImmutableMap<K,V> extends AbstractMap<K,V> implements Serializable { @Override public void clear() { throw uoe(); } @Override public V compute(K key, BiFunction<? super K,? super V,? extends V> rf) { throw uoe(); } @Override public V computeIfAbsent(K key, Function<? super K,? extends V> mf) { throw uoe(); } @Override public V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> rf) { throw uoe(); } @Override public V merge(K key, V value, BiFunction<? super V,? super V,? extends V> rf) { throw uoe(); } @Override public V put(K key, V value) { throw uoe(); } @Override public void putAll(Map<? extends K,? extends V> m) { throw uoe(); } @Override public V putIfAbsent(K key, V value) { throw uoe(); } @Override public V remove(Object key) { throw uoe(); } @Override public boolean remove(Object key, Object value) { throw uoe(); } @Override public V replace(K key, V value) { throw uoe(); } @Override public boolean replace(K key, V oldValue, V newValue) { throw uoe(); } @Override public void replaceAll(BiFunction<? super K,? super V,? extends V> f) { throw uoe(); } } static final class Map1<K,V> extends AbstractImmutableMap<K,V> { /* J2ObjC removed @Stable */ private final K k0; /* J2ObjC removed @Stable */ private final V v0; Map1(K k0, V v0) { this.k0 = Objects.requireNonNull(k0); this.v0 = Objects.requireNonNull(v0); } @Override public Set<Map.Entry<K,V>> entrySet() { return Set.of(new KeyValueHolder<>(k0, v0)); } @Override public V get(Object o) { return o.equals(k0) ? v0 : null; // implicit nullcheck of o } @Override public boolean containsKey(Object o) { return o.equals(k0); // implicit nullcheck of o } @Override public boolean containsValue(Object o) { return o.equals(v0); // implicit nullcheck of o } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { throw new InvalidObjectException("not serial proxy"); } private Object writeReplace() { return new CollSer(CollSer.IMM_MAP, k0, v0); } @Override public int hashCode() { return k0.hashCode() ^ v0.hashCode(); } } /** * An array-based Map implementation. There is a single array "table" that * contains keys and values interleaved: table[0] is kA, table[1] is vA, * table[2] is kB, table[3] is vB, etc. The table size must be even. It must * also be strictly larger than the size (the number of key-value pairs contained * in the map) so that at least one null key is always present. * @param <K> the key type * @param <V> the value type */ static final class MapN<K,V> extends AbstractImmutableMap<K,V> { // EMPTY_MAP may be initialized from the CDS archive. static /* @Stable */ Map<?,?> EMPTY_MAP; static { // Android-removed: CDS is not supported. // VM.initializeFromArchive(MapN.class); if (EMPTY_MAP == null) { EMPTY_MAP = new MapN<>(); } } /* J2ObjC removed @Stable */ final Object[] table; // pairs of key, value /* J2ObjC removed @Stable */ final int size; // number of pairs MapN(Object... input) { if ((input.length & 1) != 0) { // implicit nullcheck of input throw new InternalError("length is odd"); } size = input.length >> 1; int len = EXPAND_FACTOR * input.length; len = (len + 1) & ~1; // ensure table is even length table = new Object[len]; for (int i = 0; i < input.length; i += 2) { @SuppressWarnings("unchecked") K k = Objects.requireNonNull((K)input[i]); @SuppressWarnings("unchecked") V v = Objects.requireNonNull((V)input[i+1]); int idx = probe(k); if (idx >= 0) { throw new IllegalArgumentException("duplicate key: " + k); } else { int dest = -(idx + 1); table[dest] = k; table[dest+1] = v; } } } @Override public boolean containsKey(Object o) { Objects.requireNonNull(o); return size > 0 && probe(o) >= 0; } @Override public boolean containsValue(Object o) { Objects.requireNonNull(o); for (int i = 1; i < table.length; i += 2) { Object v = table[i]; if (v != null && o.equals(v)) { return true; } } return false; } @Override public int hashCode() { int hash = 0; for (int i = 0; i < table.length; i += 2) { Object k = table[i]; if (k != null) { hash += k.hashCode() ^ table[i + 1].hashCode(); } } return hash; } @Override @SuppressWarnings("unchecked") public V get(Object o) { if (size == 0) { Objects.requireNonNull(o); return null; } int i = probe(o); if (i >= 0) { return (V)table[i+1]; } else { return null; } } @Override public int size() { return size; } class MapNIterator implements Iterator<Map.Entry<K,V>> { private int remaining; private int idx; MapNIterator() { remaining = size(); if (remaining > 0) { idx = Math.floorMod(SALT, table.length >> 1) << 1; } } @Override public boolean hasNext() { return remaining > 0; } private int nextIndex() { int idx = this.idx; if (SALT >= 0) { if ((idx += 2) >= table.length) { idx = 0; } } else { if ((idx -= 2) < 0) { idx = table.length - 2; } } return this.idx = idx; } @Override public Map.Entry<K,V> next() { if (hasNext()) { while (table[nextIndex()] == null) {} @SuppressWarnings("unchecked") Map.Entry<K,V> e = new KeyValueHolder<>((K)table[idx], (V)table[idx+1]); remaining--; return e; } else { throw new NoSuchElementException(); } } } @Override public Set<Map.Entry<K,V>> entrySet() { return new AbstractSet<>() { @Override public int size() { return MapN.this.size; } @Override public Iterator<Map.Entry<K,V>> iterator() { return new MapNIterator(); } // Android-added: AbstractCollection#clear implementation is no-op when // collection is empty. Overriding this method to make Map.of().clear() // and Map.of().entrySet().clear() behaviour equal. @Override public void clear() { throw uoe(); } }; } // returns index at which the probe key is present; or if absent, // (-i - 1) where i is location where element should be inserted. // Callers are relying on this method to perform an implicit nullcheck // of pk. private int probe(Object pk) { int idx = Math.floorMod(pk.hashCode(), table.length >> 1) << 1; while (true) { @SuppressWarnings("unchecked") K ek = (K)table[idx]; if (ek == null) { return -idx - 1; } else if (pk.equals(ek)) { return idx; } else if ((idx += 2) == table.length) { idx = 0; } } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { throw new InvalidObjectException("not serial proxy"); } private Object writeReplace() { Object[] array = new Object[2 * size]; int len = table.length; int dest = 0; for (int i = 0; i < len; i += 2) { if (table[i] != null) { array[dest++] = table[i]; array[dest++] = table[i+1]; } } return new CollSer(CollSer.IMM_MAP, array); } } } // ---------- Serialization Proxy ---------- /** * A unified serialization proxy class for the immutable collections. * * @serial * @since 9 */ final class CollSer implements Serializable { private static final long serialVersionUID = 6309168927139932177L; static final int IMM_LIST = 1; static final int IMM_SET = 2; static final int IMM_MAP = 3; /** * Indicates the type of collection that is serialized. * The low order 8 bits have the value 1 for an immutable * {@code List}, 2 for an immutable {@code Set}, and 3 for * an immutable {@code Map}. Any other value causes an * {@link InvalidObjectException} to be thrown. The high * order 24 bits are zero when an instance is serialized, * and they are ignored when an instance is deserialized. * They can thus be used by future implementations without * causing compatibility issues. * * <p>The tag value also determines the interpretation of the * transient {@code Object[] array} field. * For {@code List} and {@code Set}, the array's length is the size * of the collection, and the array contains the elements of the collection. * Null elements are not allowed. For {@code Set}, duplicate elements * are not allowed. * * <p>For {@code Map}, the array's length is twice the number of mappings * present in the map. The array length is necessarily even. * The array contains a succession of key and value pairs: * {@code k1, v1, k2, v2, ..., kN, vN.} Nulls are not allowed, * and duplicate keys are not allowed. * * @serial * @since 9 */ private final int tag; /** * @serial * @since 9 */ private transient Object[] array; CollSer(int t, Object... a) { tag = t; array = a; } /** * Reads objects from the stream and stores them * in the transient {@code Object[] array} field. * * @serialData * A nonnegative int, indicating the count of objects, * followed by that many objects. * * @param ois the ObjectInputStream from which data is read * @throws IOException if an I/O error occurs * @throws ClassNotFoundException if a serialized class cannot be loaded * @throws InvalidObjectException if the count is negative * @since 9 */ private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); int len = ois.readInt(); if (len < 0) { throw new InvalidObjectException("negative length " + len); } /* J2ObjC removed sun.misc.SharedSecrets.getJavaObjectInputStreamAccess().checkArray(ois, Object[].class, len); */ Object[] a = new Object[len]; for (int i = 0; i < len; i++) { a[i] = ois.readObject(); } array = a; } /** * Writes objects to the stream from * the transient {@code Object[] array} field. * * @serialData * A nonnegative int, indicating the count of objects, * followed by that many objects. * * @param oos the ObjectOutputStream to which data is written * @throws IOException if an I/O error occurs * @since 9 */ private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); oos.writeInt(array.length); for (int i = 0; i < array.length; i++) { oos.writeObject(array[i]); } } /** * Creates and returns an immutable collection from this proxy class. * The instance returned is created as if by calling one of the * static factory methods for * <a href="List.html#immutable">List</a>, * <a href="Map.html#immutable">Map</a>, or * <a href="Set.html#immutable">Set</a>. * This proxy class is the serial form for all immutable collection instances, * regardless of implementation type. This is necessary to ensure that the * existence of any particular implementation type is kept out of the * serialized form. * * @return a collection created from this proxy object * @throws InvalidObjectException if the tag value is illegal or if an exception * is thrown during creation of the collection * @throws ObjectStreamException if another serialization error has occurred * @since 9 */ private Object readResolve() throws ObjectStreamException { try { if (array == null) { throw new InvalidObjectException("null array"); } // use low order 8 bits to indicate "kind" // ignore high order 24 bits switch (tag & 0xff) { case IMM_LIST: return List.of(array); case IMM_SET: return Set.of(array); case IMM_MAP: if (array.length == 0) { return ImmutableCollections.emptyMap(); } else if (array.length == 2) { return new ImmutableCollections.Map1<>(array[0], array[1]); } else { return new ImmutableCollections.MapN<>(array); } default: throw new InvalidObjectException(String.format("invalid flags 0x%x", tag)); } } catch (NullPointerException|IllegalArgumentException ex) { InvalidObjectException ioe = new InvalidObjectException("invalid object"); ioe.initCause(ex); throw ioe; } } }
apache/hertzbeat
37,586
hertzbeat-warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/history/tsdb/vm/VictoriaMetricsDataStorage.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hertzbeat.warehouse.store.history.tsdb.vm; import java.io.ByteArrayOutputStream; import java.math.BigDecimal; import java.math.RoundingMode; import java.net.URI; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.ZonedDateTime; import java.time.temporal.TemporalAmount; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.zip.GZIPOutputStream; import com.google.common.collect.Maps; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.math.NumberUtils; import org.apache.hertzbeat.common.constants.CommonConstants; import org.apache.hertzbeat.common.constants.MetricDataConstants; import org.apache.hertzbeat.common.constants.NetworkConstants; import org.apache.hertzbeat.common.constants.SignConstants; import org.apache.hertzbeat.common.entity.arrow.RowWrapper; import org.apache.hertzbeat.common.entity.dto.Value; import org.apache.hertzbeat.common.entity.message.CollectRep; import org.apache.hertzbeat.common.timer.HashedWheelTimer; import org.apache.hertzbeat.common.timer.Timeout; import org.apache.hertzbeat.common.timer.TimerTask; import org.apache.hertzbeat.common.util.Base64Util; import org.apache.hertzbeat.common.util.CommonUtil; import org.apache.hertzbeat.common.util.JsonUtil; import org.apache.hertzbeat.common.util.TimePeriodUtil; import org.apache.hertzbeat.warehouse.store.history.tsdb.AbstractHistoryDataStorage; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Primary; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; /** * VictoriaMetrics data storage */ @Primary @Component @ConditionalOnProperty(prefix = "warehouse.store.victoria-metrics", name = "enabled", havingValue = "true") @Slf4j public class VictoriaMetricsDataStorage extends AbstractHistoryDataStorage { private static final String IMPORT_PATH = "/api/v1/import"; /** * <a href="https://docs.victoriametrics.com/Single-server-VictoriaMetrics.html#how-to-export-data-in-json-line-format"> * https://docs.victoriametrics.com/Single-server-VictoriaMetrics.html#how-to-export-data-in-json-line-format * </a> */ private static final String EXPORT_PATH = "/api/v1/export"; private static final String QUERY_RANGE_PATH = "/api/v1/query_range"; private static final String STATUS_PATH = "/api/v1/status/tsdb"; private static final String LABEL_KEY_NAME = "__name__"; private static final String LABEL_KEY_JOB = "job"; private static final String LABEL_KEY_INSTANCE = "instance"; private static final String LABEL_KEY_HOST = "host"; private static final String SPILT = "_"; private static final String MONITOR_METRICS_KEY = "__metrics__"; private static final String MONITOR_METRIC_KEY = "__metric__"; private static final long MAX_WAIT_MS = 500L; private static final int MAX_RETRIES = 3; private final VictoriaMetricsProperties victoriaMetricsProp; private final RestTemplate restTemplate; private final BlockingQueue<VictoriaMetricsDataStorage.VictoriaMetricsContent> metricsBufferQueue; private HashedWheelTimer metricsFlushTimer = null; private final VictoriaMetricsProperties.InsertConfig insertConfig; private final AtomicBoolean draining = new AtomicBoolean(false); public VictoriaMetricsDataStorage(VictoriaMetricsProperties victoriaMetricsProperties, RestTemplate restTemplate) { if (victoriaMetricsProperties == null) { log.error("init error, please config Warehouse victoriaMetrics props in application.yml"); throw new IllegalArgumentException("please config Warehouse victoriaMetrics props"); } this.restTemplate = restTemplate; victoriaMetricsProp = victoriaMetricsProperties; serverAvailable = checkVictoriaMetricsDatasourceAvailable(); insertConfig = victoriaMetricsProperties.insert() == null ? new VictoriaMetricsProperties.InsertConfig(100, 3, new VictoriaMetricsProperties.Compression(false)) : victoriaMetricsProperties.insert(); metricsBufferQueue = new LinkedBlockingQueue<>(insertConfig.bufferSize()); initializeFlushTimer(); } private void initializeFlushTimer() { this.metricsFlushTimer = new HashedWheelTimer(r -> { Thread thread = new Thread(r, "victoria-metrics-cluster-flush-timer"); thread.setDaemon(true); return thread; }, 1, TimeUnit.SECONDS, 512); // start flush interval timer this.metricsFlushTimer.newTimeout(new MetricsFlushTask(null), insertConfig.flushInterval(), TimeUnit.SECONDS); } private boolean checkVictoriaMetricsDatasourceAvailable() { // check server status try { HttpHeaders headers = new HttpHeaders(); if (StringUtils.hasText(victoriaMetricsProp.username()) && StringUtils.hasText(victoriaMetricsProp.password())) { String authStr = victoriaMetricsProp.username() + SignConstants.DOUBLE_MARK + victoriaMetricsProp.password(); String encodedAuth = Base64Util.encode(authStr); headers.add(HttpHeaders.AUTHORIZATION, NetworkConstants.BASIC + " " + encodedAuth); } HttpEntity<Void> httpEntity = new HttpEntity<>(headers); ResponseEntity<String> responseEntity = restTemplate.exchange(victoriaMetricsProp.url() + STATUS_PATH, HttpMethod.GET, httpEntity, String.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { log.info("check victoria metrics server status success."); return true; } log.error("check victoria metrics server status not success: {}.", responseEntity.getBody()); } catch (Exception e) { log.error("check victoria metrics server status error: {}.", e.getMessage()); } return false; } @Override public void saveData(CollectRep.MetricsData metricsData) { if (!isServerAvailable()) { serverAvailable = checkVictoriaMetricsDatasourceAvailable(); } if (!isServerAvailable() || metricsData.getCode() != CollectRep.Code.SUCCESS) { return; } if (metricsData.getValues().isEmpty()) { log.info("[warehouse victoria-metrics] flush metrics data {} {} {} is null, ignore.", metricsData.getId(), metricsData.getApp(), metricsData.getMetrics()); return; } Map<String, String> defaultLabels = Maps.newHashMapWithExpectedSize(8); defaultLabels.put(MONITOR_METRICS_KEY, metricsData.getMetrics()); boolean isPrometheusAuto = false; if (metricsData.getApp().startsWith(CommonConstants.PROMETHEUS_APP_PREFIX)) { isPrometheusAuto = true; defaultLabels.remove(MONITOR_METRICS_KEY); defaultLabels.put(LABEL_KEY_JOB, metricsData.getApp() .substring(CommonConstants.PROMETHEUS_APP_PREFIX.length())); } else { defaultLabels.put(LABEL_KEY_JOB, metricsData.getApp()); } defaultLabels.put(LABEL_KEY_INSTANCE, String.valueOf(metricsData.getId())); List<VictoriaMetricsContent> contentList = new LinkedList<>(); try { final int fieldSize = metricsData.getFields().size(); Long[] timestamp = new Long[]{metricsData.getTime()}; Map<String, Double> fieldsValue = Maps.newHashMapWithExpectedSize(fieldSize); Map<String, String> labels = Maps.newHashMapWithExpectedSize(fieldSize); RowWrapper rowWrapper = metricsData.readRow(); while (rowWrapper.hasNextRow()) { rowWrapper = rowWrapper.nextRow(); fieldsValue.clear(); labels.clear(); rowWrapper.cellStream().forEach(cell -> { String value = cell.getValue(); boolean isLabel = cell.getMetadataAsBoolean(MetricDataConstants.LABEL); byte type = cell.getMetadataAsByte(MetricDataConstants.TYPE); if (type == CommonConstants.TYPE_NUMBER && !isLabel) { // number metrics data if (!CommonConstants.NULL_VALUE.equals(value)) { fieldsValue.put(cell.getField().getName(), CommonUtil.parseStrDouble(value)); } } // label if (isLabel && !CommonConstants.NULL_VALUE.equals(value)) { labels.put(cell.getField().getName(), value); } }); for (Map.Entry<String, Double> entry : fieldsValue.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { try { labels.putAll(defaultLabels); String labelName = isPrometheusAuto ? metricsData.getMetrics() : metricsData.getMetrics() + SPILT + entry.getKey(); labels.put(LABEL_KEY_NAME, labelName); if (!isPrometheusAuto) { labels.put(MONITOR_METRIC_KEY, entry.getKey()); } labels.put(LABEL_KEY_HOST, metricsData.getInstanceHost()); // add customized labels as identifier var customizedLabels = metricsData.getLabels(); if (!ObjectUtils.isEmpty(customizedLabels)) { labels.putAll(customizedLabels); } VictoriaMetricsContent content = VictoriaMetricsContent.builder() .metric(new HashMap<>(labels)) .values(new Double[]{entry.getValue()}) .timestamps(timestamp) .build(); contentList.add(content); } catch (Exception e) { log.error("combine metrics data error: {}.", e.getMessage(), e); } } } } } catch (Exception e) { log.error("save metrics data to victoria error: {}.", e.getMessage(), e); } if (contentList.isEmpty()) { log.info("[warehouse victoria-metrics] flush metrics data {} is empty, ignore.", metricsData.getId()); return; } sendVictoriaMetrics(contentList); } @Override public void destroy() { if (metricsFlushTimer != null && !metricsFlushTimer.isStop()) { metricsFlushTimer.stop(); } } @Override public Map<String, List<Value>> getHistoryMetricData(Long monitorId, String app, String metrics, String metric, String label, String history) { String labelName = metrics + SPILT + metric; if (CommonConstants.PROMETHEUS.equals(app)) { labelName = metrics; } String timeSeriesSelector = LABEL_KEY_NAME + "=\"" + labelName + "\"" + "," + LABEL_KEY_INSTANCE + "=\"" + monitorId + "\"" + (CommonConstants.PROMETHEUS.equals(app) ? "" : "," + MONITOR_METRIC_KEY + "=\"" + metric + "\""); Map<String, List<Value>> instanceValuesMap = new HashMap<>(8); try { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(List.of(MediaType.APPLICATION_JSON)); if (StringUtils.hasText(victoriaMetricsProp.username()) && StringUtils.hasText(victoriaMetricsProp.password())) { String authStr = victoriaMetricsProp.username() + ":" + victoriaMetricsProp.password(); String encodedAuth = Base64Util.encode(authStr); headers.add(HttpHeaders.AUTHORIZATION, NetworkConstants.BASIC + SignConstants.BLANK + encodedAuth); } HttpEntity<Void> httpEntity = new HttpEntity<>(headers); URI uri = UriComponentsBuilder.fromUriString(victoriaMetricsProp.url() + EXPORT_PATH) .queryParam(URLEncoder.encode("match[]", StandardCharsets.UTF_8), URLEncoder.encode("{" + timeSeriesSelector + "}", StandardCharsets.UTF_8)) .queryParam("start", URLEncoder.encode("now-" + history, StandardCharsets.UTF_8)) .queryParam("end", "now") .build(true).toUri(); ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { log.debug("query metrics data from victoria-metrics success. {}", uri); if (StringUtils.hasText(responseEntity.getBody())) { String[] contentJsonArr = responseEntity.getBody().split("\n"); List<VictoriaMetricsContent> contents = Arrays.stream(contentJsonArr).map( item -> JsonUtil.fromJson(item, VictoriaMetricsContent.class) ).toList(); for (VictoriaMetricsContent content : contents) { Map<String, String> labels = content.getMetric(); labels.remove(LABEL_KEY_NAME); labels.remove(LABEL_KEY_JOB); labels.remove(LABEL_KEY_INSTANCE); labels.remove(MONITOR_METRICS_KEY); labels.remove(MONITOR_METRIC_KEY); String labelStr = JsonUtil.toJson(labels); if (content.getValues() != null && content.getTimestamps() != null) { List<Value> valueList = instanceValuesMap.computeIfAbsent(labelStr, k -> new LinkedList<>()); if (content.getValues().length != content.getTimestamps().length) { log.error("content.getValues().length != content.getTimestamps().length"); continue; } Double[] values = content.getValues(); Long[] timestamps = content.getTimestamps(); for (int index = 0; index < content.getValues().length; index++) { String strValue = BigDecimal.valueOf(values[index]).setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString(); // read timestamp here is ms unit valueList.add(new Value(strValue, timestamps[index])); } } } } } else { log.error("query metrics data from victoria-metrics failed. {}", responseEntity); } } catch (Exception e) { log.error("query metrics data from victoria-metrics error. {}.", e.getMessage(), e); } return instanceValuesMap; } @Override public Map<String, List<Value>> getHistoryIntervalMetricData(Long monitorId, String app, String metrics, String metric, String label, String history) { if (!serverAvailable) { log.error(""" \t---------------VictoriaMetrics Init Failed--------------- \t--------------Please Config VictoriaMetrics-------------- \t----------Can Not Use Metric History Now---------- """); return Collections.emptyMap(); } long endTime = ZonedDateTime.now().toEpochSecond(); long startTime; try { if (NumberUtils.isParsable(history)) { startTime = NumberUtils.toLong(history); startTime = (ZonedDateTime.now().toEpochSecond() - startTime); } else { TemporalAmount temporalAmount = TimePeriodUtil.parseTokenTime(history); ZonedDateTime dateTime = ZonedDateTime.now().minus(temporalAmount); startTime = dateTime.toEpochSecond(); } } catch (Exception e) { log.error("history time error: {}. use default: 6h", e.getMessage()); ZonedDateTime dateTime = ZonedDateTime.now().minus(Duration.ofHours(6)); startTime = dateTime.toEpochSecond(); } String labelName = metrics + SPILT + metric; if (CommonConstants.PROMETHEUS.equals(app)) { labelName = metrics; } String timeSeriesSelector = LABEL_KEY_NAME + "=\"" + labelName + "\"" + "," + LABEL_KEY_INSTANCE + "=\"" + monitorId + "\"" + (CommonConstants.PROMETHEUS.equals(app) ? "" : "," + MONITOR_METRIC_KEY + "=\"" + metric + "\""); Map<String, List<Value>> instanceValuesMap = new HashMap<>(8); try { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(List.of(MediaType.APPLICATION_JSON)); if (StringUtils.hasText(victoriaMetricsProp.username()) && StringUtils.hasText(victoriaMetricsProp.password())) { String authStr = victoriaMetricsProp.username() + ":" + victoriaMetricsProp.password(); String encodedAuth = Base64Util.encode(authStr); headers.add(HttpHeaders.AUTHORIZATION, NetworkConstants.BASIC + SignConstants.BLANK + encodedAuth); } HttpEntity<Void> httpEntity = new HttpEntity<>(headers); URI uri = UriComponentsBuilder.fromUriString(victoriaMetricsProp.url() + QUERY_RANGE_PATH) .queryParam(URLEncoder.encode("query", StandardCharsets.UTF_8), URLEncoder.encode("{" + timeSeriesSelector + "}", StandardCharsets.UTF_8)) .queryParam("step", "4h") .queryParam("start", startTime) .queryParam("end", endTime) .build(true).toUri(); ResponseEntity<PromQlQueryContent> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, PromQlQueryContent.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { log.debug("query metrics data from victoria-metrics success. {}", uri); if (responseEntity.getBody() != null && responseEntity.getBody().getData() != null && responseEntity.getBody().getData().getResult() != null) { List<PromQlQueryContent.ContentData.Content> contents = responseEntity.getBody().getData().getResult(); for (PromQlQueryContent.ContentData.Content content : contents) { Map<String, String> labels = content.getMetric(); labels.remove(LABEL_KEY_NAME); labels.remove(LABEL_KEY_JOB); labels.remove(LABEL_KEY_INSTANCE); labels.remove(MONITOR_METRICS_KEY); labels.remove(MONITOR_METRIC_KEY); String labelStr = JsonUtil.toJson(labels); if (content.getValues() != null && !content.getValues().isEmpty()) { List<Value> valueList = instanceValuesMap.computeIfAbsent(labelStr, k -> new LinkedList<>()); for (Object[] valueArr : content.getValues()) { long timestamp = Long.parseLong(String.valueOf(valueArr[0])); String value = new BigDecimal(String.valueOf(valueArr[1])).setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString(); // read timestamp here is s unit valueList.add(new Value(value, timestamp * 1000)); } } } } } else { log.error("query metrics data from victoria-metrics failed. {}", responseEntity); } // max uri = UriComponentsBuilder.fromUriString(victoriaMetricsProp.url() + QUERY_RANGE_PATH) .queryParam(URLEncoder.encode("query", StandardCharsets.UTF_8), URLEncoder.encode("max_over_time({" + timeSeriesSelector + "})", StandardCharsets.UTF_8)) .queryParam("step", "4h") .queryParam("start", startTime) .queryParam("end", endTime) .build(true).toUri(); responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, PromQlQueryContent.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { if (responseEntity.getBody() != null && responseEntity.getBody().getData() != null && responseEntity.getBody().getData().getResult() != null) { List<PromQlQueryContent.ContentData.Content> contents = responseEntity.getBody().getData().getResult(); for (PromQlQueryContent.ContentData.Content content : contents) { Map<String, String> labels = content.getMetric(); labels.remove(LABEL_KEY_NAME); labels.remove(LABEL_KEY_JOB); labels.remove(LABEL_KEY_INSTANCE); labels.remove(MONITOR_METRICS_KEY); labels.remove(MONITOR_METRIC_KEY); String labelStr = JsonUtil.toJson(labels); if (content.getValues() != null && !content.getValues().isEmpty()) { List<Value> valueList = instanceValuesMap.computeIfAbsent(labelStr, k -> new LinkedList<>()); if (valueList.size() == content.getValues().size()) { for (int timestampIndex = 0; timestampIndex < valueList.size(); timestampIndex++) { Value value = valueList.get(timestampIndex); Object[] valueArr = content.getValues().get(timestampIndex); String maxValue = new BigDecimal(String.valueOf(valueArr[1])).setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString(); value.setMax(maxValue); } } } } } } // min uri = UriComponentsBuilder.fromUriString(victoriaMetricsProp.url() + QUERY_RANGE_PATH) .queryParam(URLEncoder.encode("query", StandardCharsets.UTF_8), URLEncoder.encode("min_over_time({" + timeSeriesSelector + "})", StandardCharsets.UTF_8)) .queryParam("step", "4h") .queryParam("start", startTime) .queryParam("end", endTime) .build(true).toUri(); responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, PromQlQueryContent.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { if (responseEntity.getBody() != null && responseEntity.getBody().getData() != null && responseEntity.getBody().getData().getResult() != null) { List<PromQlQueryContent.ContentData.Content> contents = responseEntity.getBody().getData().getResult(); for (PromQlQueryContent.ContentData.Content content : contents) { Map<String, String> labels = content.getMetric(); labels.remove(LABEL_KEY_NAME); labels.remove(LABEL_KEY_JOB); labels.remove(LABEL_KEY_INSTANCE); labels.remove(MONITOR_METRICS_KEY); labels.remove(MONITOR_METRIC_KEY); String labelStr = JsonUtil.toJson(labels); if (content.getValues() != null && !content.getValues().isEmpty()) { List<Value> valueList = instanceValuesMap.computeIfAbsent(labelStr, k -> new LinkedList<>()); if (valueList.size() == content.getValues().size()) { for (int timestampIndex = 0; timestampIndex < valueList.size(); timestampIndex++) { Value value = valueList.get(timestampIndex); Object[] valueArr = content.getValues().get(timestampIndex); String minValue = new BigDecimal(String.valueOf(valueArr[1])).setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString(); value.setMin(minValue); } } } } } } // avg uri = UriComponentsBuilder.fromUriString(victoriaMetricsProp.url() + QUERY_RANGE_PATH) .queryParam(URLEncoder.encode("query", StandardCharsets.UTF_8), URLEncoder.encode("avg_over_time({" + timeSeriesSelector + "})", StandardCharsets.UTF_8)) .queryParam("step", "4h") .queryParam("start", startTime) .queryParam("end", endTime) .build(true).toUri(); responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, PromQlQueryContent.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { if (responseEntity.getBody() != null && responseEntity.getBody().getData() != null && responseEntity.getBody().getData().getResult() != null) { List<PromQlQueryContent.ContentData.Content> contents = responseEntity.getBody().getData().getResult(); for (PromQlQueryContent.ContentData.Content content : contents) { Map<String, String> labels = content.getMetric(); labels.remove(LABEL_KEY_NAME); labels.remove(LABEL_KEY_JOB); labels.remove(LABEL_KEY_INSTANCE); labels.remove(MONITOR_METRICS_KEY); labels.remove(MONITOR_METRIC_KEY); String labelStr = JsonUtil.toJson(labels); if (content.getValues() != null && !content.getValues().isEmpty()) { List<Value> valueList = instanceValuesMap.computeIfAbsent(labelStr, k -> new LinkedList<>()); if (valueList.size() == content.getValues().size()) { for (int timestampIndex = 0; timestampIndex < valueList.size(); timestampIndex++) { Value value = valueList.get(timestampIndex); Object[] valueArr = content.getValues().get(timestampIndex); String avgValue = new BigDecimal(String.valueOf(valueArr[1])).setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString(); value.setMean(avgValue); } } } } } } } catch (Exception e) { log.error("query metrics data from victoria-metrics error. {}.", e.getMessage(), e); } return instanceValuesMap; } /** * victoria metrics content */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public static final class VictoriaMetricsContent { /** * metric contains metric name plus labels for a particular time series */ private Map<String, String> metric; /** * values contains raw sample values for the given time series */ private Double[] values; /** * timestamps contains raw sample UNIX timestamps in milliseconds for the given time series * every timestamp is associated with the value at the corresponding position */ private Long[] timestamps; } /** * add victoriaMetricsContent to buffer * @param contentList victoriaMetricsContent List */ private void sendVictoriaMetrics(List<VictoriaMetricsDataStorage.VictoriaMetricsContent> contentList) { for (VictoriaMetricsDataStorage.VictoriaMetricsContent content : contentList) { boolean offered = false; int retryCount = 0; while (!offered && retryCount < MAX_RETRIES) { try { // Attempt to add to the queue for a limited time offered = metricsBufferQueue.offer(content, MAX_WAIT_MS, TimeUnit.MILLISECONDS); if (!offered) { // If the queue is still full, trigger an immediate refresh to free up space if (retryCount == 0) { log.debug("victoria metrics buffer queue is full, triggering immediate flush"); triggerImmediateFlush(); } retryCount++; // The short sleep allows the queue to clear out if (retryCount < MAX_RETRIES) { Thread.sleep(100L * retryCount); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.error("[Victoria Metrics] Interrupted while offering metrics to buffer queue", e); break; } } // When the maximum number of retries is reached, if it still cannot be added to the queue, the data is saved directly if (!offered) { log.warn("[Victoria Metrics] Failed to add metrics to buffer after {} retries, saving directly", MAX_RETRIES); try { doSaveData(contentList); } catch (Exception e) { log.error("[Victoria Metrics] Failed to save metrics directly: {}", e.getMessage(), e); } } } // Refresh in advance to avoid waiting if (metricsBufferQueue.size() >= insertConfig.bufferSize() * 0.8 && draining.compareAndSet(false, true)) { triggerImmediateFlush(); } } private void triggerImmediateFlush() { List<VictoriaMetricsDataStorage.VictoriaMetricsContent> batch = new ArrayList<>(insertConfig.bufferSize()); metricsBufferQueue.drainTo(batch, insertConfig.bufferSize()); draining.set(false); if (!batch.isEmpty()) { metricsFlushTimer.newTimeout(new MetricsFlushTask(batch), 0, TimeUnit.MILLISECONDS); } } /** * Regularly refresh the buffer queue to the vm */ private class MetricsFlushTask implements TimerTask { private final List<VictoriaMetricsDataStorage.VictoriaMetricsContent> batch; public MetricsFlushTask(List<VictoriaMetricsDataStorage.VictoriaMetricsContent> batch) { this.batch = batch; } @Override public void run(Timeout timeout) { try { if (batch == null) { // If the batch is null, it means that the timer is triggered by flush interval timer List<VictoriaMetricsDataStorage.VictoriaMetricsContent> batchT = new ArrayList<>(insertConfig.bufferSize()); metricsBufferQueue.drainTo(batchT, insertConfig.bufferSize()); triggerDoSaveData(batchT); // Reschedule the next flush task triggerIntervalFlushTimer(); } else { // If the batch is not null, it means that the timer is triggered by the immediate flush triggerDoSaveData(batch); } } catch (Exception e) { log.error("[VictoriaMetrics] flush task error: {}", e.getMessage(), e); } } private void triggerDoSaveData(List<VictoriaMetricsContent> batch) { if (!batch.isEmpty()) { doSaveData(batch); log.debug("[Victoria Metrics] Flushed {} metrics items", batch.size()); } } private void triggerIntervalFlushTimer() { if (metricsFlushTimer != null && !metricsFlushTimer.isStop()) { metricsFlushTimer.newTimeout(new MetricsFlushTask(null), insertConfig.flushInterval(), TimeUnit.SECONDS); log.debug("[Victoria Metrics] Rescheduled next flush task in {} seconds.", insertConfig.flushInterval()); } } } /** * Save metric data to victoria-metric via HTTP call */ private void doSaveData(List<VictoriaMetricsContent> contentList) { try { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); if (StringUtils.hasText(victoriaMetricsProp.username()) && StringUtils.hasText(victoriaMetricsProp.password())) { String authStr = victoriaMetricsProp.username() + ":" + victoriaMetricsProp.password(); String encodedAuth = Base64Util.encode(authStr); headers.add(HttpHeaders.AUTHORIZATION, NetworkConstants.BASIC + SignConstants.BLANK + encodedAuth); } StringBuilder stringBuilder = new StringBuilder(); for (VictoriaMetricsContent content : contentList) { stringBuilder.append(JsonUtil.toJson(content)).append("\n"); } String payload = stringBuilder.toString(); Object httpEntity; if (insertConfig.compression().enabled()) { // enable compression headers.set(HttpHeaders.CONTENT_ENCODING, "gzip"); // compress the payload using gzip try (ByteArrayOutputStream bos = new ByteArrayOutputStream(payload.length()); GZIPOutputStream gzip = new GZIPOutputStream(bos)) { gzip.write(payload.getBytes(StandardCharsets.UTF_8)); // finishes writing compressed data before the gzip stream is closed. gzip.finish(); httpEntity = new HttpEntity<>(bos.toByteArray(), headers); } } else { httpEntity = new HttpEntity<>(payload, headers); } ResponseEntity<String> responseEntity = restTemplate.postForEntity(victoriaMetricsProp.url() + IMPORT_PATH, httpEntity, String.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { log.debug("insert metrics data to victoria-metrics success."); } else { log.error("insert metrics data to victoria-metrics failed. {}", responseEntity.getBody()); } } catch (Exception e){ log.error("flush metrics data to victoria-metrics error: {}.", e.getMessage(), e); } } }
googleapis/google-cloud-java
37,420
java-dialogflow/proto-google-cloud-dialogflow-v2/src/main/java/com/google/cloud/dialogflow/v2/InferenceParameter.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/v2/generator.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.v2; /** * * * <pre> * The parameters of inference. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.InferenceParameter} */ public final class InferenceParameter extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.InferenceParameter) InferenceParameterOrBuilder { private static final long serialVersionUID = 0L; // Use InferenceParameter.newBuilder() to construct. private InferenceParameter(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private InferenceParameter() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new InferenceParameter(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.GeneratorProto .internal_static_google_cloud_dialogflow_v2_InferenceParameter_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.GeneratorProto .internal_static_google_cloud_dialogflow_v2_InferenceParameter_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.InferenceParameter.class, com.google.cloud.dialogflow.v2.InferenceParameter.Builder.class); } private int bitField0_; public static final int MAX_OUTPUT_TOKENS_FIELD_NUMBER = 1; private int maxOutputTokens_ = 0; /** * * * <pre> * Optional. Maximum number of the output tokens for the generator. * </pre> * * <code>optional int32 max_output_tokens = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the maxOutputTokens field is set. */ @java.lang.Override public boolean hasMaxOutputTokens() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Optional. Maximum number of the output tokens for the generator. * </pre> * * <code>optional int32 max_output_tokens = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The maxOutputTokens. */ @java.lang.Override public int getMaxOutputTokens() { return maxOutputTokens_; } public static final int TEMPERATURE_FIELD_NUMBER = 2; private double temperature_ = 0D; /** * * * <pre> * Optional. Controls the randomness of LLM predictions. * Low temperature = less random. High temperature = more random. * If unset (or 0), uses a default value of 0. * </pre> * * <code>optional double temperature = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the temperature field is set. */ @java.lang.Override public boolean hasTemperature() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Optional. Controls the randomness of LLM predictions. * Low temperature = less random. High temperature = more random. * If unset (or 0), uses a default value of 0. * </pre> * * <code>optional double temperature = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The temperature. */ @java.lang.Override public double getTemperature() { return temperature_; } public static final int TOP_K_FIELD_NUMBER = 3; private int topK_ = 0; /** * * * <pre> * Optional. Top-k changes how the model selects tokens for output. A top-k of * 1 means the selected token is the most probable among all tokens in the * model's vocabulary (also called greedy decoding), while a top-k of 3 means * that the next token is selected from among the 3 most probable tokens * (using temperature). For each token selection step, the top K tokens with * the highest probabilities are sampled. Then tokens are further filtered * based on topP with the final token selected using temperature sampling. * Specify a lower value for less random responses and a higher value for more * random responses. Acceptable value is [1, 40], default to 40. * </pre> * * <code>optional int32 top_k = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the topK field is set. */ @java.lang.Override public boolean hasTopK() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Optional. Top-k changes how the model selects tokens for output. A top-k of * 1 means the selected token is the most probable among all tokens in the * model's vocabulary (also called greedy decoding), while a top-k of 3 means * that the next token is selected from among the 3 most probable tokens * (using temperature). For each token selection step, the top K tokens with * the highest probabilities are sampled. Then tokens are further filtered * based on topP with the final token selected using temperature sampling. * Specify a lower value for less random responses and a higher value for more * random responses. Acceptable value is [1, 40], default to 40. * </pre> * * <code>optional int32 top_k = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The topK. */ @java.lang.Override public int getTopK() { return topK_; } public static final int TOP_P_FIELD_NUMBER = 4; private double topP_ = 0D; /** * * * <pre> * Optional. Top-p changes how the model selects tokens for output. Tokens are * selected from most K (see topK parameter) probable to least until the sum * of their probabilities equals the top-p value. For example, if tokens A, B, * and C have a probability of 0.3, 0.2, and 0.1 and the top-p value is 0.5, * then the model will select either A or B as the next token (using * temperature) and doesn't consider C. The default top-p value is 0.95. * Specify a lower value for less random responses and a higher value for more * random responses. Acceptable value is [0.0, 1.0], default to 0.95. * </pre> * * <code>optional double top_p = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the topP field is set. */ @java.lang.Override public boolean hasTopP() { return ((bitField0_ & 0x00000008) != 0); } /** * * * <pre> * Optional. Top-p changes how the model selects tokens for output. Tokens are * selected from most K (see topK parameter) probable to least until the sum * of their probabilities equals the top-p value. For example, if tokens A, B, * and C have a probability of 0.3, 0.2, and 0.1 and the top-p value is 0.5, * then the model will select either A or B as the next token (using * temperature) and doesn't consider C. The default top-p value is 0.95. * Specify a lower value for less random responses and a higher value for more * random responses. Acceptable value is [0.0, 1.0], default to 0.95. * </pre> * * <code>optional double top_p = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The topP. */ @java.lang.Override public double getTopP() { return topP_; } 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.writeInt32(1, maxOutputTokens_); } if (((bitField0_ & 0x00000002) != 0)) { output.writeDouble(2, temperature_); } if (((bitField0_ & 0x00000004) != 0)) { output.writeInt32(3, topK_); } if (((bitField0_ & 0x00000008) != 0)) { output.writeDouble(4, topP_); } 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.computeInt32Size(1, maxOutputTokens_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeDoubleSize(2, temperature_); } if (((bitField0_ & 0x00000004) != 0)) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, topK_); } if (((bitField0_ & 0x00000008) != 0)) { size += com.google.protobuf.CodedOutputStream.computeDoubleSize(4, topP_); } 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.InferenceParameter)) { return super.equals(obj); } com.google.cloud.dialogflow.v2.InferenceParameter other = (com.google.cloud.dialogflow.v2.InferenceParameter) obj; if (hasMaxOutputTokens() != other.hasMaxOutputTokens()) return false; if (hasMaxOutputTokens()) { if (getMaxOutputTokens() != other.getMaxOutputTokens()) return false; } if (hasTemperature() != other.hasTemperature()) return false; if (hasTemperature()) { if (java.lang.Double.doubleToLongBits(getTemperature()) != java.lang.Double.doubleToLongBits(other.getTemperature())) return false; } if (hasTopK() != other.hasTopK()) return false; if (hasTopK()) { if (getTopK() != other.getTopK()) return false; } if (hasTopP() != other.hasTopP()) return false; if (hasTopP()) { if (java.lang.Double.doubleToLongBits(getTopP()) != java.lang.Double.doubleToLongBits(other.getTopP())) 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 (hasMaxOutputTokens()) { hash = (37 * hash) + MAX_OUTPUT_TOKENS_FIELD_NUMBER; hash = (53 * hash) + getMaxOutputTokens(); } if (hasTemperature()) { hash = (37 * hash) + TEMPERATURE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( java.lang.Double.doubleToLongBits(getTemperature())); } if (hasTopK()) { hash = (37 * hash) + TOP_K_FIELD_NUMBER; hash = (53 * hash) + getTopK(); } if (hasTopP()) { hash = (37 * hash) + TOP_P_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong(java.lang.Double.doubleToLongBits(getTopP())); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.v2.InferenceParameter parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.InferenceParameter 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.InferenceParameter parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.InferenceParameter 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.InferenceParameter parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.InferenceParameter 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.InferenceParameter parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.InferenceParameter 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.InferenceParameter parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.InferenceParameter 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.InferenceParameter 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.InferenceParameter 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.InferenceParameter 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 parameters of inference. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.InferenceParameter} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.InferenceParameter) com.google.cloud.dialogflow.v2.InferenceParameterOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.GeneratorProto .internal_static_google_cloud_dialogflow_v2_InferenceParameter_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.GeneratorProto .internal_static_google_cloud_dialogflow_v2_InferenceParameter_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.InferenceParameter.class, com.google.cloud.dialogflow.v2.InferenceParameter.Builder.class); } // Construct using com.google.cloud.dialogflow.v2.InferenceParameter.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; maxOutputTokens_ = 0; temperature_ = 0D; topK_ = 0; topP_ = 0D; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2.GeneratorProto .internal_static_google_cloud_dialogflow_v2_InferenceParameter_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2.InferenceParameter getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2.InferenceParameter.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2.InferenceParameter build() { com.google.cloud.dialogflow.v2.InferenceParameter result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2.InferenceParameter buildPartial() { com.google.cloud.dialogflow.v2.InferenceParameter result = new com.google.cloud.dialogflow.v2.InferenceParameter(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.dialogflow.v2.InferenceParameter result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.maxOutputTokens_ = maxOutputTokens_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.temperature_ = temperature_; to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000004) != 0)) { result.topK_ = topK_; to_bitField0_ |= 0x00000004; } if (((from_bitField0_ & 0x00000008) != 0)) { result.topP_ = topP_; 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.dialogflow.v2.InferenceParameter) { return mergeFrom((com.google.cloud.dialogflow.v2.InferenceParameter) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.v2.InferenceParameter other) { if (other == com.google.cloud.dialogflow.v2.InferenceParameter.getDefaultInstance()) return this; if (other.hasMaxOutputTokens()) { setMaxOutputTokens(other.getMaxOutputTokens()); } if (other.hasTemperature()) { setTemperature(other.getTemperature()); } if (other.hasTopK()) { setTopK(other.getTopK()); } if (other.hasTopP()) { setTopP(other.getTopP()); } 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: { maxOutputTokens_ = input.readInt32(); bitField0_ |= 0x00000001; break; } // case 8 case 17: { temperature_ = input.readDouble(); bitField0_ |= 0x00000002; break; } // case 17 case 24: { topK_ = input.readInt32(); bitField0_ |= 0x00000004; break; } // case 24 case 33: { topP_ = input.readDouble(); bitField0_ |= 0x00000008; 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 int maxOutputTokens_; /** * * * <pre> * Optional. Maximum number of the output tokens for the generator. * </pre> * * <code>optional int32 max_output_tokens = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the maxOutputTokens field is set. */ @java.lang.Override public boolean hasMaxOutputTokens() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Optional. Maximum number of the output tokens for the generator. * </pre> * * <code>optional int32 max_output_tokens = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The maxOutputTokens. */ @java.lang.Override public int getMaxOutputTokens() { return maxOutputTokens_; } /** * * * <pre> * Optional. Maximum number of the output tokens for the generator. * </pre> * * <code>optional int32 max_output_tokens = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The maxOutputTokens to set. * @return This builder for chaining. */ public Builder setMaxOutputTokens(int value) { maxOutputTokens_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Optional. Maximum number of the output tokens for the generator. * </pre> * * <code>optional int32 max_output_tokens = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearMaxOutputTokens() { bitField0_ = (bitField0_ & ~0x00000001); maxOutputTokens_ = 0; onChanged(); return this; } private double temperature_; /** * * * <pre> * Optional. Controls the randomness of LLM predictions. * Low temperature = less random. High temperature = more random. * If unset (or 0), uses a default value of 0. * </pre> * * <code>optional double temperature = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the temperature field is set. */ @java.lang.Override public boolean hasTemperature() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Optional. Controls the randomness of LLM predictions. * Low temperature = less random. High temperature = more random. * If unset (or 0), uses a default value of 0. * </pre> * * <code>optional double temperature = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The temperature. */ @java.lang.Override public double getTemperature() { return temperature_; } /** * * * <pre> * Optional. Controls the randomness of LLM predictions. * Low temperature = less random. High temperature = more random. * If unset (or 0), uses a default value of 0. * </pre> * * <code>optional double temperature = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The temperature to set. * @return This builder for chaining. */ public Builder setTemperature(double value) { temperature_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Controls the randomness of LLM predictions. * Low temperature = less random. High temperature = more random. * If unset (or 0), uses a default value of 0. * </pre> * * <code>optional double temperature = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearTemperature() { bitField0_ = (bitField0_ & ~0x00000002); temperature_ = 0D; onChanged(); return this; } private int topK_; /** * * * <pre> * Optional. Top-k changes how the model selects tokens for output. A top-k of * 1 means the selected token is the most probable among all tokens in the * model's vocabulary (also called greedy decoding), while a top-k of 3 means * that the next token is selected from among the 3 most probable tokens * (using temperature). For each token selection step, the top K tokens with * the highest probabilities are sampled. Then tokens are further filtered * based on topP with the final token selected using temperature sampling. * Specify a lower value for less random responses and a higher value for more * random responses. Acceptable value is [1, 40], default to 40. * </pre> * * <code>optional int32 top_k = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the topK field is set. */ @java.lang.Override public boolean hasTopK() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Optional. Top-k changes how the model selects tokens for output. A top-k of * 1 means the selected token is the most probable among all tokens in the * model's vocabulary (also called greedy decoding), while a top-k of 3 means * that the next token is selected from among the 3 most probable tokens * (using temperature). For each token selection step, the top K tokens with * the highest probabilities are sampled. Then tokens are further filtered * based on topP with the final token selected using temperature sampling. * Specify a lower value for less random responses and a higher value for more * random responses. Acceptable value is [1, 40], default to 40. * </pre> * * <code>optional int32 top_k = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The topK. */ @java.lang.Override public int getTopK() { return topK_; } /** * * * <pre> * Optional. Top-k changes how the model selects tokens for output. A top-k of * 1 means the selected token is the most probable among all tokens in the * model's vocabulary (also called greedy decoding), while a top-k of 3 means * that the next token is selected from among the 3 most probable tokens * (using temperature). For each token selection step, the top K tokens with * the highest probabilities are sampled. Then tokens are further filtered * based on topP with the final token selected using temperature sampling. * Specify a lower value for less random responses and a higher value for more * random responses. Acceptable value is [1, 40], default to 40. * </pre> * * <code>optional int32 top_k = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The topK to set. * @return This builder for chaining. */ public Builder setTopK(int value) { topK_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Top-k changes how the model selects tokens for output. A top-k of * 1 means the selected token is the most probable among all tokens in the * model's vocabulary (also called greedy decoding), while a top-k of 3 means * that the next token is selected from among the 3 most probable tokens * (using temperature). For each token selection step, the top K tokens with * the highest probabilities are sampled. Then tokens are further filtered * based on topP with the final token selected using temperature sampling. * Specify a lower value for less random responses and a higher value for more * random responses. Acceptable value is [1, 40], default to 40. * </pre> * * <code>optional int32 top_k = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearTopK() { bitField0_ = (bitField0_ & ~0x00000004); topK_ = 0; onChanged(); return this; } private double topP_; /** * * * <pre> * Optional. Top-p changes how the model selects tokens for output. Tokens are * selected from most K (see topK parameter) probable to least until the sum * of their probabilities equals the top-p value. For example, if tokens A, B, * and C have a probability of 0.3, 0.2, and 0.1 and the top-p value is 0.5, * then the model will select either A or B as the next token (using * temperature) and doesn't consider C. The default top-p value is 0.95. * Specify a lower value for less random responses and a higher value for more * random responses. Acceptable value is [0.0, 1.0], default to 0.95. * </pre> * * <code>optional double top_p = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the topP field is set. */ @java.lang.Override public boolean hasTopP() { return ((bitField0_ & 0x00000008) != 0); } /** * * * <pre> * Optional. Top-p changes how the model selects tokens for output. Tokens are * selected from most K (see topK parameter) probable to least until the sum * of their probabilities equals the top-p value. For example, if tokens A, B, * and C have a probability of 0.3, 0.2, and 0.1 and the top-p value is 0.5, * then the model will select either A or B as the next token (using * temperature) and doesn't consider C. The default top-p value is 0.95. * Specify a lower value for less random responses and a higher value for more * random responses. Acceptable value is [0.0, 1.0], default to 0.95. * </pre> * * <code>optional double top_p = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The topP. */ @java.lang.Override public double getTopP() { return topP_; } /** * * * <pre> * Optional. Top-p changes how the model selects tokens for output. Tokens are * selected from most K (see topK parameter) probable to least until the sum * of their probabilities equals the top-p value. For example, if tokens A, B, * and C have a probability of 0.3, 0.2, and 0.1 and the top-p value is 0.5, * then the model will select either A or B as the next token (using * temperature) and doesn't consider C. The default top-p value is 0.95. * Specify a lower value for less random responses and a higher value for more * random responses. Acceptable value is [0.0, 1.0], default to 0.95. * </pre> * * <code>optional double top_p = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The topP to set. * @return This builder for chaining. */ public Builder setTopP(double value) { topP_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Optional. Top-p changes how the model selects tokens for output. Tokens are * selected from most K (see topK parameter) probable to least until the sum * of their probabilities equals the top-p value. For example, if tokens A, B, * and C have a probability of 0.3, 0.2, and 0.1 and the top-p value is 0.5, * then the model will select either A or B as the next token (using * temperature) and doesn't consider C. The default top-p value is 0.95. * Specify a lower value for less random responses and a higher value for more * random responses. Acceptable value is [0.0, 1.0], default to 0.95. * </pre> * * <code>optional double top_p = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearTopP() { bitField0_ = (bitField0_ & ~0x00000008); topP_ = 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.dialogflow.v2.InferenceParameter) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.InferenceParameter) private static final com.google.cloud.dialogflow.v2.InferenceParameter DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.InferenceParameter(); } public static com.google.cloud.dialogflow.v2.InferenceParameter getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<InferenceParameter> PARSER = new com.google.protobuf.AbstractParser<InferenceParameter>() { @java.lang.Override public InferenceParameter 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<InferenceParameter> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<InferenceParameter> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2.InferenceParameter getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/sis
37,689
endorsed/src/org.apache.sis.feature/test/org/apache/sis/coverage/grid/ResampledGridCoverageTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sis.coverage.grid; import java.util.Arrays; import java.util.Random; import java.util.EnumSet; import java.util.stream.IntStream; import java.awt.Color; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.awt.image.WritableRaster; import org.opengis.referencing.cs.AxisDirection; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.TransformException; import org.opengis.util.FactoryException; import org.apache.sis.geometry.Envelope2D; import org.apache.sis.geometry.DirectPosition2D; import org.apache.sis.geometry.ImmutableEnvelope; import org.apache.sis.image.Interpolation; import org.apache.sis.image.internal.shared.TiledImage; import org.apache.sis.image.internal.shared.ReshapedImage; import org.apache.sis.referencing.CommonCRS; import org.apache.sis.referencing.internal.shared.Formulas; import org.apache.sis.referencing.internal.shared.AffineTransform2D; import org.apache.sis.referencing.cs.AxesConvention; import org.apache.sis.referencing.operation.matrix.Matrices; import org.apache.sis.referencing.operation.matrix.MatrixSIS; import org.apache.sis.referencing.operation.transform.MathTransforms; import org.apache.sis.referencing.operation.transform.TransformSeparator; import static org.apache.sis.coverage.grid.PixelInCell.CELL_CENTER; // Test dependencies import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import org.apache.sis.test.TestCase; import org.apache.sis.test.TestUtilities; import org.apache.sis.image.TiledImageMock; import org.apache.sis.referencing.crs.HardCodedCRS; import org.apache.sis.referencing.operation.HardCodedConversions; import static org.apache.sis.referencing.Assertions.assertEnvelopeEquals; import static org.apache.sis.feature.Assertions.assertValuesEqual; import static org.apache.sis.feature.Assertions.assertPixelsEqual; // Specific to the main branch: import static org.apache.sis.test.GeoapiAssert.assertAxisDirectionsEqual; /** * Tests the {@link ResampledGridCoverage} implementation. * The tests in this class does not verify interpolation results * (this is {@link org.apache.sis.image.ResampledImageTest} job). * Instead, it focuses on the grid geometry inferred by the operation. * * @author Martin Desruisseaux (Geomatys) * @author Alexis Manin (Geomatys) * @author Johann Sorel (Geomatys) */ public final class ResampledGridCoverageTest extends TestCase { /** * The random number generator used for generating some grid coverage values. * Created only if needed. */ private Random random; /** * Arbitrary non-zero grid coordinate for the <var>z</var> dimensions. */ private int gridZ; /** * Creates a new test case. */ public ResampledGridCoverageTest() { } /** * Creates a small grid coverage with arbitrary data. The rendered image will * have only one tile because testing tiling is not the purpose of this class. * This simple coverage is two-dimensional. */ private GridCoverage2D createCoverage2D() { random = TestUtilities.createRandomNumberGenerator(); final int width = random.nextInt(8) + 3; final int height = random.nextInt(8) + 3; final TiledImageMock image = new TiledImageMock( DataBuffer.TYPE_USHORT, 2, // dataType and numBands random.nextInt(32) - 10, // minX (no effect on tests) random.nextInt(32) - 10, // minY (no effect on tests) width, height, // Image size width, height, // Tile size random.nextInt(32) - 10, // minTileX random.nextInt(32) - 10, // minTileY random.nextBoolean()); // Banded or interleaved sample model image.validate(); image.initializeAllTiles(0); final int x = random.nextInt(32) - 10; final int y = random.nextInt(32) - 10; final GridGeometry gg = new GridGeometry( new GridExtent(null, new long[] {x, y}, new long[] {x+width, y+height}, false), new Envelope2D(HardCodedCRS.WGS84, 20, 15, 60, 62), GridOrientation.HOMOTHETY); return new GridCoverage2D(gg, null, image); } /** * Size of a quadrant in the coverage created by {@link #createCoverageND(boolean)}. * The total image width and height are {@code 2*Q}. */ private static final int QS = 3; /** * Low values for the grid extent created by {@link #createCoverage2D()}. */ private static final int LX = 3, LY = -2; /** * Creates a coverage in {@linkplain HardCodedCRS#WGS84_3D OGC:CRS:84 + elevation} reference system. * If the {@code withTime} argument is {@code true}, then the coverage will also include a temporal * dimension. The grid coverage characteristics are: * <ul> * <li>Dimension is 6×6.</li> * <li>Grid extent starts at arbitrary non-zero low values.</li> * <li>Envelope is arbitrary but stable (no random values).</li> * <li>Display oriented (origin is in upper-left corner).</li> * <li>3 byte bands for RGB coloration.</li> * <li>Each quarter of the overall image is filled with a plain color: * <table style="color:white;border-collapse:collapse;"> * <tbody style="border:none"> * <tr> * <td style="width:50%; background-color:black">Black</td> * <td style="width:50%; background-color:red">Red</td> * </tr> * <tr> * <td style="width:50%; background-color:green">Green</td> * <td style="width:50%; background-color:blue">Blue</td> * </tr> * </tbody> * </table> * </li> * </ul> * * @param withTime {@code false} for a three-dimensional coverage, or {@code true} for adding a temporal dimension. * @return a new three- or four-dimensional RGB Grid Coverage. */ private GridCoverage createCoverageND(final boolean withTime) { random = TestUtilities.createRandomNumberGenerator(); final BufferedImage image = new BufferedImage(2*QS, 2*QS, BufferedImage.TYPE_3BYTE_BGR); final int[] color = new int[QS*QS]; /* Upper-left quarter */ // Keep default value, which is black. /* Upper-right quarter */ Arrays.fill(color, Color.RED .getRGB()); image.setRGB(QS, 0, QS, QS, color, 0, QS); /* Lower-left quarter */ Arrays.fill(color, Color.GREEN.getRGB()); image.setRGB( 0, QS, QS, QS, color, 0, QS); /* Lower-right quarter */ Arrays.fill(color, Color.BLUE .getRGB()); image.setRGB(QS, QS, QS, QS, color, 0, QS); /* * Create an image with origin between -2 and +2. We use a random image location for more * complete testing, but actually the tests in this class are independent of image origin. * Note that grid extent origin does not need to be the same as image origin. */ final int minX = random.nextInt(5) - 2; final int minY = random.nextInt(5) - 2; GridGeometry gg = createGridGeometryND(withTime ? HardCodedCRS.WGS84_4D : HardCodedCRS.WGS84_3D, 0, 1, 2, 3, false); final TiledImage shiftedImage = new TiledImage(null, image.getColorModel(), image.getWidth(), image.getHeight(), // Image size random.nextInt(32) - 10, // minTileX random.nextInt(32) - 10, // minTileY image.getRaster().createTranslatedChild(minX, minY)); return new GridCoverage2D(gg, null, shiftedImage); } /** * Creates the grid geometry associated with {@link #createCoverageND(boolean)}, optionally with swapped * horizontal axes and flipped Y axis. The given CRS shall have 3 or 4 dimensions. * * @param crs the coordinate reference system to assign to the grid geometry. * @param x dimension of <var>x</var> coordinates (typically 0). * @param y dimension of <var>y</var> coordinates (typically 1). * @param z dimension of <var>z</var> coordinates (typically 2). * @param t dimension of <var>t</var> coordinates (typically 3). Ignored if the CRS is not four-dimensional. * @param flipY whether to flip the <var>y</var> axis. */ private GridGeometry createGridGeometryND(final CoordinateReferenceSystem crs, final int x, final int y, final int z, final int t, final boolean flipY) { final int dim = crs.getCoordinateSystem().getDimension(); final long[] lower = new long[dim]; final long[] upper = new long[dim]; lower[x] = LX; upper[x] = LX + 2*QS - 1; lower[y] = LY; upper[y] = LY + 2*QS - 1; final MatrixSIS gridToCRS = Matrices.createIdentity(dim + 1); gridToCRS.setElement(x, x, 44./(2*QS)); // X scale gridToCRS.setElement(x, dim, -50./(2*QS)); // X translation gridToCRS.setElement(y, y, -3.5); // Y scale gridToCRS.setElement(y, dim, -0.75); // Y translation gridToCRS.setElement(z, dim, -100); lower[z] = upper[z] = gridZ = 7; // Arbitrary non-zero position in the grid. if (t < dim) { gridToCRS.setElement(t, dim, 48055); lower[t] = upper[t] = 12; } if (flipY) { /* * Lower Y coordinate before flip: Ty₁ + scale × LY * Upper Y coordinate after flip: Ty₂ − scale × (LY+2×QS−1) * Condition Ty₁ = Ty₂ gives: Ty₂ = Ty₁ + scale × (2(QS+LY)−1) */ gridToCRS.setElement(y, y, 3.5); // Inverse sign. gridToCRS.setElement(y, dim, -0.75 + -3.5 * (2*(QS+LY) - 1)); } return new GridGeometry(new GridExtent(null, lower, upper, true), CELL_CENTER, MathTransforms.linear(gridToCRS), crs); } /** * Verifies that the given target coverage has the same pixel values as the source coverage. * This method opportunistically verifies that the target {@link GridCoverage} instance has a * {@link GridCoverage#render(GridExtent)} implementation conforms to the specification, i.e. * that requesting only a sub-area results in an image where pixel coordinate (0,0) corresponds * to cell coordinates in the lower corner of specified {@code sliceExtent}. */ private void assertContentEquals(final GridCoverage source, final GridCoverage target) { final int tx = random.nextInt(3); final int ty = random.nextInt(3); final GridExtent sourceExtent = source.gridGeometry.getExtent(); final int newWidth = StrictMath.toIntExact(sourceExtent.getSize(0) - tx); final int newHeight = StrictMath.toIntExact(sourceExtent.getSize(1) - ty); GridExtent subExtent = new GridExtent( StrictMath.toIntExact(sourceExtent.getLow(0) + tx), StrictMath.toIntExact(sourceExtent.getLow(1) + ty), newWidth, newHeight ); assertPixelsEqual(source.render(null), new Rectangle(tx, ty, newWidth, newHeight), target.render(subExtent), new Rectangle(newWidth, newHeight)); } /** * Returns a resampled coverage using processor with default configuration. * We use processor instead of instantiating {@link ResampledGridCoverage} directly in order * to test {@link GridCoverageProcessor#resample(GridCoverage, GridGeometry)} method as well. * * <p>{@link GridCoverageProcessor.Optimization#REPLACE_OPERATION} is disabled for avoiding to * test another operation than the resampling one.</p> */ private static GridCoverage resample(final GridCoverage source, final GridGeometry target) throws TransformException { final GridCoverageProcessor processor = new GridCoverageProcessor(); processor.setOptimizations(EnumSet.of(GridCoverageProcessor.Optimization.REPLACE_SOURCE)); processor.setInterpolation(Interpolation.NEAREST); return processor.resample(source, target); } /** * Tests application of an identity transform computed from an explicitly given "grid to CRS" transform. * We expect the source coverage to be returned unchanged. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testExplicitIdentity() throws TransformException { final GridCoverage2D source = createCoverage2D(); GridGeometry gg = source.getGridGeometry(); gg = new GridGeometry(null, CELL_CENTER, gg.getGridToCRS(CELL_CENTER), gg.getCoordinateReferenceSystem()); final GridCoverage target = resample(source, gg); assertSame(source, target, "Identity transform should result in same coverage."); assertContentEquals(source, target); } /** * Tests application of an identity transform without specifying explicitly the desired grid geometry. * This test is identical to {@link #testExplicitIdentity()} except that the "grid to CRS" transform * specified to the {@code resample(…)} operation is null. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testImplicitIdentity() throws TransformException { final GridCoverage2D source = createCoverage2D(); GridGeometry gg = source.getGridGeometry(); gg = new GridGeometry(null, CELL_CENTER, null, gg.getCoordinateReferenceSystem()); final GridCoverage target = resample(source, gg); assertSame(source, target, "Identity transform should result in same coverage."); assertContentEquals(source, target); } /** * Tests resampling with a transform which is only a translation by integer values. * This test verifies that an optimized path (much cheaper than real resampling) is taken. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testIntegerTranslation() throws TransformException { final GridCoverageProcessor processor = new GridCoverageProcessor(); // With all optimization enabled. final GridCoverage source = createCoverage2D(); final GridGeometry sourceGG = source.getGridGeometry(); final GridGeometry targetGG = sourceGG.shiftGrid(-10, 15); final GridCoverage target = processor.resample(source, targetGG); assertInstanceOf(TranslatedGridCoverage.class, target, "Expected fast path."); assertSame(targetGG, target.getGridGeometry()); assertEnvelopeEquals(sourceGG.getEnvelope(), targetGG.getEnvelope(), STRICT); /* * The envelope is BOX(20 15, 80 77). Evaluate a single point inside that envelope. * The result for identical "real world" coordinates should be the same for both coverages. */ final DirectPosition2D p = new DirectPosition2D(sourceGG.getCoordinateReferenceSystem(), 50, 30); assertArrayEquals(source.evaluator().apply(p), target.evaluator().apply(p)); } /** * Tests application of axis swapping in a two-dimensional coverage. * This test verifies the envelope of resampled coverage. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testAxisSwap() throws TransformException { final GridCoverage2D source = createCoverage2D(); GridGeometry gg = new GridGeometry(null, CELL_CENTER, null, HardCodedCRS.WGS84_LATITUDE_FIRST); final GridCoverage target = resample(source, gg); /* * We expect the same image since `ResampledGridCoverage` should have been * able to apply the operation with only a change of `gridToCRS` transform. */ assertNotSame(source, target); assertSame(unwrap(source.render(null)), unwrap(target.render(null))); /* * As an easy way to check that axis swapping has happened, check the envelopes. */ final ImmutableEnvelope se = source.getGridGeometry().envelope; final ImmutableEnvelope te = target.getGridGeometry().envelope; assertEquals(se.getLower(0), te.getLower(1), Formulas.ANGULAR_TOLERANCE); assertEquals(se.getLower(1), te.getLower(0), Formulas.ANGULAR_TOLERANCE); assertEquals(se.getUpper(0), te.getUpper(1), Formulas.ANGULAR_TOLERANCE); assertEquals(se.getUpper(1), te.getUpper(0), Formulas.ANGULAR_TOLERANCE); } /** * Unwraps the given image if it is an instance of {@link ReshapedImage}. */ private static RenderedImage unwrap(final RenderedImage image) { assertEquals(0, image.getMinX(), "GridCoverage.render(null) should have their origin at (0,0)."); assertEquals(0, image.getMinY(), "GridCoverage.render(null) should have their origin at (0,0)."); return (image instanceof ReshapedImage) ? ((ReshapedImage) image).source : image; } /** * Tests application of axis swapping in a three-dimensional coverage, together with an axis flip. * This test verifies that the pixel values of resampled coverage are found in expected quadrant. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testAxisSwapAndFlip() throws TransformException { final GridCoverage source = createCoverageND(false); final GridGeometry target = createGridGeometryND(CommonCRS.WGS84.geographic3D(), 1, 0, 2, 3, true); final GridCoverage result = resample(source, target); final RenderedImage sourceImage = source.render(null); final RenderedImage targetImage = result.render(null); assertEquals(target, result.getGridGeometry()); assertEquals(0, sourceImage.getMinX()); // As per GridCoverage.render(…) contract. assertEquals(0, sourceImage.getMinY()); assertEquals(0, targetImage.getMinX()); assertEquals(0, targetImage.getMinY()); assertPixelsEqual(sourceImage, new Rectangle( 0, QS, QS, QS), targetImage, new Rectangle( 0, 0, QS, QS)); // Green should be top-left. assertPixelsEqual(sourceImage, new Rectangle( 0, 0, QS, QS), targetImage, new Rectangle(QS, 0, QS, QS)); // Black should be upper-right. assertPixelsEqual(sourceImage, new Rectangle(QS, QS, QS, QS), targetImage, new Rectangle( 0, QS, QS, QS)); // Blue should be lower-left. assertPixelsEqual(sourceImage, new Rectangle(QS, 0, QS, QS), targetImage, new Rectangle(QS, QS, QS, QS)); // Red should be lower-right. } /** * Tests an operation moving the dimension of temporal axis in a four-dimensional coverage. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testTemporalAxisMoved() throws TransformException { final GridCoverage source = createCoverageND(true); final GridGeometry target = createGridGeometryND(HardCodedCRS.WGS84_4D_TIME_FIRST, 1, 2, 3, 0, false); final GridCoverage result = resample(source, target); assertAxisDirectionsEqual(result.getGridGeometry().getCoordinateReferenceSystem().getCoordinateSystem(), new AxisDirection[] {AxisDirection.FUTURE, AxisDirection.EAST, AxisDirection.NORTH, AxisDirection.UP}, "Expected (t,λ,φ,H) axes."); assertPixelsEqual(source.render(null), null, result.render(null), null); } /** * Tests resampling in a sub-region specified by a grid extent. This method uses a three-dimensional coverage, * which implies that this method also tests the capability to identify which slice needs to be resampled. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testSubGridExtent() throws TransformException { final GridCoverage source = createCoverageND(false); final GridGeometry sourceGeom = source.getGridGeometry(); final GridGeometry targetGeom = new GridGeometry( new GridExtent(null, new long[] {LX+2, LY+2, gridZ}, new long[] {LX+5, LY+5, gridZ}, true), CELL_CENTER, sourceGeom.gridToCRS, sourceGeom.getCoordinateReferenceSystem()); final GridCoverage result = resample(source, targetGeom); assertEquals(targetGeom, result.getGridGeometry()); /* * Verify that the target coverage contains all pixel values of the source coverage. * Iteration over source pixels needs to be restricted to the `targetGeom` extent. */ final RenderedImage sourceImage = source.render(null); RenderedImage targetImage = result.render(null); assertPixelsEqual(sourceImage, new Rectangle(2, 2, 4, 4), targetImage, null); /* * Verify GridCoverage.render(GridExtent) contract: the origin of the returned image * shall be the lower-left corner of `sliceExtent`, which is (3,3) in this test. */ targetImage = result.render(new GridExtent(null, new long[] {LX+3, LY+3, gridZ}, new long[] {LX+4, LY+4, gridZ}, true)); assertPixelsEqual(sourceImage, new Rectangle(3, 3, 2, 2), targetImage, new Rectangle(0, 0, 2, 2)); } /** * Tests resampling in a sub-region specified by a grid extent spanning a single column. * When trying to optimize resampling by dropping dimensions, it can happen that transform dimensions * are reduced to 1D. However, it is a problem for image case which requires 2D coordinates. * So we must ensure that resample conversion keeps at least two dimensions. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testSubGridExtentColumnar() throws TransformException { final GridCoverage2D source = createCoverage2D(); final GridGeometry sourceGeom = source.getGridGeometry(); final GridExtent sourceExtent = sourceGeom.getExtent(); final GridExtent targetExtent = new GridExtent(null, new long[] {sourceExtent.getLow(0), sourceExtent.getLow (1)}, new long[] {sourceExtent.getLow(0), sourceExtent.getHigh(1)}, true); final GridGeometry targetGeom = new GridGeometry( targetExtent, CELL_CENTER, sourceGeom.getGridToCRS(CELL_CENTER), sourceGeom.getCoordinateReferenceSystem()); final GridCoverage result = resample(source, targetGeom); final int height = (int) targetExtent.getSize(1); assertPixelsEqual(source.render(null), new Rectangle(0, 0, 1, height), result.render(null), null); } /** * Tests resampling in a sub-region specified by an envelope. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testSubGeographicArea() throws TransformException { final GridCoverage2D source = createCoverage2D(); // Envelope2D(20, 15, 60, 62) final GridGeometry gg = new GridGeometry(null, new Envelope2D(HardCodedCRS.WGS84, 18, 20, 17, 31), GridOrientation.HOMOTHETY); final GridCoverage target = resample(source, gg); final GridExtent sourceExtent = source.getGridGeometry().getExtent(); final GridExtent targetExtent = target.getGridGeometry().getExtent(); assertTrue(sourceExtent.getSize(0) > targetExtent.getSize(0)); assertTrue(sourceExtent.getSize(1) > targetExtent.getSize(1)); } /** * Tests application of a non-linear transform. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testReprojection() throws TransformException { final GridCoverage2D source = createCoverage2D(); GridGeometry gg = new GridGeometry(null, CELL_CENTER, null, HardCodedConversions.mercator()); final GridCoverage target = resample(source, gg); assertTrue(target.getGridGeometry().getExtent().startsAtZero()); /* * Mercator projection does not change pixel width, but change pixel height. */ final GridExtent sourceExtent = source.getGridGeometry().getExtent(); final GridExtent targetExtent = target.getGridGeometry().getExtent(); assertEquals(sourceExtent.getSize(0), targetExtent.getSize(0)); assertTrue (sourceExtent.getSize(1) <= targetExtent.getSize(1)); } /** * Tests application of a three-dimensional transform which cannot be reduced to a two-dimensional transform. * It happens for example when transformation of <var>x</var> or <var>y</var> coordinate depends on <var>z</var> * coordinate value. In such case we cannot separate the 3D transform into (2D + 1D) transforms. This method * verifies that {@link ResampledGridCoverage} nevertheless manages to do its work even in that situation. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testNonSeparableGridToCRS() throws TransformException { final GridCoverage source = createCoverageND(false); final MatrixSIS nonSeparableMatrix = Matrices.createDiagonal(4, 4); nonSeparableMatrix.setElement(0, 2, 1); // Make X dependent of Z. nonSeparableMatrix.setElement(1, 2, 1); // Make Y dependent of Z. final MathTransform nonSeparableG2C = MathTransforms.concatenate( source.getGridGeometry().getGridToCRS(CELL_CENTER), MathTransforms.linear(nonSeparableMatrix)); { /* * The test in this block is not a `ResampleGridCoverage` test, but rather a * check for a condition that we need for the test performed in this method. */ final TransformSeparator separator = new TransformSeparator(nonSeparableG2C); separator.addSourceDimensions(0, 1); separator.addTargetDimensions(0, 1); assertNotNull(assertThrows(FactoryException.class, () -> separator.separate(), "Test requires a non-separable transform, but separation succeed.")); } final GridGeometry targetGeom = new GridGeometry( null, // Let the resample operation compute the extent automatically. CELL_CENTER, nonSeparableG2C, source.getCoordinateReferenceSystem()); /* * Real test is below (above code was only initialization). * Target image should be 6×6 pixels, like source image. */ final GridCoverage result = resample(source, targetGeom); assertPixelsEqual(source.render(null), null, result.render(null), null); } /** * Tests the addition of a temporal axis. The value to insert in the temporal coordinate can be computed * from the four-dimensional "grid to CRS" transform given in argument to the {@code resample(…)} method, * combined with the source grid extent. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testDimensionalityIncrease() throws TransformException { final GridCoverage source3D = createCoverageND(false); final GridGeometry target4D = createGridGeometryND(HardCodedCRS.WGS84_4D, 0, 1, 2, 3, false); final GridCoverage result = resample(source3D, target4D); assertEquals(target4D, result.getGridGeometry()); assertPixelsEqual(source3D.render(null), null, result.render(null), null); } /** * Tests the removal of temporal axis. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testDimensionalityReduction() throws TransformException { final GridGeometry target3D = createGridGeometryND(HardCodedCRS.WGS84_3D, 0, 1, 2, 3, false); final GridCoverage source4D = createCoverageND(true); final GridCoverage result = resample(source4D, target3D); assertEquals(target3D, result.getGridGeometry()); assertPixelsEqual(source4D.render(null), null, result.render(null), null); } /** * Tests resampling with a target domain larger than the source domain. * Pixel outside the source domain shall be set to fill value, which is 0. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. * * @see <a href="https://issues.apache.org/jira/browse/SIS-495">SIS-495</a> */ @Test public void testDomainIncrease() throws TransformException { final int size = 2; final CoordinateReferenceSystem crs = HardCodedCRS.WGS84; final BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_BYTE_GRAY); image.getRaster().setDataElements(0, 0, size, size, new byte[] {10, 12, 16, 14}); final AffineTransform2D gridToCRS = new AffineTransform2D(1, 0, 0, -1, 0, 0); final GridGeometry sourceGrid = new GridGeometry(null, CELL_CENTER, gridToCRS, crs); final GridGeometry targetGrid = new GridGeometry(new GridExtent(4, 4), CELL_CENTER, gridToCRS, crs); final GridCoverage source = new GridCoverage2D(sourceGrid, null, image); final GridCoverage target = resample(source, targetGrid); assertValuesEqual(target.render(null), 0, new double[][] { {10, 12, 0, 0}, {16, 14, 0, 0}, { 0, 0, 0, 0}, { 0, 0, 0, 0} }); } /** * Tests resampling of an image associated to a coordinate system using the 0 to 360° range of longitude. * The image crosses the 180° longitude. The resampling does not involve map projection. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testLongitude360() throws TransformException { final int width = 32; final int height = 3; final GridGeometry source = new GridGeometry( new GridExtent(width, height), CELL_CENTER, new AffineTransform2D(1, 0, 0, -1, 164, 0), HardCodedCRS.WGS84.forConvention(AxesConvention.POSITIVE_RANGE)); /* * Above grid extent is [164 … 195]° in longitude. The part that exceed 180° is equivalent to * a [-180 … -165]° range. The extent below requests only a part of it, namely [-173 … -167]°. * The first pixel of resampled image is the 23th pixel of original image. */ final GridGeometry target = new GridGeometry( new GridExtent(7, height), CELL_CENTER, new AffineTransform2D(1, 0, 0, -1, -173, 0), HardCodedCRS.WGS84); final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); image.getRaster().setPixels(0, 0, width, height, IntStream.range(100, 100 + width*height).toArray()); final GridCoverage2D coverage = new GridCoverage2D(source, null, image); final GridCoverage resampled = resample(coverage, target); assertValuesEqual(resampled.render(null), 0, new double[][] { {123, 124, 125, 126, 127, 128, 129}, {155, 156, 157, 158, 159, 160, 161}, {187, 188, 189, 190, 191, 192, 193} }); } /** * Tests map reprojection of an image associated to a coordinate system using the 0 to 360° range of longitude. * * @throws TransformException if some coordinates cannot be transformed to the target grid geometry. */ @Test public void testReprojectionFromLongitude360() throws TransformException { /* * Longitudes from 91°E to 235°E (in WGS84 geographic CRS), which is equivalent to 91°E to 125°W. * Latitude range is not important for this test. */ final int width = 8; final int height = 5; final GridGeometry source = new GridGeometry( new GridExtent(null, null, new long[] {width, height}, false), CELL_CENTER, new AffineTransform2D(18, 0, 0, 19, 100, -20), HardCodedCRS.WGS84.forConvention(AxesConvention.POSITIVE_RANGE)); /* * 180°W to 180″E (the world) and 80°S to 80°N in Mercator projection. * Latitude range is about the same as source grid geometry. */ final double xmin = -2.0037508342789244E7; final GridGeometry target = new GridGeometry( new GridExtent(null, null, new long[] {2*width, height}, false), CELL_CENTER, new AffineTransform2D(-xmin/width, 0, 0, 2610000, xmin, -2376500), HardCodedConversions.mercator()); /* * Resample the image by specifying fully the target grid geometry. * The grid coverage should have the exact same instance. */ final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); image.getRaster().setPixels(0, 0, width, height, IntStream.range(100, 100 + width*height).toArray()); final GridCoverage2D coverage = new GridCoverage2D(source, null, image); final GridCoverage resampled = resample(coverage, target); assertSame(target, resampled.getGridGeometry()); /* * Sample values 100, 101, 102, … should be distributed on both sides of the image. */ assertValuesEqual(resampled.render(null), 0, new double[][] { {104, 106, 107, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 101, 102, 103}, {112, 114, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 109, 110, 111}, {120, 122, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 117, 118, 119}, {128, 130, 131, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 125, 126, 127}, {136, 138, 139, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 133, 134, 135}, }); } /** * Returns an image with only the queries part of the given image. * This is a helper tools which can be invoked during debugging * session in IDE capable to display images. * * <h4>Usage</h4> * Add a new watch calling this method on wanted image. * * <h4>Limitations</h4> * <ul> * <li>If given image color-model is null, this method assumes 3 byte/RGB image.</li> * <li>Works only with single-tile images.</li> * </ul> * * @param source the image to display. * @param extent if non-null, crop rendering to the rectangle defined by given extent, * assuming extent low coordinate matches source image (0,0) coordinate. * @return the image directly displayable through debugger. */ private static BufferedImage debug(final RenderedImage source, final GridExtent extent) { Raster tile = source.getTile(source.getMinTileX(), source.getMinTileY()); final int width, height; if (extent == null) { tile = tile.createTranslatedChild(0, 0); width = tile.getWidth(); height = tile.getHeight(); } else { width = StrictMath.toIntExact(extent.getSize(0)); height = StrictMath.toIntExact(extent.getSize(1)); tile = tile.createChild(0, 0, width, height, 0, 0, null); } final BufferedImage view; if (source.getColorModel() == null) { view = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); view.getRaster().setRect(tile); } else { final WritableRaster wr = tile.createCompatibleWritableRaster(0, 0, width, height); wr.setRect(tile); view = new BufferedImage(source.getColorModel(), wr, false, null); } return view; } }
googleapis/google-cloud-java
37,383
java-billingbudgets/proto-google-cloud-billingbudgets-v1/src/main/java/com/google/cloud/billing/budgets/v1/UpdateBudgetRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/billing/budgets/v1/budget_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.billing.budgets.v1; /** * * * <pre> * Request for UpdateBudget * </pre> * * Protobuf type {@code google.cloud.billing.budgets.v1.UpdateBudgetRequest} */ public final class UpdateBudgetRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.billing.budgets.v1.UpdateBudgetRequest) UpdateBudgetRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateBudgetRequest.newBuilder() to construct. private UpdateBudgetRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateBudgetRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateBudgetRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.billing.budgets.v1.BudgetServiceProto .internal_static_google_cloud_billing_budgets_v1_UpdateBudgetRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.billing.budgets.v1.BudgetServiceProto .internal_static_google_cloud_billing_budgets_v1_UpdateBudgetRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.billing.budgets.v1.UpdateBudgetRequest.class, com.google.cloud.billing.budgets.v1.UpdateBudgetRequest.Builder.class); } private int bitField0_; public static final int BUDGET_FIELD_NUMBER = 1; private com.google.cloud.billing.budgets.v1.Budget budget_; /** * * * <pre> * Required. The updated budget object. * The budget to update is specified by the budget name in the budget. * </pre> * * <code> * .google.cloud.billing.budgets.v1.Budget budget = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the budget field is set. */ @java.lang.Override public boolean hasBudget() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The updated budget object. * The budget to update is specified by the budget name in the budget. * </pre> * * <code> * .google.cloud.billing.budgets.v1.Budget budget = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The budget. */ @java.lang.Override public com.google.cloud.billing.budgets.v1.Budget getBudget() { return budget_ == null ? com.google.cloud.billing.budgets.v1.Budget.getDefaultInstance() : budget_; } /** * * * <pre> * Required. The updated budget object. * The budget to update is specified by the budget name in the budget. * </pre> * * <code> * .google.cloud.billing.budgets.v1.Budget budget = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.billing.budgets.v1.BudgetOrBuilder getBudgetOrBuilder() { return budget_ == null ? com.google.cloud.billing.budgets.v1.Budget.getDefaultInstance() : budget_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Optional. Indicates which fields in the provided budget to update. * Read-only fields (such as `name`) cannot be changed. If this is not * provided, then only fields with non-default values from the request are * updated. See * https://developers.google.com/protocol-buffers/docs/proto3#default for more * details about default values. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Optional. Indicates which fields in the provided budget to update. * Read-only fields (such as `name`) cannot be changed. If this is not * provided, then only fields with non-default values from the request are * updated. See * https://developers.google.com/protocol-buffers/docs/proto3#default for more * details about default values. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Optional. Indicates which fields in the provided budget to update. * Read-only fields (such as `name`) cannot be changed. If this is not * provided, then only fields with non-default values from the request are * updated. See * https://developers.google.com/protocol-buffers/docs/proto3#default for more * details about default values. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </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, getBudget()); } 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, getBudget()); } 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.billing.budgets.v1.UpdateBudgetRequest)) { return super.equals(obj); } com.google.cloud.billing.budgets.v1.UpdateBudgetRequest other = (com.google.cloud.billing.budgets.v1.UpdateBudgetRequest) obj; if (hasBudget() != other.hasBudget()) return false; if (hasBudget()) { if (!getBudget().equals(other.getBudget())) 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 (hasBudget()) { hash = (37 * hash) + BUDGET_FIELD_NUMBER; hash = (53 * hash) + getBudget().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.billing.budgets.v1.UpdateBudgetRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.billing.budgets.v1.UpdateBudgetRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.billing.budgets.v1.UpdateBudgetRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.billing.budgets.v1.UpdateBudgetRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.billing.budgets.v1.UpdateBudgetRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.billing.budgets.v1.UpdateBudgetRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.billing.budgets.v1.UpdateBudgetRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.billing.budgets.v1.UpdateBudgetRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.billing.budgets.v1.UpdateBudgetRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.billing.budgets.v1.UpdateBudgetRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.billing.budgets.v1.UpdateBudgetRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.billing.budgets.v1.UpdateBudgetRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.billing.budgets.v1.UpdateBudgetRequest 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 UpdateBudget * </pre> * * Protobuf type {@code google.cloud.billing.budgets.v1.UpdateBudgetRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.billing.budgets.v1.UpdateBudgetRequest) com.google.cloud.billing.budgets.v1.UpdateBudgetRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.billing.budgets.v1.BudgetServiceProto .internal_static_google_cloud_billing_budgets_v1_UpdateBudgetRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.billing.budgets.v1.BudgetServiceProto .internal_static_google_cloud_billing_budgets_v1_UpdateBudgetRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.billing.budgets.v1.UpdateBudgetRequest.class, com.google.cloud.billing.budgets.v1.UpdateBudgetRequest.Builder.class); } // Construct using com.google.cloud.billing.budgets.v1.UpdateBudgetRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getBudgetFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; budget_ = null; if (budgetBuilder_ != null) { budgetBuilder_.dispose(); budgetBuilder_ = 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.billing.budgets.v1.BudgetServiceProto .internal_static_google_cloud_billing_budgets_v1_UpdateBudgetRequest_descriptor; } @java.lang.Override public com.google.cloud.billing.budgets.v1.UpdateBudgetRequest getDefaultInstanceForType() { return com.google.cloud.billing.budgets.v1.UpdateBudgetRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.billing.budgets.v1.UpdateBudgetRequest build() { com.google.cloud.billing.budgets.v1.UpdateBudgetRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.billing.budgets.v1.UpdateBudgetRequest buildPartial() { com.google.cloud.billing.budgets.v1.UpdateBudgetRequest result = new com.google.cloud.billing.budgets.v1.UpdateBudgetRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.billing.budgets.v1.UpdateBudgetRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.budget_ = budgetBuilder_ == null ? budget_ : budgetBuilder_.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.billing.budgets.v1.UpdateBudgetRequest) { return mergeFrom((com.google.cloud.billing.budgets.v1.UpdateBudgetRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.billing.budgets.v1.UpdateBudgetRequest other) { if (other == com.google.cloud.billing.budgets.v1.UpdateBudgetRequest.getDefaultInstance()) return this; if (other.hasBudget()) { mergeBudget(other.getBudget()); } 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(getBudgetFieldBuilder().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.billing.budgets.v1.Budget budget_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.billing.budgets.v1.Budget, com.google.cloud.billing.budgets.v1.Budget.Builder, com.google.cloud.billing.budgets.v1.BudgetOrBuilder> budgetBuilder_; /** * * * <pre> * Required. The updated budget object. * The budget to update is specified by the budget name in the budget. * </pre> * * <code> * .google.cloud.billing.budgets.v1.Budget budget = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the budget field is set. */ public boolean hasBudget() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The updated budget object. * The budget to update is specified by the budget name in the budget. * </pre> * * <code> * .google.cloud.billing.budgets.v1.Budget budget = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The budget. */ public com.google.cloud.billing.budgets.v1.Budget getBudget() { if (budgetBuilder_ == null) { return budget_ == null ? com.google.cloud.billing.budgets.v1.Budget.getDefaultInstance() : budget_; } else { return budgetBuilder_.getMessage(); } } /** * * * <pre> * Required. The updated budget object. * The budget to update is specified by the budget name in the budget. * </pre> * * <code> * .google.cloud.billing.budgets.v1.Budget budget = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setBudget(com.google.cloud.billing.budgets.v1.Budget value) { if (budgetBuilder_ == null) { if (value == null) { throw new NullPointerException(); } budget_ = value; } else { budgetBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The updated budget object. * The budget to update is specified by the budget name in the budget. * </pre> * * <code> * .google.cloud.billing.budgets.v1.Budget budget = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setBudget(com.google.cloud.billing.budgets.v1.Budget.Builder builderForValue) { if (budgetBuilder_ == null) { budget_ = builderForValue.build(); } else { budgetBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The updated budget object. * The budget to update is specified by the budget name in the budget. * </pre> * * <code> * .google.cloud.billing.budgets.v1.Budget budget = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeBudget(com.google.cloud.billing.budgets.v1.Budget value) { if (budgetBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && budget_ != null && budget_ != com.google.cloud.billing.budgets.v1.Budget.getDefaultInstance()) { getBudgetBuilder().mergeFrom(value); } else { budget_ = value; } } else { budgetBuilder_.mergeFrom(value); } if (budget_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The updated budget object. * The budget to update is specified by the budget name in the budget. * </pre> * * <code> * .google.cloud.billing.budgets.v1.Budget budget = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearBudget() { bitField0_ = (bitField0_ & ~0x00000001); budget_ = null; if (budgetBuilder_ != null) { budgetBuilder_.dispose(); budgetBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The updated budget object. * The budget to update is specified by the budget name in the budget. * </pre> * * <code> * .google.cloud.billing.budgets.v1.Budget budget = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.billing.budgets.v1.Budget.Builder getBudgetBuilder() { bitField0_ |= 0x00000001; onChanged(); return getBudgetFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The updated budget object. * The budget to update is specified by the budget name in the budget. * </pre> * * <code> * .google.cloud.billing.budgets.v1.Budget budget = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.billing.budgets.v1.BudgetOrBuilder getBudgetOrBuilder() { if (budgetBuilder_ != null) { return budgetBuilder_.getMessageOrBuilder(); } else { return budget_ == null ? com.google.cloud.billing.budgets.v1.Budget.getDefaultInstance() : budget_; } } /** * * * <pre> * Required. The updated budget object. * The budget to update is specified by the budget name in the budget. * </pre> * * <code> * .google.cloud.billing.budgets.v1.Budget budget = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.billing.budgets.v1.Budget, com.google.cloud.billing.budgets.v1.Budget.Builder, com.google.cloud.billing.budgets.v1.BudgetOrBuilder> getBudgetFieldBuilder() { if (budgetBuilder_ == null) { budgetBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.billing.budgets.v1.Budget, com.google.cloud.billing.budgets.v1.Budget.Builder, com.google.cloud.billing.budgets.v1.BudgetOrBuilder>( getBudget(), getParentForChildren(), isClean()); budget_ = null; } return budgetBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Optional. Indicates which fields in the provided budget to update. * Read-only fields (such as `name`) cannot be changed. If this is not * provided, then only fields with non-default values from the request are * updated. See * https://developers.google.com/protocol-buffers/docs/proto3#default for more * details about default values. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Optional. Indicates which fields in the provided budget to update. * Read-only fields (such as `name`) cannot be changed. If this is not * provided, then only fields with non-default values from the request are * updated. See * https://developers.google.com/protocol-buffers/docs/proto3#default for more * details about default values. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Optional. Indicates which fields in the provided budget to update. * Read-only fields (such as `name`) cannot be changed. If this is not * provided, then only fields with non-default values from the request are * updated. See * https://developers.google.com/protocol-buffers/docs/proto3#default for more * details about default values. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Indicates which fields in the provided budget to update. * Read-only fields (such as `name`) cannot be changed. If this is not * provided, then only fields with non-default values from the request are * updated. See * https://developers.google.com/protocol-buffers/docs/proto3#default for more * details about default values. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Indicates which fields in the provided budget to update. * Read-only fields (such as `name`) cannot be changed. If this is not * provided, then only fields with non-default values from the request are * updated. See * https://developers.google.com/protocol-buffers/docs/proto3#default for more * details about default values. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </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> * Optional. Indicates which fields in the provided budget to update. * Read-only fields (such as `name`) cannot be changed. If this is not * provided, then only fields with non-default values from the request are * updated. See * https://developers.google.com/protocol-buffers/docs/proto3#default for more * details about default values. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Optional. Indicates which fields in the provided budget to update. * Read-only fields (such as `name`) cannot be changed. If this is not * provided, then only fields with non-default values from the request are * updated. See * https://developers.google.com/protocol-buffers/docs/proto3#default for more * details about default values. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Optional. Indicates which fields in the provided budget to update. * Read-only fields (such as `name`) cannot be changed. If this is not * provided, then only fields with non-default values from the request are * updated. See * https://developers.google.com/protocol-buffers/docs/proto3#default for more * details about default values. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Optional. Indicates which fields in the provided budget to update. * Read-only fields (such as `name`) cannot be changed. If this is not * provided, then only fields with non-default values from the request are * updated. See * https://developers.google.com/protocol-buffers/docs/proto3#default for more * details about default values. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.billing.budgets.v1.UpdateBudgetRequest) } // @@protoc_insertion_point(class_scope:google.cloud.billing.budgets.v1.UpdateBudgetRequest) private static final com.google.cloud.billing.budgets.v1.UpdateBudgetRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.billing.budgets.v1.UpdateBudgetRequest(); } public static com.google.cloud.billing.budgets.v1.UpdateBudgetRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateBudgetRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateBudgetRequest>() { @java.lang.Override public UpdateBudgetRequest 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<UpdateBudgetRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateBudgetRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.billing.budgets.v1.UpdateBudgetRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,599
java-compute/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/HttpJsonAutoscalersStub.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.InternalApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.core.BackgroundResourceAggregation; import com.google.api.gax.httpjson.ApiMethodDescriptor; import com.google.api.gax.httpjson.HttpJsonCallSettings; import com.google.api.gax.httpjson.HttpJsonOperationSnapshot; import com.google.api.gax.httpjson.HttpJsonStubCallableFactory; import com.google.api.gax.httpjson.ProtoMessageRequestFormatter; import com.google.api.gax.httpjson.ProtoMessageResponseParser; import com.google.api.gax.httpjson.ProtoRestSerializer; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.RequestParamsBuilder; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.compute.v1.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.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.Operation.Status; import com.google.cloud.compute.v1.PatchAutoscalerRequest; import com.google.cloud.compute.v1.UpdateAutoscalerRequest; import com.google.protobuf.TypeRegistry; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * REST stub implementation for the Autoscalers service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @Generated("by gapic-generator-java") public class HttpJsonAutoscalersStub extends AutoscalersStub { private static final TypeRegistry typeRegistry = TypeRegistry.newBuilder().add(Operation.getDescriptor()).build(); private static final ApiMethodDescriptor< AggregatedListAutoscalersRequest, AutoscalerAggregatedList> aggregatedListMethodDescriptor = ApiMethodDescriptor .<AggregatedListAutoscalersRequest, AutoscalerAggregatedList>newBuilder() .setFullMethodName("google.cloud.compute.v1.Autoscalers/AggregatedList") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<AggregatedListAutoscalersRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/aggregated/autoscalers", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<AggregatedListAutoscalersRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<AggregatedListAutoscalersRequest> serializer = ProtoRestSerializer.create(); if (request.hasFilter()) { serializer.putQueryParam(fields, "filter", request.getFilter()); } if (request.hasIncludeAllScopes()) { serializer.putQueryParam( fields, "includeAllScopes", request.getIncludeAllScopes()); } if (request.hasMaxResults()) { serializer.putQueryParam( fields, "maxResults", request.getMaxResults()); } if (request.hasOrderBy()) { serializer.putQueryParam(fields, "orderBy", request.getOrderBy()); } if (request.hasPageToken()) { serializer.putQueryParam(fields, "pageToken", request.getPageToken()); } if (request.hasReturnPartialSuccess()) { serializer.putQueryParam( fields, "returnPartialSuccess", request.getReturnPartialSuccess()); } if (request.hasServiceProjectNumber()) { serializer.putQueryParam( fields, "serviceProjectNumber", request.getServiceProjectNumber()); } return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<AutoscalerAggregatedList>newBuilder() .setDefaultInstance(AutoscalerAggregatedList.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<DeleteAutoscalerRequest, Operation> deleteMethodDescriptor = ApiMethodDescriptor.<DeleteAutoscalerRequest, Operation>newBuilder() .setFullMethodName("google.cloud.compute.v1.Autoscalers/Delete") .setHttpMethod("DELETE") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<DeleteAutoscalerRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/zones/{zone}/autoscalers/{autoscaler}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<DeleteAutoscalerRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "autoscaler", request.getAutoscaler()); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "zone", request.getZone()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<DeleteAutoscalerRequest> serializer = ProtoRestSerializer.create(); if (request.hasRequestId()) { serializer.putQueryParam(fields, "requestId", request.getRequestId()); } return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (DeleteAutoscalerRequest request, Operation response) -> { StringBuilder opName = new StringBuilder(response.getName()); opName.append(":").append(request.getProject()); opName.append(":").append(request.getZone()); return HttpJsonOperationSnapshot.newBuilder() .setName(opName.toString()) .setMetadata(response) .setDone(Status.DONE.equals(response.getStatus())) .setResponse(response) .setError(response.getHttpErrorStatusCode(), response.getHttpErrorMessage()) .build(); }) .build(); private static final ApiMethodDescriptor<GetAutoscalerRequest, Autoscaler> getMethodDescriptor = ApiMethodDescriptor.<GetAutoscalerRequest, Autoscaler>newBuilder() .setFullMethodName("google.cloud.compute.v1.Autoscalers/Get") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetAutoscalerRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/zones/{zone}/autoscalers/{autoscaler}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetAutoscalerRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "autoscaler", request.getAutoscaler()); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "zone", request.getZone()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetAutoscalerRequest> serializer = ProtoRestSerializer.create(); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Autoscaler>newBuilder() .setDefaultInstance(Autoscaler.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<InsertAutoscalerRequest, Operation> insertMethodDescriptor = ApiMethodDescriptor.<InsertAutoscalerRequest, Operation>newBuilder() .setFullMethodName("google.cloud.compute.v1.Autoscalers/Insert") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<InsertAutoscalerRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/zones/{zone}/autoscalers", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<InsertAutoscalerRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "zone", request.getZone()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<InsertAutoscalerRequest> serializer = ProtoRestSerializer.create(); if (request.hasRequestId()) { serializer.putQueryParam(fields, "requestId", request.getRequestId()); } return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody( "autoscalerResource", request.getAutoscalerResource(), false)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (InsertAutoscalerRequest request, Operation response) -> { StringBuilder opName = new StringBuilder(response.getName()); opName.append(":").append(request.getProject()); opName.append(":").append(request.getZone()); return HttpJsonOperationSnapshot.newBuilder() .setName(opName.toString()) .setMetadata(response) .setDone(Status.DONE.equals(response.getStatus())) .setResponse(response) .setError(response.getHttpErrorStatusCode(), response.getHttpErrorMessage()) .build(); }) .build(); private static final ApiMethodDescriptor<ListAutoscalersRequest, AutoscalerList> listMethodDescriptor = ApiMethodDescriptor.<ListAutoscalersRequest, AutoscalerList>newBuilder() .setFullMethodName("google.cloud.compute.v1.Autoscalers/List") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<ListAutoscalersRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/zones/{zone}/autoscalers", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<ListAutoscalersRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "zone", request.getZone()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<ListAutoscalersRequest> serializer = ProtoRestSerializer.create(); if (request.hasFilter()) { serializer.putQueryParam(fields, "filter", request.getFilter()); } if (request.hasMaxResults()) { serializer.putQueryParam( fields, "maxResults", request.getMaxResults()); } if (request.hasOrderBy()) { serializer.putQueryParam(fields, "orderBy", request.getOrderBy()); } if (request.hasPageToken()) { serializer.putQueryParam(fields, "pageToken", request.getPageToken()); } if (request.hasReturnPartialSuccess()) { serializer.putQueryParam( fields, "returnPartialSuccess", request.getReturnPartialSuccess()); } return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<AutoscalerList>newBuilder() .setDefaultInstance(AutoscalerList.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<PatchAutoscalerRequest, Operation> patchMethodDescriptor = ApiMethodDescriptor.<PatchAutoscalerRequest, Operation>newBuilder() .setFullMethodName("google.cloud.compute.v1.Autoscalers/Patch") .setHttpMethod("PATCH") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<PatchAutoscalerRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/zones/{zone}/autoscalers", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<PatchAutoscalerRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "zone", request.getZone()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<PatchAutoscalerRequest> serializer = ProtoRestSerializer.create(); if (request.hasAutoscaler()) { serializer.putQueryParam( fields, "autoscaler", request.getAutoscaler()); } if (request.hasRequestId()) { serializer.putQueryParam(fields, "requestId", request.getRequestId()); } return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody( "autoscalerResource", request.getAutoscalerResource(), false)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (PatchAutoscalerRequest request, Operation response) -> { StringBuilder opName = new StringBuilder(response.getName()); opName.append(":").append(request.getProject()); opName.append(":").append(request.getZone()); return HttpJsonOperationSnapshot.newBuilder() .setName(opName.toString()) .setMetadata(response) .setDone(Status.DONE.equals(response.getStatus())) .setResponse(response) .setError(response.getHttpErrorStatusCode(), response.getHttpErrorMessage()) .build(); }) .build(); private static final ApiMethodDescriptor<UpdateAutoscalerRequest, Operation> updateMethodDescriptor = ApiMethodDescriptor.<UpdateAutoscalerRequest, Operation>newBuilder() .setFullMethodName("google.cloud.compute.v1.Autoscalers/Update") .setHttpMethod("PUT") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<UpdateAutoscalerRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/zones/{zone}/autoscalers", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<UpdateAutoscalerRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "zone", request.getZone()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<UpdateAutoscalerRequest> serializer = ProtoRestSerializer.create(); if (request.hasAutoscaler()) { serializer.putQueryParam( fields, "autoscaler", request.getAutoscaler()); } if (request.hasRequestId()) { serializer.putQueryParam(fields, "requestId", request.getRequestId()); } return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody( "autoscalerResource", request.getAutoscalerResource(), false)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (UpdateAutoscalerRequest request, Operation response) -> { StringBuilder opName = new StringBuilder(response.getName()); opName.append(":").append(request.getProject()); opName.append(":").append(request.getZone()); return HttpJsonOperationSnapshot.newBuilder() .setName(opName.toString()) .setMetadata(response) .setDone(Status.DONE.equals(response.getStatus())) .setResponse(response) .setError(response.getHttpErrorStatusCode(), response.getHttpErrorMessage()) .build(); }) .build(); private final UnaryCallable<AggregatedListAutoscalersRequest, AutoscalerAggregatedList> aggregatedListCallable; private final UnaryCallable<AggregatedListAutoscalersRequest, AggregatedListPagedResponse> aggregatedListPagedCallable; private final UnaryCallable<DeleteAutoscalerRequest, Operation> deleteCallable; private final OperationCallable<DeleteAutoscalerRequest, Operation, Operation> deleteOperationCallable; private final UnaryCallable<GetAutoscalerRequest, Autoscaler> getCallable; private final UnaryCallable<InsertAutoscalerRequest, Operation> insertCallable; private final OperationCallable<InsertAutoscalerRequest, Operation, Operation> insertOperationCallable; private final UnaryCallable<ListAutoscalersRequest, AutoscalerList> listCallable; private final UnaryCallable<ListAutoscalersRequest, ListPagedResponse> listPagedCallable; private final UnaryCallable<PatchAutoscalerRequest, Operation> patchCallable; private final OperationCallable<PatchAutoscalerRequest, Operation, Operation> patchOperationCallable; private final UnaryCallable<UpdateAutoscalerRequest, Operation> updateCallable; private final OperationCallable<UpdateAutoscalerRequest, Operation, Operation> updateOperationCallable; private final BackgroundResource backgroundResources; private final HttpJsonZoneOperationsStub httpJsonOperationsStub; private final HttpJsonStubCallableFactory callableFactory; public static final HttpJsonAutoscalersStub create(AutoscalersStubSettings settings) throws IOException { return new HttpJsonAutoscalersStub(settings, ClientContext.create(settings)); } public static final HttpJsonAutoscalersStub create(ClientContext clientContext) throws IOException { return new HttpJsonAutoscalersStub(AutoscalersStubSettings.newBuilder().build(), clientContext); } public static final HttpJsonAutoscalersStub create( ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { return new HttpJsonAutoscalersStub( AutoscalersStubSettings.newBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of HttpJsonAutoscalersStub, using the given settings. This is protected * so that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected HttpJsonAutoscalersStub(AutoscalersStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new HttpJsonAutoscalersCallableFactory()); } /** * Constructs an instance of HttpJsonAutoscalersStub, using the given settings. This is protected * so that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected HttpJsonAutoscalersStub( AutoscalersStubSettings settings, ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { this.callableFactory = callableFactory; this.httpJsonOperationsStub = HttpJsonZoneOperationsStub.create(clientContext, callableFactory); HttpJsonCallSettings<AggregatedListAutoscalersRequest, AutoscalerAggregatedList> aggregatedListTransportSettings = HttpJsonCallSettings .<AggregatedListAutoscalersRequest, AutoscalerAggregatedList>newBuilder() .setMethodDescriptor(aggregatedListMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); return builder.build(); }) .build(); HttpJsonCallSettings<DeleteAutoscalerRequest, Operation> deleteTransportSettings = HttpJsonCallSettings.<DeleteAutoscalerRequest, Operation>newBuilder() .setMethodDescriptor(deleteMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("autoscaler", String.valueOf(request.getAutoscaler())); builder.add("project", String.valueOf(request.getProject())); builder.add("zone", String.valueOf(request.getZone())); return builder.build(); }) .build(); HttpJsonCallSettings<GetAutoscalerRequest, Autoscaler> getTransportSettings = HttpJsonCallSettings.<GetAutoscalerRequest, Autoscaler>newBuilder() .setMethodDescriptor(getMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("autoscaler", String.valueOf(request.getAutoscaler())); builder.add("project", String.valueOf(request.getProject())); builder.add("zone", String.valueOf(request.getZone())); return builder.build(); }) .build(); HttpJsonCallSettings<InsertAutoscalerRequest, Operation> insertTransportSettings = HttpJsonCallSettings.<InsertAutoscalerRequest, Operation>newBuilder() .setMethodDescriptor(insertMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); builder.add("zone", String.valueOf(request.getZone())); return builder.build(); }) .build(); HttpJsonCallSettings<ListAutoscalersRequest, AutoscalerList> listTransportSettings = HttpJsonCallSettings.<ListAutoscalersRequest, AutoscalerList>newBuilder() .setMethodDescriptor(listMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); builder.add("zone", String.valueOf(request.getZone())); return builder.build(); }) .build(); HttpJsonCallSettings<PatchAutoscalerRequest, Operation> patchTransportSettings = HttpJsonCallSettings.<PatchAutoscalerRequest, Operation>newBuilder() .setMethodDescriptor(patchMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); builder.add("zone", String.valueOf(request.getZone())); return builder.build(); }) .build(); HttpJsonCallSettings<UpdateAutoscalerRequest, Operation> updateTransportSettings = HttpJsonCallSettings.<UpdateAutoscalerRequest, Operation>newBuilder() .setMethodDescriptor(updateMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); builder.add("zone", String.valueOf(request.getZone())); return builder.build(); }) .build(); this.aggregatedListCallable = callableFactory.createUnaryCallable( aggregatedListTransportSettings, settings.aggregatedListSettings(), clientContext); this.aggregatedListPagedCallable = callableFactory.createPagedCallable( aggregatedListTransportSettings, settings.aggregatedListSettings(), clientContext); this.deleteCallable = callableFactory.createUnaryCallable( deleteTransportSettings, settings.deleteSettings(), clientContext); this.deleteOperationCallable = callableFactory.createOperationCallable( deleteTransportSettings, settings.deleteOperationSettings(), clientContext, httpJsonOperationsStub); this.getCallable = callableFactory.createUnaryCallable( getTransportSettings, settings.getSettings(), clientContext); this.insertCallable = callableFactory.createUnaryCallable( insertTransportSettings, settings.insertSettings(), clientContext); this.insertOperationCallable = callableFactory.createOperationCallable( insertTransportSettings, settings.insertOperationSettings(), clientContext, httpJsonOperationsStub); this.listCallable = callableFactory.createUnaryCallable( listTransportSettings, settings.listSettings(), clientContext); this.listPagedCallable = callableFactory.createPagedCallable( listTransportSettings, settings.listSettings(), clientContext); this.patchCallable = callableFactory.createUnaryCallable( patchTransportSettings, settings.patchSettings(), clientContext); this.patchOperationCallable = callableFactory.createOperationCallable( patchTransportSettings, settings.patchOperationSettings(), clientContext, httpJsonOperationsStub); this.updateCallable = callableFactory.createUnaryCallable( updateTransportSettings, settings.updateSettings(), clientContext); this.updateOperationCallable = callableFactory.createOperationCallable( updateTransportSettings, settings.updateOperationSettings(), clientContext, httpJsonOperationsStub); this.backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources()); } @InternalApi public static List<ApiMethodDescriptor> getMethodDescriptors() { List<ApiMethodDescriptor> methodDescriptors = new ArrayList<>(); methodDescriptors.add(aggregatedListMethodDescriptor); methodDescriptors.add(deleteMethodDescriptor); methodDescriptors.add(getMethodDescriptor); methodDescriptors.add(insertMethodDescriptor); methodDescriptors.add(listMethodDescriptor); methodDescriptors.add(patchMethodDescriptor); methodDescriptors.add(updateMethodDescriptor); return methodDescriptors; } @Override public UnaryCallable<AggregatedListAutoscalersRequest, AutoscalerAggregatedList> aggregatedListCallable() { return aggregatedListCallable; } @Override public UnaryCallable<AggregatedListAutoscalersRequest, AggregatedListPagedResponse> aggregatedListPagedCallable() { return aggregatedListPagedCallable; } @Override public UnaryCallable<DeleteAutoscalerRequest, Operation> deleteCallable() { return deleteCallable; } @Override public OperationCallable<DeleteAutoscalerRequest, Operation, Operation> deleteOperationCallable() { return deleteOperationCallable; } @Override public UnaryCallable<GetAutoscalerRequest, Autoscaler> getCallable() { return getCallable; } @Override public UnaryCallable<InsertAutoscalerRequest, Operation> insertCallable() { return insertCallable; } @Override public OperationCallable<InsertAutoscalerRequest, Operation, Operation> insertOperationCallable() { return insertOperationCallable; } @Override public UnaryCallable<ListAutoscalersRequest, AutoscalerList> listCallable() { return listCallable; } @Override public UnaryCallable<ListAutoscalersRequest, ListPagedResponse> listPagedCallable() { return listPagedCallable; } @Override public UnaryCallable<PatchAutoscalerRequest, Operation> patchCallable() { return patchCallable; } @Override public OperationCallable<PatchAutoscalerRequest, Operation, Operation> patchOperationCallable() { return patchOperationCallable; } @Override public UnaryCallable<UpdateAutoscalerRequest, Operation> updateCallable() { return updateCallable; } @Override public OperationCallable<UpdateAutoscalerRequest, Operation, Operation> updateOperationCallable() { return updateOperationCallable; } @Override public final void close() { try { backgroundResources.close(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalStateException("Failed to close resource", e); } } @Override public void shutdown() { backgroundResources.shutdown(); } @Override public boolean isShutdown() { return backgroundResources.isShutdown(); } @Override public boolean isTerminated() { return backgroundResources.isTerminated(); } @Override public void shutdownNow() { backgroundResources.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return backgroundResources.awaitTermination(duration, unit); } }
googleapis/google-cloud-java
37,301
java-service-management/proto-google-cloud-service-management-v1/src/main/java/com/google/api/servicemanagement/v1/GetServiceConfigRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/servicemanagement/v1/servicemanager.proto // Protobuf Java Version: 3.25.8 package com.google.api.servicemanagement.v1; /** * * * <pre> * Request message for GetServiceConfig method. * </pre> * * Protobuf type {@code google.api.servicemanagement.v1.GetServiceConfigRequest} */ public final class GetServiceConfigRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.api.servicemanagement.v1.GetServiceConfigRequest) GetServiceConfigRequestOrBuilder { private static final long serialVersionUID = 0L; // Use GetServiceConfigRequest.newBuilder() to construct. private GetServiceConfigRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GetServiceConfigRequest() { serviceName_ = ""; configId_ = ""; view_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new GetServiceConfigRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.api.servicemanagement.v1.ServiceManagerProto .internal_static_google_api_servicemanagement_v1_GetServiceConfigRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.api.servicemanagement.v1.ServiceManagerProto .internal_static_google_api_servicemanagement_v1_GetServiceConfigRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.api.servicemanagement.v1.GetServiceConfigRequest.class, com.google.api.servicemanagement.v1.GetServiceConfigRequest.Builder.class); } /** Protobuf enum {@code google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView} */ public enum ConfigView implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Server response includes all fields except SourceInfo. * </pre> * * <code>BASIC = 0;</code> */ BASIC(0), /** * * * <pre> * Server response includes all fields including SourceInfo. * SourceFiles are of type 'google.api.servicemanagement.v1.ConfigFile' * and are only available for configs created using the * SubmitConfigSource method. * </pre> * * <code>FULL = 1;</code> */ FULL(1), UNRECOGNIZED(-1), ; /** * * * <pre> * Server response includes all fields except SourceInfo. * </pre> * * <code>BASIC = 0;</code> */ public static final int BASIC_VALUE = 0; /** * * * <pre> * Server response includes all fields including SourceInfo. * SourceFiles are of type 'google.api.servicemanagement.v1.ConfigFile' * and are only available for configs created using the * SubmitConfigSource method. * </pre> * * <code>FULL = 1;</code> */ public static final int FULL_VALUE = 1; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static ConfigView 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 ConfigView forNumber(int value) { switch (value) { case 0: return BASIC; case 1: return FULL; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<ConfigView> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<ConfigView> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<ConfigView>() { public ConfigView findValueByNumber(int number) { return ConfigView.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.api.servicemanagement.v1.GetServiceConfigRequest.getDescriptor() .getEnumTypes() .get(0); } private static final ConfigView[] VALUES = values(); public static ConfigView 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 ConfigView(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView) } public static final int SERVICE_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object serviceName_ = ""; /** * * * <pre> * Required. The name of the service. See the * [overview](https://cloud.google.com/service-management/overview) for naming * requirements. For example: `example.googleapis.com`. * </pre> * * <code>string service_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The serviceName. */ @java.lang.Override public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } } /** * * * <pre> * Required. The name of the service. See the * [overview](https://cloud.google.com/service-management/overview) for naming * requirements. For example: `example.googleapis.com`. * </pre> * * <code>string service_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for serviceName. */ @java.lang.Override public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CONFIG_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object configId_ = ""; /** * * * <pre> * Required. The id of the service configuration resource. * * This field must be specified for the server to return all fields, including * `SourceInfo`. * </pre> * * <code>string config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The configId. */ @java.lang.Override public java.lang.String getConfigId() { java.lang.Object ref = configId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); configId_ = s; return s; } } /** * * * <pre> * Required. The id of the service configuration resource. * * This field must be specified for the server to return all fields, including * `SourceInfo`. * </pre> * * <code>string config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for configId. */ @java.lang.Override public com.google.protobuf.ByteString getConfigIdBytes() { java.lang.Object ref = configId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); configId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VIEW_FIELD_NUMBER = 3; private int view_ = 0; /** * * * <pre> * Specifies which parts of the Service Config should be returned in the * response. * </pre> * * <code>.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView view = 3;</code> * * @return The enum numeric value on the wire for view. */ @java.lang.Override public int getViewValue() { return view_; } /** * * * <pre> * Specifies which parts of the Service Config should be returned in the * response. * </pre> * * <code>.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView view = 3;</code> * * @return The view. */ @java.lang.Override public com.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView getView() { com.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView result = com.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView.forNumber(view_); return result == null ? com.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, serviceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(configId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, configId_); } if (view_ != com.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView.BASIC .getNumber()) { output.writeEnum(3, view_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, serviceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(configId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, configId_); } if (view_ != com.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView.BASIC .getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(3, view_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.api.servicemanagement.v1.GetServiceConfigRequest)) { return super.equals(obj); } com.google.api.servicemanagement.v1.GetServiceConfigRequest other = (com.google.api.servicemanagement.v1.GetServiceConfigRequest) obj; if (!getServiceName().equals(other.getServiceName())) return false; if (!getConfigId().equals(other.getConfigId())) return false; if (view_ != other.view_) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SERVICE_NAME_FIELD_NUMBER; hash = (53 * hash) + getServiceName().hashCode(); hash = (37 * hash) + CONFIG_ID_FIELD_NUMBER; hash = (53 * hash) + getConfigId().hashCode(); hash = (37 * hash) + VIEW_FIELD_NUMBER; hash = (53 * hash) + view_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.api.servicemanagement.v1.GetServiceConfigRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.api.servicemanagement.v1.GetServiceConfigRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.api.servicemanagement.v1.GetServiceConfigRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.api.servicemanagement.v1.GetServiceConfigRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.api.servicemanagement.v1.GetServiceConfigRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.api.servicemanagement.v1.GetServiceConfigRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.api.servicemanagement.v1.GetServiceConfigRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.api.servicemanagement.v1.GetServiceConfigRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.api.servicemanagement.v1.GetServiceConfigRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.api.servicemanagement.v1.GetServiceConfigRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.api.servicemanagement.v1.GetServiceConfigRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.api.servicemanagement.v1.GetServiceConfigRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.api.servicemanagement.v1.GetServiceConfigRequest 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 GetServiceConfig method. * </pre> * * Protobuf type {@code google.api.servicemanagement.v1.GetServiceConfigRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.api.servicemanagement.v1.GetServiceConfigRequest) com.google.api.servicemanagement.v1.GetServiceConfigRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.api.servicemanagement.v1.ServiceManagerProto .internal_static_google_api_servicemanagement_v1_GetServiceConfigRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.api.servicemanagement.v1.ServiceManagerProto .internal_static_google_api_servicemanagement_v1_GetServiceConfigRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.api.servicemanagement.v1.GetServiceConfigRequest.class, com.google.api.servicemanagement.v1.GetServiceConfigRequest.Builder.class); } // Construct using com.google.api.servicemanagement.v1.GetServiceConfigRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; serviceName_ = ""; configId_ = ""; view_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.api.servicemanagement.v1.ServiceManagerProto .internal_static_google_api_servicemanagement_v1_GetServiceConfigRequest_descriptor; } @java.lang.Override public com.google.api.servicemanagement.v1.GetServiceConfigRequest getDefaultInstanceForType() { return com.google.api.servicemanagement.v1.GetServiceConfigRequest.getDefaultInstance(); } @java.lang.Override public com.google.api.servicemanagement.v1.GetServiceConfigRequest build() { com.google.api.servicemanagement.v1.GetServiceConfigRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.api.servicemanagement.v1.GetServiceConfigRequest buildPartial() { com.google.api.servicemanagement.v1.GetServiceConfigRequest result = new com.google.api.servicemanagement.v1.GetServiceConfigRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.api.servicemanagement.v1.GetServiceConfigRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.serviceName_ = serviceName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.configId_ = configId_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.view_ = view_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.api.servicemanagement.v1.GetServiceConfigRequest) { return mergeFrom((com.google.api.servicemanagement.v1.GetServiceConfigRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.api.servicemanagement.v1.GetServiceConfigRequest other) { if (other == com.google.api.servicemanagement.v1.GetServiceConfigRequest.getDefaultInstance()) return this; if (!other.getServiceName().isEmpty()) { serviceName_ = other.serviceName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getConfigId().isEmpty()) { configId_ = other.configId_; bitField0_ |= 0x00000002; onChanged(); } if (other.view_ != 0) { setViewValue(other.getViewValue()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { serviceName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { configId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { view_ = input.readEnum(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object serviceName_ = ""; /** * * * <pre> * Required. The name of the service. See the * [overview](https://cloud.google.com/service-management/overview) for naming * requirements. For example: `example.googleapis.com`. * </pre> * * <code>string service_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The serviceName. */ public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of the service. See the * [overview](https://cloud.google.com/service-management/overview) for naming * requirements. For example: `example.googleapis.com`. * </pre> * * <code>string service_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for serviceName. */ public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of the service. See the * [overview](https://cloud.google.com/service-management/overview) for naming * requirements. For example: `example.googleapis.com`. * </pre> * * <code>string service_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The serviceName to set. * @return This builder for chaining. */ public Builder setServiceName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } serviceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The name of the service. See the * [overview](https://cloud.google.com/service-management/overview) for naming * requirements. For example: `example.googleapis.com`. * </pre> * * <code>string service_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearServiceName() { serviceName_ = getDefaultInstance().getServiceName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The name of the service. See the * [overview](https://cloud.google.com/service-management/overview) for naming * requirements. For example: `example.googleapis.com`. * </pre> * * <code>string service_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for serviceName to set. * @return This builder for chaining. */ public Builder setServiceNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); serviceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object configId_ = ""; /** * * * <pre> * Required. The id of the service configuration resource. * * This field must be specified for the server to return all fields, including * `SourceInfo`. * </pre> * * <code>string config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The configId. */ public java.lang.String getConfigId() { java.lang.Object ref = configId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); configId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The id of the service configuration resource. * * This field must be specified for the server to return all fields, including * `SourceInfo`. * </pre> * * <code>string config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for configId. */ public com.google.protobuf.ByteString getConfigIdBytes() { java.lang.Object ref = configId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); configId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The id of the service configuration resource. * * This field must be specified for the server to return all fields, including * `SourceInfo`. * </pre> * * <code>string config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The configId to set. * @return This builder for chaining. */ public Builder setConfigId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } configId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The id of the service configuration resource. * * This field must be specified for the server to return all fields, including * `SourceInfo`. * </pre> * * <code>string config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearConfigId() { configId_ = getDefaultInstance().getConfigId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Required. The id of the service configuration resource. * * This field must be specified for the server to return all fields, including * `SourceInfo`. * </pre> * * <code>string config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for configId to set. * @return This builder for chaining. */ public Builder setConfigIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); configId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int view_ = 0; /** * * * <pre> * Specifies which parts of the Service Config should be returned in the * response. * </pre> * * <code>.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView view = 3;</code> * * @return The enum numeric value on the wire for view. */ @java.lang.Override public int getViewValue() { return view_; } /** * * * <pre> * Specifies which parts of the Service Config should be returned in the * response. * </pre> * * <code>.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView view = 3;</code> * * @param value The enum numeric value on the wire for view to set. * @return This builder for chaining. */ public Builder setViewValue(int value) { view_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Specifies which parts of the Service Config should be returned in the * response. * </pre> * * <code>.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView view = 3;</code> * * @return The view. */ @java.lang.Override public com.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView getView() { com.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView result = com.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView.forNumber(view_); return result == null ? com.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView.UNRECOGNIZED : result; } /** * * * <pre> * Specifies which parts of the Service Config should be returned in the * response. * </pre> * * <code>.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView view = 3;</code> * * @param value The view to set. * @return This builder for chaining. */ public Builder setView( com.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; view_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Specifies which parts of the Service Config should be returned in the * response. * </pre> * * <code>.google.api.servicemanagement.v1.GetServiceConfigRequest.ConfigView view = 3;</code> * * @return This builder for chaining. */ public Builder clearView() { bitField0_ = (bitField0_ & ~0x00000004); view_ = 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.api.servicemanagement.v1.GetServiceConfigRequest) } // @@protoc_insertion_point(class_scope:google.api.servicemanagement.v1.GetServiceConfigRequest) private static final com.google.api.servicemanagement.v1.GetServiceConfigRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.api.servicemanagement.v1.GetServiceConfigRequest(); } public static com.google.api.servicemanagement.v1.GetServiceConfigRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GetServiceConfigRequest> PARSER = new com.google.protobuf.AbstractParser<GetServiceConfigRequest>() { @java.lang.Override public GetServiceConfigRequest 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<GetServiceConfigRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GetServiceConfigRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.api.servicemanagement.v1.GetServiceConfigRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,319
java-vision/proto-google-cloud-vision-v1/src/main/java/com/google/cloud/vision/v1/CreateProductSetRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/vision/v1/product_search_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.vision.v1; /** * * * <pre> * Request message for the `CreateProductSet` method. * </pre> * * Protobuf type {@code google.cloud.vision.v1.CreateProductSetRequest} */ public final class CreateProductSetRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.vision.v1.CreateProductSetRequest) CreateProductSetRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateProductSetRequest.newBuilder() to construct. private CreateProductSetRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateProductSetRequest() { parent_ = ""; productSetId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateProductSetRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vision.v1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1_CreateProductSetRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vision.v1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1_CreateProductSetRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vision.v1.CreateProductSetRequest.class, com.google.cloud.vision.v1.CreateProductSetRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The project in which the ProductSet should be created. * * Format is `projects/PROJECT_ID/locations/LOC_ID`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The project in which the ProductSet should be created. * * Format is `projects/PROJECT_ID/locations/LOC_ID`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PRODUCT_SET_FIELD_NUMBER = 2; private com.google.cloud.vision.v1.ProductSet productSet_; /** * * * <pre> * Required. The ProductSet to create. * </pre> * * <code> * .google.cloud.vision.v1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the productSet field is set. */ @java.lang.Override public boolean hasProductSet() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The ProductSet to create. * </pre> * * <code> * .google.cloud.vision.v1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The productSet. */ @java.lang.Override public com.google.cloud.vision.v1.ProductSet getProductSet() { return productSet_ == null ? com.google.cloud.vision.v1.ProductSet.getDefaultInstance() : productSet_; } /** * * * <pre> * Required. The ProductSet to create. * </pre> * * <code> * .google.cloud.vision.v1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.vision.v1.ProductSetOrBuilder getProductSetOrBuilder() { return productSet_ == null ? com.google.cloud.vision.v1.ProductSet.getDefaultInstance() : productSet_; } public static final int PRODUCT_SET_ID_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object productSetId_ = ""; /** * * * <pre> * A user-supplied resource id for this ProductSet. If set, the server will * attempt to use this value as the resource id. If it is already in use, an * error is returned with code ALREADY_EXISTS. Must be at most 128 characters * long. It cannot contain the character `/`. * </pre> * * <code>string product_set_id = 3;</code> * * @return The productSetId. */ @java.lang.Override public java.lang.String getProductSetId() { java.lang.Object ref = productSetId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); productSetId_ = s; return s; } } /** * * * <pre> * A user-supplied resource id for this ProductSet. If set, the server will * attempt to use this value as the resource id. If it is already in use, an * error is returned with code ALREADY_EXISTS. Must be at most 128 characters * long. It cannot contain the character `/`. * </pre> * * <code>string product_set_id = 3;</code> * * @return The bytes for productSetId. */ @java.lang.Override public com.google.protobuf.ByteString getProductSetIdBytes() { java.lang.Object ref = productSetId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); productSetId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getProductSet()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(productSetId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, productSetId_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getProductSet()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(productSetId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, productSetId_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.vision.v1.CreateProductSetRequest)) { return super.equals(obj); } com.google.cloud.vision.v1.CreateProductSetRequest other = (com.google.cloud.vision.v1.CreateProductSetRequest) obj; if (!getParent().equals(other.getParent())) return false; if (hasProductSet() != other.hasProductSet()) return false; if (hasProductSet()) { if (!getProductSet().equals(other.getProductSet())) return false; } if (!getProductSetId().equals(other.getProductSetId())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); if (hasProductSet()) { hash = (37 * hash) + PRODUCT_SET_FIELD_NUMBER; hash = (53 * hash) + getProductSet().hashCode(); } hash = (37 * hash) + PRODUCT_SET_ID_FIELD_NUMBER; hash = (53 * hash) + getProductSetId().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.vision.v1.CreateProductSetRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vision.v1.CreateProductSetRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vision.v1.CreateProductSetRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vision.v1.CreateProductSetRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vision.v1.CreateProductSetRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vision.v1.CreateProductSetRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vision.v1.CreateProductSetRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vision.v1.CreateProductSetRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.vision.v1.CreateProductSetRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.vision.v1.CreateProductSetRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.vision.v1.CreateProductSetRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vision.v1.CreateProductSetRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.vision.v1.CreateProductSetRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for the `CreateProductSet` method. * </pre> * * Protobuf type {@code google.cloud.vision.v1.CreateProductSetRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.vision.v1.CreateProductSetRequest) com.google.cloud.vision.v1.CreateProductSetRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vision.v1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1_CreateProductSetRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vision.v1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1_CreateProductSetRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vision.v1.CreateProductSetRequest.class, com.google.cloud.vision.v1.CreateProductSetRequest.Builder.class); } // Construct using com.google.cloud.vision.v1.CreateProductSetRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getProductSetFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; productSet_ = null; if (productSetBuilder_ != null) { productSetBuilder_.dispose(); productSetBuilder_ = null; } productSetId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.vision.v1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1_CreateProductSetRequest_descriptor; } @java.lang.Override public com.google.cloud.vision.v1.CreateProductSetRequest getDefaultInstanceForType() { return com.google.cloud.vision.v1.CreateProductSetRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.vision.v1.CreateProductSetRequest build() { com.google.cloud.vision.v1.CreateProductSetRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.vision.v1.CreateProductSetRequest buildPartial() { com.google.cloud.vision.v1.CreateProductSetRequest result = new com.google.cloud.vision.v1.CreateProductSetRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.vision.v1.CreateProductSetRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.productSet_ = productSetBuilder_ == null ? productSet_ : productSetBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.productSetId_ = productSetId_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.vision.v1.CreateProductSetRequest) { return mergeFrom((com.google.cloud.vision.v1.CreateProductSetRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.vision.v1.CreateProductSetRequest other) { if (other == com.google.cloud.vision.v1.CreateProductSetRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasProductSet()) { mergeProductSet(other.getProductSet()); } if (!other.getProductSetId().isEmpty()) { productSetId_ = other.productSetId_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getProductSetFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { productSetId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The project in which the ProductSet should be created. * * Format is `projects/PROJECT_ID/locations/LOC_ID`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The project in which the ProductSet should be created. * * Format is `projects/PROJECT_ID/locations/LOC_ID`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The project in which the ProductSet should be created. * * Format is `projects/PROJECT_ID/locations/LOC_ID`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The project in which the ProductSet should be created. * * Format is `projects/PROJECT_ID/locations/LOC_ID`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The project in which the ProductSet should be created. * * Format is `projects/PROJECT_ID/locations/LOC_ID`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.cloud.vision.v1.ProductSet productSet_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.vision.v1.ProductSet, com.google.cloud.vision.v1.ProductSet.Builder, com.google.cloud.vision.v1.ProductSetOrBuilder> productSetBuilder_; /** * * * <pre> * Required. The ProductSet to create. * </pre> * * <code> * .google.cloud.vision.v1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the productSet field is set. */ public boolean hasProductSet() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The ProductSet to create. * </pre> * * <code> * .google.cloud.vision.v1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The productSet. */ public com.google.cloud.vision.v1.ProductSet getProductSet() { if (productSetBuilder_ == null) { return productSet_ == null ? com.google.cloud.vision.v1.ProductSet.getDefaultInstance() : productSet_; } else { return productSetBuilder_.getMessage(); } } /** * * * <pre> * Required. The ProductSet to create. * </pre> * * <code> * .google.cloud.vision.v1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setProductSet(com.google.cloud.vision.v1.ProductSet value) { if (productSetBuilder_ == null) { if (value == null) { throw new NullPointerException(); } productSet_ = value; } else { productSetBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The ProductSet to create. * </pre> * * <code> * .google.cloud.vision.v1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setProductSet(com.google.cloud.vision.v1.ProductSet.Builder builderForValue) { if (productSetBuilder_ == null) { productSet_ = builderForValue.build(); } else { productSetBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The ProductSet to create. * </pre> * * <code> * .google.cloud.vision.v1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeProductSet(com.google.cloud.vision.v1.ProductSet value) { if (productSetBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && productSet_ != null && productSet_ != com.google.cloud.vision.v1.ProductSet.getDefaultInstance()) { getProductSetBuilder().mergeFrom(value); } else { productSet_ = value; } } else { productSetBuilder_.mergeFrom(value); } if (productSet_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The ProductSet to create. * </pre> * * <code> * .google.cloud.vision.v1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearProductSet() { bitField0_ = (bitField0_ & ~0x00000002); productSet_ = null; if (productSetBuilder_ != null) { productSetBuilder_.dispose(); productSetBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The ProductSet to create. * </pre> * * <code> * .google.cloud.vision.v1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.vision.v1.ProductSet.Builder getProductSetBuilder() { bitField0_ |= 0x00000002; onChanged(); return getProductSetFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The ProductSet to create. * </pre> * * <code> * .google.cloud.vision.v1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.vision.v1.ProductSetOrBuilder getProductSetOrBuilder() { if (productSetBuilder_ != null) { return productSetBuilder_.getMessageOrBuilder(); } else { return productSet_ == null ? com.google.cloud.vision.v1.ProductSet.getDefaultInstance() : productSet_; } } /** * * * <pre> * Required. The ProductSet to create. * </pre> * * <code> * .google.cloud.vision.v1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.vision.v1.ProductSet, com.google.cloud.vision.v1.ProductSet.Builder, com.google.cloud.vision.v1.ProductSetOrBuilder> getProductSetFieldBuilder() { if (productSetBuilder_ == null) { productSetBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.vision.v1.ProductSet, com.google.cloud.vision.v1.ProductSet.Builder, com.google.cloud.vision.v1.ProductSetOrBuilder>( getProductSet(), getParentForChildren(), isClean()); productSet_ = null; } return productSetBuilder_; } private java.lang.Object productSetId_ = ""; /** * * * <pre> * A user-supplied resource id for this ProductSet. If set, the server will * attempt to use this value as the resource id. If it is already in use, an * error is returned with code ALREADY_EXISTS. Must be at most 128 characters * long. It cannot contain the character `/`. * </pre> * * <code>string product_set_id = 3;</code> * * @return The productSetId. */ public java.lang.String getProductSetId() { java.lang.Object ref = productSetId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); productSetId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A user-supplied resource id for this ProductSet. If set, the server will * attempt to use this value as the resource id. If it is already in use, an * error is returned with code ALREADY_EXISTS. Must be at most 128 characters * long. It cannot contain the character `/`. * </pre> * * <code>string product_set_id = 3;</code> * * @return The bytes for productSetId. */ public com.google.protobuf.ByteString getProductSetIdBytes() { java.lang.Object ref = productSetId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); productSetId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A user-supplied resource id for this ProductSet. If set, the server will * attempt to use this value as the resource id. If it is already in use, an * error is returned with code ALREADY_EXISTS. Must be at most 128 characters * long. It cannot contain the character `/`. * </pre> * * <code>string product_set_id = 3;</code> * * @param value The productSetId to set. * @return This builder for chaining. */ public Builder setProductSetId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } productSetId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * A user-supplied resource id for this ProductSet. If set, the server will * attempt to use this value as the resource id. If it is already in use, an * error is returned with code ALREADY_EXISTS. Must be at most 128 characters * long. It cannot contain the character `/`. * </pre> * * <code>string product_set_id = 3;</code> * * @return This builder for chaining. */ public Builder clearProductSetId() { productSetId_ = getDefaultInstance().getProductSetId(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * A user-supplied resource id for this ProductSet. If set, the server will * attempt to use this value as the resource id. If it is already in use, an * error is returned with code ALREADY_EXISTS. Must be at most 128 characters * long. It cannot contain the character `/`. * </pre> * * <code>string product_set_id = 3;</code> * * @param value The bytes for productSetId to set. * @return This builder for chaining. */ public Builder setProductSetIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); productSetId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.vision.v1.CreateProductSetRequest) } // @@protoc_insertion_point(class_scope:google.cloud.vision.v1.CreateProductSetRequest) private static final com.google.cloud.vision.v1.CreateProductSetRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.vision.v1.CreateProductSetRequest(); } public static com.google.cloud.vision.v1.CreateProductSetRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateProductSetRequest> PARSER = new com.google.protobuf.AbstractParser<CreateProductSetRequest>() { @java.lang.Override public CreateProductSetRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<CreateProductSetRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateProductSetRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.vision.v1.CreateProductSetRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/derby
36,014
java/org.apache.derby.tests/org/apache/derbyTesting/functionTests/tests/store/TableLockBasicTest.java
/* Derby - Class org.apache.derbyTesting.functionTests.tests.store.TableLockBasicTest 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.derbyTesting.functionTests.tests.store; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Locale; import junit.framework.Test; import org.apache.derbyTesting.junit.BaseJDBCTestCase; import org.apache.derbyTesting.junit.DatabasePropertyTestSetup; import org.apache.derbyTesting.junit.JDBC; import org.apache.derbyTesting.junit.LocaleTestSetup; import org.apache.derbyTesting.junit.TestConfiguration; /** * Very basic single user testing of table locking, verify that the right locks * are obtained for simple operations. This test only looks at table and * row logical locks, it does not verify physical latches or lock ordering. -- * The basic methodology is: * start transaction * simple operation * print lock table which should match the master * end transation * */ public class TableLockBasicTest extends BaseJDBCTestCase { public TableLockBasicTest(String name) { super(name); } public static Test suite() { Test test = TestConfiguration.defaultSuite(TableLockBasicTest.class); test = DatabasePropertyTestSetup.singleProperty(test, "derby.storage.rowLocking", "false", true); test = new LocaleTestSetup(test, Locale.ENGLISH); return TestConfiguration.singleUseDatabaseDecorator(test); } protected void setUp() throws SQLException { Statement s = createStatement(); s.execute("CREATE FUNCTION PADSTRING (DATA VARCHAR(32000), " + "LENGTH INTEGER) RETURNS VARCHAR(32000) EXTERNAL NAME " + "'org.apache.derbyTesting.functionTests.util.Formatters" + ".padString' LANGUAGE JAVA PARAMETER STYLE JAVA"); createLockTableQueryEntries(s); s.close(); getConnection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); getConnection().setAutoCommit(false); } private void createLockTableQueryEntries(Statement s) throws SQLException { s.execute("create view lock_table as " + "select " + "cast(username as char(8)) as username," + "cast(t.type as char(8)) as trantype," + "cast(l.type as char(8)) as type," + "cast(lockcount as char(3)) as cnt," + "mode," + "cast(tablename as char(12)) as tabname," + "cast(lockname as char(10)) as lockname," + "state," + "status " + "from " + "syscs_diag.lock_table l right outer join syscs_diag.transaction_table t " + "on l.xid = t.xid where l.tableType <> 'S' and t.type='UserTransaction'"); //lock table with system catalog locks included. s.execute("create view full_lock_table as " + "select " + "cast(username as char(8)) as username, " + "cast(t.type as char(8)) as trantype," + "cast(l.type as char(8)) as type," + "cast(lockcount as char(3)) as cnt," + "mode, " + "cast(tablename as char(12)) as tabname," + "cast(lockname as char(10)) as lockname," + "state," + "status " + "from " + "syscs_diag.lock_table l right outer join syscs_diag.transaction_table t " + "on l.xid = t.xid where l.tableType <> 'S' "); //lock table with no join. s.execute("create view lock_table2 as " + "select " + "cast(l.xid as char(8)) as xid," + "cast(l.type as char(8)) as type," + "cast(lockcount as char(3)) as cnt," + "mode," + "cast(tablename as char(12)) as tabname," + "cast(lockname as char(10)) as lockname," + "state " + "from " + "syscs_diag.lock_table l " + "where l.tableType <> 'S' "); //-- transaction table with no join. s.execute("create view tran_table as " + "select " + "* " + "from " + "syscs_diag.transaction_table"); } public void tearDown() throws Exception { Statement st = createStatement(); st.executeUpdate("DROP FUNCTION PADSTRING"); st.execute("drop view lock_table"); st.execute("drop view full_lock_table"); st.execute("drop view lock_table2"); st.execute("drop view tran_table"); st.close(); commit(); super.tearDown(); } public void testInsertIntoHeap() throws SQLException { Statement st = createStatement(); st.execute("create table heap_only (a int)"); commit(); //Test insert into empty heap, should just get table lock st.execute("insert into heap_only values (1)"); ResultSet rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "1", "X", "HEAP_ONLY", "Tablelock", "GRANT", "ACTIVE"}, }); commit(); //Test insert into heap with one row, just get table lock st.execute("insert into heap_only values (2)"); rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "1", "X", "HEAP_ONLY", "Tablelock", "GRANT", "ACTIVE"}, }); commit(); st.close(); dropTable("heap_only"); } /** * Test select from a heap, should get shared table lock. */ public void testSelectFromHeap () throws SQLException { Statement st = createStatement(); constructHeap(st); ResultSet rs = st.executeQuery("select a from heap_only where a = 1"); JDBC.assertFullResultSet(rs, new String[][]{ {"1"}, }); rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "1", "S", "HEAP_ONLY", "Tablelock", "GRANT", "ACTIVE"} }); commit(); st.close(); dropTable("heap_only"); } private void constructHeap(Statement st) throws SQLException { st.execute("create table heap_only (a int)"); commit(); st.execute("insert into heap_only values (1)"); commit(); st.execute("insert into heap_only values (2)"); commit(); } /** * Test delete from a heap, should get exclusive table lock. */ public void testDelectFromHeap () throws SQLException { Statement st = createStatement(); constructHeap(st); st.execute("delete from heap_only where a = 1"); ResultSet rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "2", "X", "HEAP_ONLY", "Tablelock", "GRANT", "ACTIVE"}, }); commit(); st.close(); dropTable("heap_only"); } /** * Test update to heap, should get exclusive table lock. */ public void testUpdateToHeap () throws SQLException { Statement st = createStatement(); constructHeap(st); st.execute("update heap_only set a = 1000 where a = 2"); ResultSet rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "2", "X", "HEAP_ONLY", "Tablelock", "GRANT", "ACTIVE"}, }); commit(); st.close(); dropTable("heap_only"); } /** * Test drop of heap, should get exclusive table lock. */ public void testDropHeap () throws SQLException { Statement st = createStatement(); constructHeap(st); st.execute("drop table heap_only"); ResultSet rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "3", "X", "*** TRANSIEN", "Tablelock", "GRANT", "ACTIVE"}, }); commit(); st.close(); dropTable("heap_only"); } public void testCreateIndex() throws SQLException { Statement st = createStatement(); st.execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.storage.pageSize', '4096')"); st.execute("create table indexed_heap (a int, b varchar(1000))"); st.execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.storage.pageSize', NULL)"); ResultSet rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "1", "X", "INDEXED_HEAP", "Tablelock", "GRANT", "ACTIVE"}, }); commit(); st.execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.storage.pageSize', '4096')"); st.execute("create index a_idx on indexed_heap (a, b)"); st.execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.storage.pageSize', NULL)"); rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "4", "S", "INDEXED_HEAP", "Tablelock", "GRANT", "ACTIVE"}, {"APP", "UserTran", "TABLE", "1", "X", "INDEXED_HEAP", "Tablelock", "GRANT", "ACTIVE"}, {"APP", "UserTran", "TABLE", "1", "X", "INDEXED_HEAP", "Tablelock", "GRANT", "ACTIVE"}, }); commit(); st.close(); dropTable("indexed_heap"); } public void testInsertIntoEmtpyIndexedHeaP() throws SQLException { Statement st = createStatement(); st.execute("create table indexed_heap (a int, b varchar(1000))"); commit(); st.execute("create index a_idx on indexed_heap (a, b)"); commit(); // Test insert into indexed heap, should just get table lock st.execute("insert into indexed_heap (a) values (1)"); ResultSet rs = st.executeQuery(" select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][] { {"APP", "UserTran", "TABLE", "2", "X", "INDEXED_HEAP", "Tablelock", "GRANT", "ACTIVE"}, }); commit(); // Test insert into indexed heap with one row, just get table lock st.execute("insert into indexed_heap (a) values (2)"); rs = st.executeQuery(" select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][] { {"APP", "UserTran", "TABLE", "2", "X", "INDEXED_HEAP", "Tablelock", "GRANT", "ACTIVE"} }); commit(); st.close(); dropTable("indexed_heap"); } /** * Test select from a indexed heap, should get shared table lock. */ public void testSelectFromIndexedHeap () throws SQLException { Statement st = createStatement(); constructIndexedHeap(st); ResultSet rs = st.executeQuery("select a from indexed_heap where a = 1"); JDBC.assertFullResultSet(rs, new String[][]{ {"1"}, }); rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "1", "S", "INDEXED_HEAP", "Tablelock", "GRANT", "ACTIVE"}, }); commit(); st.close(); dropTable("indexed_heap"); } private void constructIndexedHeap(Statement st) throws SQLException { st.execute("create table indexed_heap (a int, b varchar(1000))"); st.execute("create index a_idx on indexed_heap (a, b)"); st.execute("insert into indexed_heap (a) values (1)"); st.execute("insert into indexed_heap (a) values (2)"); commit(); } /** * Test delete from a indexed heap, should get exclusive table lock. */ public void testDeleteFromIndexedHeap () throws SQLException { Statement st = createStatement(); constructIndexedHeap(st); st.execute("delete from indexed_heap where a = 1"); ResultSet rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "3", "X", "INDEXED_HEAP", "Tablelock", "GRANT", "ACTIVE"}, }); commit(); st.close(); dropTable("indexed_heap"); } /** * Test update to indexed heap, should get exclusive table lock. */ public void testUpdateToIndexedHeap () throws SQLException { Statement st = createStatement(); constructIndexedHeap(st); st.execute("update indexed_heap set a = 1000 where a = 2"); ResultSet rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "4", "X", "INDEXED_HEAP", "Tablelock", "GRANT", "ACTIVE"}, }); commit(); st.close(); dropTable("indexed_heap"); } /** * Test drop of indexed heap, should get exclusive table lock. */ public void testDropIndexedHeap () throws SQLException { Statement st = createStatement(); constructIndexedHeap(st); st.execute("drop table indexed_heap"); ResultSet rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "1", "X", "*** TRANSIEN", "Tablelock", "GRANT", "ACTIVE"}, {"APP", "UserTran", "TABLE", "4", "X", "*** TRANSIEN", "Tablelock", "GRANT", "ACTIVE"}, }); commit(); st.close(); } /** * Test LOCK TABLE statement */ public void testLockTableStatement() throws SQLException { Statement st = createStatement(); st.execute("create table t1(c1 int)"); commit(); PreparedStatement pst = prepareStatement("lock table t1 in exclusive mode"); pst.execute(); ResultSet rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "1", "X", "T1", "Tablelock", "GRANT", "ACTIVE"}, }); //verify that statement gets recompiled correctly st.execute("drop table t1"); st.execute("create table t1(c1 int)"); pst.execute(); commit(); st.execute("lock table t1 in share mode"); rs = st.executeQuery( " select * from lock_table order by tabname, type " + "desc, mode, cnt, lockname"); JDBC.assertFullResultSet(rs, new String[][]{ {"APP", "UserTran", "TABLE", "1", "S", "T1", "Tablelock", "GRANT", "ACTIVE"}, }); st.execute("drop table t1"); commit(); st.close(); } /** * verify that lock table not allowed in sys schema */ public void testLockTableInSysSchema() throws SQLException { Statement st = createStatement(); assertStatementError("42X62", st, "lock table sys.systables in exclusive mode"); st.close(); } /** * Test RTS output when table locking configured */ public void testRTSOutput() throws SQLException { Statement st = createStatement(); st.execute("call SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS(1)"); st.execute("create table rts(c1 int)"); st.execute("insert into rts values 1"); commit(); ResultSet rs = st.executeQuery("select * from rts with cs"); JDBC.assertFullResultSet(rs, new String[][]{ {"1"} }); rs = st.executeQuery("values SYSCS_UTIL.SYSCS_GET_RUNTIMESTATISTICS()"); JDBC.assertFullResultSet(rs, new String[][]{ {"Statement Name: \n" + " " + (getTestConfiguration().getJDBCClient().isEmbedded() ? "null\n" : "SQL_CURLH000C3\n") + "Statement Text: \n" + " select * from rts with cs\n" + "Parse Time: 0\n" + "Bind Time: 0\n" + "Optimize Time: 0\n" + "Generate Time: 0\n" + "Compile Time: 0\n" + "Execute Time: 0\n" + "Begin Compilation Timestamp : null\n" + "End Compilation Timestamp : null\n" + "Begin Execution Timestamp : null\n" + "End Execution Timestamp : null\n" + "Statement Execution Plan Text: \n" + "Table Scan ResultSet for RTS at read committed isolation level using instantaneous share row locking chosen by the optimizer (Actual locking used: table level locking.)\n" + "Number of opens = 1\n" + "Rows seen = 1\n" + "Rows filtered = 0\n" + "Fetch Size = 16\n" + " constructor time (milliseconds) = 0\n" + " open time (milliseconds) = 0\n" + " next time (milliseconds) = 0\n" + " close time (milliseconds) = 0\n" + " next time in milliseconds/row = 0\n\n" + "scan information:\n" + " Bit set of columns fetched=All\n" + " Number of columns fetched=1\n" + " Number of pages visited=1\n" + " Number of rows qualified=1\n" + " Number of rows visited=1\n" + " Scan type=heap\n" + " start position:\n" + " null\n" + " stop position:\n" + " null\n" + " qualifiers:\n" + " None\n" + " optimizer estimated row count: 6.00\n" + " optimizer estimated cost: 100.40" }, }); st.execute("drop table rts"); commit(); st.close(); } public void testDDLTableLockMode() throws SQLException { Statement st = createStatement(); st.execute("call SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS(1)"); st.execute("create table default_granularity(c1 int)"); st.execute("create table row_granularity(c1 int)"); st.execute("alter table row_granularity locksize row"); st.execute("create table table_granularity(c1 int)"); st.execute("alter table table_granularity locksize table"); ResultSet rs = st.executeQuery("select * from default_granularity with cs"); JDBC.assertEmpty(rs); rs = st.executeQuery("values SYSCS_UTIL.SYSCS_GET_RUNTIMESTATISTICS()"); JDBC.assertFullResultSet(rs, new String[][]{ {"Statement Name: \n" + " " + (getTestConfiguration().getJDBCClient().isEmbedded() ? "null\n" : "SQL_CURLH000C2\n") + "Statement Text: \n" + " select * from default_granularity with cs\n" + "Parse Time: 0\n" + "Bind Time: 0\n" + "Optimize Time: 0\n" + "Generate Time: 0\n" + "Compile Time: 0\n" + "Execute Time: 0\n" + "Begin Compilation Timestamp : null\n" + "End Compilation Timestamp : null\n" + "Begin Execution Timestamp : null\n" + "End Execution Timestamp : null\n" + "Statement Execution Plan Text: \n" + "Table Scan ResultSet for DEFAULT_GRANULARITY at read committed isolation level using instantaneous share row locking chosen by the optimizer (Actual locking used: table level locking.)\n" + "Number of opens = 1\n" + "Rows seen = 0\n" + "Rows filtered = 0\n" + "Fetch Size = 16\n" + " constructor time (milliseconds) = 0\n" + " open time (milliseconds) = 0\n" + " next time (milliseconds) = 0\n" + " close time (milliseconds) = 0\n\n" + "scan information:\n" + " Bit set of columns fetched=All\n" + " Number of columns fetched=1\n" + " Number of pages visited=1\n" + " Number of rows qualified=0\n" + " Number of rows visited=0\n" + " Scan type=heap\n" + " start position:\n" + " null\n" + " stop position:\n" + " null\n" + " qualifiers:\n" + " None\n" + " optimizer estimated row count: 6.00\n" + " optimizer estimated cost: 100.40" } } ); rs = st.executeQuery("select * from default_granularity with rr"); JDBC.assertEmpty(rs); rs = st.executeQuery("values SYSCS_UTIL.SYSCS_GET_RUNTIMESTATISTICS()"); JDBC.assertFullResultSet(rs, new String[][]{ {"Statement Name: \n" + " " + (getTestConfiguration().getJDBCClient().isEmbedded() ? "null\n" : "SQL_CURLH000C2\n") + "Statement Text: \n" + " select * from default_granularity with rr\n" + "Parse Time: 0\n" + "Bind Time: 0\n" + "Optimize Time: 0\n" + "Generate Time: 0\n" + "Compile Time: 0\n" + "Execute Time: 0\n" + "Begin Compilation Timestamp : null\n" + "End Compilation Timestamp : null\n" + "Begin Execution Timestamp : null\n" + "End Execution Timestamp : null\n" + "Statement Execution Plan Text: \n" + "Table Scan ResultSet for DEFAULT_GRANULARITY at serializable isolation level using share table locking chosen by the optimizer\n" + "Number of opens = 1\n" + "Rows seen = 0\n" + "Rows filtered = 0\n" + "Fetch Size = 16\n" + " constructor time (milliseconds) = 0\n" + " open time (milliseconds) = 0\n" + " next time (milliseconds) = 0\n" + " close time (milliseconds) = 0\n\n" + "scan information:\n" + " Bit set of columns fetched=All\n" + " Number of columns fetched=1\n" + " Number of pages visited=1\n" + " Number of rows qualified=0\n" + " Number of rows visited=0\n" + " Scan type=heap\n" + " start position:\n" + " null\n" + " stop position:\n" + " null\n" + " qualifiers:\n" + " None\n" + " optimizer estimated row count: 6.00\n" + " optimizer estimated cost: 100.40" } } ); rs = st.executeQuery("select * from default_granularity with cs"); JDBC.assertEmpty(rs); rs = st.executeQuery("values SYSCS_UTIL.SYSCS_GET_RUNTIMESTATISTICS()"); JDBC.assertFullResultSet(rs, new String[][]{ {"Statement Name: \n" + " " + (getTestConfiguration().getJDBCClient().isEmbedded() ? "null\n" : "SQL_CURLH000C2\n") + "Statement Text: \n" + " select * from default_granularity with cs\n" + "Parse Time: 0\n" + "Bind Time: 0\n" + "Optimize Time: 0\n" + "Generate Time: 0\n" + "Compile Time: 0\n" + "Execute Time: 0\n" + "Begin Compilation Timestamp : null\n" + "End Compilation Timestamp : null\n" + "Begin Execution Timestamp : null\n" + "End Execution Timestamp : null\n" + "Statement Execution Plan Text: \n" + "Table Scan ResultSet for DEFAULT_GRANULARITY at read committed isolation level using instantaneous share row locking chosen by the optimizer (Actual locking used: table level locking.)\n" + "Number of opens = 1\n" + "Rows seen = 0\n" + "Rows filtered = 0\n" + "Fetch Size = 16\n" + " constructor time (milliseconds) = 0\n" + " open time (milliseconds) = 0\n" + " next time (milliseconds) = 0\n" + " close time (milliseconds) = 0\n\n" + "scan information:\n" + " Bit set of columns fetched=All\n" + " Number of columns fetched=1\n" + " Number of pages visited=1\n" + " Number of rows qualified=0\n" + " Number of rows visited=0\n" + " Scan type=heap\n" + " start position:\n" + " null\n" + " stop position:\n" + " null\n" + " qualifiers:\n" + " None\n" + " optimizer estimated row count: 6.00\n" + " optimizer estimated cost: 100.40" } } ); rs = st.executeQuery("select * from row_granularity with rr"); JDBC.assertEmpty(rs); rs = st.executeQuery("values SYSCS_UTIL.SYSCS_GET_RUNTIMESTATISTICS()"); JDBC.assertFullResultSet(rs, new String[][]{ {"Statement Name: \n" + " " + (getTestConfiguration().getJDBCClient().isEmbedded() ? "null\n" : "SQL_CURLH000C2\n") + "Statement Text: \n" + " select * from row_granularity with rr\n" + "Parse Time: 0\n" + "Bind Time: 0\n" + "Optimize Time: 0\n" + "Generate Time: 0\n" + "Compile Time: 0\n" + "Execute Time: 0\n" + "Begin Compilation Timestamp : null\n" + "End Compilation Timestamp : null\n" + "Begin Execution Timestamp : null\n" + "End Execution Timestamp : null\n" + "Statement Execution Plan Text: \n" + "Table Scan ResultSet for ROW_GRANULARITY at serializable isolation level using share table locking chosen by the optimizer\n" + "Number of opens = 1\n" + "Rows seen = 0\n" + "Rows filtered = 0\n" + "Fetch Size = 16\n" + " constructor time (milliseconds) = 0\n" + " open time (milliseconds) = 0\n" + " next time (milliseconds) = 0\n" + " close time (milliseconds) = 0\n\n" + "scan information:\n" + " Bit set of columns fetched=All\n" + " Number of columns fetched=1\n" + " Number of pages visited=1\n" + " Number of rows qualified=0\n" + " Number of rows visited=0\n" + " Scan type=heap\n" + " start position:\n" + " null\n" + " stop position:\n" + " null\n" + " qualifiers:\n" + " None\n" + " optimizer estimated row count: 6.00\n" + " optimizer estimated cost: 100.40" } } ); rs = st.executeQuery("select * from table_granularity with cs"); JDBC.assertEmpty(rs); rs = st.executeQuery("values SYSCS_UTIL.SYSCS_GET_RUNTIMESTATISTICS()"); JDBC.assertFullResultSet(rs, new String[][]{ {"Statement Name: \n" + " " + (getTestConfiguration().getJDBCClient().isEmbedded() ? "null\n" : "SQL_CURLH000C2\n") + "Statement Text: \n" + " select * from table_granularity with cs\n" + "Parse Time: 0\n" + "Bind Time: 0\n" + "Optimize Time: 0\n" + "Generate Time: 0\n" + "Compile Time: 0\n" + "Execute Time: 0\n" + "Begin Compilation Timestamp : null\n" + "End Compilation Timestamp : null\n" + "Begin Execution Timestamp : null\n" + "End Execution Timestamp : null\n" + "Statement Execution Plan Text: \n" + "Table Scan ResultSet for TABLE_GRANULARITY at read committed isolation level using instantaneous share table locking chosen by the optimizer\n" + "Number of opens = 1\n" + "Rows seen = 0\n" + "Rows filtered = 0\n" + "Fetch Size = 16\n" + " constructor time (milliseconds) = 0\n" + " open time (milliseconds) = 0\n" + " next time (milliseconds) = 0\n" + " close time (milliseconds) = 0\n\n" + "scan information:\n" + " Bit set of columns fetched=All\n" + " Number of columns fetched=1\n" + " Number of pages visited=1\n" + " Number of rows qualified=0\n" + " Number of rows visited=0\n" + " Scan type=heap\n" + " start position:\n" + " null\n" + " stop position:\n" + " null\n" + " qualifiers:\n" + " None\n" + " optimizer estimated row count: 6.00\n" + " optimizer estimated cost: 100.40" } } ); rs = st.executeQuery("select * from table_granularity with rr"); JDBC.assertEmpty(rs); rs = st.executeQuery("values SYSCS_UTIL.SYSCS_GET_RUNTIMESTATISTICS()"); JDBC.assertFullResultSet(rs, new String[][]{ {"Statement Name: \n" + " " + (getTestConfiguration().getJDBCClient().isEmbedded() ? "null\n" : "SQL_CURLH000C2\n") + "Statement Text: \n" + " select * from table_granularity with rr\n" + "Parse Time: 0\n" + "Bind Time: 0\n" + "Optimize Time: 0\n" + "Generate Time: 0\n" + "Compile Time: 0\n" + "Execute Time: 0\n" + "Begin Compilation Timestamp : null\n" + "End Compilation Timestamp : null\n" + "Begin Execution Timestamp : null\n" + "End Execution Timestamp : null\n" + "Statement Execution Plan Text: \n" + "Table Scan ResultSet for TABLE_GRANULARITY at serializable isolation level using share table locking chosen by the optimizer\n" + "Number of opens = 1\n" + "Rows seen = 0\n" + "Rows filtered = 0\n" + "Fetch Size = 16\n" + " constructor time (milliseconds) = 0\n" + " open time (milliseconds) = 0\n" + " next time (milliseconds) = 0\n" + " close time (milliseconds) = 0\n\n" + "scan information:\n" + " Bit set of columns fetched=All\n" + " Number of columns fetched=1\n" + " Number of pages visited=1\n" + " Number of rows qualified=0\n" + " Number of rows visited=0\n" + " Scan type=heap\n" + " start position:\n" + " null\n" + " stop position:\n" + " null\n" + " qualifiers:\n" + " None\n" + " optimizer estimated row count: 6.00\n" + " optimizer estimated cost: 100.40" } } ); st.close(); rollback(); } }
apache/manifoldcf
37,273
framework/connector-common/src/main/java/org/apache/manifoldcf/connectorcommon/fuzzyml/TagParseState.java
/* $Id$ */ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.manifoldcf.connectorcommon.fuzzyml; import org.apache.manifoldcf.core.interfaces.*; import org.apache.manifoldcf.core.system.Logging; import java.util.*; /** This class represents a basic xml/html tag parser. * It is capable of recognizing the following xml and html constructs: * * <pre> * '&lt;' &lt;token&gt; &lt;attrs&gt; '&gt;' ... '&lt;/' &lt;token&gt; '&gt;' * '&lt;' &lt;token&gt; &lt;attrs&gt; '/&gt;' * '&lt;?' &lt;token&gt; &lt;attrs&gt; '?&gt;' * '&lt;![' [&lt;token&gt;] '[' ... ']]&gt;' * '&lt;!' &lt;token&gt; ... '&gt;' * '&lt;!--' ... '--&gt;' * </pre> * * Each of these, save the comment, has supporting protected methods that will be * called by the parsing engine. Overriding these methods will allow an extending * class to perform higher-level data extraction and parsing. * * Of these, the messiest is the &lt;! ... &gt; construct, since there can be multiple nested * btags, cdata-like escapes, and qtags inside. Ideally the parser should produce a * sequence of preparsed tokens from these tags. Since they can be nested, keeping * track of the depth is also essential, so we do that with a btag depth counter. * Thus, in this case, it is not the state that matters, but the btag depth, to determine * if the parser is operating inside a btag. */ public class TagParseState extends SingleCharacterReceiver { protected static final int TAGPARSESTATE_NORMAL = 0; protected static final int TAGPARSESTATE_SAWLEFTANGLE = 1; protected static final int TAGPARSESTATE_SAWEXCLAMATION = 2; protected static final int TAGPARSESTATE_SAWDASH = 3; protected static final int TAGPARSESTATE_IN_COMMENT = 4; protected static final int TAGPARSESTATE_SAWCOMMENTDASH = 5; protected static final int TAGPARSESTATE_SAWSECONDCOMMENTDASH = 6; protected static final int TAGPARSESTATE_IN_TAG_NAME = 7; protected static final int TAGPARSESTATE_IN_ATTR_NAME = 8; protected static final int TAGPARSESTATE_IN_ATTR_VALUE = 9; protected static final int TAGPARSESTATE_IN_TAG_SAW_SLASH = 10; protected static final int TAGPARSESTATE_IN_END_TAG_NAME = 11; protected static final int TAGPARSESTATE_IN_ATTR_LOOKING_FOR_VALUE = 12; protected static final int TAGPARSESTATE_IN_SINGLE_QUOTES_ATTR_VALUE = 13; protected static final int TAGPARSESTATE_IN_DOUBLE_QUOTES_ATTR_VALUE = 14; protected static final int TAGPARSESTATE_IN_UNQUOTED_ATTR_VALUE = 15; protected static final int TAGPARSESTATE_IN_QTAG_NAME = 16; protected static final int TAGPARSESTATE_IN_QTAG_ATTR_NAME = 17; protected static final int TAGPARSESTATE_IN_QTAG_SAW_QUESTION = 18; protected static final int TAGPARSESTATE_IN_QTAG_ATTR_VALUE = 19; protected static final int TAGPARSESTATE_IN_QTAG_ATTR_LOOKING_FOR_VALUE = 20; protected static final int TAGPARSESTATE_IN_QTAG_SINGLE_QUOTES_ATTR_VALUE = 21; protected static final int TAGPARSESTATE_IN_QTAG_DOUBLE_QUOTES_ATTR_VALUE = 22; protected static final int TAGPARSESTATE_IN_QTAG_UNQUOTED_ATTR_VALUE = 23; protected static final int TAGPARSESTATE_IN_BRACKET_TOKEN = 24; protected static final int TAGPARSESTATE_NEED_FINAL_BRACKET = 25; protected static final int TAGPARSESTATE_IN_BANG_TOKEN = 26; protected static final int TAGPARSESTATE_IN_CDATA_BODY = 27; protected static final int TAGPARSESTATE_SAWRIGHTBRACKET = 28; protected static final int TAGPARSESTATE_SAWSECONDRIGHTBRACKET = 29; protected static final int TAGPARSESTATE_IN_UNQUOTED_ATTR_VALUE_SAW_SLASH = 30; protected int currentState = TAGPARSESTATE_NORMAL; /** The btag depth, which indicates btag behavior when &gt; 0. */ protected int bTagDepth = 0; /** This is the only buffer we actually accumulate stuff in. */ protected StringBuilder accumBuffer = new StringBuilder(); // The following are pointers to the accum buffer above, when allocated. protected StringBuilder currentTagNameBuffer = null; protected StringBuilder currentAttrNameBuffer = null; protected StringBuilder currentValueBuffer = null; protected String currentTagName = null; protected String currentAttrName = null; protected List<AttrNameValue> currentAttrList = null; // Body decoding state /** Whether we've seen an ampersand */ protected boolean inAmpersand = false; /** Buffer of characters seen after ampersand. */ protected StringBuilder ampBuffer = new StringBuilder(); protected static final Map<String,String> mapLookup = new HashMap<String,String>(); static { mapLookup.put("amp","&"); mapLookup.put("lt","<"); mapLookup.put("gt",">"); mapLookup.put("quot","\""); mapLookup.put("apos","'"); } public TagParseState() { super(65536); } /** Deal with a character. No exceptions are allowed, since those would represent * syntax errors, and we don't want those to cause difficulty. */ @Override public boolean dealWithCharacter(char thisChar) throws ManifoldCFException { // At this level we want basic lexical analysis - that is, we deal with identifying tags and comments, that's it. // We don't even attempt to map to lower case, that's how naive this is. switch (currentState) { case TAGPARSESTATE_NORMAL: if (thisChar == '<') { if (inAmpersand) { outputAmpBuffer(); inAmpersand = false; } currentState = TAGPARSESTATE_SAWLEFTANGLE; } else if (bTagDepth > 0 && thisChar == '>') { // Output current token, if any if (currentTagNameBuffer != null && currentTagNameBuffer.length() > 0) { currentTagName = currentTagNameBuffer.toString(); if (noteBTagToken(currentTagName)) return true; currentTagName = null; currentTagNameBuffer = null; } if (noteEndBTag()) return true; bTagDepth--; } else if (bTagDepth == 0) { if (inAmpersand) { if (thisChar == ';') { // We append the semi so that the output function can make good decisions ampBuffer.append(thisChar); if (outputAmpBuffer()) return true; inAmpersand = false; } else if (isWhitespace(thisChar)) { // Interpret ampersand buffer. if (outputAmpBuffer()) return true; inAmpersand = false; if (noteNormalCharacter(thisChar)) return true; } else ampBuffer.append(thisChar); } else if (thisChar == '&') { inAmpersand = true; ampBuffer.setLength(0); } else { if (noteNormalCharacter(thisChar)) return true; } } else { // In btag; accumulate tokens if (isPunctuation(thisChar)) { if (currentTagNameBuffer != null && currentTagNameBuffer.length() > 0) { currentTagName = currentTagNameBuffer.toString(); if (noteBTagToken(currentTagName)) return true; currentTagNameBuffer = null; currentTagName = null; } if (noteBTagToken(new StringBuilder().append(thisChar).toString())) return true; } else if (isWhitespace(thisChar)) { if (currentTagNameBuffer != null && currentTagNameBuffer.length() > 0) { currentTagName = currentTagNameBuffer.toString(); if (noteBTagToken(currentTagName)) return true; currentTagNameBuffer = null; currentTagName = null; } } else { if (currentTagNameBuffer == null) currentTagNameBuffer = newBuffer(); currentTagNameBuffer.append(thisChar); } } break; case TAGPARSESTATE_IN_CDATA_BODY: if (thisChar == ']') currentState = TAGPARSESTATE_SAWRIGHTBRACKET; else { if (noteEscapedCharacter(thisChar)) return true; } break; case TAGPARSESTATE_SAWRIGHTBRACKET: if (thisChar == ']') currentState = TAGPARSESTATE_SAWSECONDRIGHTBRACKET; else { currentState = TAGPARSESTATE_IN_CDATA_BODY; if (noteEscapedCharacter(']')) return true; if (noteEscapedCharacter(thisChar)) return true; } break; case TAGPARSESTATE_SAWSECONDRIGHTBRACKET: if (thisChar == '>') currentState = TAGPARSESTATE_NORMAL; else if (thisChar == ']') { // currentstate unchanged; emit the first bracket if (noteEscapedCharacter(']')) return true; } else { currentState = TAGPARSESTATE_IN_CDATA_BODY; if (noteEscapedCharacter(']')) return true; if (noteEscapedCharacter(']')) return true; if (noteEscapedCharacter(thisChar)) return true; } break; case TAGPARSESTATE_SAWLEFTANGLE: if (thisChar == '!') currentState = TAGPARSESTATE_SAWEXCLAMATION; else if (thisChar == '?') { currentState = TAGPARSESTATE_IN_QTAG_NAME; currentTagNameBuffer = newBuffer(); } else if (bTagDepth == 0 && thisChar == '/') { currentState = TAGPARSESTATE_IN_END_TAG_NAME; currentTagNameBuffer = newBuffer(); } else if (bTagDepth == 0) { if (isWhitespace(thisChar) || !acceptNewTag()) { // Not a tag. currentState = TAGPARSESTATE_NORMAL; if (noteNormalCharacter('<')) return true; if (noteNormalCharacter(thisChar)) return true; } else { currentState = TAGPARSESTATE_IN_TAG_NAME; currentTagNameBuffer = newBuffer(); currentTagNameBuffer.append(thisChar); } } else { // in btag, saw left angle, nothing recognizable after - must be a token if (noteBTagToken("<")) return true; if (!isWhitespace(thisChar)) { // Add char to current token buffer. currentTagNameBuffer = newBuffer(); currentTagNameBuffer.append(thisChar); } currentState = TAGPARSESTATE_NORMAL; } break; case TAGPARSESTATE_SAWEXCLAMATION: if (thisChar == '-') currentState = TAGPARSESTATE_SAWDASH; else if (thisChar == '[') { currentState = TAGPARSESTATE_IN_BRACKET_TOKEN; currentTagNameBuffer = newBuffer(); } else { bTagDepth++; currentState = TAGPARSESTATE_IN_BANG_TOKEN; currentTagNameBuffer = newBuffer(); if (!isWhitespace(thisChar)) currentTagNameBuffer.append(thisChar); } break; case TAGPARSESTATE_SAWDASH: if (thisChar == '-') currentState = TAGPARSESTATE_IN_COMMENT; else currentState = TAGPARSESTATE_NORMAL; break; case TAGPARSESTATE_IN_COMMENT: // We're in a comment. All we should look for is the end of the comment. if (thisChar == '-') currentState = TAGPARSESTATE_SAWCOMMENTDASH; break; case TAGPARSESTATE_SAWCOMMENTDASH: if (thisChar == '-') currentState = TAGPARSESTATE_SAWSECONDCOMMENTDASH; else currentState = TAGPARSESTATE_IN_COMMENT; break; case TAGPARSESTATE_SAWSECONDCOMMENTDASH: if (thisChar == '>') currentState = TAGPARSESTATE_NORMAL; else if (thisChar != '-') currentState = TAGPARSESTATE_IN_COMMENT; break; case TAGPARSESTATE_IN_QTAG_NAME: if (isWhitespace(thisChar)) { if (currentTagNameBuffer.length() > 0) { // Done with the tag name! currentTagName = currentTagNameBuffer.toString(); currentTagNameBuffer = null; currentAttrList = new ArrayList<AttrNameValue>(); currentState = TAGPARSESTATE_IN_QTAG_ATTR_NAME; currentAttrNameBuffer = newBuffer(); } } else if (thisChar == '?') { if (currentTagNameBuffer.length() > 0) { currentTagName = currentTagNameBuffer.toString(); currentTagNameBuffer = null; currentAttrList = new ArrayList<AttrNameValue>(); currentState = TAGPARSESTATE_IN_QTAG_SAW_QUESTION; if (noteQTag(currentTagName,currentAttrList)) return true; } else { currentState = TAGPARSESTATE_NORMAL; currentTagNameBuffer = null; } } else if (thisChar == '>') { if (currentTagNameBuffer.length() > 0) { currentTagName = currentTagNameBuffer.toString(); currentTagNameBuffer = null; currentAttrList = new ArrayList<AttrNameValue>(); } if (currentTagName != null) { if (noteQTag(currentTagName,currentAttrList)) return true; } currentState = TAGPARSESTATE_NORMAL; currentTagName = null; currentAttrList = null; } else currentTagNameBuffer.append(thisChar); break; case TAGPARSESTATE_IN_BRACKET_TOKEN: if (isWhitespace(thisChar)) { if (currentTagNameBuffer.length() > 0) { // Done with the bracket token! currentTagName = currentTagNameBuffer.toString(); currentTagNameBuffer = null; currentState = TAGPARSESTATE_NEED_FINAL_BRACKET; } } else if (thisChar == '[') { currentTagName = currentTagNameBuffer.toString(); currentTagNameBuffer = null; currentState = TAGPARSESTATE_IN_CDATA_BODY; if (noteEscaped(currentTagName)) return true; currentTagName = null; } else currentTagNameBuffer.append(thisChar); break; case TAGPARSESTATE_NEED_FINAL_BRACKET: if (thisChar == '[') { if (noteEscaped(currentTagName)) return true; currentTagName = null; currentState = TAGPARSESTATE_IN_CDATA_BODY; } break; case TAGPARSESTATE_IN_BANG_TOKEN: if (isWhitespace(thisChar)) { if (currentTagNameBuffer.length() > 0) { // Done with bang token currentTagName = currentTagNameBuffer.toString(); currentTagNameBuffer = null; if (noteBTag(currentTagName)) return true; currentTagName = null; currentState = TAGPARSESTATE_NORMAL; } } else if (thisChar == '>') { // Also done, but signal end too. currentTagName = currentTagNameBuffer.toString(); currentTagNameBuffer = null; if (noteBTag(currentTagName)) return true; currentTagName = null; currentState = TAGPARSESTATE_NORMAL; if (noteEndBTag()) return true; bTagDepth--; } else currentTagNameBuffer.append(thisChar); break; case TAGPARSESTATE_IN_TAG_NAME: if (isWhitespace(thisChar)) { if (currentTagNameBuffer.length() > 0) { // Done with the tag name! currentTagName = currentTagNameBuffer.toString(); currentTagNameBuffer = null; currentAttrList = new ArrayList<AttrNameValue>(); currentState = TAGPARSESTATE_IN_ATTR_NAME; currentAttrNameBuffer = newBuffer(); } } else if (thisChar == '/') { if (currentTagNameBuffer.length() > 0) { currentTagName = currentTagNameBuffer.toString(); currentTagNameBuffer = null; currentAttrList = new ArrayList<AttrNameValue>(); currentState = TAGPARSESTATE_IN_TAG_SAW_SLASH; if (noteTag(currentTagName,currentAttrList)) return true; } else { currentState = TAGPARSESTATE_NORMAL; currentTagNameBuffer = null; } } else if (thisChar == '>') { if (currentTagNameBuffer.length() > 0) { currentTagName = currentTagNameBuffer.toString(); currentTagNameBuffer = null; currentAttrList = new ArrayList<AttrNameValue>(); } if (currentTagName != null) { if (noteTag(currentTagName,currentAttrList)) return true; } currentState = TAGPARSESTATE_NORMAL; currentTagName = null; currentAttrList = null; } else currentTagNameBuffer.append(thisChar); break; case TAGPARSESTATE_IN_QTAG_ATTR_NAME: if (isWhitespace(thisChar)) { if (currentAttrNameBuffer.length() > 0) { // Done with attr name! currentAttrName = currentAttrNameBuffer.toString(); currentAttrNameBuffer = null; currentState = TAGPARSESTATE_IN_QTAG_ATTR_LOOKING_FOR_VALUE; } } else if (thisChar == '=') { if (currentAttrNameBuffer.length() > 0) { currentAttrName = currentAttrNameBuffer.toString(); currentAttrNameBuffer = null; currentState = TAGPARSESTATE_IN_QTAG_ATTR_VALUE; currentValueBuffer = newBuffer(); } } else if (thisChar == '?') { if (currentAttrNameBuffer.length() > 0) { currentAttrName = currentAttrNameBuffer.toString(); currentAttrNameBuffer = null; } if (currentAttrName != null) { currentAttrList.add(new AttrNameValue(currentAttrName,"")); currentAttrName = null; } if (noteQTag(currentTagName,currentAttrList)) return true; currentState = TAGPARSESTATE_IN_QTAG_SAW_QUESTION; } else if (thisChar == '>') { if (currentAttrNameBuffer.length() > 0) { currentAttrName = currentAttrNameBuffer.toString(); currentAttrNameBuffer = null; } if (currentAttrName != null) { currentAttrList.add(new AttrNameValue(currentAttrName,"")); currentAttrName = null; } currentState = TAGPARSESTATE_NORMAL; if (noteQTag(currentTagName,currentAttrList)) return true; currentTagName = null; currentAttrList = null; } else currentAttrNameBuffer.append(thisChar); break; case TAGPARSESTATE_IN_ATTR_NAME: if (isWhitespace(thisChar)) { if (currentAttrNameBuffer.length() > 0) { // Done with attr name! currentAttrName = currentAttrNameBuffer.toString(); currentAttrNameBuffer = null; currentState = TAGPARSESTATE_IN_ATTR_LOOKING_FOR_VALUE; } } else if (thisChar == '=') { if (currentAttrNameBuffer.length() > 0) { currentAttrName = currentAttrNameBuffer.toString(); currentAttrNameBuffer = null; currentState = TAGPARSESTATE_IN_ATTR_VALUE; currentValueBuffer = newBuffer(); } } else if (thisChar == '/') { if (currentAttrNameBuffer.length() > 0) { currentAttrName = currentAttrNameBuffer.toString(); currentAttrNameBuffer = null; } if (currentAttrName != null) { currentAttrList.add(new AttrNameValue(currentAttrName,"")); currentAttrName = null; } if (noteTag(currentTagName,currentAttrList)) return true; currentState = TAGPARSESTATE_IN_TAG_SAW_SLASH; } else if (thisChar == '>') { if (currentAttrNameBuffer.length() > 0) { currentAttrName = currentAttrNameBuffer.toString(); currentAttrNameBuffer = null; } if (currentAttrName != null) { currentAttrList.add(new AttrNameValue(currentAttrName,"")); currentAttrName = null; } currentState = TAGPARSESTATE_NORMAL; if (noteTag(currentTagName,currentAttrList)) return true; currentTagName = null; currentAttrList = null; } else currentAttrNameBuffer.append(thisChar); break; case TAGPARSESTATE_IN_QTAG_ATTR_LOOKING_FOR_VALUE: if (thisChar == '=') { currentState = TAGPARSESTATE_IN_QTAG_ATTR_VALUE; currentValueBuffer = newBuffer(); } else if (thisChar == '>') { currentState = TAGPARSESTATE_NORMAL; if (noteQTag(currentTagName,currentAttrList)) return true; currentTagName = null; currentAttrList = null; } else if (thisChar == '?') { currentState = TAGPARSESTATE_IN_QTAG_SAW_QUESTION; currentAttrList.add(new AttrNameValue(currentAttrName,"")); currentAttrName = null; if (noteQTag(currentTagName,currentAttrList)) return true; } else if (!isWhitespace(thisChar)) { currentAttrList.add(new AttrNameValue(currentAttrName,"")); currentState = TAGPARSESTATE_IN_QTAG_ATTR_NAME; currentAttrNameBuffer = newBuffer(); currentAttrNameBuffer.append(thisChar); currentAttrName = null; } break; case TAGPARSESTATE_IN_ATTR_LOOKING_FOR_VALUE: if (thisChar == '=') { currentState = TAGPARSESTATE_IN_ATTR_VALUE; currentValueBuffer = newBuffer(); } else if (thisChar == '>') { currentState = TAGPARSESTATE_NORMAL; if (noteTag(currentTagName,currentAttrList)) return true; currentTagName = null; currentAttrList = null; } else if (thisChar == '/') { currentState = TAGPARSESTATE_IN_TAG_SAW_SLASH; currentAttrList.add(new AttrNameValue(currentAttrName,"")); currentAttrName = null; if (noteTag(currentTagName,currentAttrList)) return true; } else if (!isWhitespace(thisChar)) { currentAttrList.add(new AttrNameValue(currentAttrName,"")); currentState = TAGPARSESTATE_IN_ATTR_NAME; currentAttrNameBuffer = newBuffer(); currentAttrNameBuffer.append(thisChar); currentAttrName = null; } break; case TAGPARSESTATE_IN_QTAG_ATTR_VALUE: if (thisChar == '\'') currentState = TAGPARSESTATE_IN_QTAG_SINGLE_QUOTES_ATTR_VALUE; else if (thisChar == '"') currentState = TAGPARSESTATE_IN_QTAG_DOUBLE_QUOTES_ATTR_VALUE; else if (!isWhitespace(thisChar)) { currentState = TAGPARSESTATE_IN_QTAG_UNQUOTED_ATTR_VALUE; currentValueBuffer.append(thisChar); } break; case TAGPARSESTATE_IN_ATTR_VALUE: if (thisChar == '\'') currentState = TAGPARSESTATE_IN_SINGLE_QUOTES_ATTR_VALUE; else if (thisChar == '"') currentState = TAGPARSESTATE_IN_DOUBLE_QUOTES_ATTR_VALUE; else if (thisChar == '/') currentState = TAGPARSESTATE_IN_UNQUOTED_ATTR_VALUE_SAW_SLASH; else if (!isWhitespace(thisChar)) { currentState = TAGPARSESTATE_IN_UNQUOTED_ATTR_VALUE; currentValueBuffer.append(thisChar); } break; case TAGPARSESTATE_IN_QTAG_SAW_QUESTION: if (thisChar == '>') { // No end-tag notification for this one currentState = TAGPARSESTATE_NORMAL; currentTagName = null; currentAttrList = null; } break; case TAGPARSESTATE_IN_TAG_SAW_SLASH: if (thisChar == '>') { if (noteEndTag(currentTagName)) return true; currentState = TAGPARSESTATE_NORMAL; currentTagName = null; currentAttrList = null; } break; case TAGPARSESTATE_IN_END_TAG_NAME: if (isWhitespace(thisChar)) { if (currentTagNameBuffer != null && currentTagNameBuffer.length() > 0) { // Done with the tag name! currentTagName = currentTagNameBuffer.toString(); currentTagNameBuffer = null; } } else if (thisChar == '>') { if (currentTagNameBuffer != null && currentTagNameBuffer.length() > 0) { currentTagName = currentTagNameBuffer.toString(); currentTagNameBuffer = null; } if (currentTagName != null) { if (noteEndTag(currentTagName)) return true; } currentTagName = null; currentState = TAGPARSESTATE_NORMAL; } else if (currentTagNameBuffer != null) currentTagNameBuffer.append(thisChar); break; case TAGPARSESTATE_IN_QTAG_SINGLE_QUOTES_ATTR_VALUE: if (thisChar == '\'' || thisChar == '\n' || thisChar == '\r') { currentAttrList.add(new AttrNameValue(currentAttrName,attributeDecode(currentValueBuffer.toString()))); currentAttrName = null; currentValueBuffer = null; currentState = TAGPARSESTATE_IN_QTAG_ATTR_NAME; currentAttrNameBuffer = newBuffer(); } else currentValueBuffer.append(thisChar); break; case TAGPARSESTATE_IN_SINGLE_QUOTES_ATTR_VALUE: if (thisChar == '\'' || thisChar == '\n' || thisChar == '\r') { currentAttrList.add(new AttrNameValue(currentAttrName,attributeDecode(currentValueBuffer.toString()))); currentAttrName = null; currentValueBuffer = null; currentState = TAGPARSESTATE_IN_ATTR_NAME; currentAttrNameBuffer = newBuffer(); } else currentValueBuffer.append(thisChar); break; case TAGPARSESTATE_IN_QTAG_DOUBLE_QUOTES_ATTR_VALUE: if (thisChar == '"' || thisChar == '\n' || thisChar == '\r') { currentAttrList.add(new AttrNameValue(currentAttrName,attributeDecode(currentValueBuffer.toString()))); currentAttrName = null; currentValueBuffer = null; currentState = TAGPARSESTATE_IN_QTAG_ATTR_NAME; currentAttrNameBuffer = newBuffer(); } else currentValueBuffer.append(thisChar); break; case TAGPARSESTATE_IN_DOUBLE_QUOTES_ATTR_VALUE: if (thisChar == '"' || thisChar == '\n' || thisChar == '\r') { currentAttrList.add(new AttrNameValue(currentAttrName,attributeDecode(currentValueBuffer.toString()))); currentAttrName = null; currentValueBuffer = null; currentState = TAGPARSESTATE_IN_ATTR_NAME; currentAttrNameBuffer = newBuffer(); } else currentValueBuffer.append(thisChar); break; case TAGPARSESTATE_IN_QTAG_UNQUOTED_ATTR_VALUE: if (isWhitespace(thisChar)) { currentAttrList.add(new AttrNameValue(currentAttrName,attributeDecode(currentValueBuffer.toString()))); currentAttrName = null; currentValueBuffer = null; currentState = TAGPARSESTATE_IN_QTAG_ATTR_NAME; currentAttrNameBuffer = newBuffer(); } else if (thisChar == '?') { currentAttrList.add(new AttrNameValue(currentAttrName,attributeDecode(currentValueBuffer.toString()))); if (noteTag(currentTagName,currentAttrList)) return true; currentState = TAGPARSESTATE_IN_QTAG_SAW_QUESTION; } else if (thisChar == '>') { currentAttrList.add(new AttrNameValue(currentAttrName,attributeDecode(currentValueBuffer.toString()))); currentAttrName = null; currentValueBuffer = null; currentState = TAGPARSESTATE_NORMAL; if (noteTag(currentTagName,currentAttrList)) return true; currentTagName = null; currentAttrList = null; } else currentValueBuffer.append(thisChar); break; case TAGPARSESTATE_IN_UNQUOTED_ATTR_VALUE_SAW_SLASH: if (isWhitespace(thisChar)) { currentValueBuffer.append('/'); currentAttrList.add(new AttrNameValue(currentAttrName,attributeDecode(currentValueBuffer.toString()))); currentAttrName = null; currentValueBuffer = null; currentState = TAGPARSESTATE_IN_ATTR_NAME; currentAttrNameBuffer = newBuffer(); } else if (thisChar == '/') { currentValueBuffer.append('/'); } else if (thisChar == '>') { currentValueBuffer.append('/'); currentAttrList.add(new AttrNameValue(currentAttrName,attributeDecode(currentValueBuffer.toString()))); currentAttrName = null; currentValueBuffer = null; currentState = TAGPARSESTATE_NORMAL; if (noteTag(currentTagName,currentAttrList)) return true; currentTagName = null; currentAttrList = null; } else { currentValueBuffer.append('/'); currentValueBuffer.append(thisChar); currentState = TAGPARSESTATE_IN_UNQUOTED_ATTR_VALUE; } break; case TAGPARSESTATE_IN_UNQUOTED_ATTR_VALUE: if (isWhitespace(thisChar)) { currentAttrList.add(new AttrNameValue(currentAttrName,attributeDecode(currentValueBuffer.toString()))); currentAttrName = null; currentValueBuffer = null; currentState = TAGPARSESTATE_IN_ATTR_NAME; currentAttrNameBuffer = newBuffer(); } else if (thisChar == '/') { currentState = TAGPARSESTATE_IN_UNQUOTED_ATTR_VALUE_SAW_SLASH; } else if (thisChar == '>') { currentAttrList.add(new AttrNameValue(currentAttrName,attributeDecode(currentValueBuffer.toString()))); currentAttrName = null; currentValueBuffer = null; currentState = TAGPARSESTATE_NORMAL; if (noteTag(currentTagName,currentAttrList)) return true; currentTagName = null; currentAttrList = null; } else currentValueBuffer.append(thisChar); break; default: throw new ManifoldCFException("Invalid state: "+Integer.toString(currentState)); } return false; } /** Allow parsing within tag. */ protected boolean acceptNewTag() { return true; } /** Allocate the buffer. */ protected StringBuilder newBuffer() { accumBuffer.setLength(0); return accumBuffer; } /** Interpret ampersand buffer. */ protected boolean outputAmpBuffer() throws ManifoldCFException { if (ampBuffer.length() == 0 || (ampBuffer.length() == 1 && ampBuffer.charAt(0) == ';')) { // Length is zero; probably a mistake, so just output the whole thing if (noteNormalCharacter('&')) return true; if (dumpValues(ampBuffer.toString())) return true; return false; } else { // Is it a known entity? String entity = ampBuffer.toString(); if (entity.endsWith(";")) entity = entity.substring(0,entity.length()-1); String replacement = mapChunk(entity); if (replacement != null) { if (dumpValues(replacement)) return true; } return false; } } protected boolean dumpValues(String value) throws ManifoldCFException { for (int i = 0; i < value.length(); i++) { if (noteNormalCharacter(value.charAt(i))) return true; } return false; } /** This method gets called for every tag. Override this method to intercept tag begins. *@return true to halt further processing. */ protected boolean noteTag(String tagName, List<AttrNameValue> attributes) throws ManifoldCFException { if (Logging.misc.isDebugEnabled()) Logging.misc.debug(" Saw tag '"+tagName+"'"); return false; } /** This method gets called for every end tag. Override this method to intercept tag ends. *@return true to halt further processing. */ protected boolean noteEndTag(String tagName) throws ManifoldCFException { if (Logging.misc.isDebugEnabled()) Logging.misc.debug(" Saw end tag '"+tagName+"'"); return false; } /** This method is called for every &lt;? ... ?&gt; construct, or 'qtag'. * Override it to intercept such constructs. *@return true to halt further processing. */ protected boolean noteQTag(String tagName, List<AttrNameValue> attributes) throws ManifoldCFException { if (Logging.misc.isDebugEnabled()) Logging.misc.debug(" Saw QTag '"+tagName+"'"); return false; } /** This method is called for every &lt;! &lt;token&gt; ... &gt; construct, or 'btag'. * Override it to intercept these. *@return true to halt further processing. */ protected boolean noteBTag(String tagName) throws ManifoldCFException { if (Logging.misc.isDebugEnabled()) Logging.misc.debug(" Saw BTag '"+tagName+"'"); return false; } /** This method is called for the end of every btag, or any time * there's a naked '&gt;' in the document. Override it if you want to intercept these. *@return true to halt further processing. */ protected boolean noteEndBTag() throws ManifoldCFException { Logging.misc.debug(" Saw end BTag"); return false; } /** Called for the start of every cdata-like tag, e.g. &lt;![ &lt;token&gt; [ ... ]]&gt; *@param token may be empty!!! *@return true to halt further processing. */ protected boolean noteEscaped(String token) throws ManifoldCFException { if (Logging.misc.isDebugEnabled()) Logging.misc.debug(" Saw escaped block '"+token+"'"); return false; } /** Called for the end of every cdata-like tag. *@return true to halt further processing. */ protected boolean noteEndEscaped() throws ManifoldCFException { Logging.misc.debug(" Saw end of escaped block"); return false; } /** This method gets called for every token inside a btag. *@return true to halt further processing. */ protected boolean noteBTagToken(String token) throws ManifoldCFException { return false; } /** This method gets called for every character that is not part of a tag etc. * Override this method to intercept such characters. *@return true to halt further processing. */ protected boolean noteNormalCharacter(char thisChar) throws ManifoldCFException { return false; } /** This method gets called for every character that is found within an * escape block, e.g. CDATA. * Override this method to intercept such characters. *@return true to halt further processing. */ protected boolean noteEscapedCharacter(char thisChar) throws ManifoldCFException { return false; } /** Decode an html attribute */ protected static String attributeDecode(String input) { StringBuilder output = new StringBuilder(); int i = 0; while (i < input.length()) { char x = input.charAt(i++); if (x == '&') { int index = input.indexOf(";",i); if (index != -1) { String chunk = input.substring(i,index); String replacement = mapChunk(chunk); if (replacement != null) { output.append(replacement); i = index + 1; continue; } } } output.append(x); } return output.toString(); } /** Map an entity reference back to a character */ protected static String mapChunk(String input) { if (input.startsWith("#")) { // Treat as a decimal value try { input = input.substring(1); int value; if (input.startsWith("x")) { // Hex value = Integer.decode("0"+input); } else { // Decimal value = Integer.parseInt(input); } StringBuilder sb = new StringBuilder(); sb.append((char)value); return sb.toString(); } catch (NumberFormatException e) { return null; } } else return mapLookup.get(input); } /** Is a character markup language whitespace? */ protected static boolean isWhitespace(char x) { return x <= ' '; } /** Is a character markup language punctuation? */ protected static boolean isPunctuation(char x) { return x == '%' || x == '|' || x == '&' || x == '!' || x == '^' || x == ',' || x == ';' || x == '[' || x == ']' || x == '(' || x == ')' || x == ':' || x == '/' || x == '\\' || x == '+' || x == '='; } }
googleapis/google-cloud-java
37,205
java-dialogflow-cx/proto-google-cloud-dialogflow-cx-v3beta1/src/main/java/com/google/cloud/dialogflow/cx/v3beta1/ParameterDefinition.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/cx/v3beta1/parameter_definition.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.cx.v3beta1; /** * * * <pre> * Defines the properties of a parameter. * Used to define parameters used in the agent and the * input / output parameters for each fulfillment. * (-- Next Id: 4 --) * (-- api-linter: core::0123::resource-annotation=disabled * aip.dev/not-precedent: ParameterDefinition is not an exposed resource. * --) * </pre> * * Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.ParameterDefinition} */ public final class ParameterDefinition extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.cx.v3beta1.ParameterDefinition) ParameterDefinitionOrBuilder { private static final long serialVersionUID = 0L; // Use ParameterDefinition.newBuilder() to construct. private ParameterDefinition(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ParameterDefinition() { name_ = ""; type_ = 0; description_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ParameterDefinition(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinitionProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ParameterDefinition_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinitionProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ParameterDefinition_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.class, com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.Builder.class); } /** * * * <pre> * Parameter types are used for validation. * These types are consistent with [google.protobuf.Value][]. * </pre> * * Protobuf enum {@code google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType} */ public enum ParameterType implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Not specified. No validation will be performed. * </pre> * * <code>PARAMETER_TYPE_UNSPECIFIED = 0;</code> */ PARAMETER_TYPE_UNSPECIFIED(0), /** * * * <pre> * Represents any string value. * </pre> * * <code>STRING = 1;</code> */ STRING(1), /** * * * <pre> * Represents any number value. * </pre> * * <code>NUMBER = 2;</code> */ NUMBER(2), /** * * * <pre> * Represents a boolean value. * </pre> * * <code>BOOLEAN = 3;</code> */ BOOLEAN(3), /** * * * <pre> * Represents a null value. * </pre> * * <code>NULL = 4;</code> */ NULL(4), /** * * * <pre> * Represents any object value. * </pre> * * <code>OBJECT = 5;</code> */ OBJECT(5), /** * * * <pre> * Represents a repeated value. * </pre> * * <code>LIST = 6;</code> */ LIST(6), UNRECOGNIZED(-1), ; /** * * * <pre> * Not specified. No validation will be performed. * </pre> * * <code>PARAMETER_TYPE_UNSPECIFIED = 0;</code> */ public static final int PARAMETER_TYPE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Represents any string value. * </pre> * * <code>STRING = 1;</code> */ public static final int STRING_VALUE = 1; /** * * * <pre> * Represents any number value. * </pre> * * <code>NUMBER = 2;</code> */ public static final int NUMBER_VALUE = 2; /** * * * <pre> * Represents a boolean value. * </pre> * * <code>BOOLEAN = 3;</code> */ public static final int BOOLEAN_VALUE = 3; /** * * * <pre> * Represents a null value. * </pre> * * <code>NULL = 4;</code> */ public static final int NULL_VALUE = 4; /** * * * <pre> * Represents any object value. * </pre> * * <code>OBJECT = 5;</code> */ public static final int OBJECT_VALUE = 5; /** * * * <pre> * Represents a repeated value. * </pre> * * <code>LIST = 6;</code> */ public static final int LIST_VALUE = 6; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static ParameterType 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 ParameterType forNumber(int value) { switch (value) { case 0: return PARAMETER_TYPE_UNSPECIFIED; case 1: return STRING; case 2: return NUMBER; case 3: return BOOLEAN; case 4: return NULL; case 5: return OBJECT; case 6: return LIST; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<ParameterType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<ParameterType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<ParameterType>() { public ParameterType findValueByNumber(int number) { return ParameterType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.getDescriptor() .getEnumTypes() .get(0); } private static final ParameterType[] VALUES = values(); public static ParameterType 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 ParameterType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType) } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Name of parameter. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Name of parameter. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TYPE_FIELD_NUMBER = 2; private int type_ = 0; /** * * * <pre> * Type of parameter. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType type = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** * * * <pre> * Type of parameter. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType type = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The type. */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType getType() { com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType result = com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType.forNumber(type_); return result == null ? com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType.UNRECOGNIZED : result; } public static final int DESCRIPTION_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object description_ = ""; /** * * * <pre> * Human-readable description of the parameter. Limited to 300 characters. * </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> * Human-readable description of the parameter. Limited to 300 characters. * </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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (type_ != com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType .PARAMETER_TYPE_UNSPECIFIED .getNumber()) { output.writeEnum(2, type_); } 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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (type_ != com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType .PARAMETER_TYPE_UNSPECIFIED .getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, type_); } 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.cloud.dialogflow.cx.v3beta1.ParameterDefinition)) { return super.equals(obj); } com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition other = (com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition) obj; if (!getName().equals(other.getName())) return false; if (type_ != other.type_) 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) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + TYPE_FIELD_NUMBER; hash = (53 * hash) + type_; hash = (37 * hash) + DESCRIPTION_FIELD_NUMBER; hash = (53 * hash) + getDescription().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition 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> * Defines the properties of a parameter. * Used to define parameters used in the agent and the * input / output parameters for each fulfillment. * (-- Next Id: 4 --) * (-- api-linter: core::0123::resource-annotation=disabled * aip.dev/not-precedent: ParameterDefinition is not an exposed resource. * --) * </pre> * * Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.ParameterDefinition} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.cx.v3beta1.ParameterDefinition) com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinitionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinitionProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ParameterDefinition_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinitionProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ParameterDefinition_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.class, com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.Builder.class); } // Construct using com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; type_ = 0; description_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinitionProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ParameterDefinition_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition getDefaultInstanceForType() { return com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition build() { com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition buildPartial() { com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition result = new com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.type_ = type_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.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.cloud.dialogflow.cx.v3beta1.ParameterDefinition) { return mergeFrom((com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition other) { if (other == com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (other.type_ != 0) { setTypeValue(other.getTypeValue()); } 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 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { type_ = 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 java.lang.Object name_ = ""; /** * * * <pre> * Name of parameter. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Name of parameter. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Name of parameter. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Name of parameter. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Name of parameter. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int type_ = 0; /** * * * <pre> * Type of parameter. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType type = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** * * * <pre> * Type of parameter. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType type = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The enum numeric value on the wire for type to set. * @return This builder for chaining. */ public Builder setTypeValue(int value) { type_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Type of parameter. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType type = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The type. */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType getType() { com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType result = com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType.forNumber(type_); return result == null ? com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType.UNRECOGNIZED : result; } /** * * * <pre> * Type of parameter. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType type = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The type to set. * @return This builder for chaining. */ public Builder setType( com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; type_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Type of parameter. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3beta1.ParameterDefinition.ParameterType type = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return This builder for chaining. */ public Builder clearType() { bitField0_ = (bitField0_ & ~0x00000002); type_ = 0; onChanged(); return this; } private java.lang.Object description_ = ""; /** * * * <pre> * Human-readable description of the parameter. Limited to 300 characters. * </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> * Human-readable description of the parameter. Limited to 300 characters. * </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> * Human-readable description of the parameter. Limited to 300 characters. * </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> * Human-readable description of the parameter. Limited to 300 characters. * </pre> * * <code>string description = 3;</code> * * @return This builder for chaining. */ public Builder clearDescription() { description_ = getDefaultInstance().getDescription(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Human-readable description of the parameter. Limited to 300 characters. * </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.cloud.dialogflow.cx.v3beta1.ParameterDefinition) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.cx.v3beta1.ParameterDefinition) private static final com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition(); } public static com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ParameterDefinition> PARSER = new com.google.protobuf.AbstractParser<ParameterDefinition>() { @java.lang.Override public ParameterDefinition 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<ParameterDefinition> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ParameterDefinition> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ParameterDefinition getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/paimon
37,559
paimon-common/src/main/java/org/apache/paimon/data/BinaryString.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.data; import org.apache.paimon.annotation.Public; import org.apache.paimon.memory.MemorySegment; import org.apache.paimon.memory.MemorySegmentUtils; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import static org.apache.paimon.memory.MemorySegmentUtils.allocateReuseBytes; import static org.apache.paimon.memory.MemorySegmentUtils.allocateReuseChars; import static org.apache.paimon.utils.Preconditions.checkArgument; /** * A string which is backed by {@link MemorySegment}s. * * @since 0.4.0 */ @Public public final class BinaryString extends BinarySection implements Comparable<BinaryString> { private static final long serialVersionUID = 1L; public static final BinaryString EMPTY_UTF8 = BinaryString.fromBytes(encodeUTF8("")); public BinaryString(MemorySegment[] segments, int offset, int sizeInBytes) { super(segments, offset, sizeInBytes); this.segments = segments; this.offset = offset; this.sizeInBytes = sizeInBytes; } // ------------------------------------------------------------------------------------------ // Construction Utilities // ------------------------------------------------------------------------------------------ public static BinaryString fromAddress(MemorySegment[] segments, int offset, int numBytes) { return new BinaryString(segments, offset, numBytes); } @Nullable public static BinaryString fromString(String str) { if (str == null) { return null; } return fromBytes(encodeUTF8(str)); } /** Creates a {@link BinaryString} instance from the given UTF-8 bytes. */ public static BinaryString fromBytes(byte[] bytes) { return fromBytes(bytes, 0, bytes.length); } /** * Creates a {@link BinaryString} instance from the given UTF-8 bytes with offset and number of * bytes. */ public static BinaryString fromBytes(byte[] bytes, int offset, int numBytes) { return new BinaryString(new MemorySegment[] {MemorySegment.wrap(bytes)}, offset, numBytes); } /** Creates a {@link BinaryString} instance that contains `length` spaces. */ public static BinaryString blankString(int length) { byte[] spaces = new byte[length]; Arrays.fill(spaces, (byte) ' '); return fromBytes(spaces); } // ------------------------------------------------------------------------------------------ // Public Interfaces // ------------------------------------------------------------------------------------------ @Override public String toString() { byte[] bytes = allocateReuseBytes(sizeInBytes); MemorySegmentUtils.copyToBytes(segments, offset, bytes, 0, sizeInBytes); return decodeUTF8(bytes, 0, sizeInBytes); } /** * Compares two strings lexicographically. Since UTF-8 uses groups of six bits, it is sometimes * useful to use octal notation which uses 3-bit groups. With a calculator which can convert * between hexadecimal and octal it can be easier to manually create or interpret UTF-8 compared * with using binary. So we just compare the binary. */ @Override public int compareTo(@Nonnull BinaryString other) { if (segments.length == 1 && other.segments.length == 1) { int len = Math.min(sizeInBytes, other.sizeInBytes); MemorySegment seg1 = segments[0]; MemorySegment seg2 = other.segments[0]; for (int i = 0; i < len; i++) { int res = (seg1.get(offset + i) & 0xFF) - (seg2.get(other.offset + i) & 0xFF); if (res != 0) { return res; } } return sizeInBytes - other.sizeInBytes; } // if there are multi segments. return compareMultiSegments(other); } /** Find the boundaries of segments, and then compare MemorySegment. */ private int compareMultiSegments(BinaryString other) { if (sizeInBytes == 0 || other.sizeInBytes == 0) { return sizeInBytes - other.sizeInBytes; } int len = Math.min(sizeInBytes, other.sizeInBytes); MemorySegment seg1 = segments[0]; MemorySegment seg2 = other.segments[0]; int segmentSize = segments[0].size(); int otherSegmentSize = other.segments[0].size(); int sizeOfFirst1 = segmentSize - offset; int sizeOfFirst2 = otherSegmentSize - other.offset; int varSegIndex1 = 1; int varSegIndex2 = 1; // find the first segment of this string. while (sizeOfFirst1 <= 0) { sizeOfFirst1 += segmentSize; seg1 = segments[varSegIndex1++]; } while (sizeOfFirst2 <= 0) { sizeOfFirst2 += otherSegmentSize; seg2 = other.segments[varSegIndex2++]; } int offset1 = segmentSize - sizeOfFirst1; int offset2 = otherSegmentSize - sizeOfFirst2; int needCompare = Math.min(Math.min(sizeOfFirst1, sizeOfFirst2), len); while (needCompare > 0) { // compare in one segment. for (int i = 0; i < needCompare; i++) { int res = (seg1.get(offset1 + i) & 0xFF) - (seg2.get(offset2 + i) & 0xFF); if (res != 0) { return res; } } if (needCompare == len) { break; } len -= needCompare; // next segment if (sizeOfFirst1 < sizeOfFirst2) { // I am smaller seg1 = segments[varSegIndex1++]; offset1 = 0; offset2 += needCompare; sizeOfFirst1 = segmentSize; sizeOfFirst2 -= needCompare; } else if (sizeOfFirst1 > sizeOfFirst2) { // other is smaller seg2 = other.segments[varSegIndex2++]; offset2 = 0; offset1 += needCompare; sizeOfFirst2 = otherSegmentSize; sizeOfFirst1 -= needCompare; } else { // same, should go ahead both. seg1 = segments[varSegIndex1++]; seg2 = other.segments[varSegIndex2++]; offset1 = 0; offset2 = 0; sizeOfFirst1 = segmentSize; sizeOfFirst2 = otherSegmentSize; } needCompare = Math.min(Math.min(sizeOfFirst1, sizeOfFirst2), len); } checkArgument(needCompare == len); return sizeInBytes - other.sizeInBytes; } // ------------------------------------------------------------------------------------------ // Public methods on BinaryString // ------------------------------------------------------------------------------------------ /** Returns the number of UTF-8 code points in the string. */ public int numChars() { if (inFirstSegment()) { int len = 0; for (int i = 0; i < sizeInBytes; i += numBytesForFirstByte(getByteOneSegment(i))) { len++; } return len; } else { return numCharsMultiSegs(); } } private int numCharsMultiSegs() { int len = 0; int segSize = segments[0].size(); BinaryString.SegmentAndOffset index = firstSegmentAndOffset(segSize); int i = 0; while (i < sizeInBytes) { int charBytes = numBytesForFirstByte(index.value()); i += charBytes; len++; index.skipBytes(charBytes, segSize); } return len; } /** * Returns the {@code byte} value at the specified index. An index ranges from {@code 0} to * {@code sizeInBytes - 1}. * * @param index the index of the {@code byte} value. * @return the {@code byte} value at the specified index of this UTF-8 bytes. * @exception IndexOutOfBoundsException if the {@code index} argument is negative or not less * than the length of this UTF-8 bytes. */ public byte byteAt(int index) { int globalOffset = offset + index; int size = segments[0].size(); if (globalOffset < size) { return segments[0].get(globalOffset); } else { return segments[globalOffset / size].get(globalOffset % size); } } /** Copy a new {@code BinaryString}. */ public BinaryString copy() { byte[] copy = MemorySegmentUtils.copyToBytes(segments, offset, sizeInBytes); return BinaryString.fromBytes(copy); } /** * Returns a binary string that is a substring of this binary string. The substring begins at * the specified {@code beginIndex} and extends to the character at index {@code endIndex - 1}. * * <p>Examples: * * <blockquote> * * <pre> * fromString("hamburger").substring(4, 8) returns binary string "urge" * fromString("smiles").substring(1, 5) returns binary string "mile" * </pre> * * </blockquote> * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring, return EMPTY_UTF8 when index out of bounds instead of * StringIndexOutOfBoundsException. */ public BinaryString substring(int beginIndex, int endIndex) { if (endIndex <= beginIndex || beginIndex >= sizeInBytes) { return EMPTY_UTF8; } if (inFirstSegment()) { MemorySegment segment = segments[0]; int i = 0; int c = 0; while (i < sizeInBytes && c < beginIndex) { i += numBytesForFirstByte(segment.get(i + offset)); c += 1; } int j = i; while (i < sizeInBytes && c < endIndex) { i += numBytesForFirstByte(segment.get(i + offset)); c += 1; } if (i > j) { byte[] bytes = new byte[i - j]; segment.get(offset + j, bytes, 0, i - j); return fromBytes(bytes); } else { return EMPTY_UTF8; } } else { return substringMultiSegs(beginIndex, endIndex); } } private BinaryString substringMultiSegs(final int start, final int until) { int segSize = segments[0].size(); BinaryString.SegmentAndOffset index = firstSegmentAndOffset(segSize); int i = 0; int c = 0; while (i < sizeInBytes && c < start) { int charSize = numBytesForFirstByte(index.value()); i += charSize; index.skipBytes(charSize, segSize); c += 1; } int j = i; while (i < sizeInBytes && c < until) { int charSize = numBytesForFirstByte(index.value()); i += charSize; index.skipBytes(charSize, segSize); c += 1; } if (i > j) { return fromBytes(MemorySegmentUtils.copyToBytes(segments, offset + j, i - j)); } else { return EMPTY_UTF8; } } /** * Returns true if and only if this BinaryString contains the specified sequence of bytes * values. * * @param s the sequence to search for * @return true if this BinaryString contains {@code s}, false otherwise */ public boolean contains(final BinaryString s) { if (s.sizeInBytes == 0) { return true; } int find = MemorySegmentUtils.find( segments, offset, sizeInBytes, s.segments, s.offset, s.sizeInBytes); return find != -1; } /** * Tests if this BinaryString starts with the specified prefix. * * @param prefix the prefix. * @return {@code true} if the bytes represented by the argument is a prefix of the bytes * represented by this string; {@code false} otherwise. Note also that {@code true} will be * returned if the argument is an empty BinaryString or is equal to this {@code * BinaryString} object as determined by the {@link #equals(Object)} method. */ public boolean startsWith(final BinaryString prefix) { return matchAt(prefix, 0); } /** * Tests if this BinaryString ends with the specified suffix. * * @param suffix the suffix. * @return {@code true} if the bytes represented by the argument is a suffix of the bytes * represented by this object; {@code false} otherwise. Note that the result will be {@code * true} if the argument is the empty string or is equal to this {@code BinaryString} object * as determined by the {@link #equals(Object)} method. */ public boolean endsWith(final BinaryString suffix) { return matchAt(suffix, sizeInBytes - suffix.sizeInBytes); } /** * Returns a string whose value is this string, with any leading and trailing whitespace * removed. * * @return A string whose value is this string, with any leading and trailing white space * removed, or this string if it has no leading or trailing white space. */ public BinaryString trim() { if (inFirstSegment()) { int s = 0; int e = this.sizeInBytes - 1; // skip all of the space (0x20) in the left side while (s < this.sizeInBytes && getByteOneSegment(s) == 0x20) { s++; } // skip all of the space (0x20) in the right side while (e >= s && getByteOneSegment(e) == 0x20) { e--; } if (s > e) { // empty string return EMPTY_UTF8; } else { return copyBinaryStringInOneSeg(s, e - s + 1); } } else { return trimMultiSegs(); } } private BinaryString trimMultiSegs() { int s = 0; int e = this.sizeInBytes - 1; int segSize = segments[0].size(); BinaryString.SegmentAndOffset front = firstSegmentAndOffset(segSize); // skip all of the space (0x20) in the left side while (s < this.sizeInBytes && front.value() == 0x20) { s++; front.nextByte(segSize); } BinaryString.SegmentAndOffset behind = lastSegmentAndOffset(segSize); // skip all of the space (0x20) in the right side while (e >= s && behind.value() == 0x20) { e--; behind.previousByte(segSize); } if (s > e) { // empty string return EMPTY_UTF8; } else { return copyBinaryString(s, e); } } /** * Returns the index within this string of the first occurrence of the specified substring, * starting at the specified index. * * @param str the substring to search for. * @param fromIndex the index from which to start the search. * @return the index of the first occurrence of the specified substring, starting at the * specified index, or {@code -1} if there is no such occurrence. */ public int indexOf(BinaryString str, int fromIndex) { if (str.sizeInBytes == 0) { return 0; } if (inFirstSegment()) { // position in byte int byteIdx = 0; // position is char int charIdx = 0; while (byteIdx < sizeInBytes && charIdx < fromIndex) { byteIdx += numBytesForFirstByte(getByteOneSegment(byteIdx)); charIdx++; } do { if (byteIdx + str.sizeInBytes > sizeInBytes) { return -1; } if (MemorySegmentUtils.equals( segments, offset + byteIdx, str.segments, str.offset, str.sizeInBytes)) { return charIdx; } byteIdx += numBytesForFirstByte(getByteOneSegment(byteIdx)); charIdx++; } while (byteIdx < sizeInBytes); return -1; } else { return indexOfMultiSegs(str, fromIndex); } } private int indexOfMultiSegs(BinaryString str, int fromIndex) { // position in byte int byteIdx = 0; // position is char int charIdx = 0; int segSize = segments[0].size(); BinaryString.SegmentAndOffset index = firstSegmentAndOffset(segSize); while (byteIdx < sizeInBytes && charIdx < fromIndex) { int charBytes = numBytesForFirstByte(index.value()); byteIdx += charBytes; charIdx++; index.skipBytes(charBytes, segSize); } do { if (byteIdx + str.sizeInBytes > sizeInBytes) { return -1; } if (MemorySegmentUtils.equals( segments, offset + byteIdx, str.segments, str.offset, str.sizeInBytes)) { return charIdx; } int charBytes = numBytesForFirstByte(index.segment.get(index.offset)); byteIdx += charBytes; charIdx++; index.skipBytes(charBytes, segSize); } while (byteIdx < sizeInBytes); return -1; } /** * Converts all of the characters in this {@code BinaryString} to upper case. * * @return the {@code BinaryString}, converted to uppercase. */ public BinaryString toUpperCase() { if (sizeInBytes == 0) { return EMPTY_UTF8; } int size = segments[0].size(); BinaryString.SegmentAndOffset segmentAndOffset = startSegmentAndOffset(size); byte[] bytes = new byte[sizeInBytes]; bytes[0] = (byte) Character.toTitleCase(segmentAndOffset.value()); for (int i = 0; i < sizeInBytes; i++) { byte b = segmentAndOffset.value(); if (numBytesForFirstByte(b) != 1) { // fallback return javaToUpperCase(); } int upper = Character.toUpperCase((int) b); if (upper > 127) { // fallback return javaToUpperCase(); } bytes[i] = (byte) upper; segmentAndOffset.nextByte(size); } return fromBytes(bytes); } private BinaryString javaToUpperCase() { return fromString(toString().toUpperCase()); } /** * Converts all of the characters in this {@code BinaryString} to lower case. * * @return the {@code BinaryString}, converted to lowercase. */ public BinaryString toLowerCase() { if (sizeInBytes == 0) { return EMPTY_UTF8; } int size = segments[0].size(); BinaryString.SegmentAndOffset segmentAndOffset = startSegmentAndOffset(size); byte[] bytes = new byte[sizeInBytes]; bytes[0] = (byte) Character.toTitleCase(segmentAndOffset.value()); for (int i = 0; i < sizeInBytes; i++) { byte b = segmentAndOffset.value(); if (numBytesForFirstByte(b) != 1) { // fallback return javaToLowerCase(); } int lower = Character.toLowerCase((int) b); if (lower > 127) { // fallback return javaToLowerCase(); } bytes[i] = (byte) lower; segmentAndOffset.nextByte(size); } return fromBytes(bytes); } private BinaryString javaToLowerCase() { return fromString(toString().toLowerCase()); } // ------------------------------------------------------------------------------------------ // Internal methods on BinaryString // ------------------------------------------------------------------------------------------ byte getByteOneSegment(int i) { return segments[0].get(offset + i); } boolean inFirstSegment() { return sizeInBytes + offset <= segments[0].size(); } private boolean matchAt(final BinaryString s, int pos) { return (inFirstSegment() && s.inFirstSegment()) ? matchAtOneSeg(s, pos) : matchAtVarSeg(s, pos); } private boolean matchAtOneSeg(final BinaryString s, int pos) { return s.sizeInBytes + pos <= sizeInBytes && pos >= 0 && segments[0].equalTo(s.segments[0], offset + pos, s.offset, s.sizeInBytes); } private boolean matchAtVarSeg(final BinaryString s, int pos) { return s.sizeInBytes + pos <= sizeInBytes && pos >= 0 && MemorySegmentUtils.equals( segments, offset + pos, s.segments, s.offset, s.sizeInBytes); } BinaryString copyBinaryStringInOneSeg(int start, int len) { byte[] newBytes = new byte[len]; segments[0].get(offset + start, newBytes, 0, len); return fromBytes(newBytes); } BinaryString copyBinaryString(int start, int end) { int len = end - start + 1; byte[] newBytes = new byte[len]; MemorySegmentUtils.copyToBytes(segments, offset + start, newBytes, 0, len); return fromBytes(newBytes); } BinaryString.SegmentAndOffset firstSegmentAndOffset(int segSize) { int segIndex = offset / segSize; return new BinaryString.SegmentAndOffset(segIndex, offset % segSize); } BinaryString.SegmentAndOffset lastSegmentAndOffset(int segSize) { int lastOffset = offset + sizeInBytes - 1; int segIndex = lastOffset / segSize; return new BinaryString.SegmentAndOffset(segIndex, lastOffset % segSize); } private BinaryString.SegmentAndOffset startSegmentAndOffset(int segSize) { return inFirstSegment() ? new BinaryString.SegmentAndOffset(0, offset) : firstSegmentAndOffset(segSize); } /** CurrentSegment and positionInSegment. */ class SegmentAndOffset { int segIndex; MemorySegment segment; int offset; private SegmentAndOffset(int segIndex, int offset) { this.segIndex = segIndex; this.segment = segments[segIndex]; this.offset = offset; } private void assignSegment() { segment = segIndex >= 0 && segIndex < segments.length ? segments[segIndex] : null; } void previousByte(int segSize) { offset--; if (offset == -1) { segIndex--; assignSegment(); offset = segSize - 1; } } void nextByte(int segSize) { offset++; checkAdvance(segSize); } private void checkAdvance(int segSize) { if (offset == segSize) { advance(); } } private void advance() { segIndex++; assignSegment(); offset = 0; } void skipBytes(int n, int segSize) { int remaining = segSize - this.offset; if (remaining > n) { this.offset += n; } else { while (true) { int toSkip = Math.min(remaining, n); n -= toSkip; if (n <= 0) { this.offset += toSkip; checkAdvance(segSize); return; } advance(); remaining = segSize - this.offset; } } } byte value() { return this.segment.get(this.offset); } } /** * Returns the number of bytes for a code point with the first byte as `b`. * * @param b The first byte of a code point */ static int numBytesForFirstByte(final byte b) { if (b >= 0) { // 1 byte, 7 bits: 0xxxxxxx return 1; } else if ((b >> 5) == -2 && (b & 0x1e) != 0) { // 2 bytes, 11 bits: 110xxxxx 10xxxxxx return 2; } else if ((b >> 4) == -2) { // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx return 3; } else if ((b >> 3) == -2) { // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx return 4; } else { // Skip the first byte disallowed in UTF-8 // Handling errors quietly, same semantics to java String. return 1; } } // ------------------------------------------------------------------------ // UTF-8 encoding and decoding (High-speed version, 30% faster+) // ------------------------------------------------------------------------ private static final int MAX_BYTES_PER_CHAR = 3; /** This method must have the same result with JDK's String.getBytes. */ public static byte[] encodeUTF8(String str) { byte[] bytes = allocateReuseBytes(str.length() * MAX_BYTES_PER_CHAR); int len = encodeUTF8(str, bytes); return Arrays.copyOf(bytes, len); } public static int encodeUTF8(String str, byte[] bytes) { int offset = 0; int len = str.length(); int sl = offset + len; int dp = 0; int dlASCII = dp + Math.min(len, bytes.length); // ASCII only optimized loop while (dp < dlASCII && str.charAt(offset) < '\u0080') { bytes[dp++] = (byte) str.charAt(offset++); } while (offset < sl) { char c = str.charAt(offset++); if (c < 0x80) { // Have at most seven bits bytes[dp++] = (byte) c; } else if (c < 0x800) { // 2 bytes, 11 bits bytes[dp++] = (byte) (0xc0 | (c >> 6)); bytes[dp++] = (byte) (0x80 | (c & 0x3f)); } else if (Character.isSurrogate(c)) { final int uc; int ip = offset - 1; if (Character.isHighSurrogate(c)) { if (sl - ip < 2) { uc = -1; } else { char d = str.charAt(ip + 1); if (Character.isLowSurrogate(d)) { uc = Character.toCodePoint(c, d); } else { // for some illegal character // the jdk will ignore the origin character and cast it to '?' // this acts the same with jdk return defaultEncodeUTF8(str, bytes); } } } else { if (Character.isLowSurrogate(c)) { // for some illegal character // the jdk will ignore the origin character and cast it to '?' // this acts the same with jdk return defaultEncodeUTF8(str, bytes); } else { uc = c; } } if (uc < 0) { bytes[dp++] = (byte) '?'; } else { bytes[dp++] = (byte) (0xf0 | ((uc >> 18))); bytes[dp++] = (byte) (0x80 | ((uc >> 12) & 0x3f)); bytes[dp++] = (byte) (0x80 | ((uc >> 6) & 0x3f)); bytes[dp++] = (byte) (0x80 | (uc & 0x3f)); offset++; // 2 chars } } else { // 3 bytes, 16 bits bytes[dp++] = (byte) (0xe0 | ((c >> 12))); bytes[dp++] = (byte) (0x80 | ((c >> 6) & 0x3f)); bytes[dp++] = (byte) (0x80 | (c & 0x3f)); } } return dp; } public static int defaultEncodeUTF8(String str, byte[] bytes) { try { byte[] buffer = str.getBytes("UTF-8"); System.arraycopy(buffer, 0, bytes, 0, buffer.length); return buffer.length; } catch (UnsupportedEncodingException e) { throw new RuntimeException("encodeUTF8 error", e); } } public static String decodeUTF8(byte[] input, int offset, int byteLen) { char[] chars = allocateReuseChars(byteLen); int len = decodeUTF8Strict(input, offset, byteLen, chars); if (len < 0) { return defaultDecodeUTF8(input, offset, byteLen); } return new String(chars, 0, len); } public static int decodeUTF8Strict(byte[] sa, int sp, int len, char[] da) { final int sl = sp + len; int dp = 0; int dlASCII = Math.min(len, da.length); // ASCII only optimized loop while (dp < dlASCII && sa[sp] >= 0) { da[dp++] = (char) sa[sp++]; } while (sp < sl) { int b1 = sa[sp++]; if (b1 >= 0) { // 1 byte, 7 bits: 0xxxxxxx da[dp++] = (char) b1; } else if ((b1 >> 5) == -2 && (b1 & 0x1e) != 0) { // 2 bytes, 11 bits: 110xxxxx 10xxxxxx if (sp < sl) { int b2 = sa[sp++]; if ((b2 & 0xc0) != 0x80) { // isNotContinuation(b2) return -1; } else { da[dp++] = (char) (((b1 << 6) ^ b2) ^ (((byte) 0xC0 << 6) ^ ((byte) 0x80))); } continue; } return -1; } else if ((b1 >> 4) == -2) { // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx if (sp + 1 < sl) { int b2 = sa[sp++]; int b3 = sa[sp++]; if ((b1 == (byte) 0xe0 && (b2 & 0xe0) == 0x80) || (b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80) { // isMalformed3(b1, b2, b3) return -1; } else { char c = (char) ((b1 << 12) ^ (b2 << 6) ^ (b3 ^ (((byte) 0xE0 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80)))); if (Character.isSurrogate(c)) { return -1; } else { da[dp++] = c; } } continue; } return -1; } else if ((b1 >> 3) == -2) { // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx if (sp + 2 < sl) { int b2 = sa[sp++]; int b3 = sa[sp++]; int b4 = sa[sp++]; int uc = ((b1 << 18) ^ (b2 << 12) ^ (b3 << 6) ^ (b4 ^ (((byte) 0xF0 << 18) ^ ((byte) 0x80 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80)))); // isMalformed4 and shortest form check if (((b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80 || (b4 & 0xc0) != 0x80) || !Character.isSupplementaryCodePoint(uc)) { return -1; } else { da[dp++] = Character.highSurrogate(uc); da[dp++] = Character.lowSurrogate(uc); } continue; } return -1; } else { return -1; } } return dp; } public static String decodeUTF8(MemorySegment input, int offset, int byteLen) { char[] chars = allocateReuseChars(byteLen); int len = decodeUTF8Strict(input, offset, byteLen, chars); if (len < 0) { byte[] bytes = allocateReuseBytes(byteLen); input.get(offset, bytes, 0, byteLen); return defaultDecodeUTF8(bytes, 0, byteLen); } return new String(chars, 0, len); } public static int decodeUTF8Strict(MemorySegment segment, int sp, int len, char[] da) { final int sl = sp + len; int dp = 0; int dlASCII = Math.min(len, da.length); // ASCII only optimized loop while (dp < dlASCII && segment.get(sp) >= 0) { da[dp++] = (char) segment.get(sp++); } while (sp < sl) { int b1 = segment.get(sp++); if (b1 >= 0) { // 1 byte, 7 bits: 0xxxxxxx da[dp++] = (char) b1; } else if ((b1 >> 5) == -2 && (b1 & 0x1e) != 0) { // 2 bytes, 11 bits: 110xxxxx 10xxxxxx if (sp < sl) { int b2 = segment.get(sp++); if ((b2 & 0xc0) != 0x80) { // isNotContinuation(b2) return -1; } else { da[dp++] = (char) (((b1 << 6) ^ b2) ^ (((byte) 0xC0 << 6) ^ ((byte) 0x80))); } continue; } return -1; } else if ((b1 >> 4) == -2) { // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx if (sp + 1 < sl) { int b2 = segment.get(sp++); int b3 = segment.get(sp++); if ((b1 == (byte) 0xe0 && (b2 & 0xe0) == 0x80) || (b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80) { // isMalformed3(b1, b2, b3) return -1; } else { char c = (char) ((b1 << 12) ^ (b2 << 6) ^ (b3 ^ (((byte) 0xE0 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80)))); if (Character.isSurrogate(c)) { return -1; } else { da[dp++] = c; } } continue; } return -1; } else if ((b1 >> 3) == -2) { // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx if (sp + 2 < sl) { int b2 = segment.get(sp++); int b3 = segment.get(sp++); int b4 = segment.get(sp++); int uc = ((b1 << 18) ^ (b2 << 12) ^ (b3 << 6) ^ (b4 ^ (((byte) 0xF0 << 18) ^ ((byte) 0x80 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80)))); // isMalformed4 and shortest form check if (((b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80 || (b4 & 0xc0) != 0x80) || !Character.isSupplementaryCodePoint(uc)) { return -1; } else { da[dp++] = Character.highSurrogate(uc); da[dp++] = Character.lowSurrogate(uc); } continue; } return -1; } else { return -1; } } return dp; } public static String defaultDecodeUTF8(byte[] bytes, int offset, int len) { return new String(bytes, offset, len, StandardCharsets.UTF_8); } }
googleapis/google-cloud-java
37,225
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/TunedModelRef.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/tuning_job.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1beta1; /** * * * <pre> * TunedModel Reference for legacy model migration. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.TunedModelRef} */ public final class TunedModelRef extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.TunedModelRef) TunedModelRefOrBuilder { private static final long serialVersionUID = 0L; // Use TunedModelRef.newBuilder() to construct. private TunedModelRef(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private TunedModelRef() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new TunedModelRef(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.TuningJobProto .internal_static_google_cloud_aiplatform_v1beta1_TunedModelRef_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.TuningJobProto .internal_static_google_cloud_aiplatform_v1beta1_TunedModelRef_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.TunedModelRef.class, com.google.cloud.aiplatform.v1beta1.TunedModelRef.Builder.class); } private int tunedModelRefCase_ = 0; @SuppressWarnings("serial") private java.lang.Object tunedModelRef_; public enum TunedModelRefCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { TUNED_MODEL(1), TUNING_JOB(2), PIPELINE_JOB(3), TUNEDMODELREF_NOT_SET(0); private final int value; private TunedModelRefCase(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 TunedModelRefCase valueOf(int value) { return forNumber(value); } public static TunedModelRefCase forNumber(int value) { switch (value) { case 1: return TUNED_MODEL; case 2: return TUNING_JOB; case 3: return PIPELINE_JOB; case 0: return TUNEDMODELREF_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public TunedModelRefCase getTunedModelRefCase() { return TunedModelRefCase.forNumber(tunedModelRefCase_); } public static final int TUNED_MODEL_FIELD_NUMBER = 1; /** * * * <pre> * Support migration from model registry. * </pre> * * <code>string tuned_model = 1 [(.google.api.resource_reference) = { ... }</code> * * @return Whether the tunedModel field is set. */ public boolean hasTunedModel() { return tunedModelRefCase_ == 1; } /** * * * <pre> * Support migration from model registry. * </pre> * * <code>string tuned_model = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The tunedModel. */ public java.lang.String getTunedModel() { java.lang.Object ref = ""; if (tunedModelRefCase_ == 1) { ref = tunedModelRef_; } if (ref instanceof java.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 (tunedModelRefCase_ == 1) { tunedModelRef_ = s; } return s; } } /** * * * <pre> * Support migration from model registry. * </pre> * * <code>string tuned_model = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for tunedModel. */ public com.google.protobuf.ByteString getTunedModelBytes() { java.lang.Object ref = ""; if (tunedModelRefCase_ == 1) { ref = tunedModelRef_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (tunedModelRefCase_ == 1) { tunedModelRef_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TUNING_JOB_FIELD_NUMBER = 2; /** * * * <pre> * Support migration from tuning job list page, from gemini-1.0-pro-002 * to 1.5 and above. * </pre> * * <code>string tuning_job = 2 [(.google.api.resource_reference) = { ... }</code> * * @return Whether the tuningJob field is set. */ public boolean hasTuningJob() { return tunedModelRefCase_ == 2; } /** * * * <pre> * Support migration from tuning job list page, from gemini-1.0-pro-002 * to 1.5 and above. * </pre> * * <code>string tuning_job = 2 [(.google.api.resource_reference) = { ... }</code> * * @return The tuningJob. */ public java.lang.String getTuningJob() { java.lang.Object ref = ""; if (tunedModelRefCase_ == 2) { ref = tunedModelRef_; } if (ref instanceof java.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 (tunedModelRefCase_ == 2) { tunedModelRef_ = s; } return s; } } /** * * * <pre> * Support migration from tuning job list page, from gemini-1.0-pro-002 * to 1.5 and above. * </pre> * * <code>string tuning_job = 2 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for tuningJob. */ public com.google.protobuf.ByteString getTuningJobBytes() { java.lang.Object ref = ""; if (tunedModelRefCase_ == 2) { ref = tunedModelRef_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (tunedModelRefCase_ == 2) { tunedModelRef_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PIPELINE_JOB_FIELD_NUMBER = 3; /** * * * <pre> * Support migration from tuning job list page, from bison model to gemini * model. * </pre> * * <code>string pipeline_job = 3 [(.google.api.resource_reference) = { ... }</code> * * @return Whether the pipelineJob field is set. */ public boolean hasPipelineJob() { return tunedModelRefCase_ == 3; } /** * * * <pre> * Support migration from tuning job list page, from bison model to gemini * model. * </pre> * * <code>string pipeline_job = 3 [(.google.api.resource_reference) = { ... }</code> * * @return The pipelineJob. */ public java.lang.String getPipelineJob() { java.lang.Object ref = ""; if (tunedModelRefCase_ == 3) { ref = tunedModelRef_; } if (ref instanceof java.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 (tunedModelRefCase_ == 3) { tunedModelRef_ = s; } return s; } } /** * * * <pre> * Support migration from tuning job list page, from bison model to gemini * model. * </pre> * * <code>string pipeline_job = 3 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for pipelineJob. */ public com.google.protobuf.ByteString getPipelineJobBytes() { java.lang.Object ref = ""; if (tunedModelRefCase_ == 3) { ref = tunedModelRef_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (tunedModelRefCase_ == 3) { tunedModelRef_ = 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 (tunedModelRefCase_ == 1) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, tunedModelRef_); } if (tunedModelRefCase_ == 2) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, tunedModelRef_); } if (tunedModelRefCase_ == 3) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, tunedModelRef_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (tunedModelRefCase_ == 1) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, tunedModelRef_); } if (tunedModelRefCase_ == 2) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, tunedModelRef_); } if (tunedModelRefCase_ == 3) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, tunedModelRef_); } 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.TunedModelRef)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.TunedModelRef other = (com.google.cloud.aiplatform.v1beta1.TunedModelRef) obj; if (!getTunedModelRefCase().equals(other.getTunedModelRefCase())) return false; switch (tunedModelRefCase_) { case 1: if (!getTunedModel().equals(other.getTunedModel())) return false; break; case 2: if (!getTuningJob().equals(other.getTuningJob())) return false; break; case 3: if (!getPipelineJob().equals(other.getPipelineJob())) 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 (tunedModelRefCase_) { case 1: hash = (37 * hash) + TUNED_MODEL_FIELD_NUMBER; hash = (53 * hash) + getTunedModel().hashCode(); break; case 2: hash = (37 * hash) + TUNING_JOB_FIELD_NUMBER; hash = (53 * hash) + getTuningJob().hashCode(); break; case 3: hash = (37 * hash) + PIPELINE_JOB_FIELD_NUMBER; hash = (53 * hash) + getPipelineJob().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1beta1.TunedModelRef parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.TunedModelRef 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.TunedModelRef parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.TunedModelRef 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.TunedModelRef parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.TunedModelRef 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.TunedModelRef parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.TunedModelRef 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.TunedModelRef parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.TunedModelRef 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.TunedModelRef 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.TunedModelRef 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.TunedModelRef 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> * TunedModel Reference for legacy model migration. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.TunedModelRef} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.TunedModelRef) com.google.cloud.aiplatform.v1beta1.TunedModelRefOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.TuningJobProto .internal_static_google_cloud_aiplatform_v1beta1_TunedModelRef_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.TuningJobProto .internal_static_google_cloud_aiplatform_v1beta1_TunedModelRef_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.TunedModelRef.class, com.google.cloud.aiplatform.v1beta1.TunedModelRef.Builder.class); } // Construct using com.google.cloud.aiplatform.v1beta1.TunedModelRef.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; tunedModelRefCase_ = 0; tunedModelRef_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.TuningJobProto .internal_static_google_cloud_aiplatform_v1beta1_TunedModelRef_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.TunedModelRef getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.TunedModelRef.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.TunedModelRef build() { com.google.cloud.aiplatform.v1beta1.TunedModelRef result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.TunedModelRef buildPartial() { com.google.cloud.aiplatform.v1beta1.TunedModelRef result = new com.google.cloud.aiplatform.v1beta1.TunedModelRef(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.cloud.aiplatform.v1beta1.TunedModelRef result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs(com.google.cloud.aiplatform.v1beta1.TunedModelRef result) { result.tunedModelRefCase_ = tunedModelRefCase_; result.tunedModelRef_ = this.tunedModelRef_; } @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.TunedModelRef) { return mergeFrom((com.google.cloud.aiplatform.v1beta1.TunedModelRef) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.TunedModelRef other) { if (other == com.google.cloud.aiplatform.v1beta1.TunedModelRef.getDefaultInstance()) return this; switch (other.getTunedModelRefCase()) { case TUNED_MODEL: { tunedModelRefCase_ = 1; tunedModelRef_ = other.tunedModelRef_; onChanged(); break; } case TUNING_JOB: { tunedModelRefCase_ = 2; tunedModelRef_ = other.tunedModelRef_; onChanged(); break; } case PIPELINE_JOB: { tunedModelRefCase_ = 3; tunedModelRef_ = other.tunedModelRef_; onChanged(); break; } case TUNEDMODELREF_NOT_SET: { break; } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); tunedModelRefCase_ = 1; tunedModelRef_ = s; break; } // case 10 case 18: { java.lang.String s = input.readStringRequireUtf8(); tunedModelRefCase_ = 2; tunedModelRef_ = s; break; } // case 18 case 26: { java.lang.String s = input.readStringRequireUtf8(); tunedModelRefCase_ = 3; tunedModelRef_ = s; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int tunedModelRefCase_ = 0; private java.lang.Object tunedModelRef_; public TunedModelRefCase getTunedModelRefCase() { return TunedModelRefCase.forNumber(tunedModelRefCase_); } public Builder clearTunedModelRef() { tunedModelRefCase_ = 0; tunedModelRef_ = null; onChanged(); return this; } private int bitField0_; /** * * * <pre> * Support migration from model registry. * </pre> * * <code>string tuned_model = 1 [(.google.api.resource_reference) = { ... }</code> * * @return Whether the tunedModel field is set. */ @java.lang.Override public boolean hasTunedModel() { return tunedModelRefCase_ == 1; } /** * * * <pre> * Support migration from model registry. * </pre> * * <code>string tuned_model = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The tunedModel. */ @java.lang.Override public java.lang.String getTunedModel() { java.lang.Object ref = ""; if (tunedModelRefCase_ == 1) { ref = tunedModelRef_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (tunedModelRefCase_ == 1) { tunedModelRef_ = s; } return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Support migration from model registry. * </pre> * * <code>string tuned_model = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for tunedModel. */ @java.lang.Override public com.google.protobuf.ByteString getTunedModelBytes() { java.lang.Object ref = ""; if (tunedModelRefCase_ == 1) { ref = tunedModelRef_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (tunedModelRefCase_ == 1) { tunedModelRef_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Support migration from model registry. * </pre> * * <code>string tuned_model = 1 [(.google.api.resource_reference) = { ... }</code> * * @param value The tunedModel to set. * @return This builder for chaining. */ public Builder setTunedModel(java.lang.String value) { if (value == null) { throw new NullPointerException(); } tunedModelRefCase_ = 1; tunedModelRef_ = value; onChanged(); return this; } /** * * * <pre> * Support migration from model registry. * </pre> * * <code>string tuned_model = 1 [(.google.api.resource_reference) = { ... }</code> * * @return This builder for chaining. */ public Builder clearTunedModel() { if (tunedModelRefCase_ == 1) { tunedModelRefCase_ = 0; tunedModelRef_ = null; onChanged(); } return this; } /** * * * <pre> * Support migration from model registry. * </pre> * * <code>string tuned_model = 1 [(.google.api.resource_reference) = { ... }</code> * * @param value The bytes for tunedModel to set. * @return This builder for chaining. */ public Builder setTunedModelBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); tunedModelRefCase_ = 1; tunedModelRef_ = value; onChanged(); return this; } /** * * * <pre> * Support migration from tuning job list page, from gemini-1.0-pro-002 * to 1.5 and above. * </pre> * * <code>string tuning_job = 2 [(.google.api.resource_reference) = { ... }</code> * * @return Whether the tuningJob field is set. */ @java.lang.Override public boolean hasTuningJob() { return tunedModelRefCase_ == 2; } /** * * * <pre> * Support migration from tuning job list page, from gemini-1.0-pro-002 * to 1.5 and above. * </pre> * * <code>string tuning_job = 2 [(.google.api.resource_reference) = { ... }</code> * * @return The tuningJob. */ @java.lang.Override public java.lang.String getTuningJob() { java.lang.Object ref = ""; if (tunedModelRefCase_ == 2) { ref = tunedModelRef_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (tunedModelRefCase_ == 2) { tunedModelRef_ = s; } return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Support migration from tuning job list page, from gemini-1.0-pro-002 * to 1.5 and above. * </pre> * * <code>string tuning_job = 2 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for tuningJob. */ @java.lang.Override public com.google.protobuf.ByteString getTuningJobBytes() { java.lang.Object ref = ""; if (tunedModelRefCase_ == 2) { ref = tunedModelRef_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (tunedModelRefCase_ == 2) { tunedModelRef_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Support migration from tuning job list page, from gemini-1.0-pro-002 * to 1.5 and above. * </pre> * * <code>string tuning_job = 2 [(.google.api.resource_reference) = { ... }</code> * * @param value The tuningJob to set. * @return This builder for chaining. */ public Builder setTuningJob(java.lang.String value) { if (value == null) { throw new NullPointerException(); } tunedModelRefCase_ = 2; tunedModelRef_ = value; onChanged(); return this; } /** * * * <pre> * Support migration from tuning job list page, from gemini-1.0-pro-002 * to 1.5 and above. * </pre> * * <code>string tuning_job = 2 [(.google.api.resource_reference) = { ... }</code> * * @return This builder for chaining. */ public Builder clearTuningJob() { if (tunedModelRefCase_ == 2) { tunedModelRefCase_ = 0; tunedModelRef_ = null; onChanged(); } return this; } /** * * * <pre> * Support migration from tuning job list page, from gemini-1.0-pro-002 * to 1.5 and above. * </pre> * * <code>string tuning_job = 2 [(.google.api.resource_reference) = { ... }</code> * * @param value The bytes for tuningJob to set. * @return This builder for chaining. */ public Builder setTuningJobBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); tunedModelRefCase_ = 2; tunedModelRef_ = value; onChanged(); return this; } /** * * * <pre> * Support migration from tuning job list page, from bison model to gemini * model. * </pre> * * <code>string pipeline_job = 3 [(.google.api.resource_reference) = { ... }</code> * * @return Whether the pipelineJob field is set. */ @java.lang.Override public boolean hasPipelineJob() { return tunedModelRefCase_ == 3; } /** * * * <pre> * Support migration from tuning job list page, from bison model to gemini * model. * </pre> * * <code>string pipeline_job = 3 [(.google.api.resource_reference) = { ... }</code> * * @return The pipelineJob. */ @java.lang.Override public java.lang.String getPipelineJob() { java.lang.Object ref = ""; if (tunedModelRefCase_ == 3) { ref = tunedModelRef_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (tunedModelRefCase_ == 3) { tunedModelRef_ = s; } return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Support migration from tuning job list page, from bison model to gemini * model. * </pre> * * <code>string pipeline_job = 3 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for pipelineJob. */ @java.lang.Override public com.google.protobuf.ByteString getPipelineJobBytes() { java.lang.Object ref = ""; if (tunedModelRefCase_ == 3) { ref = tunedModelRef_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (tunedModelRefCase_ == 3) { tunedModelRef_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Support migration from tuning job list page, from bison model to gemini * model. * </pre> * * <code>string pipeline_job = 3 [(.google.api.resource_reference) = { ... }</code> * * @param value The pipelineJob to set. * @return This builder for chaining. */ public Builder setPipelineJob(java.lang.String value) { if (value == null) { throw new NullPointerException(); } tunedModelRefCase_ = 3; tunedModelRef_ = value; onChanged(); return this; } /** * * * <pre> * Support migration from tuning job list page, from bison model to gemini * model. * </pre> * * <code>string pipeline_job = 3 [(.google.api.resource_reference) = { ... }</code> * * @return This builder for chaining. */ public Builder clearPipelineJob() { if (tunedModelRefCase_ == 3) { tunedModelRefCase_ = 0; tunedModelRef_ = null; onChanged(); } return this; } /** * * * <pre> * Support migration from tuning job list page, from bison model to gemini * model. * </pre> * * <code>string pipeline_job = 3 [(.google.api.resource_reference) = { ... }</code> * * @param value The bytes for pipelineJob to set. * @return This builder for chaining. */ public Builder setPipelineJobBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); tunedModelRefCase_ = 3; tunedModelRef_ = 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.cloud.aiplatform.v1beta1.TunedModelRef) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.TunedModelRef) private static final com.google.cloud.aiplatform.v1beta1.TunedModelRef DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.TunedModelRef(); } public static com.google.cloud.aiplatform.v1beta1.TunedModelRef getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<TunedModelRef> PARSER = new com.google.protobuf.AbstractParser<TunedModelRef>() { @java.lang.Override public TunedModelRef 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<TunedModelRef> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<TunedModelRef> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.TunedModelRef getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/sdk-platform-java
37,386
java-showcase/proto-gapic-showcase-v1beta1/src/main/java/com/google/showcase/v1beta1/ComplianceGroup.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/compliance.proto // Protobuf Java Version: 3.25.8 package com.google.showcase.v1beta1; /** * * * <pre> * ComplianceGroups encapsulates a group of RPC requests to the Compliance * server: one request for each combination of elements of `rpcs` and of * `requests`. * </pre> * * Protobuf type {@code google.showcase.v1beta1.ComplianceGroup} */ public final class ComplianceGroup extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.showcase.v1beta1.ComplianceGroup) ComplianceGroupOrBuilder { private static final long serialVersionUID = 0L; // Use ComplianceGroup.newBuilder() to construct. private ComplianceGroup(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ComplianceGroup() { name_ = ""; rpcs_ = com.google.protobuf.LazyStringArrayList.emptyList(); requests_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ComplianceGroup(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.showcase.v1beta1.ComplianceOuterClass .internal_static_google_showcase_v1beta1_ComplianceGroup_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.showcase.v1beta1.ComplianceOuterClass .internal_static_google_showcase_v1beta1_ComplianceGroup_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.showcase.v1beta1.ComplianceGroup.class, com.google.showcase.v1beta1.ComplianceGroup.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * <code>string name = 1;</code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * <code>string name = 1;</code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RPCS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList rpcs_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** * <code>repeated string rpcs = 2;</code> * * @return A list containing the rpcs. */ public com.google.protobuf.ProtocolStringList getRpcsList() { return rpcs_; } /** * <code>repeated string rpcs = 2;</code> * * @return The count of rpcs. */ public int getRpcsCount() { return rpcs_.size(); } /** * <code>repeated string rpcs = 2;</code> * * @param index The index of the element to return. * @return The rpcs at the given index. */ public java.lang.String getRpcs(int index) { return rpcs_.get(index); } /** * <code>repeated string rpcs = 2;</code> * * @param index The index of the value to return. * @return The bytes of the rpcs at the given index. */ public com.google.protobuf.ByteString getRpcsBytes(int index) { return rpcs_.getByteString(index); } public static final int REQUESTS_FIELD_NUMBER = 3; @SuppressWarnings("serial") private java.util.List<com.google.showcase.v1beta1.RepeatRequest> requests_; /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ @java.lang.Override public java.util.List<com.google.showcase.v1beta1.RepeatRequest> getRequestsList() { return requests_; } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ @java.lang.Override public java.util.List<? extends com.google.showcase.v1beta1.RepeatRequestOrBuilder> getRequestsOrBuilderList() { return requests_; } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ @java.lang.Override public int getRequestsCount() { return requests_.size(); } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ @java.lang.Override public com.google.showcase.v1beta1.RepeatRequest getRequests(int index) { return requests_.get(index); } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ @java.lang.Override public com.google.showcase.v1beta1.RepeatRequestOrBuilder getRequestsOrBuilder(int index) { return requests_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } for (int i = 0; i < rpcs_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, rpcs_.getRaw(i)); } for (int i = 0; i < requests_.size(); i++) { output.writeMessage(3, requests_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } { int dataSize = 0; for (int i = 0; i < rpcs_.size(); i++) { dataSize += computeStringSizeNoTag(rpcs_.getRaw(i)); } size += dataSize; size += 1 * getRpcsList().size(); } for (int i = 0; i < requests_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, requests_.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.showcase.v1beta1.ComplianceGroup)) { return super.equals(obj); } com.google.showcase.v1beta1.ComplianceGroup other = (com.google.showcase.v1beta1.ComplianceGroup) obj; if (!getName().equals(other.getName())) return false; if (!getRpcsList().equals(other.getRpcsList())) return false; if (!getRequestsList().equals(other.getRequestsList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); if (getRpcsCount() > 0) { hash = (37 * hash) + RPCS_FIELD_NUMBER; hash = (53 * hash) + getRpcsList().hashCode(); } if (getRequestsCount() > 0) { hash = (37 * hash) + REQUESTS_FIELD_NUMBER; hash = (53 * hash) + getRequestsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.showcase.v1beta1.ComplianceGroup parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.showcase.v1beta1.ComplianceGroup 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.ComplianceGroup parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.showcase.v1beta1.ComplianceGroup 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.ComplianceGroup parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.showcase.v1beta1.ComplianceGroup parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.showcase.v1beta1.ComplianceGroup parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.showcase.v1beta1.ComplianceGroup 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.ComplianceGroup parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.showcase.v1beta1.ComplianceGroup 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.ComplianceGroup parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.showcase.v1beta1.ComplianceGroup 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.ComplianceGroup 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> * ComplianceGroups encapsulates a group of RPC requests to the Compliance * server: one request for each combination of elements of `rpcs` and of * `requests`. * </pre> * * Protobuf type {@code google.showcase.v1beta1.ComplianceGroup} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.showcase.v1beta1.ComplianceGroup) com.google.showcase.v1beta1.ComplianceGroupOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.showcase.v1beta1.ComplianceOuterClass .internal_static_google_showcase_v1beta1_ComplianceGroup_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.showcase.v1beta1.ComplianceOuterClass .internal_static_google_showcase_v1beta1_ComplianceGroup_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.showcase.v1beta1.ComplianceGroup.class, com.google.showcase.v1beta1.ComplianceGroup.Builder.class); } // Construct using com.google.showcase.v1beta1.ComplianceGroup.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; rpcs_ = com.google.protobuf.LazyStringArrayList.emptyList(); if (requestsBuilder_ == null) { requests_ = java.util.Collections.emptyList(); } else { requests_ = null; requestsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000004); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.showcase.v1beta1.ComplianceOuterClass .internal_static_google_showcase_v1beta1_ComplianceGroup_descriptor; } @java.lang.Override public com.google.showcase.v1beta1.ComplianceGroup getDefaultInstanceForType() { return com.google.showcase.v1beta1.ComplianceGroup.getDefaultInstance(); } @java.lang.Override public com.google.showcase.v1beta1.ComplianceGroup build() { com.google.showcase.v1beta1.ComplianceGroup result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.showcase.v1beta1.ComplianceGroup buildPartial() { com.google.showcase.v1beta1.ComplianceGroup result = new com.google.showcase.v1beta1.ComplianceGroup(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.showcase.v1beta1.ComplianceGroup result) { if (requestsBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0)) { requests_ = java.util.Collections.unmodifiableList(requests_); bitField0_ = (bitField0_ & ~0x00000004); } result.requests_ = requests_; } else { result.requests_ = requestsBuilder_.build(); } } private void buildPartial0(com.google.showcase.v1beta1.ComplianceGroup result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { rpcs_.makeImmutable(); result.rpcs_ = rpcs_; } } @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.ComplianceGroup) { return mergeFrom((com.google.showcase.v1beta1.ComplianceGroup) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.showcase.v1beta1.ComplianceGroup other) { if (other == com.google.showcase.v1beta1.ComplianceGroup.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (!other.rpcs_.isEmpty()) { if (rpcs_.isEmpty()) { rpcs_ = other.rpcs_; bitField0_ |= 0x00000002; } else { ensureRpcsIsMutable(); rpcs_.addAll(other.rpcs_); } onChanged(); } if (requestsBuilder_ == null) { if (!other.requests_.isEmpty()) { if (requests_.isEmpty()) { requests_ = other.requests_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureRequestsIsMutable(); requests_.addAll(other.requests_); } onChanged(); } } else { if (!other.requests_.isEmpty()) { if (requestsBuilder_.isEmpty()) { requestsBuilder_.dispose(); requestsBuilder_ = null; requests_ = other.requests_; bitField0_ = (bitField0_ & ~0x00000004); requestsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getRequestsFieldBuilder() : null; } else { requestsBuilder_.addAllMessages(other.requests_); } } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { java.lang.String s = input.readStringRequireUtf8(); ensureRpcsIsMutable(); rpcs_.add(s); break; } // case 18 case 26: { com.google.showcase.v1beta1.RepeatRequest m = input.readMessage( com.google.showcase.v1beta1.RepeatRequest.parser(), extensionRegistry); if (requestsBuilder_ == null) { ensureRequestsIsMutable(); requests_.add(m); } else { requestsBuilder_.addMessage(m); } break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * <code>string name = 1;</code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string name = 1;</code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string name = 1;</code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <code>string name = 1;</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <code>string name = 1;</code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.LazyStringArrayList rpcs_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureRpcsIsMutable() { if (!rpcs_.isModifiable()) { rpcs_ = new com.google.protobuf.LazyStringArrayList(rpcs_); } bitField0_ |= 0x00000002; } /** * <code>repeated string rpcs = 2;</code> * * @return A list containing the rpcs. */ public com.google.protobuf.ProtocolStringList getRpcsList() { rpcs_.makeImmutable(); return rpcs_; } /** * <code>repeated string rpcs = 2;</code> * * @return The count of rpcs. */ public int getRpcsCount() { return rpcs_.size(); } /** * <code>repeated string rpcs = 2;</code> * * @param index The index of the element to return. * @return The rpcs at the given index. */ public java.lang.String getRpcs(int index) { return rpcs_.get(index); } /** * <code>repeated string rpcs = 2;</code> * * @param index The index of the value to return. * @return The bytes of the rpcs at the given index. */ public com.google.protobuf.ByteString getRpcsBytes(int index) { return rpcs_.getByteString(index); } /** * <code>repeated string rpcs = 2;</code> * * @param index The index to set the value at. * @param value The rpcs to set. * @return This builder for chaining. */ public Builder setRpcs(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureRpcsIsMutable(); rpcs_.set(index, value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * <code>repeated string rpcs = 2;</code> * * @param value The rpcs to add. * @return This builder for chaining. */ public Builder addRpcs(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureRpcsIsMutable(); rpcs_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * <code>repeated string rpcs = 2;</code> * * @param values The rpcs to add. * @return This builder for chaining. */ public Builder addAllRpcs(java.lang.Iterable<java.lang.String> values) { ensureRpcsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, rpcs_); bitField0_ |= 0x00000002; onChanged(); return this; } /** * <code>repeated string rpcs = 2;</code> * * @return This builder for chaining. */ public Builder clearRpcs() { rpcs_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); ; onChanged(); return this; } /** * <code>repeated string rpcs = 2;</code> * * @param value The bytes of the rpcs to add. * @return This builder for chaining. */ public Builder addRpcsBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureRpcsIsMutable(); rpcs_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } private java.util.List<com.google.showcase.v1beta1.RepeatRequest> requests_ = java.util.Collections.emptyList(); private void ensureRequestsIsMutable() { if (!((bitField0_ & 0x00000004) != 0)) { requests_ = new java.util.ArrayList<com.google.showcase.v1beta1.RepeatRequest>(requests_); bitField0_ |= 0x00000004; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.showcase.v1beta1.RepeatRequest, com.google.showcase.v1beta1.RepeatRequest.Builder, com.google.showcase.v1beta1.RepeatRequestOrBuilder> requestsBuilder_; /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public java.util.List<com.google.showcase.v1beta1.RepeatRequest> getRequestsList() { if (requestsBuilder_ == null) { return java.util.Collections.unmodifiableList(requests_); } else { return requestsBuilder_.getMessageList(); } } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public int getRequestsCount() { if (requestsBuilder_ == null) { return requests_.size(); } else { return requestsBuilder_.getCount(); } } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public com.google.showcase.v1beta1.RepeatRequest getRequests(int index) { if (requestsBuilder_ == null) { return requests_.get(index); } else { return requestsBuilder_.getMessage(index); } } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public Builder setRequests(int index, com.google.showcase.v1beta1.RepeatRequest value) { if (requestsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRequestsIsMutable(); requests_.set(index, value); onChanged(); } else { requestsBuilder_.setMessage(index, value); } return this; } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public Builder setRequests( int index, com.google.showcase.v1beta1.RepeatRequest.Builder builderForValue) { if (requestsBuilder_ == null) { ensureRequestsIsMutable(); requests_.set(index, builderForValue.build()); onChanged(); } else { requestsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public Builder addRequests(com.google.showcase.v1beta1.RepeatRequest value) { if (requestsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRequestsIsMutable(); requests_.add(value); onChanged(); } else { requestsBuilder_.addMessage(value); } return this; } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public Builder addRequests(int index, com.google.showcase.v1beta1.RepeatRequest value) { if (requestsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRequestsIsMutable(); requests_.add(index, value); onChanged(); } else { requestsBuilder_.addMessage(index, value); } return this; } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public Builder addRequests(com.google.showcase.v1beta1.RepeatRequest.Builder builderForValue) { if (requestsBuilder_ == null) { ensureRequestsIsMutable(); requests_.add(builderForValue.build()); onChanged(); } else { requestsBuilder_.addMessage(builderForValue.build()); } return this; } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public Builder addRequests( int index, com.google.showcase.v1beta1.RepeatRequest.Builder builderForValue) { if (requestsBuilder_ == null) { ensureRequestsIsMutable(); requests_.add(index, builderForValue.build()); onChanged(); } else { requestsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public Builder addAllRequests( java.lang.Iterable<? extends com.google.showcase.v1beta1.RepeatRequest> values) { if (requestsBuilder_ == null) { ensureRequestsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, requests_); onChanged(); } else { requestsBuilder_.addAllMessages(values); } return this; } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public Builder clearRequests() { if (requestsBuilder_ == null) { requests_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); } else { requestsBuilder_.clear(); } return this; } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public Builder removeRequests(int index) { if (requestsBuilder_ == null) { ensureRequestsIsMutable(); requests_.remove(index); onChanged(); } else { requestsBuilder_.remove(index); } return this; } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public com.google.showcase.v1beta1.RepeatRequest.Builder getRequestsBuilder(int index) { return getRequestsFieldBuilder().getBuilder(index); } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public com.google.showcase.v1beta1.RepeatRequestOrBuilder getRequestsOrBuilder(int index) { if (requestsBuilder_ == null) { return requests_.get(index); } else { return requestsBuilder_.getMessageOrBuilder(index); } } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public java.util.List<? extends com.google.showcase.v1beta1.RepeatRequestOrBuilder> getRequestsOrBuilderList() { if (requestsBuilder_ != null) { return requestsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(requests_); } } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public com.google.showcase.v1beta1.RepeatRequest.Builder addRequestsBuilder() { return getRequestsFieldBuilder() .addBuilder(com.google.showcase.v1beta1.RepeatRequest.getDefaultInstance()); } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public com.google.showcase.v1beta1.RepeatRequest.Builder addRequestsBuilder(int index) { return getRequestsFieldBuilder() .addBuilder(index, com.google.showcase.v1beta1.RepeatRequest.getDefaultInstance()); } /** <code>repeated .google.showcase.v1beta1.RepeatRequest requests = 3;</code> */ public java.util.List<com.google.showcase.v1beta1.RepeatRequest.Builder> getRequestsBuilderList() { return getRequestsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.showcase.v1beta1.RepeatRequest, com.google.showcase.v1beta1.RepeatRequest.Builder, com.google.showcase.v1beta1.RepeatRequestOrBuilder> getRequestsFieldBuilder() { if (requestsBuilder_ == null) { requestsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.showcase.v1beta1.RepeatRequest, com.google.showcase.v1beta1.RepeatRequest.Builder, com.google.showcase.v1beta1.RepeatRequestOrBuilder>( requests_, ((bitField0_ & 0x00000004) != 0), getParentForChildren(), isClean()); requests_ = null; } return requestsBuilder_; } @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.ComplianceGroup) } // @@protoc_insertion_point(class_scope:google.showcase.v1beta1.ComplianceGroup) private static final com.google.showcase.v1beta1.ComplianceGroup DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.showcase.v1beta1.ComplianceGroup(); } public static com.google.showcase.v1beta1.ComplianceGroup getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ComplianceGroup> PARSER = new com.google.protobuf.AbstractParser<ComplianceGroup>() { @java.lang.Override public ComplianceGroup 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<ComplianceGroup> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ComplianceGroup> getParserForType() { return PARSER; } @java.lang.Override public com.google.showcase.v1beta1.ComplianceGroup getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-api-java-client-services
37,311
clients/google-api-services-compute/alpha/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/alpha/globalOperations) * * [Regional](/compute/docs/reference/rest/alpha/regionOperations) * * [Zonal](/compute/docs/reference/rest/alpha/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] Service-specific metadata attached to this operation. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.Object> metadata; /** * [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] Server-defined URL for this resource with the resource id. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLinkWithId; /** * [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] Service-specific metadata attached to this operation. * @return value or {@code null} for none */ public java.util.Map<String, java.lang.Object> getMetadata() { return metadata; } /** * [Output Only] Service-specific metadata attached to this operation. * @param metadata metadata or {@code null} for none */ public Operation setMetadata(java.util.Map<String, java.lang.Object> metadata) { this.metadata = metadata; 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] Server-defined URL for this resource with the resource id. * @return value or {@code null} for none */ public java.lang.String getSelfLinkWithId() { return selfLinkWithId; } /** * [Output Only] Server-defined URL for this resource with the resource id. * @param selfLinkWithId selfLinkWithId or {@code null} for none */ public Operation setSelfLinkWithId(java.lang.String selfLinkWithId) { this.selfLinkWithId = selfLinkWithId; 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; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private QuotaExceededInfo quotaInfo; /** * @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; } /** * @return value or {@code null} for none */ public QuotaExceededInfo getQuotaInfo() { return quotaInfo; } /** * @param quotaInfo quotaInfo or {@code null} for none */ public ErrorDetails setQuotaInfo(QuotaExceededInfo quotaInfo) { this.quotaInfo = quotaInfo; 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(); } } } }
apache/iceberg
37,390
spark/v3.4/spark/src/test/java/org/apache/iceberg/spark/TestSparkV2Filters.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iceberg.spark; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Instant; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.Map; import org.apache.iceberg.expressions.Expression; import org.apache.iceberg.expressions.ExpressionUtil; import org.apache.iceberg.expressions.Expressions; import org.apache.iceberg.expressions.UnboundTerm; import org.apache.iceberg.relocated.com.google.common.collect.Maps; import org.apache.iceberg.spark.functions.BucketFunction; import org.apache.iceberg.spark.functions.DaysFunction; import org.apache.iceberg.spark.functions.HoursFunction; import org.apache.iceberg.spark.functions.IcebergVersionFunction; import org.apache.iceberg.spark.functions.MonthsFunction; import org.apache.iceberg.spark.functions.TruncateFunction; import org.apache.iceberg.spark.functions.YearsFunction; import org.apache.iceberg.types.Types; import org.apache.iceberg.util.DateTimeUtil; import org.apache.spark.sql.connector.catalog.functions.ScalarFunction; import org.apache.spark.sql.connector.expressions.FieldReference; import org.apache.spark.sql.connector.expressions.LiteralValue; import org.apache.spark.sql.connector.expressions.NamedReference; import org.apache.spark.sql.connector.expressions.UserDefinedScalarFunc; import org.apache.spark.sql.connector.expressions.filter.And; import org.apache.spark.sql.connector.expressions.filter.Not; import org.apache.spark.sql.connector.expressions.filter.Or; import org.apache.spark.sql.connector.expressions.filter.Predicate; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.StructType; import org.apache.spark.unsafe.types.UTF8String; import org.junit.jupiter.api.Test; public class TestSparkV2Filters { private static final Types.StructType STRUCT = Types.StructType.of( Types.NestedField.optional(1, "dateCol", Types.DateType.get()), Types.NestedField.optional(2, "tsCol", Types.TimestampType.withZone()), Types.NestedField.optional(3, "tsNtzCol", Types.TimestampType.withoutZone()), Types.NestedField.optional(4, "intCol", Types.IntegerType.get()), Types.NestedField.optional(5, "strCol", Types.StringType.get())); @SuppressWarnings("checkstyle:MethodLength") @Test public void testV2Filters() { Map<String, String> attrMap = Maps.newHashMap(); attrMap.put("id", "id"); attrMap.put("`i.d`", "i.d"); attrMap.put("`i``d`", "i`d"); attrMap.put("`d`.b.`dd```", "d.b.dd`"); attrMap.put("a.`aa```.c", "a.aa`.c"); attrMap.forEach( (quoted, unquoted) -> { NamedReference namedReference = FieldReference.apply(quoted); org.apache.spark.sql.connector.expressions.Expression[] attrOnly = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference}; LiteralValue value = new LiteralValue(1, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate isNull = new Predicate("IS_NULL", attrOnly); Expression expectedIsNull = Expressions.isNull(unquoted); Expression actualIsNull = SparkV2Filters.convert(isNull); assertThat(actualIsNull) .asString() .as("IsNull must match") .isEqualTo(expectedIsNull.toString()); Predicate isNotNull = new Predicate("IS_NOT_NULL", attrOnly); Expression expectedIsNotNull = Expressions.notNull(unquoted); Expression actualIsNotNull = SparkV2Filters.convert(isNotNull); assertThat(actualIsNotNull) .asString() .as("IsNotNull must match") .isEqualTo(expectedIsNotNull.toString()); Predicate lt1 = new Predicate("<", attrAndValue); Expression expectedLt1 = Expressions.lessThan(unquoted, 1); Expression actualLt1 = SparkV2Filters.convert(lt1); assertThat(actualLt1) .asString() .as("LessThan must match") .isEqualTo(expectedLt1.toString()); Predicate lt2 = new Predicate("<", valueAndAttr); Expression expectedLt2 = Expressions.greaterThan(unquoted, 1); Expression actualLt2 = SparkV2Filters.convert(lt2); assertThat(actualLt2) .asString() .as("LessThan must match") .isEqualTo(expectedLt2.toString()); Predicate ltEq1 = new Predicate("<=", attrAndValue); Expression expectedLtEq1 = Expressions.lessThanOrEqual(unquoted, 1); Expression actualLtEq1 = SparkV2Filters.convert(ltEq1); assertThat(actualLtEq1) .asString() .as("LessThanOrEqual must match") .isEqualTo(expectedLtEq1.toString()); Predicate ltEq2 = new Predicate("<=", valueAndAttr); Expression expectedLtEq2 = Expressions.greaterThanOrEqual(unquoted, 1); Expression actualLtEq2 = SparkV2Filters.convert(ltEq2); assertThat(actualLtEq2) .asString() .as("LessThanOrEqual must match") .isEqualTo(expectedLtEq2.toString()); Predicate gt1 = new Predicate(">", attrAndValue); Expression expectedGt1 = Expressions.greaterThan(unquoted, 1); Expression actualGt1 = SparkV2Filters.convert(gt1); assertThat(actualGt1) .asString() .as("GreaterThan must match") .isEqualTo(expectedGt1.toString()); Predicate gt2 = new Predicate(">", valueAndAttr); Expression expectedGt2 = Expressions.lessThan(unquoted, 1); Expression actualGt2 = SparkV2Filters.convert(gt2); assertThat(actualGt2) .asString() .as("GreaterThan must match") .isEqualTo(expectedGt2.toString()); Predicate gtEq1 = new Predicate(">=", attrAndValue); Expression expectedGtEq1 = Expressions.greaterThanOrEqual(unquoted, 1); Expression actualGtEq1 = SparkV2Filters.convert(gtEq1); assertThat(actualGtEq1) .asString() .as("GreaterThanOrEqual must match") .isEqualTo(expectedGtEq1.toString()); Predicate gtEq2 = new Predicate(">=", valueAndAttr); Expression expectedGtEq2 = Expressions.lessThanOrEqual(unquoted, 1); Expression actualGtEq2 = SparkV2Filters.convert(gtEq2); assertThat(actualGtEq2) .asString() .as("GreaterThanOrEqual must match") .isEqualTo(expectedGtEq2.toString()); Predicate eq1 = new Predicate("=", attrAndValue); Expression expectedEq1 = Expressions.equal(unquoted, 1); Expression actualEq1 = SparkV2Filters.convert(eq1); assertThat(actualEq1) .asString() .as("EqualTo must match") .isEqualTo(expectedEq1.toString()); Predicate eq2 = new Predicate("=", valueAndAttr); Expression expectedEq2 = Expressions.equal(unquoted, 1); Expression actualEq2 = SparkV2Filters.convert(eq2); assertThat(actualEq2) .asString() .as("EqualTo must match") .isEqualTo(expectedEq2.toString()); Predicate notEq1 = new Predicate("<>", attrAndValue); Expression expectedNotEq1 = Expressions.notEqual(unquoted, 1); Expression actualNotEq1 = SparkV2Filters.convert(notEq1); assertThat(actualNotEq1) .asString() .as("NotEqualTo must match") .isEqualTo(expectedNotEq1.toString()); Predicate notEq2 = new Predicate("<>", valueAndAttr); Expression expectedNotEq2 = Expressions.notEqual(unquoted, 1); Expression actualNotEq2 = SparkV2Filters.convert(notEq2); assertThat(actualNotEq2) .asString() .as("NotEqualTo must match") .isEqualTo(expectedNotEq2.toString()); Predicate eqNullSafe1 = new Predicate("<=>", attrAndValue); Expression expectedEqNullSafe1 = Expressions.equal(unquoted, 1); Expression actualEqNullSafe1 = SparkV2Filters.convert(eqNullSafe1); assertThat(actualEqNullSafe1) .asString() .as("EqualNullSafe must match") .isEqualTo(expectedEqNullSafe1.toString()); Predicate eqNullSafe2 = new Predicate("<=>", valueAndAttr); Expression expectedEqNullSafe2 = Expressions.equal(unquoted, 1); Expression actualEqNullSafe2 = SparkV2Filters.convert(eqNullSafe2); assertThat(actualEqNullSafe2) .asString() .as("EqualNullSafe must match") .isEqualTo(expectedEqNullSafe2.toString()); LiteralValue str = new LiteralValue(UTF8String.fromString("iceberg"), DataTypes.StringType); org.apache.spark.sql.connector.expressions.Expression[] attrAndStr = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, str}; Predicate startsWith = new Predicate("STARTS_WITH", attrAndStr); Expression expectedStartsWith = Expressions.startsWith(unquoted, "iceberg"); Expression actualStartsWith = SparkV2Filters.convert(startsWith); assertThat(actualStartsWith) .asString() .as("StartsWith must match") .isEqualTo(expectedStartsWith.toString()); Predicate in = new Predicate("IN", attrAndValue); Expression expectedIn = Expressions.in(unquoted, 1); Expression actualIn = SparkV2Filters.convert(in); assertThat(actualIn).asString().as("In must match").isEqualTo(expectedIn.toString()); Predicate and = new And(lt1, eq1); Expression expectedAnd = Expressions.and(expectedLt1, expectedEq1); Expression actualAnd = SparkV2Filters.convert(and); assertThat(actualAnd).asString().as("And must match").isEqualTo(expectedAnd.toString()); org.apache.spark.sql.connector.expressions.Expression[] attrAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] { namedReference, namedReference }; Predicate invalid = new Predicate("<", attrAndAttr); Predicate andWithInvalidLeft = new And(invalid, eq1); Expression convertedAnd = SparkV2Filters.convert(andWithInvalidLeft); assertThat(convertedAnd).as("And must match").isNull(); Predicate or = new Or(lt1, eq1); Expression expectedOr = Expressions.or(expectedLt1, expectedEq1); Expression actualOr = SparkV2Filters.convert(or); assertThat(actualOr).asString().as("Or must match").isEqualTo(expectedOr.toString()); Predicate orWithInvalidLeft = new Or(invalid, eq1); Expression convertedOr = SparkV2Filters.convert(orWithInvalidLeft); assertThat(convertedOr).as("Or must match").isNull(); Predicate not = new Not(lt1); Expression expectedNot = Expressions.not(expectedLt1); Expression actualNot = SparkV2Filters.convert(not); assertThat(actualNot).asString().as("Not must match").isEqualTo(expectedNot.toString()); }); } @Test public void testEqualToNull() { String col = "col"; NamedReference namedReference = FieldReference.apply(col); LiteralValue value = new LiteralValue(null, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate eq1 = new Predicate("=", attrAndValue); assertThatThrownBy(() -> SparkV2Filters.convert(eq1)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Expression is always false"); Predicate eq2 = new Predicate("=", valueAndAttr); assertThatThrownBy(() -> SparkV2Filters.convert(eq2)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Expression is always false"); Predicate eqNullSafe1 = new Predicate("<=>", attrAndValue); Expression expectedEqNullSafe = Expressions.isNull(col); Expression actualEqNullSafe1 = SparkV2Filters.convert(eqNullSafe1); assertThat(actualEqNullSafe1.toString()).isEqualTo(expectedEqNullSafe.toString()); Predicate eqNullSafe2 = new Predicate("<=>", valueAndAttr); Expression actualEqNullSafe2 = SparkV2Filters.convert(eqNullSafe2); assertThat(actualEqNullSafe2.toString()).isEqualTo(expectedEqNullSafe.toString()); } @Test public void testEqualToNaN() { String col = "col"; NamedReference namedReference = FieldReference.apply(col); LiteralValue value = new LiteralValue(Float.NaN, DataTypes.FloatType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate eqNaN1 = new Predicate("=", attrAndValue); Expression expectedEqNaN = Expressions.isNaN(col); Expression actualEqNaN1 = SparkV2Filters.convert(eqNaN1); assertThat(actualEqNaN1.toString()).isEqualTo(expectedEqNaN.toString()); Predicate eqNaN2 = new Predicate("=", valueAndAttr); Expression actualEqNaN2 = SparkV2Filters.convert(eqNaN2); assertThat(actualEqNaN2.toString()).isEqualTo(expectedEqNaN.toString()); } @Test public void testNotEqualToNull() { String col = "col"; NamedReference namedReference = FieldReference.apply(col); LiteralValue value = new LiteralValue(null, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate notEq1 = new Predicate("<>", attrAndValue); assertThatThrownBy(() -> SparkV2Filters.convert(notEq1)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Expression is always false"); Predicate notEq2 = new Predicate("<>", valueAndAttr); assertThatThrownBy(() -> SparkV2Filters.convert(notEq2)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Expression is always false"); } @Test public void testNotEqualToNaN() { String col = "col"; NamedReference namedReference = FieldReference.apply(col); LiteralValue value = new LiteralValue(Float.NaN, DataTypes.FloatType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate notEqNaN1 = new Predicate("<>", attrAndValue); Expression expectedNotEqNaN = Expressions.notNaN(col); Expression actualNotEqNaN1 = SparkV2Filters.convert(notEqNaN1); assertThat(actualNotEqNaN1.toString()).isEqualTo(expectedNotEqNaN.toString()); Predicate notEqNaN2 = new Predicate("<>", valueAndAttr); Expression actualNotEqNaN2 = SparkV2Filters.convert(notEqNaN2); assertThat(actualNotEqNaN2.toString()).isEqualTo(expectedNotEqNaN.toString()); } @Test public void testInValuesContainNull() { String col = "strCol"; NamedReference namedReference = FieldReference.apply(col); LiteralValue nullValue = new LiteralValue(null, DataTypes.StringType); LiteralValue value1 = new LiteralValue("value1", DataTypes.StringType); LiteralValue value2 = new LiteralValue("value2", DataTypes.StringType); // Values only contains null Predicate inNull = new Predicate("IN", expressions(namedReference, nullValue)); Expression expectedInNull = Expressions.in(col); Expression actualInNull = SparkV2Filters.convert(inNull); assertEquals(expectedInNull, actualInNull); Predicate in = new Predicate("IN", expressions(namedReference, nullValue, value1, value2)); Expression expectedIn = Expressions.in(col, "value1", "value2"); Expression actualIn = SparkV2Filters.convert(in); assertEquals(expectedIn, actualIn); } @Test public void testNotInNull() { String col = "strCol"; NamedReference namedReference = FieldReference.apply(col); LiteralValue nullValue = new LiteralValue(null, DataTypes.StringType); LiteralValue value1 = new LiteralValue("value1", DataTypes.StringType); LiteralValue value2 = new LiteralValue("value2", DataTypes.StringType); // Values only contains null Predicate notInNull = new Not(new Predicate("IN", expressions(namedReference, nullValue))); Expression expectedNotInNull = Expressions.and(Expressions.notNull(col), Expressions.notIn(col)); Expression actualNotInNull = SparkV2Filters.convert(notInNull); assertEquals(expectedNotInNull, actualNotInNull); Predicate notIn = new Not(new Predicate("IN", expressions(namedReference, nullValue, value1, value2))); Expression expectedNotIn = Expressions.and(Expressions.notNull(col), Expressions.notIn(col, "value1", "value2")); Expression actualNotIn = SparkV2Filters.convert(notIn); assertEquals(expectedNotIn, actualNotIn); } @Test public void testTimestampFilterConversion() { Instant instant = Instant.parse("2018-10-18T00:00:57.907Z"); long epochMicros = ChronoUnit.MICROS.between(Instant.EPOCH, instant); NamedReference namedReference = FieldReference.apply("x"); LiteralValue ts = new LiteralValue(epochMicros, DataTypes.TimestampType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, ts}; Predicate predicate = new Predicate(">", attrAndValue); Expression tsExpression = SparkV2Filters.convert(predicate); Expression rawExpression = Expressions.greaterThan("x", epochMicros); assertThat(tsExpression) .asString() .as("Generated Timestamp expression should be correct") .isEqualTo(rawExpression.toString()); } @Test public void testDateFilterConversion() { LocalDate localDate = LocalDate.parse("2018-10-18"); long epochDay = localDate.toEpochDay(); NamedReference namedReference = FieldReference.apply("x"); LiteralValue ts = new LiteralValue(epochDay, DataTypes.DateType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, ts}; Predicate predicate = new Predicate(">", attrAndValue); Expression dateExpression = SparkV2Filters.convert(predicate); Expression rawExpression = Expressions.greaterThan("x", epochDay); assertThat(dateExpression) .asString() .as("Generated date expression should be correct") .isEqualTo(rawExpression.toString()); } @Test public void testNestedInInsideNot() { NamedReference namedReference1 = FieldReference.apply("col1"); LiteralValue v1 = new LiteralValue(1, DataTypes.IntegerType); LiteralValue v2 = new LiteralValue(2, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue1 = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference1, v1}; Predicate equal = new Predicate("=", attrAndValue1); NamedReference namedReference2 = FieldReference.apply("col2"); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue2 = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference2, v1, v2}; Predicate in = new Predicate("IN", attrAndValue2); Not filter = new Not(new And(equal, in)); Expression converted = SparkV2Filters.convert(filter); assertThat(converted).as("Expression should not be converted").isNull(); } @Test public void testNotIn() { NamedReference namedReference = FieldReference.apply("col"); LiteralValue v1 = new LiteralValue(1, DataTypes.IntegerType); LiteralValue v2 = new LiteralValue(2, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, v1, v2}; Predicate in = new Predicate("IN", attrAndValue); Not not = new Not(in); Expression actual = SparkV2Filters.convert(not); Expression expected = Expressions.and(Expressions.notNull("col"), Expressions.notIn("col", 1, 2)); assertThat(actual).asString().as("Expressions should match").isEqualTo(expected.toString()); } @Test public void testDateToYears() { ScalarFunction<Integer> dateToYearsFunc = new YearsFunction.DateToYearsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( dateToYearsFunc.name(), dateToYearsFunc.canonicalName(), expressions(FieldReference.apply("dateCol"))); testUDF(udf, Expressions.year("dateCol"), dateToYears("2023-06-25"), DataTypes.IntegerType); } @Test public void testTsToYears() { ScalarFunction<Integer> tsToYearsFunc = new YearsFunction.TimestampToYearsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsToYearsFunc.name(), tsToYearsFunc.canonicalName(), expressions(FieldReference.apply("tsCol"))); testUDF( udf, Expressions.year("tsCol"), timestampToYears("2023-12-03T10:15:30+01:00"), DataTypes.IntegerType); } @Test public void testTsNtzToYears() { ScalarFunction<Integer> tsNtzToYearsFunc = new YearsFunction.TimestampNtzToYearsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsNtzToYearsFunc.name(), tsNtzToYearsFunc.canonicalName(), expressions(FieldReference.apply("tsNtzCol"))); testUDF( udf, Expressions.year("tsNtzCol"), timestampNtzToYears("2023-06-25T13:15:30"), DataTypes.IntegerType); } @Test public void testDateToMonths() { ScalarFunction<Integer> dateToMonthsFunc = new MonthsFunction.DateToMonthsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( dateToMonthsFunc.name(), dateToMonthsFunc.canonicalName(), expressions(FieldReference.apply("dateCol"))); testUDF(udf, Expressions.month("dateCol"), dateToMonths("2023-06-25"), DataTypes.IntegerType); } @Test public void testTsToMonths() { ScalarFunction<Integer> tsToMonthsFunc = new MonthsFunction.TimestampToMonthsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsToMonthsFunc.name(), tsToMonthsFunc.canonicalName(), expressions(FieldReference.apply("tsCol"))); testUDF( udf, Expressions.month("tsCol"), timestampToMonths("2023-12-03T10:15:30+01:00"), DataTypes.IntegerType); } @Test public void testTsNtzToMonths() { ScalarFunction<Integer> tsNtzToMonthsFunc = new MonthsFunction.TimestampNtzToMonthsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsNtzToMonthsFunc.name(), tsNtzToMonthsFunc.canonicalName(), expressions(FieldReference.apply("tsNtzCol"))); testUDF( udf, Expressions.month("tsNtzCol"), timestampNtzToMonths("2023-12-03T10:15:30"), DataTypes.IntegerType); } @Test public void testDateToDays() { ScalarFunction<Integer> dateToDayFunc = new DaysFunction.DateToDaysFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( dateToDayFunc.name(), dateToDayFunc.canonicalName(), expressions(FieldReference.apply("dateCol"))); testUDF(udf, Expressions.day("dateCol"), dateToDays("2023-06-25"), DataTypes.IntegerType); } @Test public void testTsToDays() { ScalarFunction<Integer> tsToDaysFunc = new DaysFunction.TimestampToDaysFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsToDaysFunc.name(), tsToDaysFunc.canonicalName(), expressions(FieldReference.apply("tsCol"))); testUDF( udf, Expressions.day("tsCol"), timestampToDays("2023-12-03T10:15:30+01:00"), DataTypes.IntegerType); } @Test public void testTsNtzToDays() { ScalarFunction<Integer> tsNtzToDaysFunc = new DaysFunction.TimestampNtzToDaysFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsNtzToDaysFunc.name(), tsNtzToDaysFunc.canonicalName(), expressions(FieldReference.apply("tsNtzCol"))); testUDF( udf, Expressions.day("tsNtzCol"), timestampNtzToDays("2023-12-03T10:15:30"), DataTypes.IntegerType); } @Test public void testTsToHours() { ScalarFunction<Integer> tsToHourFunc = new HoursFunction.TimestampToHoursFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsToHourFunc.name(), tsToHourFunc.canonicalName(), expressions(FieldReference.apply("tsCol"))); testUDF( udf, Expressions.hour("tsCol"), timestampToHours("2023-12-03T10:15:30+01:00"), DataTypes.IntegerType); } @Test public void testTsNtzToHours() { ScalarFunction<Integer> tsNtzToHourFunc = new HoursFunction.TimestampNtzToHoursFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsNtzToHourFunc.name(), tsNtzToHourFunc.canonicalName(), expressions(FieldReference.apply("tsNtzCol"))); testUDF( udf, Expressions.hour("tsNtzCol"), timestampNtzToHours("2023-12-03T10:15:30"), DataTypes.IntegerType); } @Test public void testBucket() { ScalarFunction<Integer> bucketInt = new BucketFunction.BucketInt(DataTypes.IntegerType); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( bucketInt.name(), bucketInt.canonicalName(), expressions( LiteralValue.apply(4, DataTypes.IntegerType), FieldReference.apply("intCol"))); testUDF(udf, Expressions.bucket("intCol", 4), 2, DataTypes.IntegerType); } @Test public void testTruncate() { ScalarFunction<UTF8String> truncate = new TruncateFunction.TruncateString(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( truncate.name(), truncate.canonicalName(), expressions( LiteralValue.apply(6, DataTypes.IntegerType), FieldReference.apply("strCol"))); testUDF(udf, Expressions.truncate("strCol", 6), "prefix", DataTypes.StringType); } @Test public void testUnsupportedUDFConvert() { ScalarFunction<UTF8String> icebergVersionFunc = (ScalarFunction<UTF8String>) new IcebergVersionFunction().bind(new StructType()); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( icebergVersionFunc.name(), icebergVersionFunc.canonicalName(), new org.apache.spark.sql.connector.expressions.Expression[] {}); LiteralValue literalValue = new LiteralValue("1.3.0", DataTypes.StringType); Predicate predicate = new Predicate("=", expressions(udf, literalValue)); Expression icebergExpr = SparkV2Filters.convert(predicate); assertThat(icebergExpr).isNull(); } private <T> void testUDF( org.apache.spark.sql.connector.expressions.Expression udf, UnboundTerm<T> expectedTerm, T value, DataType dataType) { org.apache.spark.sql.connector.expressions.Expression[] attrOnly = expressions(udf); LiteralValue literalValue = new LiteralValue(value, dataType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = expressions(udf, literalValue); org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = expressions(literalValue, udf); Predicate isNull = new Predicate("IS_NULL", attrOnly); Expression expectedIsNull = Expressions.isNull(expectedTerm); Expression actualIsNull = SparkV2Filters.convert(isNull); assertEquals(expectedIsNull, actualIsNull); Predicate isNotNull = new Predicate("IS_NOT_NULL", attrOnly); Expression expectedIsNotNull = Expressions.notNull(expectedTerm); Expression actualIsNotNull = SparkV2Filters.convert(isNotNull); assertEquals(expectedIsNotNull, actualIsNotNull); Predicate lt1 = new Predicate("<", attrAndValue); Expression expectedLt1 = Expressions.lessThan(expectedTerm, value); Expression actualLt1 = SparkV2Filters.convert(lt1); assertEquals(expectedLt1, actualLt1); Predicate lt2 = new Predicate("<", valueAndAttr); Expression expectedLt2 = Expressions.greaterThan(expectedTerm, value); Expression actualLt2 = SparkV2Filters.convert(lt2); assertEquals(expectedLt2, actualLt2); Predicate ltEq1 = new Predicate("<=", attrAndValue); Expression expectedLtEq1 = Expressions.lessThanOrEqual(expectedTerm, value); Expression actualLtEq1 = SparkV2Filters.convert(ltEq1); assertEquals(expectedLtEq1, actualLtEq1); Predicate ltEq2 = new Predicate("<=", valueAndAttr); Expression expectedLtEq2 = Expressions.greaterThanOrEqual(expectedTerm, value); Expression actualLtEq2 = SparkV2Filters.convert(ltEq2); assertEquals(expectedLtEq2, actualLtEq2); Predicate gt1 = new Predicate(">", attrAndValue); Expression expectedGt1 = Expressions.greaterThan(expectedTerm, value); Expression actualGt1 = SparkV2Filters.convert(gt1); assertEquals(expectedGt1, actualGt1); Predicate gt2 = new Predicate(">", valueAndAttr); Expression expectedGt2 = Expressions.lessThan(expectedTerm, value); Expression actualGt2 = SparkV2Filters.convert(gt2); assertEquals(expectedGt2, actualGt2); Predicate gtEq1 = new Predicate(">=", attrAndValue); Expression expectedGtEq1 = Expressions.greaterThanOrEqual(expectedTerm, value); Expression actualGtEq1 = SparkV2Filters.convert(gtEq1); assertEquals(expectedGtEq1, actualGtEq1); Predicate gtEq2 = new Predicate(">=", valueAndAttr); Expression expectedGtEq2 = Expressions.lessThanOrEqual(expectedTerm, value); Expression actualGtEq2 = SparkV2Filters.convert(gtEq2); assertEquals(expectedGtEq2, actualGtEq2); Predicate eq1 = new Predicate("=", attrAndValue); Expression expectedEq1 = Expressions.equal(expectedTerm, value); Expression actualEq1 = SparkV2Filters.convert(eq1); assertEquals(expectedEq1, actualEq1); Predicate eq2 = new Predicate("=", valueAndAttr); Expression expectedEq2 = Expressions.equal(expectedTerm, value); Expression actualEq2 = SparkV2Filters.convert(eq2); assertEquals(expectedEq2, actualEq2); Predicate notEq1 = new Predicate("<>", attrAndValue); Expression expectedNotEq1 = Expressions.notEqual(expectedTerm, value); Expression actualNotEq1 = SparkV2Filters.convert(notEq1); assertEquals(expectedNotEq1, actualNotEq1); Predicate notEq2 = new Predicate("<>", valueAndAttr); Expression expectedNotEq2 = Expressions.notEqual(expectedTerm, value); Expression actualNotEq2 = SparkV2Filters.convert(notEq2); assertEquals(expectedNotEq2, actualNotEq2); Predicate eqNullSafe1 = new Predicate("<=>", attrAndValue); Expression expectedEqNullSafe1 = Expressions.equal(expectedTerm, value); Expression actualEqNullSafe1 = SparkV2Filters.convert(eqNullSafe1); assertEquals(expectedEqNullSafe1, actualEqNullSafe1); Predicate eqNullSafe2 = new Predicate("<=>", valueAndAttr); Expression expectedEqNullSafe2 = Expressions.equal(expectedTerm, value); Expression actualEqNullSafe2 = SparkV2Filters.convert(eqNullSafe2); assertEquals(expectedEqNullSafe2, actualEqNullSafe2); Predicate in = new Predicate("IN", attrAndValue); Expression expectedIn = Expressions.in(expectedTerm, value); Expression actualIn = SparkV2Filters.convert(in); assertEquals(expectedIn, actualIn); Predicate notIn = new Not(in); Expression expectedNotIn = Expressions.and(Expressions.notNull(expectedTerm), Expressions.notIn(expectedTerm, value)); Expression actualNotIn = SparkV2Filters.convert(notIn); assertEquals(expectedNotIn, actualNotIn); Predicate and = new And(lt1, eq1); Expression expectedAnd = Expressions.and(expectedLt1, expectedEq1); Expression actualAnd = SparkV2Filters.convert(and); assertEquals(expectedAnd, actualAnd); org.apache.spark.sql.connector.expressions.Expression[] attrAndAttr = expressions(udf, udf); Predicate invalid = new Predicate("<", attrAndAttr); Predicate andWithInvalidLeft = new And(invalid, eq1); Expression convertedAnd = SparkV2Filters.convert(andWithInvalidLeft); assertThat(convertedAnd).isNull(); Predicate or = new Or(lt1, eq1); Expression expectedOr = Expressions.or(expectedLt1, expectedEq1); Expression actualOr = SparkV2Filters.convert(or); assertEquals(expectedOr, actualOr); Predicate orWithInvalidLeft = new Or(invalid, eq1); Expression convertedOr = SparkV2Filters.convert(orWithInvalidLeft); assertThat(convertedOr).isNull(); Predicate not = new Not(lt1); Expression expectedNot = Expressions.not(expectedLt1); Expression actualNot = SparkV2Filters.convert(not); assertEquals(expectedNot, actualNot); } private static void assertEquals(Expression expected, Expression actual) { assertThat(ExpressionUtil.equivalent(expected, actual, STRUCT, true)).isTrue(); } private org.apache.spark.sql.connector.expressions.Expression[] expressions( org.apache.spark.sql.connector.expressions.Expression... expressions) { return expressions; } private static int dateToYears(String dateString) { return DateTimeUtil.daysToYears(DateTimeUtil.isoDateToDays(dateString)); } private static int timestampToYears(String timestampString) { return DateTimeUtil.microsToYears(DateTimeUtil.isoTimestamptzToMicros(timestampString)); } private static int timestampNtzToYears(String timestampNtzString) { return DateTimeUtil.microsToYears(DateTimeUtil.isoTimestampToMicros(timestampNtzString)); } private static int dateToMonths(String dateString) { return DateTimeUtil.daysToMonths(DateTimeUtil.isoDateToDays(dateString)); } private static int timestampToMonths(String timestampString) { return DateTimeUtil.microsToMonths(DateTimeUtil.isoTimestamptzToMicros(timestampString)); } private static int timestampNtzToMonths(String timestampNtzString) { return DateTimeUtil.microsToMonths(DateTimeUtil.isoTimestampToMicros(timestampNtzString)); } private static int dateToDays(String dateString) { return DateTimeUtil.isoDateToDays(dateString); } private static int timestampToDays(String timestampString) { return DateTimeUtil.microsToDays(DateTimeUtil.isoTimestamptzToMicros(timestampString)); } private static int timestampNtzToDays(String timestampNtzString) { return DateTimeUtil.microsToDays(DateTimeUtil.isoTimestampToMicros(timestampNtzString)); } private static int timestampToHours(String timestampString) { return DateTimeUtil.microsToHours(DateTimeUtil.isoTimestamptzToMicros(timestampString)); } private static int timestampNtzToHours(String timestampNtzString) { return DateTimeUtil.microsToHours(DateTimeUtil.isoTimestampToMicros(timestampNtzString)); } }
apache/iceberg
37,390
spark/v3.5/spark/src/test/java/org/apache/iceberg/spark/TestSparkV2Filters.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iceberg.spark; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Instant; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.Map; import org.apache.iceberg.expressions.Expression; import org.apache.iceberg.expressions.ExpressionUtil; import org.apache.iceberg.expressions.Expressions; import org.apache.iceberg.expressions.UnboundTerm; import org.apache.iceberg.relocated.com.google.common.collect.Maps; import org.apache.iceberg.spark.functions.BucketFunction; import org.apache.iceberg.spark.functions.DaysFunction; import org.apache.iceberg.spark.functions.HoursFunction; import org.apache.iceberg.spark.functions.IcebergVersionFunction; import org.apache.iceberg.spark.functions.MonthsFunction; import org.apache.iceberg.spark.functions.TruncateFunction; import org.apache.iceberg.spark.functions.YearsFunction; import org.apache.iceberg.types.Types; import org.apache.iceberg.util.DateTimeUtil; import org.apache.spark.sql.connector.catalog.functions.ScalarFunction; import org.apache.spark.sql.connector.expressions.FieldReference; import org.apache.spark.sql.connector.expressions.LiteralValue; import org.apache.spark.sql.connector.expressions.NamedReference; import org.apache.spark.sql.connector.expressions.UserDefinedScalarFunc; import org.apache.spark.sql.connector.expressions.filter.And; import org.apache.spark.sql.connector.expressions.filter.Not; import org.apache.spark.sql.connector.expressions.filter.Or; import org.apache.spark.sql.connector.expressions.filter.Predicate; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.StructType; import org.apache.spark.unsafe.types.UTF8String; import org.junit.jupiter.api.Test; public class TestSparkV2Filters { private static final Types.StructType STRUCT = Types.StructType.of( Types.NestedField.optional(1, "dateCol", Types.DateType.get()), Types.NestedField.optional(2, "tsCol", Types.TimestampType.withZone()), Types.NestedField.optional(3, "tsNtzCol", Types.TimestampType.withoutZone()), Types.NestedField.optional(4, "intCol", Types.IntegerType.get()), Types.NestedField.optional(5, "strCol", Types.StringType.get())); @SuppressWarnings("checkstyle:MethodLength") @Test public void testV2Filters() { Map<String, String> attrMap = Maps.newHashMap(); attrMap.put("id", "id"); attrMap.put("`i.d`", "i.d"); attrMap.put("`i``d`", "i`d"); attrMap.put("`d`.b.`dd```", "d.b.dd`"); attrMap.put("a.`aa```.c", "a.aa`.c"); attrMap.forEach( (quoted, unquoted) -> { NamedReference namedReference = FieldReference.apply(quoted); org.apache.spark.sql.connector.expressions.Expression[] attrOnly = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference}; LiteralValue value = new LiteralValue(1, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate isNull = new Predicate("IS_NULL", attrOnly); Expression expectedIsNull = Expressions.isNull(unquoted); Expression actualIsNull = SparkV2Filters.convert(isNull); assertThat(actualIsNull) .asString() .as("IsNull must match") .isEqualTo(expectedIsNull.toString()); Predicate isNotNull = new Predicate("IS_NOT_NULL", attrOnly); Expression expectedIsNotNull = Expressions.notNull(unquoted); Expression actualIsNotNull = SparkV2Filters.convert(isNotNull); assertThat(actualIsNotNull) .asString() .as("IsNotNull must match") .isEqualTo(expectedIsNotNull.toString()); Predicate lt1 = new Predicate("<", attrAndValue); Expression expectedLt1 = Expressions.lessThan(unquoted, 1); Expression actualLt1 = SparkV2Filters.convert(lt1); assertThat(actualLt1) .asString() .as("LessThan must match") .isEqualTo(expectedLt1.toString()); Predicate lt2 = new Predicate("<", valueAndAttr); Expression expectedLt2 = Expressions.greaterThan(unquoted, 1); Expression actualLt2 = SparkV2Filters.convert(lt2); assertThat(actualLt2) .asString() .as("LessThan must match") .isEqualTo(expectedLt2.toString()); Predicate ltEq1 = new Predicate("<=", attrAndValue); Expression expectedLtEq1 = Expressions.lessThanOrEqual(unquoted, 1); Expression actualLtEq1 = SparkV2Filters.convert(ltEq1); assertThat(actualLtEq1) .asString() .as("LessThanOrEqual must match") .isEqualTo(expectedLtEq1.toString()); Predicate ltEq2 = new Predicate("<=", valueAndAttr); Expression expectedLtEq2 = Expressions.greaterThanOrEqual(unquoted, 1); Expression actualLtEq2 = SparkV2Filters.convert(ltEq2); assertThat(actualLtEq2) .asString() .as("LessThanOrEqual must match") .isEqualTo(expectedLtEq2.toString()); Predicate gt1 = new Predicate(">", attrAndValue); Expression expectedGt1 = Expressions.greaterThan(unquoted, 1); Expression actualGt1 = SparkV2Filters.convert(gt1); assertThat(actualGt1) .asString() .as("GreaterThan must match") .isEqualTo(expectedGt1.toString()); Predicate gt2 = new Predicate(">", valueAndAttr); Expression expectedGt2 = Expressions.lessThan(unquoted, 1); Expression actualGt2 = SparkV2Filters.convert(gt2); assertThat(actualGt2) .asString() .as("GreaterThan must match") .isEqualTo(expectedGt2.toString()); Predicate gtEq1 = new Predicate(">=", attrAndValue); Expression expectedGtEq1 = Expressions.greaterThanOrEqual(unquoted, 1); Expression actualGtEq1 = SparkV2Filters.convert(gtEq1); assertThat(actualGtEq1) .asString() .as("GreaterThanOrEqual must match") .isEqualTo(expectedGtEq1.toString()); Predicate gtEq2 = new Predicate(">=", valueAndAttr); Expression expectedGtEq2 = Expressions.lessThanOrEqual(unquoted, 1); Expression actualGtEq2 = SparkV2Filters.convert(gtEq2); assertThat(actualGtEq2) .asString() .as("GreaterThanOrEqual must match") .isEqualTo(expectedGtEq2.toString()); Predicate eq1 = new Predicate("=", attrAndValue); Expression expectedEq1 = Expressions.equal(unquoted, 1); Expression actualEq1 = SparkV2Filters.convert(eq1); assertThat(actualEq1) .asString() .as("EqualTo must match") .isEqualTo(expectedEq1.toString()); Predicate eq2 = new Predicate("=", valueAndAttr); Expression expectedEq2 = Expressions.equal(unquoted, 1); Expression actualEq2 = SparkV2Filters.convert(eq2); assertThat(actualEq2) .asString() .as("EqualTo must match") .isEqualTo(expectedEq2.toString()); Predicate notEq1 = new Predicate("<>", attrAndValue); Expression expectedNotEq1 = Expressions.notEqual(unquoted, 1); Expression actualNotEq1 = SparkV2Filters.convert(notEq1); assertThat(actualNotEq1) .asString() .as("NotEqualTo must match") .isEqualTo(expectedNotEq1.toString()); Predicate notEq2 = new Predicate("<>", valueAndAttr); Expression expectedNotEq2 = Expressions.notEqual(unquoted, 1); Expression actualNotEq2 = SparkV2Filters.convert(notEq2); assertThat(actualNotEq2) .asString() .as("NotEqualTo must match") .isEqualTo(expectedNotEq2.toString()); Predicate eqNullSafe1 = new Predicate("<=>", attrAndValue); Expression expectedEqNullSafe1 = Expressions.equal(unquoted, 1); Expression actualEqNullSafe1 = SparkV2Filters.convert(eqNullSafe1); assertThat(actualEqNullSafe1) .asString() .as("EqualNullSafe must match") .isEqualTo(expectedEqNullSafe1.toString()); Predicate eqNullSafe2 = new Predicate("<=>", valueAndAttr); Expression expectedEqNullSafe2 = Expressions.equal(unquoted, 1); Expression actualEqNullSafe2 = SparkV2Filters.convert(eqNullSafe2); assertThat(actualEqNullSafe2) .asString() .as("EqualNullSafe must match") .isEqualTo(expectedEqNullSafe2.toString()); LiteralValue str = new LiteralValue(UTF8String.fromString("iceberg"), DataTypes.StringType); org.apache.spark.sql.connector.expressions.Expression[] attrAndStr = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, str}; Predicate startsWith = new Predicate("STARTS_WITH", attrAndStr); Expression expectedStartsWith = Expressions.startsWith(unquoted, "iceberg"); Expression actualStartsWith = SparkV2Filters.convert(startsWith); assertThat(actualStartsWith) .asString() .as("StartsWith must match") .isEqualTo(expectedStartsWith.toString()); Predicate in = new Predicate("IN", attrAndValue); Expression expectedIn = Expressions.in(unquoted, 1); Expression actualIn = SparkV2Filters.convert(in); assertThat(actualIn).asString().as("In must match").isEqualTo(expectedIn.toString()); Predicate and = new And(lt1, eq1); Expression expectedAnd = Expressions.and(expectedLt1, expectedEq1); Expression actualAnd = SparkV2Filters.convert(and); assertThat(actualAnd).asString().as("And must match").isEqualTo(expectedAnd.toString()); org.apache.spark.sql.connector.expressions.Expression[] attrAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] { namedReference, namedReference }; Predicate invalid = new Predicate("<", attrAndAttr); Predicate andWithInvalidLeft = new And(invalid, eq1); Expression convertedAnd = SparkV2Filters.convert(andWithInvalidLeft); assertThat(convertedAnd).as("And must match").isNull(); Predicate or = new Or(lt1, eq1); Expression expectedOr = Expressions.or(expectedLt1, expectedEq1); Expression actualOr = SparkV2Filters.convert(or); assertThat(actualOr).asString().as("Or must match").isEqualTo(expectedOr.toString()); Predicate orWithInvalidLeft = new Or(invalid, eq1); Expression convertedOr = SparkV2Filters.convert(orWithInvalidLeft); assertThat(convertedOr).as("Or must match").isNull(); Predicate not = new Not(lt1); Expression expectedNot = Expressions.not(expectedLt1); Expression actualNot = SparkV2Filters.convert(not); assertThat(actualNot).asString().as("Not must match").isEqualTo(expectedNot.toString()); }); } @Test public void testEqualToNull() { String col = "col"; NamedReference namedReference = FieldReference.apply(col); LiteralValue value = new LiteralValue(null, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate eq1 = new Predicate("=", attrAndValue); assertThatThrownBy(() -> SparkV2Filters.convert(eq1)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Expression is always false"); Predicate eq2 = new Predicate("=", valueAndAttr); assertThatThrownBy(() -> SparkV2Filters.convert(eq2)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Expression is always false"); Predicate eqNullSafe1 = new Predicate("<=>", attrAndValue); Expression expectedEqNullSafe = Expressions.isNull(col); Expression actualEqNullSafe1 = SparkV2Filters.convert(eqNullSafe1); assertThat(actualEqNullSafe1.toString()).isEqualTo(expectedEqNullSafe.toString()); Predicate eqNullSafe2 = new Predicate("<=>", valueAndAttr); Expression actualEqNullSafe2 = SparkV2Filters.convert(eqNullSafe2); assertThat(actualEqNullSafe2.toString()).isEqualTo(expectedEqNullSafe.toString()); } @Test public void testEqualToNaN() { String col = "col"; NamedReference namedReference = FieldReference.apply(col); LiteralValue value = new LiteralValue(Float.NaN, DataTypes.FloatType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate eqNaN1 = new Predicate("=", attrAndValue); Expression expectedEqNaN = Expressions.isNaN(col); Expression actualEqNaN1 = SparkV2Filters.convert(eqNaN1); assertThat(actualEqNaN1.toString()).isEqualTo(expectedEqNaN.toString()); Predicate eqNaN2 = new Predicate("=", valueAndAttr); Expression actualEqNaN2 = SparkV2Filters.convert(eqNaN2); assertThat(actualEqNaN2.toString()).isEqualTo(expectedEqNaN.toString()); } @Test public void testNotEqualToNull() { String col = "col"; NamedReference namedReference = FieldReference.apply(col); LiteralValue value = new LiteralValue(null, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate notEq1 = new Predicate("<>", attrAndValue); assertThatThrownBy(() -> SparkV2Filters.convert(notEq1)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Expression is always false"); Predicate notEq2 = new Predicate("<>", valueAndAttr); assertThatThrownBy(() -> SparkV2Filters.convert(notEq2)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Expression is always false"); } @Test public void testNotEqualToNaN() { String col = "col"; NamedReference namedReference = FieldReference.apply(col); LiteralValue value = new LiteralValue(Float.NaN, DataTypes.FloatType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate notEqNaN1 = new Predicate("<>", attrAndValue); Expression expectedNotEqNaN = Expressions.notNaN(col); Expression actualNotEqNaN1 = SparkV2Filters.convert(notEqNaN1); assertThat(actualNotEqNaN1.toString()).isEqualTo(expectedNotEqNaN.toString()); Predicate notEqNaN2 = new Predicate("<>", valueAndAttr); Expression actualNotEqNaN2 = SparkV2Filters.convert(notEqNaN2); assertThat(actualNotEqNaN2.toString()).isEqualTo(expectedNotEqNaN.toString()); } @Test public void testInValuesContainNull() { String col = "strCol"; NamedReference namedReference = FieldReference.apply(col); LiteralValue nullValue = new LiteralValue(null, DataTypes.StringType); LiteralValue value1 = new LiteralValue("value1", DataTypes.StringType); LiteralValue value2 = new LiteralValue("value2", DataTypes.StringType); // Values only contains null Predicate inNull = new Predicate("IN", expressions(namedReference, nullValue)); Expression expectedInNull = Expressions.in(col); Expression actualInNull = SparkV2Filters.convert(inNull); assertEquals(expectedInNull, actualInNull); Predicate in = new Predicate("IN", expressions(namedReference, nullValue, value1, value2)); Expression expectedIn = Expressions.in(col, "value1", "value2"); Expression actualIn = SparkV2Filters.convert(in); assertEquals(expectedIn, actualIn); } @Test public void testNotInNull() { String col = "strCol"; NamedReference namedReference = FieldReference.apply(col); LiteralValue nullValue = new LiteralValue(null, DataTypes.StringType); LiteralValue value1 = new LiteralValue("value1", DataTypes.StringType); LiteralValue value2 = new LiteralValue("value2", DataTypes.StringType); // Values only contains null Predicate notInNull = new Not(new Predicate("IN", expressions(namedReference, nullValue))); Expression expectedNotInNull = Expressions.and(Expressions.notNull(col), Expressions.notIn(col)); Expression actualNotInNull = SparkV2Filters.convert(notInNull); assertEquals(expectedNotInNull, actualNotInNull); Predicate notIn = new Not(new Predicate("IN", expressions(namedReference, nullValue, value1, value2))); Expression expectedNotIn = Expressions.and(Expressions.notNull(col), Expressions.notIn(col, "value1", "value2")); Expression actualNotIn = SparkV2Filters.convert(notIn); assertEquals(expectedNotIn, actualNotIn); } @Test public void testTimestampFilterConversion() { Instant instant = Instant.parse("2018-10-18T00:00:57.907Z"); long epochMicros = ChronoUnit.MICROS.between(Instant.EPOCH, instant); NamedReference namedReference = FieldReference.apply("x"); LiteralValue ts = new LiteralValue(epochMicros, DataTypes.TimestampType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, ts}; Predicate predicate = new Predicate(">", attrAndValue); Expression tsExpression = SparkV2Filters.convert(predicate); Expression rawExpression = Expressions.greaterThan("x", epochMicros); assertThat(tsExpression) .asString() .as("Generated Timestamp expression should be correct") .isEqualTo(rawExpression.toString()); } @Test public void testDateFilterConversion() { LocalDate localDate = LocalDate.parse("2018-10-18"); long epochDay = localDate.toEpochDay(); NamedReference namedReference = FieldReference.apply("x"); LiteralValue ts = new LiteralValue(epochDay, DataTypes.DateType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, ts}; Predicate predicate = new Predicate(">", attrAndValue); Expression dateExpression = SparkV2Filters.convert(predicate); Expression rawExpression = Expressions.greaterThan("x", epochDay); assertThat(dateExpression) .asString() .as("Generated date expression should be correct") .isEqualTo(rawExpression.toString()); } @Test public void testNestedInInsideNot() { NamedReference namedReference1 = FieldReference.apply("col1"); LiteralValue v1 = new LiteralValue(1, DataTypes.IntegerType); LiteralValue v2 = new LiteralValue(2, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue1 = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference1, v1}; Predicate equal = new Predicate("=", attrAndValue1); NamedReference namedReference2 = FieldReference.apply("col2"); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue2 = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference2, v1, v2}; Predicate in = new Predicate("IN", attrAndValue2); Not filter = new Not(new And(equal, in)); Expression converted = SparkV2Filters.convert(filter); assertThat(converted).as("Expression should not be converted").isNull(); } @Test public void testNotIn() { NamedReference namedReference = FieldReference.apply("col"); LiteralValue v1 = new LiteralValue(1, DataTypes.IntegerType); LiteralValue v2 = new LiteralValue(2, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, v1, v2}; Predicate in = new Predicate("IN", attrAndValue); Not not = new Not(in); Expression actual = SparkV2Filters.convert(not); Expression expected = Expressions.and(Expressions.notNull("col"), Expressions.notIn("col", 1, 2)); assertThat(actual).asString().as("Expressions should match").isEqualTo(expected.toString()); } @Test public void testDateToYears() { ScalarFunction<Integer> dateToYearsFunc = new YearsFunction.DateToYearsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( dateToYearsFunc.name(), dateToYearsFunc.canonicalName(), expressions(FieldReference.apply("dateCol"))); testUDF(udf, Expressions.year("dateCol"), dateToYears("2023-06-25"), DataTypes.IntegerType); } @Test public void testTsToYears() { ScalarFunction<Integer> tsToYearsFunc = new YearsFunction.TimestampToYearsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsToYearsFunc.name(), tsToYearsFunc.canonicalName(), expressions(FieldReference.apply("tsCol"))); testUDF( udf, Expressions.year("tsCol"), timestampToYears("2023-12-03T10:15:30+01:00"), DataTypes.IntegerType); } @Test public void testTsNtzToYears() { ScalarFunction<Integer> tsNtzToYearsFunc = new YearsFunction.TimestampNtzToYearsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsNtzToYearsFunc.name(), tsNtzToYearsFunc.canonicalName(), expressions(FieldReference.apply("tsNtzCol"))); testUDF( udf, Expressions.year("tsNtzCol"), timestampNtzToYears("2023-06-25T13:15:30"), DataTypes.IntegerType); } @Test public void testDateToMonths() { ScalarFunction<Integer> dateToMonthsFunc = new MonthsFunction.DateToMonthsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( dateToMonthsFunc.name(), dateToMonthsFunc.canonicalName(), expressions(FieldReference.apply("dateCol"))); testUDF(udf, Expressions.month("dateCol"), dateToMonths("2023-06-25"), DataTypes.IntegerType); } @Test public void testTsToMonths() { ScalarFunction<Integer> tsToMonthsFunc = new MonthsFunction.TimestampToMonthsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsToMonthsFunc.name(), tsToMonthsFunc.canonicalName(), expressions(FieldReference.apply("tsCol"))); testUDF( udf, Expressions.month("tsCol"), timestampToMonths("2023-12-03T10:15:30+01:00"), DataTypes.IntegerType); } @Test public void testTsNtzToMonths() { ScalarFunction<Integer> tsNtzToMonthsFunc = new MonthsFunction.TimestampNtzToMonthsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsNtzToMonthsFunc.name(), tsNtzToMonthsFunc.canonicalName(), expressions(FieldReference.apply("tsNtzCol"))); testUDF( udf, Expressions.month("tsNtzCol"), timestampNtzToMonths("2023-12-03T10:15:30"), DataTypes.IntegerType); } @Test public void testDateToDays() { ScalarFunction<Integer> dateToDayFunc = new DaysFunction.DateToDaysFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( dateToDayFunc.name(), dateToDayFunc.canonicalName(), expressions(FieldReference.apply("dateCol"))); testUDF(udf, Expressions.day("dateCol"), dateToDays("2023-06-25"), DataTypes.IntegerType); } @Test public void testTsToDays() { ScalarFunction<Integer> tsToDaysFunc = new DaysFunction.TimestampToDaysFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsToDaysFunc.name(), tsToDaysFunc.canonicalName(), expressions(FieldReference.apply("tsCol"))); testUDF( udf, Expressions.day("tsCol"), timestampToDays("2023-12-03T10:15:30+01:00"), DataTypes.IntegerType); } @Test public void testTsNtzToDays() { ScalarFunction<Integer> tsNtzToDaysFunc = new DaysFunction.TimestampNtzToDaysFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsNtzToDaysFunc.name(), tsNtzToDaysFunc.canonicalName(), expressions(FieldReference.apply("tsNtzCol"))); testUDF( udf, Expressions.day("tsNtzCol"), timestampNtzToDays("2023-12-03T10:15:30"), DataTypes.IntegerType); } @Test public void testTsToHours() { ScalarFunction<Integer> tsToHourFunc = new HoursFunction.TimestampToHoursFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsToHourFunc.name(), tsToHourFunc.canonicalName(), expressions(FieldReference.apply("tsCol"))); testUDF( udf, Expressions.hour("tsCol"), timestampToHours("2023-12-03T10:15:30+01:00"), DataTypes.IntegerType); } @Test public void testTsNtzToHours() { ScalarFunction<Integer> tsNtzToHourFunc = new HoursFunction.TimestampNtzToHoursFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsNtzToHourFunc.name(), tsNtzToHourFunc.canonicalName(), expressions(FieldReference.apply("tsNtzCol"))); testUDF( udf, Expressions.hour("tsNtzCol"), timestampNtzToHours("2023-12-03T10:15:30"), DataTypes.IntegerType); } @Test public void testBucket() { ScalarFunction<Integer> bucketInt = new BucketFunction.BucketInt(DataTypes.IntegerType); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( bucketInt.name(), bucketInt.canonicalName(), expressions( LiteralValue.apply(4, DataTypes.IntegerType), FieldReference.apply("intCol"))); testUDF(udf, Expressions.bucket("intCol", 4), 2, DataTypes.IntegerType); } @Test public void testTruncate() { ScalarFunction<UTF8String> truncate = new TruncateFunction.TruncateString(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( truncate.name(), truncate.canonicalName(), expressions( LiteralValue.apply(6, DataTypes.IntegerType), FieldReference.apply("strCol"))); testUDF(udf, Expressions.truncate("strCol", 6), "prefix", DataTypes.StringType); } @Test public void testUnsupportedUDFConvert() { ScalarFunction<UTF8String> icebergVersionFunc = (ScalarFunction<UTF8String>) new IcebergVersionFunction().bind(new StructType()); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( icebergVersionFunc.name(), icebergVersionFunc.canonicalName(), new org.apache.spark.sql.connector.expressions.Expression[] {}); LiteralValue literalValue = new LiteralValue("1.3.0", DataTypes.StringType); Predicate predicate = new Predicate("=", expressions(udf, literalValue)); Expression icebergExpr = SparkV2Filters.convert(predicate); assertThat(icebergExpr).isNull(); } private <T> void testUDF( org.apache.spark.sql.connector.expressions.Expression udf, UnboundTerm<T> expectedTerm, T value, DataType dataType) { org.apache.spark.sql.connector.expressions.Expression[] attrOnly = expressions(udf); LiteralValue literalValue = new LiteralValue(value, dataType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = expressions(udf, literalValue); org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = expressions(literalValue, udf); Predicate isNull = new Predicate("IS_NULL", attrOnly); Expression expectedIsNull = Expressions.isNull(expectedTerm); Expression actualIsNull = SparkV2Filters.convert(isNull); assertEquals(expectedIsNull, actualIsNull); Predicate isNotNull = new Predicate("IS_NOT_NULL", attrOnly); Expression expectedIsNotNull = Expressions.notNull(expectedTerm); Expression actualIsNotNull = SparkV2Filters.convert(isNotNull); assertEquals(expectedIsNotNull, actualIsNotNull); Predicate lt1 = new Predicate("<", attrAndValue); Expression expectedLt1 = Expressions.lessThan(expectedTerm, value); Expression actualLt1 = SparkV2Filters.convert(lt1); assertEquals(expectedLt1, actualLt1); Predicate lt2 = new Predicate("<", valueAndAttr); Expression expectedLt2 = Expressions.greaterThan(expectedTerm, value); Expression actualLt2 = SparkV2Filters.convert(lt2); assertEquals(expectedLt2, actualLt2); Predicate ltEq1 = new Predicate("<=", attrAndValue); Expression expectedLtEq1 = Expressions.lessThanOrEqual(expectedTerm, value); Expression actualLtEq1 = SparkV2Filters.convert(ltEq1); assertEquals(expectedLtEq1, actualLtEq1); Predicate ltEq2 = new Predicate("<=", valueAndAttr); Expression expectedLtEq2 = Expressions.greaterThanOrEqual(expectedTerm, value); Expression actualLtEq2 = SparkV2Filters.convert(ltEq2); assertEquals(expectedLtEq2, actualLtEq2); Predicate gt1 = new Predicate(">", attrAndValue); Expression expectedGt1 = Expressions.greaterThan(expectedTerm, value); Expression actualGt1 = SparkV2Filters.convert(gt1); assertEquals(expectedGt1, actualGt1); Predicate gt2 = new Predicate(">", valueAndAttr); Expression expectedGt2 = Expressions.lessThan(expectedTerm, value); Expression actualGt2 = SparkV2Filters.convert(gt2); assertEquals(expectedGt2, actualGt2); Predicate gtEq1 = new Predicate(">=", attrAndValue); Expression expectedGtEq1 = Expressions.greaterThanOrEqual(expectedTerm, value); Expression actualGtEq1 = SparkV2Filters.convert(gtEq1); assertEquals(expectedGtEq1, actualGtEq1); Predicate gtEq2 = new Predicate(">=", valueAndAttr); Expression expectedGtEq2 = Expressions.lessThanOrEqual(expectedTerm, value); Expression actualGtEq2 = SparkV2Filters.convert(gtEq2); assertEquals(expectedGtEq2, actualGtEq2); Predicate eq1 = new Predicate("=", attrAndValue); Expression expectedEq1 = Expressions.equal(expectedTerm, value); Expression actualEq1 = SparkV2Filters.convert(eq1); assertEquals(expectedEq1, actualEq1); Predicate eq2 = new Predicate("=", valueAndAttr); Expression expectedEq2 = Expressions.equal(expectedTerm, value); Expression actualEq2 = SparkV2Filters.convert(eq2); assertEquals(expectedEq2, actualEq2); Predicate notEq1 = new Predicate("<>", attrAndValue); Expression expectedNotEq1 = Expressions.notEqual(expectedTerm, value); Expression actualNotEq1 = SparkV2Filters.convert(notEq1); assertEquals(expectedNotEq1, actualNotEq1); Predicate notEq2 = new Predicate("<>", valueAndAttr); Expression expectedNotEq2 = Expressions.notEqual(expectedTerm, value); Expression actualNotEq2 = SparkV2Filters.convert(notEq2); assertEquals(expectedNotEq2, actualNotEq2); Predicate eqNullSafe1 = new Predicate("<=>", attrAndValue); Expression expectedEqNullSafe1 = Expressions.equal(expectedTerm, value); Expression actualEqNullSafe1 = SparkV2Filters.convert(eqNullSafe1); assertEquals(expectedEqNullSafe1, actualEqNullSafe1); Predicate eqNullSafe2 = new Predicate("<=>", valueAndAttr); Expression expectedEqNullSafe2 = Expressions.equal(expectedTerm, value); Expression actualEqNullSafe2 = SparkV2Filters.convert(eqNullSafe2); assertEquals(expectedEqNullSafe2, actualEqNullSafe2); Predicate in = new Predicate("IN", attrAndValue); Expression expectedIn = Expressions.in(expectedTerm, value); Expression actualIn = SparkV2Filters.convert(in); assertEquals(expectedIn, actualIn); Predicate notIn = new Not(in); Expression expectedNotIn = Expressions.and(Expressions.notNull(expectedTerm), Expressions.notIn(expectedTerm, value)); Expression actualNotIn = SparkV2Filters.convert(notIn); assertEquals(expectedNotIn, actualNotIn); Predicate and = new And(lt1, eq1); Expression expectedAnd = Expressions.and(expectedLt1, expectedEq1); Expression actualAnd = SparkV2Filters.convert(and); assertEquals(expectedAnd, actualAnd); org.apache.spark.sql.connector.expressions.Expression[] attrAndAttr = expressions(udf, udf); Predicate invalid = new Predicate("<", attrAndAttr); Predicate andWithInvalidLeft = new And(invalid, eq1); Expression convertedAnd = SparkV2Filters.convert(andWithInvalidLeft); assertThat(convertedAnd).isNull(); Predicate or = new Or(lt1, eq1); Expression expectedOr = Expressions.or(expectedLt1, expectedEq1); Expression actualOr = SparkV2Filters.convert(or); assertEquals(expectedOr, actualOr); Predicate orWithInvalidLeft = new Or(invalid, eq1); Expression convertedOr = SparkV2Filters.convert(orWithInvalidLeft); assertThat(convertedOr).isNull(); Predicate not = new Not(lt1); Expression expectedNot = Expressions.not(expectedLt1); Expression actualNot = SparkV2Filters.convert(not); assertEquals(expectedNot, actualNot); } private static void assertEquals(Expression expected, Expression actual) { assertThat(ExpressionUtil.equivalent(expected, actual, STRUCT, true)).isTrue(); } private org.apache.spark.sql.connector.expressions.Expression[] expressions( org.apache.spark.sql.connector.expressions.Expression... expressions) { return expressions; } private static int dateToYears(String dateString) { return DateTimeUtil.daysToYears(DateTimeUtil.isoDateToDays(dateString)); } private static int timestampToYears(String timestampString) { return DateTimeUtil.microsToYears(DateTimeUtil.isoTimestamptzToMicros(timestampString)); } private static int timestampNtzToYears(String timestampNtzString) { return DateTimeUtil.microsToYears(DateTimeUtil.isoTimestampToMicros(timestampNtzString)); } private static int dateToMonths(String dateString) { return DateTimeUtil.daysToMonths(DateTimeUtil.isoDateToDays(dateString)); } private static int timestampToMonths(String timestampString) { return DateTimeUtil.microsToMonths(DateTimeUtil.isoTimestamptzToMicros(timestampString)); } private static int timestampNtzToMonths(String timestampNtzString) { return DateTimeUtil.microsToMonths(DateTimeUtil.isoTimestampToMicros(timestampNtzString)); } private static int dateToDays(String dateString) { return DateTimeUtil.isoDateToDays(dateString); } private static int timestampToDays(String timestampString) { return DateTimeUtil.microsToDays(DateTimeUtil.isoTimestamptzToMicros(timestampString)); } private static int timestampNtzToDays(String timestampNtzString) { return DateTimeUtil.microsToDays(DateTimeUtil.isoTimestampToMicros(timestampNtzString)); } private static int timestampToHours(String timestampString) { return DateTimeUtil.microsToHours(DateTimeUtil.isoTimestamptzToMicros(timestampString)); } private static int timestampNtzToHours(String timestampNtzString) { return DateTimeUtil.microsToHours(DateTimeUtil.isoTimestampToMicros(timestampNtzString)); } }
apache/iceberg
37,390
spark/v4.0/spark/src/test/java/org/apache/iceberg/spark/TestSparkV2Filters.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iceberg.spark; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Instant; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.Map; import org.apache.iceberg.expressions.Expression; import org.apache.iceberg.expressions.ExpressionUtil; import org.apache.iceberg.expressions.Expressions; import org.apache.iceberg.expressions.UnboundTerm; import org.apache.iceberg.relocated.com.google.common.collect.Maps; import org.apache.iceberg.spark.functions.BucketFunction; import org.apache.iceberg.spark.functions.DaysFunction; import org.apache.iceberg.spark.functions.HoursFunction; import org.apache.iceberg.spark.functions.IcebergVersionFunction; import org.apache.iceberg.spark.functions.MonthsFunction; import org.apache.iceberg.spark.functions.TruncateFunction; import org.apache.iceberg.spark.functions.YearsFunction; import org.apache.iceberg.types.Types; import org.apache.iceberg.util.DateTimeUtil; import org.apache.spark.sql.connector.catalog.functions.ScalarFunction; import org.apache.spark.sql.connector.expressions.FieldReference; import org.apache.spark.sql.connector.expressions.LiteralValue; import org.apache.spark.sql.connector.expressions.NamedReference; import org.apache.spark.sql.connector.expressions.UserDefinedScalarFunc; import org.apache.spark.sql.connector.expressions.filter.And; import org.apache.spark.sql.connector.expressions.filter.Not; import org.apache.spark.sql.connector.expressions.filter.Or; import org.apache.spark.sql.connector.expressions.filter.Predicate; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.StructType; import org.apache.spark.unsafe.types.UTF8String; import org.junit.jupiter.api.Test; public class TestSparkV2Filters { private static final Types.StructType STRUCT = Types.StructType.of( Types.NestedField.optional(1, "dateCol", Types.DateType.get()), Types.NestedField.optional(2, "tsCol", Types.TimestampType.withZone()), Types.NestedField.optional(3, "tsNtzCol", Types.TimestampType.withoutZone()), Types.NestedField.optional(4, "intCol", Types.IntegerType.get()), Types.NestedField.optional(5, "strCol", Types.StringType.get())); @SuppressWarnings("checkstyle:MethodLength") @Test public void testV2Filters() { Map<String, String> attrMap = Maps.newHashMap(); attrMap.put("id", "id"); attrMap.put("`i.d`", "i.d"); attrMap.put("`i``d`", "i`d"); attrMap.put("`d`.b.`dd```", "d.b.dd`"); attrMap.put("a.`aa```.c", "a.aa`.c"); attrMap.forEach( (quoted, unquoted) -> { NamedReference namedReference = FieldReference.apply(quoted); org.apache.spark.sql.connector.expressions.Expression[] attrOnly = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference}; LiteralValue value = new LiteralValue(1, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate isNull = new Predicate("IS_NULL", attrOnly); Expression expectedIsNull = Expressions.isNull(unquoted); Expression actualIsNull = SparkV2Filters.convert(isNull); assertThat(actualIsNull) .asString() .as("IsNull must match") .isEqualTo(expectedIsNull.toString()); Predicate isNotNull = new Predicate("IS_NOT_NULL", attrOnly); Expression expectedIsNotNull = Expressions.notNull(unquoted); Expression actualIsNotNull = SparkV2Filters.convert(isNotNull); assertThat(actualIsNotNull) .asString() .as("IsNotNull must match") .isEqualTo(expectedIsNotNull.toString()); Predicate lt1 = new Predicate("<", attrAndValue); Expression expectedLt1 = Expressions.lessThan(unquoted, 1); Expression actualLt1 = SparkV2Filters.convert(lt1); assertThat(actualLt1) .asString() .as("LessThan must match") .isEqualTo(expectedLt1.toString()); Predicate lt2 = new Predicate("<", valueAndAttr); Expression expectedLt2 = Expressions.greaterThan(unquoted, 1); Expression actualLt2 = SparkV2Filters.convert(lt2); assertThat(actualLt2) .asString() .as("LessThan must match") .isEqualTo(expectedLt2.toString()); Predicate ltEq1 = new Predicate("<=", attrAndValue); Expression expectedLtEq1 = Expressions.lessThanOrEqual(unquoted, 1); Expression actualLtEq1 = SparkV2Filters.convert(ltEq1); assertThat(actualLtEq1) .asString() .as("LessThanOrEqual must match") .isEqualTo(expectedLtEq1.toString()); Predicate ltEq2 = new Predicate("<=", valueAndAttr); Expression expectedLtEq2 = Expressions.greaterThanOrEqual(unquoted, 1); Expression actualLtEq2 = SparkV2Filters.convert(ltEq2); assertThat(actualLtEq2) .asString() .as("LessThanOrEqual must match") .isEqualTo(expectedLtEq2.toString()); Predicate gt1 = new Predicate(">", attrAndValue); Expression expectedGt1 = Expressions.greaterThan(unquoted, 1); Expression actualGt1 = SparkV2Filters.convert(gt1); assertThat(actualGt1) .asString() .as("GreaterThan must match") .isEqualTo(expectedGt1.toString()); Predicate gt2 = new Predicate(">", valueAndAttr); Expression expectedGt2 = Expressions.lessThan(unquoted, 1); Expression actualGt2 = SparkV2Filters.convert(gt2); assertThat(actualGt2) .asString() .as("GreaterThan must match") .isEqualTo(expectedGt2.toString()); Predicate gtEq1 = new Predicate(">=", attrAndValue); Expression expectedGtEq1 = Expressions.greaterThanOrEqual(unquoted, 1); Expression actualGtEq1 = SparkV2Filters.convert(gtEq1); assertThat(actualGtEq1) .asString() .as("GreaterThanOrEqual must match") .isEqualTo(expectedGtEq1.toString()); Predicate gtEq2 = new Predicate(">=", valueAndAttr); Expression expectedGtEq2 = Expressions.lessThanOrEqual(unquoted, 1); Expression actualGtEq2 = SparkV2Filters.convert(gtEq2); assertThat(actualGtEq2) .asString() .as("GreaterThanOrEqual must match") .isEqualTo(expectedGtEq2.toString()); Predicate eq1 = new Predicate("=", attrAndValue); Expression expectedEq1 = Expressions.equal(unquoted, 1); Expression actualEq1 = SparkV2Filters.convert(eq1); assertThat(actualEq1) .asString() .as("EqualTo must match") .isEqualTo(expectedEq1.toString()); Predicate eq2 = new Predicate("=", valueAndAttr); Expression expectedEq2 = Expressions.equal(unquoted, 1); Expression actualEq2 = SparkV2Filters.convert(eq2); assertThat(actualEq2) .asString() .as("EqualTo must match") .isEqualTo(expectedEq2.toString()); Predicate notEq1 = new Predicate("<>", attrAndValue); Expression expectedNotEq1 = Expressions.notEqual(unquoted, 1); Expression actualNotEq1 = SparkV2Filters.convert(notEq1); assertThat(actualNotEq1) .asString() .as("NotEqualTo must match") .isEqualTo(expectedNotEq1.toString()); Predicate notEq2 = new Predicate("<>", valueAndAttr); Expression expectedNotEq2 = Expressions.notEqual(unquoted, 1); Expression actualNotEq2 = SparkV2Filters.convert(notEq2); assertThat(actualNotEq2) .asString() .as("NotEqualTo must match") .isEqualTo(expectedNotEq2.toString()); Predicate eqNullSafe1 = new Predicate("<=>", attrAndValue); Expression expectedEqNullSafe1 = Expressions.equal(unquoted, 1); Expression actualEqNullSafe1 = SparkV2Filters.convert(eqNullSafe1); assertThat(actualEqNullSafe1) .asString() .as("EqualNullSafe must match") .isEqualTo(expectedEqNullSafe1.toString()); Predicate eqNullSafe2 = new Predicate("<=>", valueAndAttr); Expression expectedEqNullSafe2 = Expressions.equal(unquoted, 1); Expression actualEqNullSafe2 = SparkV2Filters.convert(eqNullSafe2); assertThat(actualEqNullSafe2) .asString() .as("EqualNullSafe must match") .isEqualTo(expectedEqNullSafe2.toString()); LiteralValue str = new LiteralValue(UTF8String.fromString("iceberg"), DataTypes.StringType); org.apache.spark.sql.connector.expressions.Expression[] attrAndStr = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, str}; Predicate startsWith = new Predicate("STARTS_WITH", attrAndStr); Expression expectedStartsWith = Expressions.startsWith(unquoted, "iceberg"); Expression actualStartsWith = SparkV2Filters.convert(startsWith); assertThat(actualStartsWith) .asString() .as("StartsWith must match") .isEqualTo(expectedStartsWith.toString()); Predicate in = new Predicate("IN", attrAndValue); Expression expectedIn = Expressions.in(unquoted, 1); Expression actualIn = SparkV2Filters.convert(in); assertThat(actualIn).asString().as("In must match").isEqualTo(expectedIn.toString()); Predicate and = new And(lt1, eq1); Expression expectedAnd = Expressions.and(expectedLt1, expectedEq1); Expression actualAnd = SparkV2Filters.convert(and); assertThat(actualAnd).asString().as("And must match").isEqualTo(expectedAnd.toString()); org.apache.spark.sql.connector.expressions.Expression[] attrAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] { namedReference, namedReference }; Predicate invalid = new Predicate("<", attrAndAttr); Predicate andWithInvalidLeft = new And(invalid, eq1); Expression convertedAnd = SparkV2Filters.convert(andWithInvalidLeft); assertThat(convertedAnd).as("And must match").isNull(); Predicate or = new Or(lt1, eq1); Expression expectedOr = Expressions.or(expectedLt1, expectedEq1); Expression actualOr = SparkV2Filters.convert(or); assertThat(actualOr).asString().as("Or must match").isEqualTo(expectedOr.toString()); Predicate orWithInvalidLeft = new Or(invalid, eq1); Expression convertedOr = SparkV2Filters.convert(orWithInvalidLeft); assertThat(convertedOr).as("Or must match").isNull(); Predicate not = new Not(lt1); Expression expectedNot = Expressions.not(expectedLt1); Expression actualNot = SparkV2Filters.convert(not); assertThat(actualNot).asString().as("Not must match").isEqualTo(expectedNot.toString()); }); } @Test public void testEqualToNull() { String col = "col"; NamedReference namedReference = FieldReference.apply(col); LiteralValue value = new LiteralValue(null, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate eq1 = new Predicate("=", attrAndValue); assertThatThrownBy(() -> SparkV2Filters.convert(eq1)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Expression is always false"); Predicate eq2 = new Predicate("=", valueAndAttr); assertThatThrownBy(() -> SparkV2Filters.convert(eq2)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Expression is always false"); Predicate eqNullSafe1 = new Predicate("<=>", attrAndValue); Expression expectedEqNullSafe = Expressions.isNull(col); Expression actualEqNullSafe1 = SparkV2Filters.convert(eqNullSafe1); assertThat(actualEqNullSafe1.toString()).isEqualTo(expectedEqNullSafe.toString()); Predicate eqNullSafe2 = new Predicate("<=>", valueAndAttr); Expression actualEqNullSafe2 = SparkV2Filters.convert(eqNullSafe2); assertThat(actualEqNullSafe2.toString()).isEqualTo(expectedEqNullSafe.toString()); } @Test public void testEqualToNaN() { String col = "col"; NamedReference namedReference = FieldReference.apply(col); LiteralValue value = new LiteralValue(Float.NaN, DataTypes.FloatType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate eqNaN1 = new Predicate("=", attrAndValue); Expression expectedEqNaN = Expressions.isNaN(col); Expression actualEqNaN1 = SparkV2Filters.convert(eqNaN1); assertThat(actualEqNaN1.toString()).isEqualTo(expectedEqNaN.toString()); Predicate eqNaN2 = new Predicate("=", valueAndAttr); Expression actualEqNaN2 = SparkV2Filters.convert(eqNaN2); assertThat(actualEqNaN2.toString()).isEqualTo(expectedEqNaN.toString()); } @Test public void testNotEqualToNull() { String col = "col"; NamedReference namedReference = FieldReference.apply(col); LiteralValue value = new LiteralValue(null, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate notEq1 = new Predicate("<>", attrAndValue); assertThatThrownBy(() -> SparkV2Filters.convert(notEq1)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Expression is always false"); Predicate notEq2 = new Predicate("<>", valueAndAttr); assertThatThrownBy(() -> SparkV2Filters.convert(notEq2)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Expression is always false"); } @Test public void testNotEqualToNaN() { String col = "col"; NamedReference namedReference = FieldReference.apply(col); LiteralValue value = new LiteralValue(Float.NaN, DataTypes.FloatType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, value}; org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = new org.apache.spark.sql.connector.expressions.Expression[] {value, namedReference}; Predicate notEqNaN1 = new Predicate("<>", attrAndValue); Expression expectedNotEqNaN = Expressions.notNaN(col); Expression actualNotEqNaN1 = SparkV2Filters.convert(notEqNaN1); assertThat(actualNotEqNaN1.toString()).isEqualTo(expectedNotEqNaN.toString()); Predicate notEqNaN2 = new Predicate("<>", valueAndAttr); Expression actualNotEqNaN2 = SparkV2Filters.convert(notEqNaN2); assertThat(actualNotEqNaN2.toString()).isEqualTo(expectedNotEqNaN.toString()); } @Test public void testInValuesContainNull() { String col = "strCol"; NamedReference namedReference = FieldReference.apply(col); LiteralValue nullValue = new LiteralValue(null, DataTypes.StringType); LiteralValue value1 = new LiteralValue("value1", DataTypes.StringType); LiteralValue value2 = new LiteralValue("value2", DataTypes.StringType); // Values only contains null Predicate inNull = new Predicate("IN", expressions(namedReference, nullValue)); Expression expectedInNull = Expressions.in(col); Expression actualInNull = SparkV2Filters.convert(inNull); assertEquals(expectedInNull, actualInNull); Predicate in = new Predicate("IN", expressions(namedReference, nullValue, value1, value2)); Expression expectedIn = Expressions.in(col, "value1", "value2"); Expression actualIn = SparkV2Filters.convert(in); assertEquals(expectedIn, actualIn); } @Test public void testNotInNull() { String col = "strCol"; NamedReference namedReference = FieldReference.apply(col); LiteralValue nullValue = new LiteralValue(null, DataTypes.StringType); LiteralValue value1 = new LiteralValue("value1", DataTypes.StringType); LiteralValue value2 = new LiteralValue("value2", DataTypes.StringType); // Values only contains null Predicate notInNull = new Not(new Predicate("IN", expressions(namedReference, nullValue))); Expression expectedNotInNull = Expressions.and(Expressions.notNull(col), Expressions.notIn(col)); Expression actualNotInNull = SparkV2Filters.convert(notInNull); assertEquals(expectedNotInNull, actualNotInNull); Predicate notIn = new Not(new Predicate("IN", expressions(namedReference, nullValue, value1, value2))); Expression expectedNotIn = Expressions.and(Expressions.notNull(col), Expressions.notIn(col, "value1", "value2")); Expression actualNotIn = SparkV2Filters.convert(notIn); assertEquals(expectedNotIn, actualNotIn); } @Test public void testTimestampFilterConversion() { Instant instant = Instant.parse("2018-10-18T00:00:57.907Z"); long epochMicros = ChronoUnit.MICROS.between(Instant.EPOCH, instant); NamedReference namedReference = FieldReference.apply("x"); LiteralValue ts = new LiteralValue(epochMicros, DataTypes.TimestampType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, ts}; Predicate predicate = new Predicate(">", attrAndValue); Expression tsExpression = SparkV2Filters.convert(predicate); Expression rawExpression = Expressions.greaterThan("x", epochMicros); assertThat(tsExpression) .asString() .as("Generated Timestamp expression should be correct") .isEqualTo(rawExpression.toString()); } @Test public void testDateFilterConversion() { LocalDate localDate = LocalDate.parse("2018-10-18"); long epochDay = localDate.toEpochDay(); NamedReference namedReference = FieldReference.apply("x"); LiteralValue ts = new LiteralValue(epochDay, DataTypes.DateType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, ts}; Predicate predicate = new Predicate(">", attrAndValue); Expression dateExpression = SparkV2Filters.convert(predicate); Expression rawExpression = Expressions.greaterThan("x", epochDay); assertThat(dateExpression) .asString() .as("Generated date expression should be correct") .isEqualTo(rawExpression.toString()); } @Test public void testNestedInInsideNot() { NamedReference namedReference1 = FieldReference.apply("col1"); LiteralValue v1 = new LiteralValue(1, DataTypes.IntegerType); LiteralValue v2 = new LiteralValue(2, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue1 = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference1, v1}; Predicate equal = new Predicate("=", attrAndValue1); NamedReference namedReference2 = FieldReference.apply("col2"); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue2 = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference2, v1, v2}; Predicate in = new Predicate("IN", attrAndValue2); Not filter = new Not(new And(equal, in)); Expression converted = SparkV2Filters.convert(filter); assertThat(converted).as("Expression should not be converted").isNull(); } @Test public void testNotIn() { NamedReference namedReference = FieldReference.apply("col"); LiteralValue v1 = new LiteralValue(1, DataTypes.IntegerType); LiteralValue v2 = new LiteralValue(2, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.expressions.Expression[] {namedReference, v1, v2}; Predicate in = new Predicate("IN", attrAndValue); Not not = new Not(in); Expression actual = SparkV2Filters.convert(not); Expression expected = Expressions.and(Expressions.notNull("col"), Expressions.notIn("col", 1, 2)); assertThat(actual).asString().as("Expressions should match").isEqualTo(expected.toString()); } @Test public void testDateToYears() { ScalarFunction<Integer> dateToYearsFunc = new YearsFunction.DateToYearsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( dateToYearsFunc.name(), dateToYearsFunc.canonicalName(), expressions(FieldReference.apply("dateCol"))); testUDF(udf, Expressions.year("dateCol"), dateToYears("2023-06-25"), DataTypes.IntegerType); } @Test public void testTsToYears() { ScalarFunction<Integer> tsToYearsFunc = new YearsFunction.TimestampToYearsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsToYearsFunc.name(), tsToYearsFunc.canonicalName(), expressions(FieldReference.apply("tsCol"))); testUDF( udf, Expressions.year("tsCol"), timestampToYears("2023-12-03T10:15:30+01:00"), DataTypes.IntegerType); } @Test public void testTsNtzToYears() { ScalarFunction<Integer> tsNtzToYearsFunc = new YearsFunction.TimestampNtzToYearsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsNtzToYearsFunc.name(), tsNtzToYearsFunc.canonicalName(), expressions(FieldReference.apply("tsNtzCol"))); testUDF( udf, Expressions.year("tsNtzCol"), timestampNtzToYears("2023-06-25T13:15:30"), DataTypes.IntegerType); } @Test public void testDateToMonths() { ScalarFunction<Integer> dateToMonthsFunc = new MonthsFunction.DateToMonthsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( dateToMonthsFunc.name(), dateToMonthsFunc.canonicalName(), expressions(FieldReference.apply("dateCol"))); testUDF(udf, Expressions.month("dateCol"), dateToMonths("2023-06-25"), DataTypes.IntegerType); } @Test public void testTsToMonths() { ScalarFunction<Integer> tsToMonthsFunc = new MonthsFunction.TimestampToMonthsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsToMonthsFunc.name(), tsToMonthsFunc.canonicalName(), expressions(FieldReference.apply("tsCol"))); testUDF( udf, Expressions.month("tsCol"), timestampToMonths("2023-12-03T10:15:30+01:00"), DataTypes.IntegerType); } @Test public void testTsNtzToMonths() { ScalarFunction<Integer> tsNtzToMonthsFunc = new MonthsFunction.TimestampNtzToMonthsFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsNtzToMonthsFunc.name(), tsNtzToMonthsFunc.canonicalName(), expressions(FieldReference.apply("tsNtzCol"))); testUDF( udf, Expressions.month("tsNtzCol"), timestampNtzToMonths("2023-12-03T10:15:30"), DataTypes.IntegerType); } @Test public void testDateToDays() { ScalarFunction<Integer> dateToDayFunc = new DaysFunction.DateToDaysFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( dateToDayFunc.name(), dateToDayFunc.canonicalName(), expressions(FieldReference.apply("dateCol"))); testUDF(udf, Expressions.day("dateCol"), dateToDays("2023-06-25"), DataTypes.IntegerType); } @Test public void testTsToDays() { ScalarFunction<Integer> tsToDaysFunc = new DaysFunction.TimestampToDaysFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsToDaysFunc.name(), tsToDaysFunc.canonicalName(), expressions(FieldReference.apply("tsCol"))); testUDF( udf, Expressions.day("tsCol"), timestampToDays("2023-12-03T10:15:30+01:00"), DataTypes.IntegerType); } @Test public void testTsNtzToDays() { ScalarFunction<Integer> tsNtzToDaysFunc = new DaysFunction.TimestampNtzToDaysFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsNtzToDaysFunc.name(), tsNtzToDaysFunc.canonicalName(), expressions(FieldReference.apply("tsNtzCol"))); testUDF( udf, Expressions.day("tsNtzCol"), timestampNtzToDays("2023-12-03T10:15:30"), DataTypes.IntegerType); } @Test public void testTsToHours() { ScalarFunction<Integer> tsToHourFunc = new HoursFunction.TimestampToHoursFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsToHourFunc.name(), tsToHourFunc.canonicalName(), expressions(FieldReference.apply("tsCol"))); testUDF( udf, Expressions.hour("tsCol"), timestampToHours("2023-12-03T10:15:30+01:00"), DataTypes.IntegerType); } @Test public void testTsNtzToHours() { ScalarFunction<Integer> tsNtzToHourFunc = new HoursFunction.TimestampNtzToHoursFunction(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( tsNtzToHourFunc.name(), tsNtzToHourFunc.canonicalName(), expressions(FieldReference.apply("tsNtzCol"))); testUDF( udf, Expressions.hour("tsNtzCol"), timestampNtzToHours("2023-12-03T10:15:30"), DataTypes.IntegerType); } @Test public void testBucket() { ScalarFunction<Integer> bucketInt = new BucketFunction.BucketInt(DataTypes.IntegerType); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( bucketInt.name(), bucketInt.canonicalName(), expressions( LiteralValue.apply(4, DataTypes.IntegerType), FieldReference.apply("intCol"))); testUDF(udf, Expressions.bucket("intCol", 4), 2, DataTypes.IntegerType); } @Test public void testTruncate() { ScalarFunction<UTF8String> truncate = new TruncateFunction.TruncateString(); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( truncate.name(), truncate.canonicalName(), expressions( LiteralValue.apply(6, DataTypes.IntegerType), FieldReference.apply("strCol"))); testUDF(udf, Expressions.truncate("strCol", 6), "prefix", DataTypes.StringType); } @Test public void testUnsupportedUDFConvert() { ScalarFunction<UTF8String> icebergVersionFunc = (ScalarFunction<UTF8String>) new IcebergVersionFunction().bind(new StructType()); UserDefinedScalarFunc udf = new UserDefinedScalarFunc( icebergVersionFunc.name(), icebergVersionFunc.canonicalName(), new org.apache.spark.sql.connector.expressions.Expression[] {}); LiteralValue literalValue = new LiteralValue("1.3.0", DataTypes.StringType); Predicate predicate = new Predicate("=", expressions(udf, literalValue)); Expression icebergExpr = SparkV2Filters.convert(predicate); assertThat(icebergExpr).isNull(); } private <T> void testUDF( org.apache.spark.sql.connector.expressions.Expression udf, UnboundTerm<T> expectedTerm, T value, DataType dataType) { org.apache.spark.sql.connector.expressions.Expression[] attrOnly = expressions(udf); LiteralValue literalValue = new LiteralValue(value, dataType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = expressions(udf, literalValue); org.apache.spark.sql.connector.expressions.Expression[] valueAndAttr = expressions(literalValue, udf); Predicate isNull = new Predicate("IS_NULL", attrOnly); Expression expectedIsNull = Expressions.isNull(expectedTerm); Expression actualIsNull = SparkV2Filters.convert(isNull); assertEquals(expectedIsNull, actualIsNull); Predicate isNotNull = new Predicate("IS_NOT_NULL", attrOnly); Expression expectedIsNotNull = Expressions.notNull(expectedTerm); Expression actualIsNotNull = SparkV2Filters.convert(isNotNull); assertEquals(expectedIsNotNull, actualIsNotNull); Predicate lt1 = new Predicate("<", attrAndValue); Expression expectedLt1 = Expressions.lessThan(expectedTerm, value); Expression actualLt1 = SparkV2Filters.convert(lt1); assertEquals(expectedLt1, actualLt1); Predicate lt2 = new Predicate("<", valueAndAttr); Expression expectedLt2 = Expressions.greaterThan(expectedTerm, value); Expression actualLt2 = SparkV2Filters.convert(lt2); assertEquals(expectedLt2, actualLt2); Predicate ltEq1 = new Predicate("<=", attrAndValue); Expression expectedLtEq1 = Expressions.lessThanOrEqual(expectedTerm, value); Expression actualLtEq1 = SparkV2Filters.convert(ltEq1); assertEquals(expectedLtEq1, actualLtEq1); Predicate ltEq2 = new Predicate("<=", valueAndAttr); Expression expectedLtEq2 = Expressions.greaterThanOrEqual(expectedTerm, value); Expression actualLtEq2 = SparkV2Filters.convert(ltEq2); assertEquals(expectedLtEq2, actualLtEq2); Predicate gt1 = new Predicate(">", attrAndValue); Expression expectedGt1 = Expressions.greaterThan(expectedTerm, value); Expression actualGt1 = SparkV2Filters.convert(gt1); assertEquals(expectedGt1, actualGt1); Predicate gt2 = new Predicate(">", valueAndAttr); Expression expectedGt2 = Expressions.lessThan(expectedTerm, value); Expression actualGt2 = SparkV2Filters.convert(gt2); assertEquals(expectedGt2, actualGt2); Predicate gtEq1 = new Predicate(">=", attrAndValue); Expression expectedGtEq1 = Expressions.greaterThanOrEqual(expectedTerm, value); Expression actualGtEq1 = SparkV2Filters.convert(gtEq1); assertEquals(expectedGtEq1, actualGtEq1); Predicate gtEq2 = new Predicate(">=", valueAndAttr); Expression expectedGtEq2 = Expressions.lessThanOrEqual(expectedTerm, value); Expression actualGtEq2 = SparkV2Filters.convert(gtEq2); assertEquals(expectedGtEq2, actualGtEq2); Predicate eq1 = new Predicate("=", attrAndValue); Expression expectedEq1 = Expressions.equal(expectedTerm, value); Expression actualEq1 = SparkV2Filters.convert(eq1); assertEquals(expectedEq1, actualEq1); Predicate eq2 = new Predicate("=", valueAndAttr); Expression expectedEq2 = Expressions.equal(expectedTerm, value); Expression actualEq2 = SparkV2Filters.convert(eq2); assertEquals(expectedEq2, actualEq2); Predicate notEq1 = new Predicate("<>", attrAndValue); Expression expectedNotEq1 = Expressions.notEqual(expectedTerm, value); Expression actualNotEq1 = SparkV2Filters.convert(notEq1); assertEquals(expectedNotEq1, actualNotEq1); Predicate notEq2 = new Predicate("<>", valueAndAttr); Expression expectedNotEq2 = Expressions.notEqual(expectedTerm, value); Expression actualNotEq2 = SparkV2Filters.convert(notEq2); assertEquals(expectedNotEq2, actualNotEq2); Predicate eqNullSafe1 = new Predicate("<=>", attrAndValue); Expression expectedEqNullSafe1 = Expressions.equal(expectedTerm, value); Expression actualEqNullSafe1 = SparkV2Filters.convert(eqNullSafe1); assertEquals(expectedEqNullSafe1, actualEqNullSafe1); Predicate eqNullSafe2 = new Predicate("<=>", valueAndAttr); Expression expectedEqNullSafe2 = Expressions.equal(expectedTerm, value); Expression actualEqNullSafe2 = SparkV2Filters.convert(eqNullSafe2); assertEquals(expectedEqNullSafe2, actualEqNullSafe2); Predicate in = new Predicate("IN", attrAndValue); Expression expectedIn = Expressions.in(expectedTerm, value); Expression actualIn = SparkV2Filters.convert(in); assertEquals(expectedIn, actualIn); Predicate notIn = new Not(in); Expression expectedNotIn = Expressions.and(Expressions.notNull(expectedTerm), Expressions.notIn(expectedTerm, value)); Expression actualNotIn = SparkV2Filters.convert(notIn); assertEquals(expectedNotIn, actualNotIn); Predicate and = new And(lt1, eq1); Expression expectedAnd = Expressions.and(expectedLt1, expectedEq1); Expression actualAnd = SparkV2Filters.convert(and); assertEquals(expectedAnd, actualAnd); org.apache.spark.sql.connector.expressions.Expression[] attrAndAttr = expressions(udf, udf); Predicate invalid = new Predicate("<", attrAndAttr); Predicate andWithInvalidLeft = new And(invalid, eq1); Expression convertedAnd = SparkV2Filters.convert(andWithInvalidLeft); assertThat(convertedAnd).isNull(); Predicate or = new Or(lt1, eq1); Expression expectedOr = Expressions.or(expectedLt1, expectedEq1); Expression actualOr = SparkV2Filters.convert(or); assertEquals(expectedOr, actualOr); Predicate orWithInvalidLeft = new Or(invalid, eq1); Expression convertedOr = SparkV2Filters.convert(orWithInvalidLeft); assertThat(convertedOr).isNull(); Predicate not = new Not(lt1); Expression expectedNot = Expressions.not(expectedLt1); Expression actualNot = SparkV2Filters.convert(not); assertEquals(expectedNot, actualNot); } private static void assertEquals(Expression expected, Expression actual) { assertThat(ExpressionUtil.equivalent(expected, actual, STRUCT, true)).isTrue(); } private org.apache.spark.sql.connector.expressions.Expression[] expressions( org.apache.spark.sql.connector.expressions.Expression... expressions) { return expressions; } private static int dateToYears(String dateString) { return DateTimeUtil.daysToYears(DateTimeUtil.isoDateToDays(dateString)); } private static int timestampToYears(String timestampString) { return DateTimeUtil.microsToYears(DateTimeUtil.isoTimestamptzToMicros(timestampString)); } private static int timestampNtzToYears(String timestampNtzString) { return DateTimeUtil.microsToYears(DateTimeUtil.isoTimestampToMicros(timestampNtzString)); } private static int dateToMonths(String dateString) { return DateTimeUtil.daysToMonths(DateTimeUtil.isoDateToDays(dateString)); } private static int timestampToMonths(String timestampString) { return DateTimeUtil.microsToMonths(DateTimeUtil.isoTimestamptzToMicros(timestampString)); } private static int timestampNtzToMonths(String timestampNtzString) { return DateTimeUtil.microsToMonths(DateTimeUtil.isoTimestampToMicros(timestampNtzString)); } private static int dateToDays(String dateString) { return DateTimeUtil.isoDateToDays(dateString); } private static int timestampToDays(String timestampString) { return DateTimeUtil.microsToDays(DateTimeUtil.isoTimestamptzToMicros(timestampString)); } private static int timestampNtzToDays(String timestampNtzString) { return DateTimeUtil.microsToDays(DateTimeUtil.isoTimestampToMicros(timestampNtzString)); } private static int timestampToHours(String timestampString) { return DateTimeUtil.microsToHours(DateTimeUtil.isoTimestamptzToMicros(timestampString)); } private static int timestampNtzToHours(String timestampNtzString) { return DateTimeUtil.microsToHours(DateTimeUtil.isoTimestampToMicros(timestampNtzString)); } }
googleapis/google-cloud-java
37,322
java-monitoring-dashboards/proto-google-cloud-monitoring-dashboard-v1/src/main/java/com/google/monitoring/dashboard/v1/ListDashboardsResponse.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/dashboard/v1/dashboards_service.proto // Protobuf Java Version: 3.25.8 package com.google.monitoring.dashboard.v1; /** * * * <pre> * The `ListDashboards` request. * </pre> * * Protobuf type {@code google.monitoring.dashboard.v1.ListDashboardsResponse} */ public final class ListDashboardsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.monitoring.dashboard.v1.ListDashboardsResponse) ListDashboardsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListDashboardsResponse.newBuilder() to construct. private ListDashboardsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDashboardsResponse() { dashboards_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDashboardsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.monitoring.dashboard.v1.DashboardsServiceProto .internal_static_google_monitoring_dashboard_v1_ListDashboardsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.monitoring.dashboard.v1.DashboardsServiceProto .internal_static_google_monitoring_dashboard_v1_ListDashboardsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.monitoring.dashboard.v1.ListDashboardsResponse.class, com.google.monitoring.dashboard.v1.ListDashboardsResponse.Builder.class); } public static final int DASHBOARDS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.monitoring.dashboard.v1.Dashboard> dashboards_; /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ @java.lang.Override public java.util.List<com.google.monitoring.dashboard.v1.Dashboard> getDashboardsList() { return dashboards_; } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.monitoring.dashboard.v1.DashboardOrBuilder> getDashboardsOrBuilderList() { return dashboards_; } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ @java.lang.Override public int getDashboardsCount() { return dashboards_.size(); } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ @java.lang.Override public com.google.monitoring.dashboard.v1.Dashboard getDashboards(int index) { return dashboards_.get(index); } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ @java.lang.Override public com.google.monitoring.dashboard.v1.DashboardOrBuilder getDashboardsOrBuilder(int index) { return dashboards_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } 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 < dashboards_.size(); i++) { output.writeMessage(1, dashboards_.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 < dashboards_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, dashboards_.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.monitoring.dashboard.v1.ListDashboardsResponse)) { return super.equals(obj); } com.google.monitoring.dashboard.v1.ListDashboardsResponse other = (com.google.monitoring.dashboard.v1.ListDashboardsResponse) obj; if (!getDashboardsList().equals(other.getDashboardsList())) 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 (getDashboardsCount() > 0) { hash = (37 * hash) + DASHBOARDS_FIELD_NUMBER; hash = (53 * hash) + getDashboardsList().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.monitoring.dashboard.v1.ListDashboardsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.dashboard.v1.ListDashboardsResponse 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.dashboard.v1.ListDashboardsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.dashboard.v1.ListDashboardsResponse 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.dashboard.v1.ListDashboardsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.dashboard.v1.ListDashboardsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.monitoring.dashboard.v1.ListDashboardsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.monitoring.dashboard.v1.ListDashboardsResponse 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.dashboard.v1.ListDashboardsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.monitoring.dashboard.v1.ListDashboardsResponse 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.dashboard.v1.ListDashboardsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.monitoring.dashboard.v1.ListDashboardsResponse 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.dashboard.v1.ListDashboardsResponse 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 `ListDashboards` request. * </pre> * * Protobuf type {@code google.monitoring.dashboard.v1.ListDashboardsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.monitoring.dashboard.v1.ListDashboardsResponse) com.google.monitoring.dashboard.v1.ListDashboardsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.monitoring.dashboard.v1.DashboardsServiceProto .internal_static_google_monitoring_dashboard_v1_ListDashboardsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.monitoring.dashboard.v1.DashboardsServiceProto .internal_static_google_monitoring_dashboard_v1_ListDashboardsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.monitoring.dashboard.v1.ListDashboardsResponse.class, com.google.monitoring.dashboard.v1.ListDashboardsResponse.Builder.class); } // Construct using com.google.monitoring.dashboard.v1.ListDashboardsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (dashboardsBuilder_ == null) { dashboards_ = java.util.Collections.emptyList(); } else { dashboards_ = null; dashboardsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.monitoring.dashboard.v1.DashboardsServiceProto .internal_static_google_monitoring_dashboard_v1_ListDashboardsResponse_descriptor; } @java.lang.Override public com.google.monitoring.dashboard.v1.ListDashboardsResponse getDefaultInstanceForType() { return com.google.monitoring.dashboard.v1.ListDashboardsResponse.getDefaultInstance(); } @java.lang.Override public com.google.monitoring.dashboard.v1.ListDashboardsResponse build() { com.google.monitoring.dashboard.v1.ListDashboardsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.monitoring.dashboard.v1.ListDashboardsResponse buildPartial() { com.google.monitoring.dashboard.v1.ListDashboardsResponse result = new com.google.monitoring.dashboard.v1.ListDashboardsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.monitoring.dashboard.v1.ListDashboardsResponse result) { if (dashboardsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { dashboards_ = java.util.Collections.unmodifiableList(dashboards_); bitField0_ = (bitField0_ & ~0x00000001); } result.dashboards_ = dashboards_; } else { result.dashboards_ = dashboardsBuilder_.build(); } } private void buildPartial0(com.google.monitoring.dashboard.v1.ListDashboardsResponse 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.monitoring.dashboard.v1.ListDashboardsResponse) { return mergeFrom((com.google.monitoring.dashboard.v1.ListDashboardsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.monitoring.dashboard.v1.ListDashboardsResponse other) { if (other == com.google.monitoring.dashboard.v1.ListDashboardsResponse.getDefaultInstance()) return this; if (dashboardsBuilder_ == null) { if (!other.dashboards_.isEmpty()) { if (dashboards_.isEmpty()) { dashboards_ = other.dashboards_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDashboardsIsMutable(); dashboards_.addAll(other.dashboards_); } onChanged(); } } else { if (!other.dashboards_.isEmpty()) { if (dashboardsBuilder_.isEmpty()) { dashboardsBuilder_.dispose(); dashboardsBuilder_ = null; dashboards_ = other.dashboards_; bitField0_ = (bitField0_ & ~0x00000001); dashboardsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDashboardsFieldBuilder() : null; } else { dashboardsBuilder_.addAllMessages(other.dashboards_); } } } 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.monitoring.dashboard.v1.Dashboard m = input.readMessage( com.google.monitoring.dashboard.v1.Dashboard.parser(), extensionRegistry); if (dashboardsBuilder_ == null) { ensureDashboardsIsMutable(); dashboards_.add(m); } else { dashboardsBuilder_.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.monitoring.dashboard.v1.Dashboard> dashboards_ = java.util.Collections.emptyList(); private void ensureDashboardsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { dashboards_ = new java.util.ArrayList<com.google.monitoring.dashboard.v1.Dashboard>(dashboards_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.monitoring.dashboard.v1.Dashboard, com.google.monitoring.dashboard.v1.Dashboard.Builder, com.google.monitoring.dashboard.v1.DashboardOrBuilder> dashboardsBuilder_; /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public java.util.List<com.google.monitoring.dashboard.v1.Dashboard> getDashboardsList() { if (dashboardsBuilder_ == null) { return java.util.Collections.unmodifiableList(dashboards_); } else { return dashboardsBuilder_.getMessageList(); } } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public int getDashboardsCount() { if (dashboardsBuilder_ == null) { return dashboards_.size(); } else { return dashboardsBuilder_.getCount(); } } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public com.google.monitoring.dashboard.v1.Dashboard getDashboards(int index) { if (dashboardsBuilder_ == null) { return dashboards_.get(index); } else { return dashboardsBuilder_.getMessage(index); } } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public Builder setDashboards(int index, com.google.monitoring.dashboard.v1.Dashboard value) { if (dashboardsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDashboardsIsMutable(); dashboards_.set(index, value); onChanged(); } else { dashboardsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public Builder setDashboards( int index, com.google.monitoring.dashboard.v1.Dashboard.Builder builderForValue) { if (dashboardsBuilder_ == null) { ensureDashboardsIsMutable(); dashboards_.set(index, builderForValue.build()); onChanged(); } else { dashboardsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public Builder addDashboards(com.google.monitoring.dashboard.v1.Dashboard value) { if (dashboardsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDashboardsIsMutable(); dashboards_.add(value); onChanged(); } else { dashboardsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public Builder addDashboards(int index, com.google.monitoring.dashboard.v1.Dashboard value) { if (dashboardsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDashboardsIsMutable(); dashboards_.add(index, value); onChanged(); } else { dashboardsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public Builder addDashboards( com.google.monitoring.dashboard.v1.Dashboard.Builder builderForValue) { if (dashboardsBuilder_ == null) { ensureDashboardsIsMutable(); dashboards_.add(builderForValue.build()); onChanged(); } else { dashboardsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public Builder addDashboards( int index, com.google.monitoring.dashboard.v1.Dashboard.Builder builderForValue) { if (dashboardsBuilder_ == null) { ensureDashboardsIsMutable(); dashboards_.add(index, builderForValue.build()); onChanged(); } else { dashboardsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public Builder addAllDashboards( java.lang.Iterable<? extends com.google.monitoring.dashboard.v1.Dashboard> values) { if (dashboardsBuilder_ == null) { ensureDashboardsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dashboards_); onChanged(); } else { dashboardsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public Builder clearDashboards() { if (dashboardsBuilder_ == null) { dashboards_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { dashboardsBuilder_.clear(); } return this; } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public Builder removeDashboards(int index) { if (dashboardsBuilder_ == null) { ensureDashboardsIsMutable(); dashboards_.remove(index); onChanged(); } else { dashboardsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public com.google.monitoring.dashboard.v1.Dashboard.Builder getDashboardsBuilder(int index) { return getDashboardsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public com.google.monitoring.dashboard.v1.DashboardOrBuilder getDashboardsOrBuilder(int index) { if (dashboardsBuilder_ == null) { return dashboards_.get(index); } else { return dashboardsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public java.util.List<? extends com.google.monitoring.dashboard.v1.DashboardOrBuilder> getDashboardsOrBuilderList() { if (dashboardsBuilder_ != null) { return dashboardsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(dashboards_); } } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public com.google.monitoring.dashboard.v1.Dashboard.Builder addDashboardsBuilder() { return getDashboardsFieldBuilder() .addBuilder(com.google.monitoring.dashboard.v1.Dashboard.getDefaultInstance()); } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public com.google.monitoring.dashboard.v1.Dashboard.Builder addDashboardsBuilder(int index) { return getDashboardsFieldBuilder() .addBuilder(index, com.google.monitoring.dashboard.v1.Dashboard.getDefaultInstance()); } /** * * * <pre> * The list of requested dashboards. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Dashboard dashboards = 1;</code> */ public java.util.List<com.google.monitoring.dashboard.v1.Dashboard.Builder> getDashboardsBuilderList() { return getDashboardsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.monitoring.dashboard.v1.Dashboard, com.google.monitoring.dashboard.v1.Dashboard.Builder, com.google.monitoring.dashboard.v1.DashboardOrBuilder> getDashboardsFieldBuilder() { if (dashboardsBuilder_ == null) { dashboardsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.monitoring.dashboard.v1.Dashboard, com.google.monitoring.dashboard.v1.Dashboard.Builder, com.google.monitoring.dashboard.v1.DashboardOrBuilder>( dashboards_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); dashboards_ = null; } return dashboardsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * If there are more results than have been returned, then this field is set * to a non-empty value. To see the additional results, * use that value as `page_token` in the next call to this method. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @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.dashboard.v1.ListDashboardsResponse) } // @@protoc_insertion_point(class_scope:google.monitoring.dashboard.v1.ListDashboardsResponse) private static final com.google.monitoring.dashboard.v1.ListDashboardsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.monitoring.dashboard.v1.ListDashboardsResponse(); } public static com.google.monitoring.dashboard.v1.ListDashboardsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListDashboardsResponse> PARSER = new com.google.protobuf.AbstractParser<ListDashboardsResponse>() { @java.lang.Override public ListDashboardsResponse 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<ListDashboardsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDashboardsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.monitoring.dashboard.v1.ListDashboardsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,557
java-aiplatform/google-cloud-aiplatform/src/main/java/com/google/cloud/aiplatform/v1beta1/MatchServiceClient.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.v1beta1; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.paging.AbstractFixedSizeCollection; import com.google.api.gax.paging.AbstractPage; import com.google.api.gax.paging.AbstractPagedListResponse; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.aiplatform.v1beta1.stub.MatchServiceStub; import com.google.cloud.aiplatform.v1beta1.stub.MatchServiceStubSettings; import com.google.cloud.location.GetLocationRequest; import com.google.cloud.location.ListLocationsRequest; import com.google.cloud.location.ListLocationsResponse; import com.google.cloud.location.Location; import com.google.common.util.concurrent.MoreExecutors; import com.google.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 java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: MatchService is a Google managed service for efficient vector similarity * search at scale. * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * FindNeighborsRequest request = * FindNeighborsRequest.newBuilder() * .setIndexEndpoint( * IndexEndpointName.of("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]").toString()) * .setDeployedIndexId("deployedIndexId-1101212953") * .addAllQueries(new ArrayList<FindNeighborsRequest.Query>()) * .setReturnFullDatapoint(true) * .build(); * FindNeighborsResponse response = matchServiceClient.findNeighbors(request); * } * }</pre> * * <p>Note: close() needs to be called on the MatchServiceClient object to clean up resources such * as threads. In the example above, try-with-resources is used, which automatically calls close(). * * <table> * <caption>Methods</caption> * <tr> * <th>Method</th> * <th>Description</th> * <th>Method Variants</th> * </tr> * <tr> * <td><p> FindNeighbors</td> * <td><p> Finds the nearest neighbors of each vector within the request.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> findNeighbors(FindNeighborsRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> findNeighborsCallable() * </ul> * </td> * </tr> * <tr> * <td><p> ReadIndexDatapoints</td> * <td><p> Reads the datapoints/vectors of the given IDs. A maximum of 1000 datapoints can be retrieved in a batch.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> readIndexDatapoints(ReadIndexDatapointsRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> readIndexDatapointsCallable() * </ul> * </td> * </tr> * <tr> * <td><p> ListLocations</td> * <td><p> Lists information about the supported locations for this service.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> listLocations(ListLocationsRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> listLocationsPagedCallable() * <li><p> listLocationsCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GetLocation</td> * <td><p> Gets information about a location.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> getLocation(GetLocationRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> getLocationCallable() * </ul> * </td> * </tr> * <tr> * <td><p> SetIamPolicy</td> * <td><p> Sets the access control policy on the specified resource. Replacesany existing policy. * <p> Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> setIamPolicy(SetIamPolicyRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> setIamPolicyCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GetIamPolicy</td> * <td><p> Gets the access control policy for a resource. Returns an empty policyif the resource exists and does not have a policy set.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> getIamPolicy(GetIamPolicyRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> getIamPolicyCallable() * </ul> * </td> * </tr> * <tr> * <td><p> TestIamPermissions</td> * <td><p> Returns permissions that a caller has on the specified resource. If theresource does not exist, this will return an empty set ofpermissions, not a `NOT_FOUND` error. * <p> Note: This operation is designed to be used for buildingpermission-aware UIs and command-line tools, not for authorizationchecking. This operation may "fail open" without warning.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> testIamPermissions(TestIamPermissionsRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> testIamPermissionsCallable() * </ul> * </td> * </tr> * </table> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of MatchServiceSettings to * create(). For example: * * <p>To customize credentials: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * MatchServiceSettings matchServiceSettings = * MatchServiceSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * MatchServiceClient matchServiceClient = MatchServiceClient.create(matchServiceSettings); * }</pre> * * <p>To customize the endpoint: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * MatchServiceSettings matchServiceSettings = * MatchServiceSettings.newBuilder().setEndpoint(myEndpoint).build(); * MatchServiceClient matchServiceClient = MatchServiceClient.create(matchServiceSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @BetaApi @Generated("by gapic-generator-java") public class MatchServiceClient implements BackgroundResource { private final MatchServiceSettings settings; private final MatchServiceStub stub; /** Constructs an instance of MatchServiceClient with default settings. */ public static final MatchServiceClient create() throws IOException { return create(MatchServiceSettings.newBuilder().build()); } /** * Constructs an instance of MatchServiceClient, using the given settings. The channels are * created based on the settings passed in, or defaults for any settings that are not set. */ public static final MatchServiceClient create(MatchServiceSettings settings) throws IOException { return new MatchServiceClient(settings); } /** * Constructs an instance of MatchServiceClient, using the given stub for making calls. This is * for advanced usage - prefer using create(MatchServiceSettings). */ public static final MatchServiceClient create(MatchServiceStub stub) { return new MatchServiceClient(stub); } /** * Constructs an instance of MatchServiceClient, using the given settings. This is protected so * that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected MatchServiceClient(MatchServiceSettings settings) throws IOException { this.settings = settings; this.stub = ((MatchServiceStubSettings) settings.getStubSettings()).createStub(); } protected MatchServiceClient(MatchServiceStub stub) { this.settings = null; this.stub = stub; } public final MatchServiceSettings getSettings() { return settings; } public MatchServiceStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Finds the nearest neighbors of each vector within the request. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * FindNeighborsRequest request = * FindNeighborsRequest.newBuilder() * .setIndexEndpoint( * IndexEndpointName.of("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]").toString()) * .setDeployedIndexId("deployedIndexId-1101212953") * .addAllQueries(new ArrayList<FindNeighborsRequest.Query>()) * .setReturnFullDatapoint(true) * .build(); * FindNeighborsResponse response = matchServiceClient.findNeighbors(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final FindNeighborsResponse findNeighbors(FindNeighborsRequest request) { return findNeighborsCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Finds the nearest neighbors of each vector within the request. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * FindNeighborsRequest request = * FindNeighborsRequest.newBuilder() * .setIndexEndpoint( * IndexEndpointName.of("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]").toString()) * .setDeployedIndexId("deployedIndexId-1101212953") * .addAllQueries(new ArrayList<FindNeighborsRequest.Query>()) * .setReturnFullDatapoint(true) * .build(); * ApiFuture<FindNeighborsResponse> future = * matchServiceClient.findNeighborsCallable().futureCall(request); * // Do something. * FindNeighborsResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<FindNeighborsRequest, FindNeighborsResponse> findNeighborsCallable() { return stub.findNeighborsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Reads the datapoints/vectors of the given IDs. A maximum of 1000 datapoints can be retrieved in * a batch. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * ReadIndexDatapointsRequest request = * ReadIndexDatapointsRequest.newBuilder() * .setIndexEndpoint( * IndexEndpointName.of("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]").toString()) * .setDeployedIndexId("deployedIndexId-1101212953") * .addAllIds(new ArrayList<String>()) * .build(); * ReadIndexDatapointsResponse response = matchServiceClient.readIndexDatapoints(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ReadIndexDatapointsResponse readIndexDatapoints(ReadIndexDatapointsRequest request) { return readIndexDatapointsCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Reads the datapoints/vectors of the given IDs. A maximum of 1000 datapoints can be retrieved in * a batch. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * ReadIndexDatapointsRequest request = * ReadIndexDatapointsRequest.newBuilder() * .setIndexEndpoint( * IndexEndpointName.of("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]").toString()) * .setDeployedIndexId("deployedIndexId-1101212953") * .addAllIds(new ArrayList<String>()) * .build(); * ApiFuture<ReadIndexDatapointsResponse> future = * matchServiceClient.readIndexDatapointsCallable().futureCall(request); * // Do something. * ReadIndexDatapointsResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<ReadIndexDatapointsRequest, ReadIndexDatapointsResponse> readIndexDatapointsCallable() { return stub.readIndexDatapointsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists information about the supported locations for this service. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * ListLocationsRequest request = * ListLocationsRequest.newBuilder() * .setName("name3373707") * .setFilter("filter-1274492040") * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * for (Location element : matchServiceClient.listLocations(request).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListLocationsPagedResponse listLocations(ListLocationsRequest request) { return listLocationsPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists information about the supported locations for this service. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * ListLocationsRequest request = * ListLocationsRequest.newBuilder() * .setName("name3373707") * .setFilter("filter-1274492040") * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * ApiFuture<Location> future = * matchServiceClient.listLocationsPagedCallable().futureCall(request); * // Do something. * for (Location element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse> listLocationsPagedCallable() { return stub.listLocationsPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists information about the supported locations for this service. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * ListLocationsRequest request = * ListLocationsRequest.newBuilder() * .setName("name3373707") * .setFilter("filter-1274492040") * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * while (true) { * ListLocationsResponse response = matchServiceClient.listLocationsCallable().call(request); * for (Location element : response.getLocationsList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() { return stub.listLocationsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets information about a location. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build(); * Location response = matchServiceClient.getLocation(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Location getLocation(GetLocationRequest request) { return getLocationCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets information about a location. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build(); * ApiFuture<Location> future = matchServiceClient.getLocationCallable().futureCall(request); * // Do something. * Location response = future.get(); * } * }</pre> */ public final UnaryCallable<GetLocationRequest, Location> getLocationCallable() { return stub.getLocationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Sets the access control policy on the specified resource. Replacesany existing policy. * * <p>Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * SetIamPolicyRequest request = * SetIamPolicyRequest.newBuilder() * .setResource( * EndpointName.ofProjectLocationEndpointName( * "[PROJECT]", "[LOCATION]", "[ENDPOINT]") * .toString()) * .setPolicy(Policy.newBuilder().build()) * .setUpdateMask(FieldMask.newBuilder().build()) * .build(); * Policy response = matchServiceClient.setIamPolicy(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Policy setIamPolicy(SetIamPolicyRequest request) { return setIamPolicyCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Sets the access control policy on the specified resource. Replacesany existing policy. * * <p>Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * SetIamPolicyRequest request = * SetIamPolicyRequest.newBuilder() * .setResource( * EndpointName.ofProjectLocationEndpointName( * "[PROJECT]", "[LOCATION]", "[ENDPOINT]") * .toString()) * .setPolicy(Policy.newBuilder().build()) * .setUpdateMask(FieldMask.newBuilder().build()) * .build(); * ApiFuture<Policy> future = matchServiceClient.setIamPolicyCallable().futureCall(request); * // Do something. * Policy response = future.get(); * } * }</pre> */ public final UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable() { return stub.setIamPolicyCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets the access control policy for a resource. Returns an empty policyif the resource exists * and does not have a policy set. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * GetIamPolicyRequest request = * GetIamPolicyRequest.newBuilder() * .setResource( * EndpointName.ofProjectLocationEndpointName( * "[PROJECT]", "[LOCATION]", "[ENDPOINT]") * .toString()) * .setOptions(GetPolicyOptions.newBuilder().build()) * .build(); * Policy response = matchServiceClient.getIamPolicy(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Policy getIamPolicy(GetIamPolicyRequest request) { return getIamPolicyCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets the access control policy for a resource. Returns an empty policyif the resource exists * and does not have a policy set. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * GetIamPolicyRequest request = * GetIamPolicyRequest.newBuilder() * .setResource( * EndpointName.ofProjectLocationEndpointName( * "[PROJECT]", "[LOCATION]", "[ENDPOINT]") * .toString()) * .setOptions(GetPolicyOptions.newBuilder().build()) * .build(); * ApiFuture<Policy> future = matchServiceClient.getIamPolicyCallable().futureCall(request); * // Do something. * Policy response = future.get(); * } * }</pre> */ public final UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable() { return stub.getIamPolicyCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns permissions that a caller has on the specified resource. If theresource does not exist, * this will return an empty set ofpermissions, not a `NOT_FOUND` error. * * <p>Note: This operation is designed to be used for buildingpermission-aware UIs and * command-line tools, not for authorizationchecking. This operation may "fail open" without * warning. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * TestIamPermissionsRequest request = * TestIamPermissionsRequest.newBuilder() * .setResource( * EndpointName.ofProjectLocationEndpointName( * "[PROJECT]", "[LOCATION]", "[ENDPOINT]") * .toString()) * .addAllPermissions(new ArrayList<String>()) * .build(); * TestIamPermissionsResponse response = matchServiceClient.testIamPermissions(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final TestIamPermissionsResponse testIamPermissions(TestIamPermissionsRequest request) { return testIamPermissionsCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns permissions that a caller has on the specified resource. If theresource does not exist, * this will return an empty set ofpermissions, not a `NOT_FOUND` error. * * <p>Note: This operation is designed to be used for buildingpermission-aware UIs and * command-line tools, not for authorizationchecking. This operation may "fail open" without * warning. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (MatchServiceClient matchServiceClient = MatchServiceClient.create()) { * TestIamPermissionsRequest request = * TestIamPermissionsRequest.newBuilder() * .setResource( * EndpointName.ofProjectLocationEndpointName( * "[PROJECT]", "[LOCATION]", "[ENDPOINT]") * .toString()) * .addAllPermissions(new ArrayList<String>()) * .build(); * ApiFuture<TestIamPermissionsResponse> future = * matchServiceClient.testIamPermissionsCallable().futureCall(request); * // Do something. * TestIamPermissionsResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsCallable() { return stub.testIamPermissionsCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } public static class ListLocationsPagedResponse extends AbstractPagedListResponse< ListLocationsRequest, ListLocationsResponse, Location, ListLocationsPage, ListLocationsFixedSizeCollection> { public static ApiFuture<ListLocationsPagedResponse> createAsync( PageContext<ListLocationsRequest, ListLocationsResponse, Location> context, ApiFuture<ListLocationsResponse> futureResponse) { ApiFuture<ListLocationsPage> futurePage = ListLocationsPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new ListLocationsPagedResponse(input), MoreExecutors.directExecutor()); } private ListLocationsPagedResponse(ListLocationsPage page) { super(page, ListLocationsFixedSizeCollection.createEmptyCollection()); } } public static class ListLocationsPage extends AbstractPage< ListLocationsRequest, ListLocationsResponse, Location, ListLocationsPage> { private ListLocationsPage( PageContext<ListLocationsRequest, ListLocationsResponse, Location> context, ListLocationsResponse response) { super(context, response); } private static ListLocationsPage createEmptyPage() { return new ListLocationsPage(null, null); } @Override protected ListLocationsPage createPage( PageContext<ListLocationsRequest, ListLocationsResponse, Location> context, ListLocationsResponse response) { return new ListLocationsPage(context, response); } @Override public ApiFuture<ListLocationsPage> createPageAsync( PageContext<ListLocationsRequest, ListLocationsResponse, Location> context, ApiFuture<ListLocationsResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class ListLocationsFixedSizeCollection extends AbstractFixedSizeCollection< ListLocationsRequest, ListLocationsResponse, Location, ListLocationsPage, ListLocationsFixedSizeCollection> { private ListLocationsFixedSizeCollection(List<ListLocationsPage> pages, int collectionSize) { super(pages, collectionSize); } private static ListLocationsFixedSizeCollection createEmptyCollection() { return new ListLocationsFixedSizeCollection(null, 0); } @Override protected ListLocationsFixedSizeCollection createCollection( List<ListLocationsPage> pages, int collectionSize) { return new ListLocationsFixedSizeCollection(pages, collectionSize); } } }
openjdk/jdk8
37,768
jdk/src/share/classes/java/util/Spliterator.java
/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.util.function.Consumer; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; import java.util.function.LongConsumer; /** * An object for traversing and partitioning elements of a source. The source * of elements covered by a Spliterator could be, for example, an array, a * {@link Collection}, an IO channel, or a generator function. * * <p>A Spliterator may traverse elements individually ({@link * #tryAdvance tryAdvance()}) or sequentially in bulk * ({@link #forEachRemaining forEachRemaining()}). * * <p>A Spliterator may also partition off some of its elements (using * {@link #trySplit}) as another Spliterator, to be used in * possibly-parallel operations. Operations using a Spliterator that * cannot split, or does so in a highly imbalanced or inefficient * manner, are unlikely to benefit from parallelism. Traversal * and splitting exhaust elements; each Spliterator is useful for only a single * bulk computation. * * <p>A Spliterator also reports a set of {@link #characteristics()} of its * structure, source, and elements from among {@link #ORDERED}, * {@link #DISTINCT}, {@link #SORTED}, {@link #SIZED}, {@link #NONNULL}, * {@link #IMMUTABLE}, {@link #CONCURRENT}, and {@link #SUBSIZED}. These may * be employed by Spliterator clients to control, specialize or simplify * computation. For example, a Spliterator for a {@link Collection} would * report {@code SIZED}, a Spliterator for a {@link Set} would report * {@code DISTINCT}, and a Spliterator for a {@link SortedSet} would also * report {@code SORTED}. Characteristics are reported as a simple unioned bit * set. * * Some characteristics additionally constrain method behavior; for example if * {@code ORDERED}, traversal methods must conform to their documented ordering. * New characteristics may be defined in the future, so implementors should not * assign meanings to unlisted values. * * <p><a name="binding">A Spliterator that does not report {@code IMMUTABLE} or * {@code CONCURRENT} is expected to have a documented policy concerning: * when the spliterator <em>binds</em> to the element source; and detection of * structural interference of the element source detected after binding.</a> A * <em>late-binding</em> Spliterator binds to the source of elements at the * point of first traversal, first split, or first query for estimated size, * rather than at the time the Spliterator is created. A Spliterator that is * not <em>late-binding</em> binds to the source of elements at the point of * construction or first invocation of any method. Modifications made to the * source prior to binding are reflected when the Spliterator is traversed. * After binding a Spliterator should, on a best-effort basis, throw * {@link ConcurrentModificationException} if structural interference is * detected. Spliterators that do this are called <em>fail-fast</em>. The * bulk traversal method ({@link #forEachRemaining forEachRemaining()}) of a * Spliterator may optimize traversal and check for structural interference * after all elements have been traversed, rather than checking per-element and * failing immediately. * * <p>Spliterators can provide an estimate of the number of remaining elements * via the {@link #estimateSize} method. Ideally, as reflected in characteristic * {@link #SIZED}, this value corresponds exactly to the number of elements * that would be encountered in a successful traversal. However, even when not * exactly known, an estimated value value may still be useful to operations * being performed on the source, such as helping to determine whether it is * preferable to split further or traverse the remaining elements sequentially. * * <p>Despite their obvious utility in parallel algorithms, spliterators are not * expected to be thread-safe; instead, implementations of parallel algorithms * using spliterators should ensure that the spliterator is only used by one * thread at a time. This is generally easy to attain via <em>serial * thread-confinement</em>, which often is a natural consequence of typical * parallel algorithms that work by recursive decomposition. A thread calling * {@link #trySplit()} may hand over the returned Spliterator to another thread, * which in turn may traverse or further split that Spliterator. The behaviour * of splitting and traversal is undefined if two or more threads operate * concurrently on the same spliterator. If the original thread hands a * spliterator off to another thread for processing, it is best if that handoff * occurs before any elements are consumed with {@link #tryAdvance(Consumer) * tryAdvance()}, as certain guarantees (such as the accuracy of * {@link #estimateSize()} for {@code SIZED} spliterators) are only valid before * traversal has begun. * * <p>Primitive subtype specializations of {@code Spliterator} are provided for * {@link OfInt int}, {@link OfLong long}, and {@link OfDouble double} values. * The subtype default implementations of * {@link Spliterator#tryAdvance(java.util.function.Consumer)} * and {@link Spliterator#forEachRemaining(java.util.function.Consumer)} box * primitive values to instances of their corresponding wrapper class. Such * boxing may undermine any performance advantages gained by using the primitive * specializations. To avoid boxing, the corresponding primitive-based methods * should be used. For example, * {@link Spliterator.OfInt#tryAdvance(java.util.function.IntConsumer)} * and {@link Spliterator.OfInt#forEachRemaining(java.util.function.IntConsumer)} * should be used in preference to * {@link Spliterator.OfInt#tryAdvance(java.util.function.Consumer)} and * {@link Spliterator.OfInt#forEachRemaining(java.util.function.Consumer)}. * Traversal of primitive values using boxing-based methods * {@link #tryAdvance tryAdvance()} and * {@link #forEachRemaining(java.util.function.Consumer) forEachRemaining()} * does not affect the order in which the values, transformed to boxed values, * are encountered. * * @apiNote * <p>Spliterators, like {@code Iterators}s, are for traversing the elements of * a source. The {@code Spliterator} API was designed to support efficient * parallel traversal in addition to sequential traversal, by supporting * decomposition as well as single-element iteration. In addition, the * protocol for accessing elements via a Spliterator is designed to impose * smaller per-element overhead than {@code Iterator}, and to avoid the inherent * race involved in having separate methods for {@code hasNext()} and * {@code next()}. * * <p>For mutable sources, arbitrary and non-deterministic behavior may occur if * the source is structurally interfered with (elements added, replaced, or * removed) between the time that the Spliterator binds to its data source and * the end of traversal. For example, such interference will produce arbitrary, * non-deterministic results when using the {@code java.util.stream} framework. * * <p>Structural interference of a source can be managed in the following ways * (in approximate order of decreasing desirability): * <ul> * <li>The source cannot be structurally interfered with. * <br>For example, an instance of * {@link java.util.concurrent.CopyOnWriteArrayList} is an immutable source. * A Spliterator created from the source reports a characteristic of * {@code IMMUTABLE}.</li> * <li>The source manages concurrent modifications. * <br>For example, a key set of a {@link java.util.concurrent.ConcurrentHashMap} * is a concurrent source. A Spliterator created from the source reports a * characteristic of {@code CONCURRENT}.</li> * <li>The mutable source provides a late-binding and fail-fast Spliterator. * <br>Late binding narrows the window during which interference can affect * the calculation; fail-fast detects, on a best-effort basis, that structural * interference has occurred after traversal has commenced and throws * {@link ConcurrentModificationException}. For example, {@link ArrayList}, * and many other non-concurrent {@code Collection} classes in the JDK, provide * a late-binding, fail-fast spliterator.</li> * <li>The mutable source provides a non-late-binding but fail-fast Spliterator. * <br>The source increases the likelihood of throwing * {@code ConcurrentModificationException} since the window of potential * interference is larger.</li> * <li>The mutable source provides a late-binding and non-fail-fast Spliterator. * <br>The source risks arbitrary, non-deterministic behavior after traversal * has commenced since interference is not detected. * </li> * <li>The mutable source provides a non-late-binding and non-fail-fast * Spliterator. * <br>The source increases the risk of arbitrary, non-deterministic behavior * since non-detected interference may occur after construction. * </li> * </ul> * * <p><b>Example.</b> Here is a class (not a very useful one, except * for illustration) that maintains an array in which the actual data * are held in even locations, and unrelated tag data are held in odd * locations. Its Spliterator ignores the tags. * * <pre> {@code * class TaggedArray<T> { * private final Object[] elements; // immutable after construction * TaggedArray(T[] data, Object[] tags) { * int size = data.length; * if (tags.length != size) throw new IllegalArgumentException(); * this.elements = new Object[2 * size]; * for (int i = 0, j = 0; i < size; ++i) { * elements[j++] = data[i]; * elements[j++] = tags[i]; * } * } * * public Spliterator<T> spliterator() { * return new TaggedArraySpliterator<>(elements, 0, elements.length); * } * * static class TaggedArraySpliterator<T> implements Spliterator<T> { * private final Object[] array; * private int origin; // current index, advanced on split or traversal * private final int fence; // one past the greatest index * * TaggedArraySpliterator(Object[] array, int origin, int fence) { * this.array = array; this.origin = origin; this.fence = fence; * } * * public void forEachRemaining(Consumer<? super T> action) { * for (; origin < fence; origin += 2) * action.accept((T) array[origin]); * } * * public boolean tryAdvance(Consumer<? super T> action) { * if (origin < fence) { * action.accept((T) array[origin]); * origin += 2; * return true; * } * else // cannot advance * return false; * } * * public Spliterator<T> trySplit() { * int lo = origin; // divide range in half * int mid = ((lo + fence) >>> 1) & ~1; // force midpoint to be even * if (lo < mid) { // split out left half * origin = mid; // reset this Spliterator's origin * return new TaggedArraySpliterator<>(array, lo, mid); * } * else // too small to split * return null; * } * * public long estimateSize() { * return (long)((fence - origin) / 2); * } * * public int characteristics() { * return ORDERED | SIZED | IMMUTABLE | SUBSIZED; * } * } * }}</pre> * * <p>As an example how a parallel computation framework, such as the * {@code java.util.stream} package, would use Spliterator in a parallel * computation, here is one way to implement an associated parallel forEach, * that illustrates the primary usage idiom of splitting off subtasks until * the estimated amount of work is small enough to perform * sequentially. Here we assume that the order of processing across * subtasks doesn't matter; different (forked) tasks may further split * and process elements concurrently in undetermined order. This * example uses a {@link java.util.concurrent.CountedCompleter}; * similar usages apply to other parallel task constructions. * * <pre>{@code * static <T> void parEach(TaggedArray<T> a, Consumer<T> action) { * Spliterator<T> s = a.spliterator(); * long targetBatchSize = s.estimateSize() / (ForkJoinPool.getCommonPoolParallelism() * 8); * new ParEach(null, s, action, targetBatchSize).invoke(); * } * * static class ParEach<T> extends CountedCompleter<Void> { * final Spliterator<T> spliterator; * final Consumer<T> action; * final long targetBatchSize; * * ParEach(ParEach<T> parent, Spliterator<T> spliterator, * Consumer<T> action, long targetBatchSize) { * super(parent); * this.spliterator = spliterator; this.action = action; * this.targetBatchSize = targetBatchSize; * } * * public void compute() { * Spliterator<T> sub; * while (spliterator.estimateSize() > targetBatchSize && * (sub = spliterator.trySplit()) != null) { * addToPendingCount(1); * new ParEach<>(this, sub, action, targetBatchSize).fork(); * } * spliterator.forEachRemaining(action); * propagateCompletion(); * } * }}</pre> * * @implNote * If the boolean system property {@code org.openjdk.java.util.stream.tripwire} * is set to {@code true} then diagnostic warnings are reported if boxing of * primitive values occur when operating on primitive subtype specializations. * * @param <T> the type of elements returned by this Spliterator * * @see Collection * @since 1.8 */ public interface Spliterator<T> { /** * If a remaining element exists, performs the given action on it, * returning {@code true}; else returns {@code false}. If this * Spliterator is {@link #ORDERED} the action is performed on the * next element in encounter order. Exceptions thrown by the * action are relayed to the caller. * * @param action The action * @return {@code false} if no remaining elements existed * upon entry to this method, else {@code true}. * @throws NullPointerException if the specified action is null */ boolean tryAdvance(Consumer<? super T> action); /** * Performs the given action for each remaining element, sequentially in * the current thread, until all elements have been processed or the action * throws an exception. If this Spliterator is {@link #ORDERED}, actions * are performed in encounter order. Exceptions thrown by the action * are relayed to the caller. * * @implSpec * The default implementation repeatedly invokes {@link #tryAdvance} until * it returns {@code false}. It should be overridden whenever possible. * * @param action The action * @throws NullPointerException if the specified action is null */ default void forEachRemaining(Consumer<? super T> action) { do { } while (tryAdvance(action)); } /** * If this spliterator can be partitioned, returns a Spliterator * covering elements, that will, upon return from this method, not * be covered by this Spliterator. * * <p>If this Spliterator is {@link #ORDERED}, the returned Spliterator * must cover a strict prefix of the elements. * * <p>Unless this Spliterator covers an infinite number of elements, * repeated calls to {@code trySplit()} must eventually return {@code null}. * Upon non-null return: * <ul> * <li>the value reported for {@code estimateSize()} before splitting, * must, after splitting, be greater than or equal to {@code estimateSize()} * for this and the returned Spliterator; and</li> * <li>if this Spliterator is {@code SUBSIZED}, then {@code estimateSize()} * for this spliterator before splitting must be equal to the sum of * {@code estimateSize()} for this and the returned Spliterator after * splitting.</li> * </ul> * * <p>This method may return {@code null} for any reason, * including emptiness, inability to split after traversal has * commenced, data structure constraints, and efficiency * considerations. * * @apiNote * An ideal {@code trySplit} method efficiently (without * traversal) divides its elements exactly in half, allowing * balanced parallel computation. Many departures from this ideal * remain highly effective; for example, only approximately * splitting an approximately balanced tree, or for a tree in * which leaf nodes may contain either one or two elements, * failing to further split these nodes. However, large * deviations in balance and/or overly inefficient {@code * trySplit} mechanics typically result in poor parallel * performance. * * @return a {@code Spliterator} covering some portion of the * elements, or {@code null} if this spliterator cannot be split */ Spliterator<T> trySplit(); /** * Returns an estimate of the number of elements that would be * encountered by a {@link #forEachRemaining} traversal, or returns {@link * Long#MAX_VALUE} if infinite, unknown, or too expensive to compute. * * <p>If this Spliterator is {@link #SIZED} and has not yet been partially * traversed or split, or this Spliterator is {@link #SUBSIZED} and has * not yet been partially traversed, this estimate must be an accurate * count of elements that would be encountered by a complete traversal. * Otherwise, this estimate may be arbitrarily inaccurate, but must decrease * as specified across invocations of {@link #trySplit}. * * @apiNote * Even an inexact estimate is often useful and inexpensive to compute. * For example, a sub-spliterator of an approximately balanced binary tree * may return a value that estimates the number of elements to be half of * that of its parent; if the root Spliterator does not maintain an * accurate count, it could estimate size to be the power of two * corresponding to its maximum depth. * * @return the estimated size, or {@code Long.MAX_VALUE} if infinite, * unknown, or too expensive to compute. */ long estimateSize(); /** * Convenience method that returns {@link #estimateSize()} if this * Spliterator is {@link #SIZED}, else {@code -1}. * @implSpec * The default implementation returns the result of {@code estimateSize()} * if the Spliterator reports a characteristic of {@code SIZED}, and * {@code -1} otherwise. * * @return the exact size, if known, else {@code -1}. */ default long getExactSizeIfKnown() { return (characteristics() & SIZED) == 0 ? -1L : estimateSize(); } /** * Returns a set of characteristics of this Spliterator and its * elements. The result is represented as ORed values from {@link * #ORDERED}, {@link #DISTINCT}, {@link #SORTED}, {@link #SIZED}, * {@link #NONNULL}, {@link #IMMUTABLE}, {@link #CONCURRENT}, * {@link #SUBSIZED}. Repeated calls to {@code characteristics()} on * a given spliterator, prior to or in-between calls to {@code trySplit}, * should always return the same result. * * <p>If a Spliterator reports an inconsistent set of * characteristics (either those returned from a single invocation * or across multiple invocations), no guarantees can be made * about any computation using this Spliterator. * * @apiNote The characteristics of a given spliterator before splitting * may differ from the characteristics after splitting. For specific * examples see the characteristic values {@link #SIZED}, {@link #SUBSIZED} * and {@link #CONCURRENT}. * * @return a representation of characteristics */ int characteristics(); /** * Returns {@code true} if this Spliterator's {@link * #characteristics} contain all of the given characteristics. * * @implSpec * The default implementation returns true if the corresponding bits * of the given characteristics are set. * * @param characteristics the characteristics to check for * @return {@code true} if all the specified characteristics are present, * else {@code false} */ default boolean hasCharacteristics(int characteristics) { return (characteristics() & characteristics) == characteristics; } /** * If this Spliterator's source is {@link #SORTED} by a {@link Comparator}, * returns that {@code Comparator}. If the source is {@code SORTED} in * {@linkplain Comparable natural order}, returns {@code null}. Otherwise, * if the source is not {@code SORTED}, throws {@link IllegalStateException}. * * @implSpec * The default implementation always throws {@link IllegalStateException}. * * @return a Comparator, or {@code null} if the elements are sorted in the * natural order. * @throws IllegalStateException if the spliterator does not report * a characteristic of {@code SORTED}. */ default Comparator<? super T> getComparator() { throw new IllegalStateException(); } /** * Characteristic value signifying that an encounter order is defined for * elements. If so, this Spliterator guarantees that method * {@link #trySplit} splits a strict prefix of elements, that method * {@link #tryAdvance} steps by one element in prefix order, and that * {@link #forEachRemaining} performs actions in encounter order. * * <p>A {@link Collection} has an encounter order if the corresponding * {@link Collection#iterator} documents an order. If so, the encounter * order is the same as the documented order. Otherwise, a collection does * not have an encounter order. * * @apiNote Encounter order is guaranteed to be ascending index order for * any {@link List}. But no order is guaranteed for hash-based collections * such as {@link HashSet}. Clients of a Spliterator that reports * {@code ORDERED} are expected to preserve ordering constraints in * non-commutative parallel computations. */ public static final int ORDERED = 0x00000010; /** * Characteristic value signifying that, for each pair of * encountered elements {@code x, y}, {@code !x.equals(y)}. This * applies for example, to a Spliterator based on a {@link Set}. */ public static final int DISTINCT = 0x00000001; /** * Characteristic value signifying that encounter order follows a defined * sort order. If so, method {@link #getComparator()} returns the associated * Comparator, or {@code null} if all elements are {@link Comparable} and * are sorted by their natural ordering. * * <p>A Spliterator that reports {@code SORTED} must also report * {@code ORDERED}. * * @apiNote The spliterators for {@code Collection} classes in the JDK that * implement {@link NavigableSet} or {@link SortedSet} report {@code SORTED}. */ public static final int SORTED = 0x00000004; /** * Characteristic value signifying that the value returned from * {@code estimateSize()} prior to traversal or splitting represents a * finite size that, in the absence of structural source modification, * represents an exact count of the number of elements that would be * encountered by a complete traversal. * * @apiNote Most Spliterators for Collections, that cover all elements of a * {@code Collection} report this characteristic. Sub-spliterators, such as * those for {@link HashSet}, that cover a sub-set of elements and * approximate their reported size do not. */ public static final int SIZED = 0x00000040; /** * Characteristic value signifying that the source guarantees that * encountered elements will not be {@code null}. (This applies, * for example, to most concurrent collections, queues, and maps.) */ public static final int NONNULL = 0x00000100; /** * Characteristic value signifying that the element source cannot be * structurally modified; that is, elements cannot be added, replaced, or * removed, so such changes cannot occur during traversal. A Spliterator * that does not report {@code IMMUTABLE} or {@code CONCURRENT} is expected * to have a documented policy (for example throwing * {@link ConcurrentModificationException}) concerning structural * interference detected during traversal. */ public static final int IMMUTABLE = 0x00000400; /** * Characteristic value signifying that the element source may be safely * concurrently modified (allowing additions, replacements, and/or removals) * by multiple threads without external synchronization. If so, the * Spliterator is expected to have a documented policy concerning the impact * of modifications during traversal. * * <p>A top-level Spliterator should not report both {@code CONCURRENT} and * {@code SIZED}, since the finite size, if known, may change if the source * is concurrently modified during traversal. Such a Spliterator is * inconsistent and no guarantees can be made about any computation using * that Spliterator. Sub-spliterators may report {@code SIZED} if the * sub-split size is known and additions or removals to the source are not * reflected when traversing. * * @apiNote Most concurrent collections maintain a consistency policy * guaranteeing accuracy with respect to elements present at the point of * Spliterator construction, but possibly not reflecting subsequent * additions or removals. */ public static final int CONCURRENT = 0x00001000; /** * Characteristic value signifying that all Spliterators resulting from * {@code trySplit()} will be both {@link #SIZED} and {@link #SUBSIZED}. * (This means that all child Spliterators, whether direct or indirect, will * be {@code SIZED}.) * * <p>A Spliterator that does not report {@code SIZED} as required by * {@code SUBSIZED} is inconsistent and no guarantees can be made about any * computation using that Spliterator. * * @apiNote Some spliterators, such as the top-level spliterator for an * approximately balanced binary tree, will report {@code SIZED} but not * {@code SUBSIZED}, since it is common to know the size of the entire tree * but not the exact sizes of subtrees. */ public static final int SUBSIZED = 0x00004000; /** * A Spliterator specialized for primitive values. * * @param <T> the type of elements returned by this Spliterator. The * type must be a wrapper type for a primitive type, such as {@code Integer} * for the primitive {@code int} type. * @param <T_CONS> the type of primitive consumer. The type must be a * primitive specialization of {@link java.util.function.Consumer} for * {@code T}, such as {@link java.util.function.IntConsumer} for * {@code Integer}. * @param <T_SPLITR> the type of primitive Spliterator. The type must be * a primitive specialization of Spliterator for {@code T}, such as * {@link Spliterator.OfInt} for {@code Integer}. * * @see Spliterator.OfInt * @see Spliterator.OfLong * @see Spliterator.OfDouble * @since 1.8 */ public interface OfPrimitive<T, T_CONS, T_SPLITR extends Spliterator.OfPrimitive<T, T_CONS, T_SPLITR>> extends Spliterator<T> { @Override T_SPLITR trySplit(); /** * If a remaining element exists, performs the given action on it, * returning {@code true}; else returns {@code false}. If this * Spliterator is {@link #ORDERED} the action is performed on the * next element in encounter order. Exceptions thrown by the * action are relayed to the caller. * * @param action The action * @return {@code false} if no remaining elements existed * upon entry to this method, else {@code true}. * @throws NullPointerException if the specified action is null */ @SuppressWarnings("overloads") boolean tryAdvance(T_CONS action); /** * Performs the given action for each remaining element, sequentially in * the current thread, until all elements have been processed or the * action throws an exception. If this Spliterator is {@link #ORDERED}, * actions are performed in encounter order. Exceptions thrown by the * action are relayed to the caller. * * @implSpec * The default implementation repeatedly invokes {@link #tryAdvance} * until it returns {@code false}. It should be overridden whenever * possible. * * @param action The action * @throws NullPointerException if the specified action is null */ @SuppressWarnings("overloads") default void forEachRemaining(T_CONS action) { do { } while (tryAdvance(action)); } } /** * A Spliterator specialized for {@code int} values. * @since 1.8 */ public interface OfInt extends OfPrimitive<Integer, IntConsumer, OfInt> { @Override OfInt trySplit(); @Override boolean tryAdvance(IntConsumer action); @Override default void forEachRemaining(IntConsumer action) { do { } while (tryAdvance(action)); } /** * {@inheritDoc} * @implSpec * If the action is an instance of {@code IntConsumer} then it is cast * to {@code IntConsumer} and passed to * {@link #tryAdvance(java.util.function.IntConsumer)}; otherwise * the action is adapted to an instance of {@code IntConsumer}, by * boxing the argument of {@code IntConsumer}, and then passed to * {@link #tryAdvance(java.util.function.IntConsumer)}. */ @Override default boolean tryAdvance(Consumer<? super Integer> action) { if (action instanceof IntConsumer) { return tryAdvance((IntConsumer) action); } else { if (Tripwire.ENABLED) Tripwire.trip(getClass(), "{0} calling Spliterator.OfInt.tryAdvance((IntConsumer) action::accept)"); return tryAdvance((IntConsumer) action::accept); } } /** * {@inheritDoc} * @implSpec * If the action is an instance of {@code IntConsumer} then it is cast * to {@code IntConsumer} and passed to * {@link #forEachRemaining(java.util.function.IntConsumer)}; otherwise * the action is adapted to an instance of {@code IntConsumer}, by * boxing the argument of {@code IntConsumer}, and then passed to * {@link #forEachRemaining(java.util.function.IntConsumer)}. */ @Override default void forEachRemaining(Consumer<? super Integer> action) { if (action instanceof IntConsumer) { forEachRemaining((IntConsumer) action); } else { if (Tripwire.ENABLED) Tripwire.trip(getClass(), "{0} calling Spliterator.OfInt.forEachRemaining((IntConsumer) action::accept)"); forEachRemaining((IntConsumer) action::accept); } } } /** * A Spliterator specialized for {@code long} values. * @since 1.8 */ public interface OfLong extends OfPrimitive<Long, LongConsumer, OfLong> { @Override OfLong trySplit(); @Override boolean tryAdvance(LongConsumer action); @Override default void forEachRemaining(LongConsumer action) { do { } while (tryAdvance(action)); } /** * {@inheritDoc} * @implSpec * If the action is an instance of {@code LongConsumer} then it is cast * to {@code LongConsumer} and passed to * {@link #tryAdvance(java.util.function.LongConsumer)}; otherwise * the action is adapted to an instance of {@code LongConsumer}, by * boxing the argument of {@code LongConsumer}, and then passed to * {@link #tryAdvance(java.util.function.LongConsumer)}. */ @Override default boolean tryAdvance(Consumer<? super Long> action) { if (action instanceof LongConsumer) { return tryAdvance((LongConsumer) action); } else { if (Tripwire.ENABLED) Tripwire.trip(getClass(), "{0} calling Spliterator.OfLong.tryAdvance((LongConsumer) action::accept)"); return tryAdvance((LongConsumer) action::accept); } } /** * {@inheritDoc} * @implSpec * If the action is an instance of {@code LongConsumer} then it is cast * to {@code LongConsumer} and passed to * {@link #forEachRemaining(java.util.function.LongConsumer)}; otherwise * the action is adapted to an instance of {@code LongConsumer}, by * boxing the argument of {@code LongConsumer}, and then passed to * {@link #forEachRemaining(java.util.function.LongConsumer)}. */ @Override default void forEachRemaining(Consumer<? super Long> action) { if (action instanceof LongConsumer) { forEachRemaining((LongConsumer) action); } else { if (Tripwire.ENABLED) Tripwire.trip(getClass(), "{0} calling Spliterator.OfLong.forEachRemaining((LongConsumer) action::accept)"); forEachRemaining((LongConsumer) action::accept); } } } /** * A Spliterator specialized for {@code double} values. * @since 1.8 */ public interface OfDouble extends OfPrimitive<Double, DoubleConsumer, OfDouble> { @Override OfDouble trySplit(); @Override boolean tryAdvance(DoubleConsumer action); @Override default void forEachRemaining(DoubleConsumer action) { do { } while (tryAdvance(action)); } /** * {@inheritDoc} * @implSpec * If the action is an instance of {@code DoubleConsumer} then it is * cast to {@code DoubleConsumer} and passed to * {@link #tryAdvance(java.util.function.DoubleConsumer)}; otherwise * the action is adapted to an instance of {@code DoubleConsumer}, by * boxing the argument of {@code DoubleConsumer}, and then passed to * {@link #tryAdvance(java.util.function.DoubleConsumer)}. */ @Override default boolean tryAdvance(Consumer<? super Double> action) { if (action instanceof DoubleConsumer) { return tryAdvance((DoubleConsumer) action); } else { if (Tripwire.ENABLED) Tripwire.trip(getClass(), "{0} calling Spliterator.OfDouble.tryAdvance((DoubleConsumer) action::accept)"); return tryAdvance((DoubleConsumer) action::accept); } } /** * {@inheritDoc} * @implSpec * If the action is an instance of {@code DoubleConsumer} then it is * cast to {@code DoubleConsumer} and passed to * {@link #forEachRemaining(java.util.function.DoubleConsumer)}; * otherwise the action is adapted to an instance of * {@code DoubleConsumer}, by boxing the argument of * {@code DoubleConsumer}, and then passed to * {@link #forEachRemaining(java.util.function.DoubleConsumer)}. */ @Override default void forEachRemaining(Consumer<? super Double> action) { if (action instanceof DoubleConsumer) { forEachRemaining((DoubleConsumer) action); } else { if (Tripwire.ENABLED) Tripwire.trip(getClass(), "{0} calling Spliterator.OfDouble.forEachRemaining((DoubleConsumer) action::accept)"); forEachRemaining((DoubleConsumer) action::accept); } } } }
apache/solr
36,033
solr/core/src/test/org/apache/solr/BasicFunctionalityTest.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; import com.codahale.metrics.Gauge; import com.codahale.metrics.Metric; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexableField; import org.apache.lucene.misc.document.LazyDocument; import org.apache.solr.common.SolrException; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.MapSolrParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.NamedList; import org.apache.solr.core.SolrCore; import org.apache.solr.handler.RequestHandlerBase; import org.apache.solr.metrics.SolrMetricManager; import org.apache.solr.request.LocalSolrQueryRequest; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.request.SolrRequestHandler; import org.apache.solr.response.ResultContext; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.response.XMLWriter; import org.apache.solr.schema.IndexSchema; import org.apache.solr.schema.IndexSchemaFactory; import org.apache.solr.schema.SchemaField; import org.apache.solr.search.DocIterator; import org.apache.solr.search.DocList; import org.apache.solr.security.AuthorizationContext; import org.apache.solr.util.BaseTestHarness; import org.junit.BeforeClass; import org.junit.Test; /** * Tests some basic functionality of Solr while demonstrating good Best Practices for using * SolrTestCaseJ4 */ public class BasicFunctionalityTest extends SolrTestCaseJ4 { public String getCoreName() { return "basic"; } @BeforeClass public static void beforeTests() throws Exception { initCore("solrconfig.xml", "schema.xml"); } // tests the performance of dynamic field creation and // field property testing. /* public void testFieldPerf() { IndexSchema schema = h.getCore().getSchema(); SchemaField[] fields = schema.getDynamicFieldPrototypes(); boolean createNew = false; long start = System.currentTimeMillis(); int ret = 0; for (int i=0; i<10000000; i++) { for (SchemaField f : fields) { if (createNew) f = new SchemaField(f, "fakename"); if (f.indexed()) ret += 1; if (f.isCompressed()) ret += 2; if (f.isRequired()) ret += 3; if (f.multiValued()) ret += 4; if (f.omitNorms()) ret += 5; if (f.sortMissingFirst()) ret += 6; if (f.sortMissingLast())ret += 7; if (f.stored()) ret += 8; if (f.storeTermOffsets()) ret += 9; if (f.storeTermPositions()) ret += 10; if (f.storeTermVector()) ret += 11; } } long end = System.currentTimeMillis(); System.out.println("ret=" + ret + " time="+ (end-start)); } ***/ @Test public void testIgnoredFields() { assertU("adding doc with ignored field", adoc("id", "42", "foo_ignored", "blah blah")); assertU("commit", commit()); // :TODO: the behavior of querying on an unindexed field should be better specified in the // future. assertQ( "query with ignored field", req("bar_ignored:yo id:42"), "//*[@numFound='1']", "//str[@name='id'][.='42']"); } @Test public void testSomeStuff() { clearIndex(); SolrCore core = h.getCore(); // test that we got the expected config, not just hardcoded defaults assertNotNull(core.getRequestHandler("/mock")); // test stats call SolrMetricManager manager = core.getCoreContainer().getMetricManager(); String registry = core.getCoreMetricManager().getRegistryName(); Map<String, Metric> metrics = manager.registry(registry).getMetrics(); assertTrue(metrics.containsKey("CORE.coreName")); assertTrue(metrics.containsKey("CORE.refCount")); @SuppressWarnings({"unchecked"}) Gauge<Number> g = (Gauge<Number>) metrics.get("CORE.refCount"); assertTrue(g.getValue().intValue() > 0); assertQ( "test query on empty index", req("qlkciyopsbgzyvkylsjhchghjrdf"), "//result[@numFound='0']"); // test escaping of ";" assertU("deleting 42 for no reason at all", delI("42")); assertU("adding doc#42", adoc("id", "42", "val_s", "aa;bb")); assertU("does commit work?", commit()); assertQ( "backslash escaping semicolon", req("id:42 AND val_s:aa\\;bb"), "//*[@numFound='1']", "//str[@name='id'][.='42']"); assertQ( "quote escaping semicolon", req("id:42 AND val_s:\"aa;bb\""), "//*[@numFound='1']", "//str[@name='id'][.='42']"); assertQ("no escaping semicolon", req("id:42 AND val_s:aa"), "//*[@numFound='0']"); assertU(delI("42")); assertU(commit()); assertQ(req("id:42"), "//*[@numFound='0']"); // test overwrite default of true assertU(adoc("id", "42", "val_s", "AAA")); assertU(adoc("id", "42", "val_s", "BBB")); assertU(commit()); assertQ(req("id:42"), "//*[@numFound='1']", "//str[.='BBB']"); assertU(adoc("id", "42", "val_s", "CCC")); assertU(adoc("id", "42", "val_s", "DDD")); assertU(commit()); assertQ(req("id:42"), "//*[@numFound='1']", "//str[.='DDD']"); // test deletes String[] adds = new String[] { add(doc("id", "101"), "overwrite", "true"), add(doc("id", "101"), "overwrite", "true"), add(doc("id", "105"), "overwrite", "false"), add(doc("id", "102"), "overwrite", "true"), add(doc("id", "103"), "overwrite", "false"), add(doc("id", "101"), "overwrite", "true"), }; for (String a : adds) { assertU(a, a); } assertU(commit()); // test maxint assertQ(req("q", "id:[100 TO 110]", "rows", "2147483647"), "//*[@numFound='4']"); // test big limit assertQ(req("q", "id:[100 TO 111]", "rows", "1147483647"), "//*[@numFound='4']"); assertQ(req("id:[100 TO 110]"), "//*[@numFound='4']"); assertU(delI("102")); assertU(commit()); assertQ(req("id:[100 TO 110]"), "//*[@numFound='3']"); assertU(delI("105")); assertU(commit()); assertQ(req("id:[100 TO 110]"), "//*[@numFound='2']"); assertU(delQ("id:[100 TO 110]")); assertU(commit()); assertQ(req("id:[100 TO 110]"), "//*[@numFound='0']"); assertU(BaseTestHarness.simpleTag("rollback")); assertU(commit()); } /** verify that delete by query works with the QParser framework and pure negative queries */ public void testNonTrivialDeleteByQuery() { clearIndex(); // setup assertU(add(doc("id", "101", "text", "red apple"))); assertU(add(doc("id", "102", "text", "purple grape"))); assertU(add(doc("id", "103", "text", "green grape"))); assertU(add(doc("id", "104", "text", "green pear"))); assertU(add(doc("id", "105", "text", "yellow banana"))); assertU(add(doc("id", "106", "text", "red cherry"))); // sanity checks assertU(commit()); assertQ(req("id:[100 TO 110]"), "//*[@numFound='6']"); assertQ(req("*:*"), "//*[@numFound='6']"); assertQ(req("text:red"), "//*[@numFound='2']"); assertQ(req("-text:red"), "//*[@numFound='4']"); assertQ(req("text:grape"), "//*[@numFound='2']"); assertQ(req("-text:grape"), "//*[@numFound='4']"); assertQ(req("-text:red -text:grape"), "//*[@numFound='2']"); assertQ( req("{!lucene q.op=AND df=text}grape green"), "//*[@numFound='1']", "//str[@name='id'][.='103']"); assertQ( req("-_val_:\"{!lucene q.op=AND df=text}grape green\""), "//*[@numFound='5']", "//str[@name='id'][.='101']", "//str[@name='id'][.='102']", "//str[@name='id'][.='104']", "//str[@name='id'][.='105']", "//str[@name='id'][.='106']"); // tests assertU(delQ("-*:*")); // NOOP assertU(commit()); assertQ(req("*:*"), "//*[@numFound='6']"); assertU(delQ("-text:grape -text:red")); assertU(commit()); assertQ( req("*:*"), "//*[@numFound='4']", "//str[@name='id'][.='101']", "//str[@name='id'][.='102']", "//str[@name='id'][.='103']", "//str[@name='id'][.='106']"); assertU(delQ("{!term f=id}106")); assertU(commit()); assertQ( req("*:*"), "//*[@numFound='3']", "//str[@name='id'][.='101']", "//str[@name='id'][.='102']", "//str[@name='id'][.='103']"); assertU(delQ("-_val_:\"{!lucene q.op=AND df=text}grape green\"")); assertU(commit()); assertQ(req("*:*"), "//*[@numFound='1']", "//str[@name='id'][.='103']"); assertU(delQ("-text:doesnotexist")); assertU(commit()); assertQ(req("*:*"), "//*[@numFound='0']"); } @Test public void testHTMLStrip() { assertU(add(doc("id", "200", "HTMLwhitetok", "&#65;&#66;&#67;"))); // do it again to make sure reuse is working assertU(add(doc("id", "201", "HTMLwhitetok", "&#65;B&#67;"))); assertU(commit()); assertQ(req("q", "HTMLwhitetok:A&#66;C"), "//*[@numFound='2']"); assertQ(req("q", "HTMLwhitetok:&#65;BC"), "//*[@numFound='2']"); } @Test public void testClientErrorOnMalformedDate() { final String BAD_VALUE = "NOT_A_DATE"; ignoreException(BAD_VALUE); final List<String> FIELDS = new ArrayList<>(); for (String type : new String[] {"tdt", "tdt1", "tdtdv", "tdtdv1", "dt_dv", "dt_dvo", "dt", "dt1", "dt_os"}) { FIELDS.add("malformed_" + type); } // test that malformed numerics cause client error not server error for (String field : FIELDS) { SolrException e1 = expectThrows( SolrException.class, "Didn't encounter an error trying to add a bad date: " + field, () -> h.update(add(doc("id", "100", field, BAD_VALUE)))); String msg1 = e1.getMessage(); assertTrue( "not an (update) client error on field: " + field + " : " + msg1, 400 <= e1.code() && e1.code() < 500); assertTrue( "(update) client error does not mention bad value: " + msg1, msg1.contains(BAD_VALUE)); assertTrue("client error does not mention document id: " + msg1, msg1.contains("[doc=100]")); SchemaField sf = h.getCore().getLatestSchema().getField(field); if (!sf.hasDocValues() && !sf.indexed()) { continue; } SolrException e2 = expectThrows( SolrException.class, "Didn't encounter an error trying to add a bad date: " + field, () -> h.query(req("q", field + ":" + BAD_VALUE))); String msg2 = e2.toString(); assertTrue( "not a (search) client error on field: " + field + " : " + msg2, 400 <= e2.code() && e2.code() < 500); assertTrue( "(search) client error does not mention bad value: " + msg2, msg2.contains(BAD_VALUE)); SolrException e3 = expectThrows( SolrException.class, "Didn't encounter an error trying to add a bad date: " + field, () -> h.query(req("q", field + ":[NOW TO " + BAD_VALUE + "]"))); String msg3 = e3.toString(); assertTrue( "not a (search) client error on field: " + field + " : " + msg3, 400 <= e3.code() && e3.code() < 500); assertTrue( "(search) client error does not mention bad value: " + msg3, msg3.contains(BAD_VALUE)); } } @Test public void testClientErrorOnMalformedNumbers() { final String BAD_VALUE = "NOT_A_NUMBER"; ignoreException(BAD_VALUE); final List<String> FIELDS = new ArrayList<>(); for (String type : new String[] { "ti", "tf", "td", "tl", "i", "f", "d", "l", "i_dv", "f_dv", "d_dv", "l_dv", "i_dvo", "f_dvo", "d_dvo", "l_dvo", "i_os", "f_os", "d_os", "l_os" }) { FIELDS.add("malformed_" + type); } // test that malformed numerics cause client error not server error for (String field : FIELDS) { SolrException e1 = expectThrows( SolrException.class, "Didn't encounter an error trying to add a non-number: " + field, () -> h.update(add(doc("id", "100", field, BAD_VALUE)))); String msg1 = e1.toString(); assertTrue( "not an (update) client error on field: " + field + " : " + msg1, 400 <= e1.code() && e1.code() < 500); assertTrue( "(update) client error does not mention bad value: " + msg1, msg1.contains(BAD_VALUE)); assertTrue("client error does not mention document id", msg1.contains("[doc=100]")); SchemaField sf = h.getCore().getLatestSchema().getField(field); if (!sf.hasDocValues() && !sf.indexed()) { continue; } SolrException e2 = expectThrows( SolrException.class, "Didn't encounter an error trying to add a non-number: " + field, () -> h.query(req("q", field + ":" + BAD_VALUE))); String msg2 = e2.toString(); assertTrue( "not a (search) client error on field: " + field + " : " + msg2, 400 <= e2.code() && e2.code() < 500); assertTrue( "(search) client error does not mention bad value: " + msg2, msg2.contains(BAD_VALUE)); SolrException e3 = expectThrows( SolrException.class, "Didn't encounter an error trying to add a non-number: " + field, () -> h.query(req("q", field + ":[10 TO " + BAD_VALUE + "]"))); String msg3 = e3.toString(); assertTrue( "not a (search) client error on field: " + field + " : " + msg3, 400 <= e3.code() && e3.code() < 500); assertTrue( "(search) client error does not mention bad value: " + msg3, msg3.contains(BAD_VALUE)); } } @Test public void testRequestHandlerBaseException() { final String tmp = "BOO! ignore_exception"; SolrRequestHandler handler = new RequestHandlerBase() { @Override public Name getPermissionName(AuthorizationContext request) { return Name.ALL; } @Override public String getDescription() { return tmp; } @Override public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) { throw new RuntimeException(tmp); } }; handler.init(new NamedList<>()); SolrQueryResponse rsp = new SolrQueryResponse(); SolrQueryRequest req = req(); h.getCore().execute(handler, req, rsp); assertNotNull("should have found an exception", rsp.getException()); req.close(); } @Test public void testMultipleUpdatesPerAdd() { clearIndex(); // big freaking kludge since the response is currently not well-formed. String res = h.update( "<add><doc><field name=\"id\">1</field></doc><doc><field name=\"id\">2</field></doc></add>"); // assertEquals("<result status=\"0\"></result>", res); assertU("<commit/>"); assertQ(req("id:[0 TO 99]"), "//*[@numFound='2']"); } @Test public void testDocBoost() throws Exception { String res = h.update( "<add>" + "<doc><field name=\"id\">1</field>" + "<field name=\"text\">hello</field></doc>" + "<doc boost=\"2.0\"><field name=\"id\">2</field>" + "<field name=\"text\">hello</field></doc>" + "</add>"); // assertEquals("<result status=\"0\"></result>", res); assertU("<commit/>"); assertQ(req("text:hello"), "//*[@numFound='2']"); String resp = h.query(lrf.makeRequest("q", "text:hello", CommonParams.DEBUG_QUERY, "true")); // System.out.println(resp); // second doc ranked first assertTrue(resp.indexOf("\"2\"") < resp.indexOf("\"1\"")); } @Test public void testFieldBoost() throws Exception { String res = h.update( "<add>" + "<doc><field name=\"id\">1</field>" + "<field name=\"text\">hello</field></doc>" + "<doc><field name=\"id\">2</field>" + "<field boost=\"2.0\" name=\"text\">hello</field></doc>" + "</add>"); // assertEquals("<result status=\"0\"></result>", res); assertU("<commit/>"); assertQ(req("text:hello"), "//*[@numFound='2']"); String resp = h.query(lrf.makeRequest("q", "text:hello", CommonParams.DEBUG_QUERY, "true")); // System.out.println(resp); // second doc ranked first assertTrue(resp.indexOf("\"2\"") < resp.indexOf("\"1\"")); } @Test public void testXMLWriter() throws Exception { SolrQueryResponse rsp = new SolrQueryResponse(); rsp.add("\"quoted\"", "\"value\""); StringWriter writer = new StringWriter(32000); SolrQueryRequest req = req("foo"); XMLWriter.writeResponse(writer, req, rsp); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); builder.parse(new ByteArrayInputStream(writer.toString().getBytes(StandardCharsets.UTF_8))); req.close(); } @Test public void testLocalSolrQueryRequestParams() { HashMap<String, Object> args = new HashMap<>(); args.put("string", "string value"); args.put("array", new String[] {"array", "value"}); SolrQueryRequest req = new LocalSolrQueryRequest(null, null, null, 0, 20, args); assertEquals("string value", req.getParams().get("string")); assertEquals("array", req.getParams().get("array")); String[] stringParams = req.getParams().getParams("string"); assertEquals(1, stringParams.length); assertEquals("string value", stringParams[0]); String[] arrayParams = req.getParams().getParams("array"); assertEquals(2, arrayParams.length); assertEquals("array", arrayParams[0]); assertEquals("value", arrayParams[1]); req.close(); } @Test public void testKeywordTokenizerFactory() { assertU( adoc( "id", "42", "keywordtok", "How nOw broWn-ish C.o.w. ?")); assertU(commit()); assertQ("stored value matches?", req("id:42"), "//str[.='How nOw broWn-ish C.o.w. ?']"); assertQ( "query on exact matches?", req("keywordtok:\"How nOw broWn-ish C.o.w. ?\""), "//str[.='How nOw broWn-ish C.o.w. ?']"); } @Test public void testTermVectorFields() { IndexSchema ischema = IndexSchemaFactory.buildIndexSchema(getSchemaFile(), solrConfig); SchemaField f; // Solr field type IndexableField luf; // Lucene field f = ischema.getField("test_basictv"); luf = f.createField("test"); assertTrue(f.storeTermVector()); assertTrue(luf.fieldType().storeTermVectors()); f = ischema.getField("test_notv"); luf = f.createField("test"); assertFalse(f.storeTermVector()); assertFalse(luf.fieldType().storeTermVectors()); f = ischema.getField("test_postv"); luf = f.createField("test"); assertTrue(f.storeTermVector() && f.storeTermPositions()); assertTrue(luf.fieldType().storeTermVectorPositions()); f = ischema.getField("test_offtv"); luf = f.createField("test"); assertTrue(f.storeTermVector() && f.storeTermOffsets()); assertTrue(luf.fieldType().storeTermVectorOffsets()); f = ischema.getField("test_posofftv"); luf = f.createField("test"); assertTrue(f.storeTermVector() && f.storeTermPositions() && f.storeTermOffsets()); assertTrue( luf.fieldType().storeTermVectorOffsets() && luf.fieldType().storeTermVectorPositions()); f = ischema.getField("test_posoffpaytv"); luf = f.createField("test"); assertTrue( f.storeTermVector() && f.storeTermPositions() && f.storeTermOffsets() && f.storeTermPayloads()); assertTrue( luf.fieldType().storeTermVectorOffsets() && luf.fieldType().storeTermVectorPositions() && luf.fieldType().storeTermVectorPayloads()); } @Test public void testSolrParams() { NamedList<Object> nl = new NamedList<>(); nl.add("i", 555); nl.add("s", "bbb"); nl.add("bt", "true"); nl.add("bf", "false"); Map<String, String> m = new HashMap<>(); m.put("f.field1.i", "1000"); m.put("s", "BBB"); m.put("ss", "SSS"); LocalSolrQueryRequest req = new LocalSolrQueryRequest(null, nl); SolrParams p = req.getParams(); assertEquals(p.get("i"), "555"); assertEquals(p.getInt("i").intValue(), 555); assertEquals(p.getInt("i", 5), 555); assertEquals(p.getInt("iii", 5), 5); assertEquals(p.getFieldParam("field1", "i"), "555"); req.setParams(SolrParams.wrapDefaults(p, new MapSolrParams(m))); p = req.getParams(); assertEquals(req.getOriginalParams().get("s"), "bbb"); assertEquals(p.get("i"), "555"); assertEquals(p.getInt("i").intValue(), 555); assertEquals(p.getInt("i", 5), 555); assertEquals(p.getInt("iii", 5), 5); assertEquals(p.getFieldParam("field1", "i"), "1000"); assertEquals(p.get("s"), "bbb"); assertEquals(p.get("ss"), "SSS"); assertEquals(!!p.getBool("bt"), !p.getBool("bf")); assertTrue(p.getBool("foo", true)); assertFalse(p.getBool("foo", false)); assertEquals(!!p.getBool("bt"), !p.getBool("bf")); NamedList<String> more = new NamedList<>(); more.add("s", "aaa"); more.add("s", "ccc"); more.add("ss", "YYY"); more.add("xx", "XXX"); p = SolrParams.wrapAppended(p, more.toSolrParams()); assertEquals(3, p.getParams("s").length); assertEquals("bbb", p.getParams("s")[0]); assertEquals("aaa", p.getParams("s")[1]); assertEquals("ccc", p.getParams("s")[2]); assertEquals(3, p.getParams("s").length); assertEquals("SSS", p.get("ss")); assertEquals("XXX", p.get("xx")); req.close(); } @Test public void testDefaultFieldValues() { clearIndex(); assertU( adoc( "id", "4055", "subject", "Hoss the Hoss man Hostetter")); assertU( adoc( "id", "4056", "intDefault", "4", "subject", "Some Other Guy")); assertU( adoc( "id", "4057", "multiDefault", "a", "multiDefault", "b", "subject", "The Dude")); assertU(commit()); assertQ( "everthing should have recent timestamp", req("timestamp:[NOW-10MINUTES TO NOW]"), "*[count(//doc)=3]", "//date[@name='timestamp']"); assertQ( "2 docs should have the default for multiDefault", req("multiDefault:muLti-Default"), "*[count(//doc)=2]", "//arr[@name='multiDefault']"); assertQ( "1 doc should have its explicit multiDefault", req("multiDefault:a"), "*[count(//doc)=1]"); assertQ( "2 docs should have the default for intDefault", req("intDefault:42"), "*[count(//doc)=2]"); assertQ( "1 doc should have its explicit intDefault", req("intDefault:[3 TO 5]"), "*[count(//doc)=1]"); } @Test public void testTokenizer() { assertU(adoc("id", "4055", "patterntok", "Hello,There")); assertU(adoc("id", "4056", "patterntok", "Goodbye,Now")); assertU(commit()); assertQ("make sure it split ok", req("patterntok:Hello"), "*[count(//doc)=1]"); assertQ("make sure it split ok", req("patterntok:Goodbye"), "*[count(//doc)=1]"); } @Test public void testConfigDefaults() { assertU( adoc( "id", "42", "name", "Zapp Brannigan")); assertU( adoc( "id", "43", "title", "Democratic Order of Planets")); assertU( adoc( "id", "44", "name", "The Zapper")); assertU( adoc( "id", "45", "title", "25 star General")); assertU( adoc( "id", "46", "subject", "Defeated the pacifists of the Gandhi nebula")); assertU( adoc( "id", "47", "text", "line up and fly directly at the enemy death cannons, clogging them with wreckage!")); assertU(commit()); assertQ( "standard request handler returns all matches", req("id:[42 TO 47]"), "*[count(//doc)=6]"); assertQ( "defaults handler returns fewer matches", req("q", "id:[42 TO 47]", "qt", "/defaults"), "*[count(//doc)=4]"); assertQ( "defaults handler includes highlighting", req("q", "name:Zapp OR title:General", "qt", "/defaults"), "//lst[@name='highlighting']"); } private String mkstr(int len) { StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append((char) (65 + i % 26)); } return new String(sb); } @Test public void testNotLazyField() throws IOException { assertU( adoc( "id", "7777", "title", "keyword", "test_hlt", mkstr(20000))); assertU(commit()); SolrCore core = h.getCore(); SolrQueryRequest req = req("q", "id:7777", "fl", "id,title,test_hlt"); SolrQueryResponse rsp = new SolrQueryResponse(); core.execute(core.getRequestHandler(req.getParams().get(CommonParams.QT)), req, rsp); DocList dl = ((ResultContext) rsp.getResponse()).getDocList(); Document d = req.getSearcher().getDocFetcher().doc(dl.iterator().nextDoc()); // ensure field in fl is not lazy assertNotEquals("LazyField", ((Field) d.getField("test_hlt")).getClass().getSimpleName()); assertNotEquals("LazyField", ((Field) d.getField("title")).getClass().getSimpleName()); req.close(); } @Test public void testLazyField() throws IOException { assertU( adoc( "id", "7777", "title", "keyword", "test_hlt", mkstr(10000), "test_hlt", mkstr(20000), "test_hlt", mkstr(30000), "test_hlt", mkstr(40000))); assertU(commit()); SolrCore core = h.getCore(); // initial request SolrQueryRequest req = req("q", "id:7777", "fl", "id,title"); SolrQueryResponse rsp = new SolrQueryResponse(); core.execute(core.getRequestHandler(req.getParams().get(CommonParams.QT)), req, rsp); DocList dl = ((ResultContext) rsp.getResponse()).getDocList(); DocIterator di = dl.iterator(); Document d1 = req.getSearcher().getDocFetcher().doc(di.nextDoc()); IndexableField[] values1 = null; // ensure fl field is non lazy, and non-fl field is lazy assertFalse(d1.getField("title") instanceof LazyDocument.LazyField); assertFalse(d1.getField("id") instanceof LazyDocument.LazyField); values1 = d1.getFields("test_hlt"); assertEquals(4, values1.length); for (IndexableField field : values1) { assertTrue(field instanceof LazyDocument.LazyField); LazyDocument.LazyField f = (LazyDocument.LazyField) field; assertFalse(f.hasBeenLoaded()); } req.close(); // followup request, different fl req = req("q", "id:7777", "fl", "id,test_hlt"); rsp = new SolrQueryResponse(); core.execute(core.getRequestHandler(req.getParams().get(CommonParams.QT)), req, rsp); dl = ((ResultContext) rsp.getResponse()).getDocList(); di = dl.iterator(); Document d2 = req.getSearcher().getDocFetcher().doc(di.nextDoc()); // ensure same doc, same lazy field now assertSame("Doc was not cached", d1, d2); IndexableField[] values2 = d2.getFields("test_hlt"); assertEquals(values1.length, values2.length); for (int i = 0; i < values1.length; i++) { assertSame("LazyField wasn't reused", values1[i], values2[i]); LazyDocument.LazyField f = (LazyDocument.LazyField) values1[i]; // still not a real boy, no response writer in play assertFalse(f.hasBeenLoaded()); } assertNotNull(values2[0].stringValue()); // actuallize one value for (IndexableField indexableField : values2) { // now all values for this field should be loaded & cached LazyDocument.LazyField f = (LazyDocument.LazyField) indexableField; assertTrue(f.hasBeenLoaded()); } req.close(); } /** * @see org.apache.solr.util.DateMathParserTest */ @Test public void testDateMath() { clearIndex(); // testing everything from query level is hard because // time marches on ... and there is no easy way to reach into the // bowels of DatePointField and muck with the definition of "now" // ... // BUT: we can test that crazy combinations of "NOW" all work correctly, // assuming the test doesn't take too long to run... final String july4 = "1976-07-04T12:08:56.235Z"; assertU(adoc("id", "1", "bday", july4)); assertU(adoc("id", "2", "bday", "NOW")); assertU(adoc("id", "3", "bday", "NOW/HOUR")); assertU(adoc("id", "4", "bday", "NOW-30MINUTES")); assertU(adoc("id", "5", "bday", "NOW+30MINUTES")); assertU(adoc("id", "6", "bday", "NOW+2YEARS")); assertU(commit()); // a ridiculoulsy long date math expression that's still equivalent to july4 final StringBuilder july4Long = new StringBuilder(july4); final int iters = atLeast(10); for (int i = 0; i < iters; i++) { final String val = String.valueOf(atLeast(1)); july4Long.append("+" + val + "SECONDS-" + val + "SECONDS"); } // term queries using date math (all of these should match doc#1) for (String q : new String[] { "bday:1976-07-04T12\\:08\\:56.45Z/SECOND+235MILLIS", "bday:1976-07-04T12\\:08\\:56.123Z/MINUTE+56SECONDS+235MILLIS", "bday:\"1976-07-04T12:08:56.45Z/SECOND+235MILLIS\"", "bday:\"1976-07-04T12:08:56.123Z/MINUTE+56SECONDS+235MILLIS\"", "{!term f=bday}1976-07-04T12:08:56.45Z/SECOND+235MILLIS", "{!term f=bday}1976-07-04T12:08:56.123Z/MINUTE+56SECONDS+235MILLIS", "{!term f=bday}" + july4, "{!term f=bday}" + july4Long, "bday:\"" + july4Long + "\"" }) { assertQ( "check math on field query: " + q, req("q", q), "*[count(//doc)=1]", "//str[@name='id'][.='1']"); } // range queries using date math assertQ( "check math on absolute date#1", req("q", "bday:[* TO " + july4 + "/SECOND]"), "*[count(//doc)=0]"); assertQ( "check math on absolute date#2", req("q", "bday:[* TO " + july4 + "/SECOND+1SECOND]"), "*[count(//doc)=1]"); assertQ( "check math on absolute date#3", req("q", "bday:[" + july4 + "/SECOND TO " + july4 + "/SECOND+1SECOND]"), "*[count(//doc)=1]"); assertQ( "check math on absolute date#4", req("q", "bday:[" + july4 + "/MINUTE+1MINUTE TO *]"), "*[count(//doc)=5]"); assertQ("check count for before now", req("q", "bday:[* TO NOW]"), "*[count(//doc)=4]"); assertQ("check count for after now", req("q", "bday:[NOW TO *]"), "*[count(//doc)=2]"); assertQ("check count for old stuff", req("q", "bday:[* TO NOW-2YEARS]"), "*[count(//doc)=1]"); assertQ( "check count for future stuff", req("q", "bday:[NOW+1MONTH TO *]"), "*[count(//doc)=1]"); assertQ( "check count for near stuff", req("q", "bday:[NOW-1MONTH TO NOW+2HOURS]"), "*[count(//doc)=4]"); assertQ( "check counts using fixed NOW", req( "q", "bday:[NOW/DAY TO NOW/DAY+1DAY]", "NOW", "205369736000" // 1976-07-04T23:08:56.235Z ), "*[count(//doc)=1]"); assertQ( "check counts using fixed NOW and TZ rounding", req( "q", "bday:[NOW/DAY TO NOW/DAY+1DAY]", "TZ", "GMT+01", "NOW", "205369736000" // 1976-07-04T23:08:56.235Z ), "*[count(//doc)=0]"); } // commented after SOLR-8904; both are false // public void testDateRoundtrip() { // assertU(adoc("id", "99", "bday", "99-01-01T12:34:56.789Z")); // assertU(commit()); // assertQ("year should be canonicallized to 4 digits", // req("q", "id:99"), // "//date[@name='bday'][.='0099-01-01T12:34:56.789Z']"); // assertU(adoc("id", "99", "bday", "1999-01-01T12:34:56.900Z")); // assertU(commit()); // assertQ("millis should be canonicallized to no trailing zeros", // req("q", "id:99"), // "//date[@name='bday'][.='1999-01-01T12:34:56.9Z']"); // } @Test public void testPatternReplaceFilter() { assertU( adoc( "id", "1", "patternreplacefilt", "My fine-feathered friend!")); assertU( adoc( "id", "2", "patternreplacefilt", " What's Up Doc?")); assertU(commit()); assertQ("don't find Up", req("q", "patternreplacefilt:Up"), "*[count(//doc)=0]"); assertQ("find doc", req("q", "patternreplacefilt:__What_s_Up_Doc_"), "*[count(//doc)=1]"); assertQ( "find birds", req("q", "patternreplacefilt:My__fine_feathered_friend_"), "*[count(//doc)=1]"); } @Test public void testAbuseOfSort() { assertU( adoc( "id", "9999991", "sortabuse_not_uninvertible", "xxx", "sortabuse_t", "zzz xxx ccc vvv bbb nnn aaa sss ddd fff ggg")); assertU( adoc( "id", "9999992", "sortabuse_not_uninvertible", "yyy", "sortabuse_t", "zzz xxx ccc vvv bbb nnn qqq www eee rrr ttt")); assertU(commit()); for (String f : Arrays.asList("sortabuse_not_uninvertible", "sortabuse_t")) { RuntimeException outerEx = expectThrows( RuntimeException.class, () -> { ignoreException("sortabuse"); assertQ( "sort on something that shouldn't work", req("q", "*:*", "sort", f + " asc"), "*[count(//doc)=2]"); }); Throwable root = getRootCause(outerEx); assertEquals("sort exception root cause", SolrException.class, root.getClass()); SolrException e = (SolrException) root; assertEquals( "incorrect error type", SolrException.ErrorCode.BAD_REQUEST, SolrException.ErrorCode.getErrorCode(e.code())); assertTrue("exception doesn't contain field name", e.getMessage().contains(f)); } } // /** this doesn't work, but if it did, this is how we'd test it. */ // public void testOverwriteFalse() { // assertU(adoc("id", "overwrite", "val_s", "AAA")); // assertU(commit()); // assertU(add(doc("id", "overwrite", "val_s", "BBB") // ,"allowDups", "false" // ,"overwriteCommitted","false" // ,"overwritePending","false" // )); // assertU(commit()); // assertQ(req("id:overwrite") // ,"//*[@numFound='1']" // ,"//str[.='AAA']" // ); // } }
apache/trafodion
35,686
dcs/src/test/jdbc_test/src/test/java/org/trafodion/jdbc_test/TestBatch.java
/* /* @@@ START COPYRIGHT @@@ /* /* 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. /* /* @@@ END COPYRIGHT @@@ /*/ import org.junit.Test; import static org.junit.Assert.*; import java.sql.*; import java.io.*; import java.lang.*; public class TestBatch { /* Test Batch insert and update*/ @Test public void JDBCBatch1() throws InterruptedException, SQLException { System.out.println("JDBC batch test 1.."); Statement stmt = null; ResultSet rs = null; String DEPT = null; String insert = null; String update = null; PreparedStatement pStmt = null; String ISTBL = "BATCHTBL1"; int totalQA = 2000; int totalDev = 2000; int totalMgr = 2000; int totalPoints = 99999; long startTime = 0; long endTime = 0; int[] insertCount = null; int[] updateCount = null; int TOTALUPDATECOUNT = 6000; boolean pass = true; String IN1 = "BATCHTBL1"; String IN2 = null; try ( Connection conn = Utils.getUserConnection(); ) { Utils.dropTable(conn, IN1); Utils.createTable(conn, IN1); insert = "insert into " + IN1 + " values(?,?,?,?)"; pStmt = conn.prepareStatement(insert); startTime = System.currentTimeMillis(); int points = totalPoints; int toggle = 1; for (int j = 1; j <= totalQA; j++) { if (toggle == 1) DEPT = "JDBC"; else if (toggle == 2) DEPT = "ODBC"; else DEPT = "DBADMIN"; pStmt.setString(1, "QA"); pStmt.setInt(2, j); pStmt.setInt(3, points); pStmt.setString(4, DEPT); points--; toggle++; if (toggle > 3) toggle = 1; pStmt.addBatch(); } points = totalPoints; toggle = 1; for (int j = (totalQA + 1); j <= (totalDev + totalQA); j++) { if (toggle == 1) DEPT = "JDBC"; else if (toggle == 2) DEPT = "ODBC"; else DEPT = "DBADMIN"; pStmt.setString(1, "DEV"); pStmt.setInt(2, j); pStmt.setInt(3, points); pStmt.setString(4, DEPT); points--; points--; toggle++; if (toggle > 3) toggle = 1; pStmt.addBatch(); } points = totalPoints; for (int j = (totalQA + totalDev + 1); j <= (totalDev + totalQA + totalMgr); j++) { if (toggle == 1) DEPT = "JDBC"; else if (toggle == 2) DEPT = "ODBC"; else DEPT = "DBADMIN"; pStmt.setString(1, "MGR"); pStmt.setInt(2, j); pStmt.setInt(3, points); pStmt.setString(4, DEPT); points--; toggle++; if (toggle > 3) toggle = 1; pStmt.addBatch(); } try { insertCount = pStmt.executeBatch(); for (int i = 0; i < insertCount.length; i++) { if ((insertCount[i] != -2) && (insertCount[i] != 1)) { pass = false; System.out.println("Batch1 : ERROR: Unexpected return code (should be -2 or 1) for " + i + "th command: " + insertCount[i]); } } } catch (BatchUpdateException bue) { System.out.println("Batch1 : ERROR: Exception in insert batch mode....."); handleBatchUpdateException(bue); } java.sql.SQLWarning sw = pStmt.getWarnings(); int totalW = 0; while (sw != null) { System.out.println("SQLMessage : " + sw.getMessage()); System.out.println("SQLState : " + sw.getSQLState()); System.out.println("ErrorCode : " + sw.getErrorCode()); totalW++; sw = sw.getNextWarning(); } // Check the update count int updateRowCount = pStmt.getUpdateCount(); if (updateRowCount != TOTALUPDATECOUNT) { System.out.println("Batch1: ERROR: Expecting updateRowCount to be " + TOTALUPDATECOUNT); pass = false; } // Verify the inserted rows stmt = conn.createStatement(); int totalI = 0; rs = stmt.executeQuery("select * from " + IN1); if (rs != null) { ResultSetMetaData rsMD = rs.getMetaData(); while (rs.next()) { totalI++; } rs.close(); } if (totalI != TOTALUPDATECOUNT) { pass = false; System.out.println("Batch1 : ERROR: Expecting total of " + totalI + " rows inserted"); } pStmt.close(); pStmt = null; stmt.close(); }// end of try catch (Exception e) { pass = false; e.printStackTrace(); System.out.println(e.getMessage()); } finally { /**/ /* @@@ START COPYRIGHT @@@ 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. /* @@@ END COPYRIGHT @@@ /**/ assertEquals(true, pass); } System.out.println("JDBCBatch1 : Done"); } /* Test Batch insert and update */ @Test public void JDBCBatch2() throws InterruptedException, SQLException { System.out.println("JDBC batch test 2.."); Statement stmt = null; ResultSet rs = null; String DEPT = null; String insert = null; String update = null; PreparedStatement pStmt = null; String ISTBL = "BATCHTBL2"; int totalQA = 2000; int totalDev = 2000; int totalMgr = 2000; int totalPoints = 999999; long startTime = 0; long endTime = 0; int[] insertCount = null; int[] updateCount = null; int TOTALUPDATECOUNT = totalQA+totalDev+totalMgr; boolean pass = true; String IN1 = "BATCHTBL2"; String IN2 = null; try ( Connection conn = Utils.getUserConnection(); ) { Utils.dropTable(conn, IN1); Utils.createTable(conn, IN1); insert = "insert into " + IN1 + " values(?,?,?,?)"; pStmt = conn.prepareStatement(insert); startTime = System.currentTimeMillis(); int points = totalPoints; int toggle = 1; for (int j = 1; j <= totalQA; j++) { if (toggle == 1) DEPT = "JDBC"; else if (toggle == 2) DEPT = "ODBC"; else DEPT = "DBADMIN"; pStmt.setString(1, "QA"); pStmt.setInt(2, j); pStmt.setInt(3, points); pStmt.setString(4, DEPT); points--; toggle++; if (toggle > 3) toggle = 1; pStmt.addBatch(); } points = totalPoints; toggle = 1; for (int j = (totalQA + 1); j <= (totalDev + totalQA); j++) { if (toggle == 1) DEPT = "JDBC"; else if (toggle == 2) DEPT = "ODBC"; else DEPT = "DBADMIN"; pStmt.setString(1, "DEV"); pStmt.setInt(2, j); pStmt.setInt(3, points); pStmt.setString(4, DEPT); points--; points--; toggle++; if (toggle > 3) toggle = 1; pStmt.addBatch(); } points = totalPoints; for (int j = (totalQA + totalDev + 1); j <= (totalDev + totalQA + totalMgr); j++) { if (toggle == 1) DEPT = "JDBC"; else if (toggle == 2) DEPT = "ODBC"; else DEPT = "DBADMIN"; pStmt.setString(1, "MGR"); pStmt.setInt(2, j); pStmt.setInt(3, points); pStmt.setString(4, DEPT); points--; toggle++; if (toggle > 3) toggle = 1; pStmt.addBatch(); } try { insertCount = pStmt.executeBatch(); for (int i = 0; i < insertCount.length; i++) { if ((insertCount[i] != -2) && (insertCount[i] != 1)) { pass = false; System.out.println("Batch2 : ERROR: Unexpected return code (should be -2 or 1) for " + i + "th command: " + insertCount[i]); } } } catch (BatchUpdateException bue) { System.out.println("Batch2 : ERROR: Exception in insert batch mode....."); handleBatchUpdateException(bue); } java.sql.SQLWarning sw = pStmt.getWarnings(); int totalW = 0; while (sw != null) { System.out.println("SQLMessage : " + sw.getMessage()); System.out.println("SQLState : " + sw.getSQLState()); System.out.println("ErrorCode : " + sw.getErrorCode()); totalW++; sw = sw.getNextWarning(); } int updateRowCount = pStmt.getUpdateCount(); if (updateRowCount != TOTALUPDATECOUNT) { System.out.println("Batch2: ERROR: Expecting updateRowCount to be " + TOTALUPDATECOUNT); pass = false; } stmt = conn.createStatement(); int totalI = 0; rs = stmt.executeQuery("select * from " + IN1); if (rs != null) { ResultSetMetaData rsMD = rs.getMetaData(); while (rs.next()) { totalI++; } rs.close(); } if (totalI != TOTALUPDATECOUNT) { pass = false; System.out.println("Batch2 : ERROR: Expecting total of " + totalI + " rows inserted"); } pStmt.close(); pStmt = null; update = "update " + IN1 + " set points = ? where TITLE = ? "; pStmt = conn.prepareStatement(update); pStmt.setInt(1, 9); pStmt.setString(2, "MGR"); pStmt.addBatch(); try { updateCount = pStmt.executeBatch(); for (int i = 0; i < updateCount.length; i++) { if ((updateCount[i] != -2) && (updateCount[i] != 2)) { pass = false; System.out.println("Batch2 : ERROR: Unexpected return code (should be -2 or 1) for " + i + "th command: " + updateCount[i]); } } } catch (BatchUpdateException bue) { System.out.println("Batch2 : ERROR: Exception in update batch mode....."); handleBatchUpdateException(bue); } updateRowCount = pStmt.getUpdateCount(); if (updateRowCount != totalMgr) { System.out.println("Batch2: ERROR: Expecting updateRowCount to be " + totalMgr); pass = false; } int ret = 0; rs = stmt.executeQuery("select POINTS from " + IN1 + " where TITLE = 'MGR'"); if (rs != null) { while (rs.next()) { ret = rs.getInt("POINTS"); if (ret != 9) { pass = false; System.out.println("Batch2: ERROR: points for MGR is not updated: " + ret); } } rs.close(); } pStmt.close(); stmt.close(); }// end of try catch (Exception e) { pass = false; e.printStackTrace(); System.out.println(e.getMessage()); } finally { if (pass) System.out.println("JDBCBatch2 : Passed"); else System.out.println("JDBCBatch2 : FAILED"); assertEquals(true, pass); } System.out.println("JDBCBatch2 : Done"); } /* Test batch insert with all datatypes */ @Test public void JDBCBatch3() throws InterruptedException, SQLException { System.out.println("JDBC batch test 3.."); Statement stmt = null; ResultSet rs = null; String DEPT = null; String insert = null; String update = null; PreparedStatement pStmt = null; String ISTBL = "TABALL"; int total = 10000; long startTime = 0; long endTime = 0; int[] insertCount = null; int[] updateCount = null; int TOTALUPDATECOUNT = total; boolean pass = true; String IN1 = "TABALL"; String IN2 = null; int insertCountTemplate = -2; int[] updateCountTemplate = { -2 }; try ( Connection conn = Utils.getUserConnection(); ) { stmt = conn.createStatement(); stmt.executeUpdate("set schema " + Utils.catalog + "." + Utils.schema); stmt.executeUpdate("drop table if exists " + IN1 + " cascade"); stmt.executeUpdate("create table " + IN1 + "(c1 LARGEINT NOT NULL, C2 LARGEINT SIGNED, C3 CHAR (100)," + " C4 NUMERIC(18,4), C5 NUMERIC(6) SIGNED, C6 NUMERIC(128,30) UNSIGNED, C7 DECIMAL, C8 DECIMAL(18,4) SIGNED, C9 DECIMAL(9,5) UNSIGNED," + " C10 INTEGER, C11 INTEGER SIGNED, c12 INTEGER UNSIGNED, C13 SMALLINT, C14 SMALLINT SIGNED, C15 SMALLINT UNSIGNED, C16 FLOAT(5), C17 REAL," + " C18 DOUBLE PRECISION, C19 VARCHAR (1000), C20 DATE, C21 TIME, C22 TIMESTAMP, C23 INTERVAL YEAR TO MONTH, C24 INTERVAL YEAR, C25 INTERVAL MONTH," + " C26 INTERVAL DAY, C27 INTERVAL YEAR TO MONTH, C28 INTERVAL DAY TO HOUR, C29 INTERVAL HOUR, C30 INTERVAL MINUTE, C31 INTERVAL SECOND," + " C32 INTERVAL HOUR TO MINUTE, C33 INTERVAL HOUR TO SECOND, C34 INTERVAL MINUTE TO SECOND, PRIMARY KEY (C1)) SALT USING 6 PARTITIONS"); insert = "insert into " + IN1 + " values(?,-2**45,'abc',1234.5678,-1234.5678,123456789.123456789,12,-123,12.56,\n" + "123456,-123456,123456,123,-123,123,0.1234,123.0989,12345.67890,'abcdefghi',DATE '2001-03-22',TIME '13:40:30.666666',TIMESTAMP '1997-09-03 09:33:30.555555',\n" + "INTERVAL '2-7' YEAR TO MONTH,INTERVAL '96' YEAR,INTERVAL '9' MONTH,INTERVAL '9' DAY,INTERVAL '4-5' YEAR TO MONTH,\n" + "INTERVAL '7 8' DAY TO HOUR,INTERVAL '12' HOUR,INTERVAL '30' MINUTE,INTERVAL '60' SECOND,INTERVAL '2:5' HOUR TO MINUTE,\n" + "INTERVAL '5:4:3' HOUR TO SECOND,INTERVAL '9:2' MINUTE TO SECOND)"; pStmt = conn.prepareStatement(insert); startTime = System.currentTimeMillis(); try { for (int j = 1; j <= total; j++) { pStmt.setInt(1, j); pStmt.addBatch(); } insertCount = pStmt.executeBatch(); for (int i = 0; i < insertCount.length; i++) { if ((insertCount[i] != -2) && (insertCount[i] != 1)) { pass = false; System.out.println("Batch3 : ERROR: Expecting return code for " + i + "th command: -2 or 1, but got : " + insertCount[i]); } } } catch (BatchUpdateException bue) { System.out.println("Batch3 : ERROR: Exception in insert batch mode....."); bue.printStackTrace(); System.out.println(bue.getMessage()); handleBatchUpdateException(bue); } // Check the SQLWarning java.sql.SQLWarning sw = pStmt.getWarnings(); int totalW = 0; while (sw != null) { System.out.println("SQLMessage : " + sw.getMessage()); System.out.println("SQLState : " + sw.getSQLState()); System.out.println("ErrorCode : " + sw.getErrorCode()); totalW++; sw = sw.getNextWarning(); } int updateRowCount = pStmt.getUpdateCount(); if (updateRowCount != TOTALUPDATECOUNT) { System.out.println("Batch3: ERROR: Expecting updateRowCount to be " + TOTALUPDATECOUNT + " but got " + updateRowCount); pass = false; } // Verify the inserted rows stmt = conn.createStatement(); int totalI = 0; rs = stmt.executeQuery("select * from " + IN1); if (rs != null) { ResultSetMetaData rsMD = rs.getMetaData(); while (rs.next()) { totalI++; } rs.close(); } if (totalI != TOTALUPDATECOUNT) { pass = false; System.out.println("Batch3 : ERROR: Expecting total of " + totalI + " rows inserted"); } pStmt.close(); pStmt = null; stmt.close(); conn.close(); }// end of try catch (Exception e) { pass = false; e.printStackTrace(); System.out.println(e.getMessage()); } finally { /**/ if (pass) System.out.println("JDBCBatch3 : Passed"); else System.out.println("JDBCBatch3 : FAILED"); /**/ assertEquals(true, pass); } System.out.println("JDBCBatch3 : Done"); } /* Test Batch Delete */ @Test public void JDBCBatch4() throws InterruptedException, SQLException { ResultSet rs = null; String DEPT = null; String insert = null; String delete = null; String update = null; PreparedStatement pStmt = null; String ISTBL = "BATCHTBL4"; int totalQA = 100; int totalPoints = 99999; long startTime = 0; long endTime = 0; int[] insertCount = null; int[] deleteCount = null; int[] updateCount = null; int TOTALUPDATECOUNT = totalQA; boolean pass = true; String IN1 = "BATCHTBL4"; String IN2 = null; System.out.println("JDBC batch test 4.."); try { Connection conn = Utils.getUserConnection(); Statement stmt = conn.createStatement(); stmt.executeUpdate("set schema " + Utils.catalog + "." + Utils.schema); stmt.executeUpdate("drop table if exists " + ISTBL + " cascade"); stmt.executeUpdate("create table " + ISTBL + "(a int not null, b varchar(2000), c int, d varchar(400), primary key(a))"); insert = "insert into " + ISTBL + " values(?,?,?,?)"; pStmt = conn.prepareStatement(insert); startTime = System.currentTimeMillis(); int points = totalPoints; int toggle = 1; for (int j = 1; j <= totalQA; j++) { if (toggle == 1) DEPT = "JDBC"; else if (toggle == 2) DEPT = "ODBC"; else DEPT = "DBADMIN"; pStmt.setInt(1, j); pStmt.setString(2, "QA"); pStmt.setInt(3, points); pStmt.setString(4, DEPT); points--; toggle++; if (toggle > 3) toggle = 1; pStmt.addBatch(); } insertCount = pStmt.executeBatch(); for (int i = 0; i < insertCount.length; i++) { if ((insertCount[i] != -2) && (insertCount[i] != 1)) { pass = false; System.out.println("JDBCBatch4 : ERROR: Unexpected return code (should be -2 or 1) for " + i + "th command: " + insertCount[i]); } } java.sql.SQLWarning sw = pStmt.getWarnings(); int totalW = 0; while (sw != null) { totalW++; sw = sw.getNextWarning(); } int updateRowCount = pStmt.getUpdateCount(); if (updateRowCount != TOTALUPDATECOUNT) { System.out.println("JDBCBatch4: 1 : ERROR: Expecting updateRowCount to be " + TOTALUPDATECOUNT + " but was " + updateRowCount); pass = false; } //DELETE BATCH //create table " + ISTBL + "(a int not null, b varchar(200000), c int, d varchar(40000), primary key(a))"); delete = "delete from " + ISTBL + " where d = ?"; pStmt = conn.prepareStatement(delete); pStmt.setString(1, "DBADMIN"); pStmt.addBatch(); pStmt.setString(1, "ODBC"); pStmt.addBatch(); deleteCount = pStmt.executeBatch(); for (int i = 0; i < deleteCount.length; i++) { if ((deleteCount[i] != -2) && (deleteCount[i] != 1)) { pass = false; System.out.println("JDBCBatch4 : ERROR: Unexpected return code (should be -2 or 1) for " + i + "th command: " + deleteCount[i]); } } sw = pStmt.getWarnings(); totalW = 0; while (sw != null) { totalW++; sw = sw.getNextWarning(); } int expDeletedRows = 66; updateRowCount = pStmt.getUpdateCount(); if (updateRowCount != expDeletedRows) { System.out.println("JDBCBatch4: 2 : ERROR: Expecting updateRowCount to be " + TOTALUPDATECOUNT + " but was " + updateRowCount); pass = false; } // Verify the deleted rows stmt = conn.createStatement(); int totalI = 0; rs = stmt.executeQuery("select * from " + IN1); int rowNo = 0; while (rs.next()) { rowNo++; if (!rs.getString(4).equals("JDBC")) System.out.println("JDBCBatch4 failed : Col d should have JDBC in row " + rowNo); } rs.close(); pStmt.close(); pStmt = null; stmt.close(); conn.close(); }// end of try catch (Exception e) { pass = false; e.printStackTrace(); System.out.println(e.getMessage()); } finally { if (pass) System.out.println("JDBC Batch4 : Passed"); else System.out.println("JDBC Batch4 : FAILED"); assertEquals(true, pass); } } /* Test BATCH UPSERT/UPDATE */ @Test public void JDBCBatch5() throws InterruptedException, SQLException { ResultSet rs = null; String DEPT = null; String insert = null; String update = null; PreparedStatement pStmt = null; String ISTBL = "BATCHTBL5"; int totalQA = 100; int totalPoints = 99999; long startTime = 0; long endTime = 0; int[] insertCount = null; int[] updateCount = null; int TOTALUPDATECOUNT = 100; boolean pass = true; String IN1 = "BATCHTBL5"; String IN2 = null; System.out.println("JDBC batch test 5.."); try { Connection conn = Utils.getUserConnection(); Statement stmt = conn.createStatement(); stmt.executeUpdate("set schema " + Utils.catalog + "." + Utils.schema); stmt.executeUpdate("drop table if exists " + ISTBL + " cascade"); stmt.executeUpdate("create table " + ISTBL + "(a int not null, b varchar(2000), c int, d varchar(400), primary key(a))"); insert = "upsert into " + ISTBL + " values(?,?,?,?)"; pStmt = conn.prepareStatement(insert); startTime = System.currentTimeMillis(); int points = totalPoints; int toggle = 1; for (int j = 1; j <= totalQA; j++) { if (toggle == 1) DEPT = "JDBC"; else if (toggle == 2) DEPT = "ODBC"; else DEPT = "DBADMIN"; pStmt.setInt(1, j); pStmt.setString(2, "QA"); pStmt.setInt(3, points); pStmt.setString(4, DEPT); points--; toggle++; if (toggle > 3) toggle = 1; pStmt.addBatch(); } insertCount = pStmt.executeBatch(); for (int i = 0; i < insertCount.length; i++) { if ((insertCount[i] != -2) && (insertCount[i] != 1)) { pass = false; System.out.println("JDBCBatch5 : ERROR: Unexpected return code (should be -2 or 1) for " + i + "th command: " + insertCount[i]); } } java.sql.SQLWarning sw = pStmt.getWarnings(); int totalW = 0; while (sw != null) { totalW++; sw = sw.getNextWarning(); } int updateRowCount = pStmt.getUpdateCount(); if (updateRowCount != TOTALUPDATECOUNT) { System.out.println("JDBCBatch5: ERROR: Expecting updateRowCount to be " + TOTALUPDATECOUNT); pass = false; } //UPDATE BATCH //create table " + ISTBL + "(a int not null, b varchar(200000), c int, d varchar(40000), primary key(a))"); update = "update " + ISTBL + " set b = ? where d = ?"; pStmt = conn.prepareStatement(update); pStmt.setString(1, "Quality"); pStmt.setString(2, "JDBC"); pStmt.addBatch(); pStmt.setString(1, "Quality"); pStmt.setString(2, "ODBC"); pStmt.addBatch(); pStmt.setString(1, "Quality"); pStmt.setString(2, "DBADMIN"); pStmt.addBatch(); updateCount = pStmt.executeBatch(); for (int i = 0; i < updateCount.length; i++) { if ((updateCount[i] != -2) && (updateCount[i] != 1)) { pass = false; System.out.println("JDBCBatch5 : ERROR: Unexpected return code (should be -2 or 1) for " + i + "th command: " + updateCount[i]); } } sw = pStmt.getWarnings(); totalW = 0; while (sw != null) { totalW++; sw = sw.getNextWarning(); } updateRowCount = pStmt.getUpdateCount(); if (updateRowCount != TOTALUPDATECOUNT) { System.out.println("JDBCBatch5: ERROR: Expecting updateRowCount to be " + TOTALUPDATECOUNT); pass = false; } // Verify the updated rows stmt = conn.createStatement(); int totalI = 0; rs = stmt.executeQuery("select * from " + IN1); int rowNo = 0; while (rs.next()) { rowNo++; if (!rs.getString(2).equals("Quality")) System.out.println("JDBCBatch5 failed : Col d should have JDBC in row " + rowNo); } rs.close(); pStmt.close(); pStmt = null; stmt.close(); conn.close(); }// end of try catch (Exception e) { pass = false; e.printStackTrace(); System.out.println(e.getMessage()); } finally { if (pass) System.out.println("JDBC Batch5 : Passed"); else System.out.println("JDBC Batch5 : FAILED"); assertEquals(true, pass); } } /* Test Batch insert with all datatypes, using params for all datatypes */ @Test public void JDBCBatch6() throws InterruptedException, SQLException { System.out.println("JDBC batch test 6.."); Statement stmt = null; ResultSet rs = null; String DEPT = null; String insert = null; String update = null; PreparedStatement pStmt = null; String ISTBL = "TABALL6"; int total = 10000; long startTime = 0; long endTime = 0; int[] insertCount = null; int[] updateCount = null; int TOTALUPDATECOUNT = total; boolean pass = true; String IN1 = "TABALL6"; String IN2 = null; int insertCountTemplate = -2; int[] updateCountTemplate = { -2 }; try ( Connection conn = Utils.getUserConnection(); ) { stmt = conn.createStatement(); stmt.executeUpdate("set schema " + Utils.catalog + "." + Utils.schema); stmt.executeUpdate("drop table if exists " + IN1 + " cascade"); stmt.executeUpdate("create table " + IN1 + "(c1 LARGEINT NOT NULL, C2 LARGEINT SIGNED, C3 CHAR (100)," + " C4 NUMERIC(18,4), C5 NUMERIC(6) SIGNED, C6 NUMERIC(128,30) UNSIGNED, C7 DECIMAL, C8 DECIMAL(18,4) SIGNED, C9 DECIMAL(9,5) UNSIGNED," + " C10 INTEGER, C11 INTEGER SIGNED, c12 INTEGER UNSIGNED, C13 SMALLINT, C14 SMALLINT SIGNED, C15 SMALLINT UNSIGNED, C16 FLOAT(5), C17 REAL," + " C18 DOUBLE PRECISION, C19 VARCHAR (1000), C20 DATE, C21 TIME, C22 TIMESTAMP, C23 INTERVAL YEAR TO MONTH, C24 INTERVAL YEAR, C25 INTERVAL MONTH," + " C26 INTERVAL DAY, C27 INTERVAL YEAR TO MONTH, C28 INTERVAL DAY TO HOUR, C29 INTERVAL HOUR, C30 INTERVAL MINUTE, C31 INTERVAL SECOND," + " C32 INTERVAL HOUR TO MINUTE, C33 INTERVAL HOUR TO SECOND, C34 INTERVAL MINUTE TO SECOND, PRIMARY KEY (C1)) SALT USING 6 PARTITIONS"); insert = "insert into " + IN1 + " values(?,-2**45,'abc',1234.5678,-1234.5678,123456789.123456789,12,-123,12.56,\n" + "123456,-123456,123456,123,-123,123,0.1234,123.0989,12345.67890,'abcdefghi',DATE '2001-03-22',TIME '13:40:30.666666',TIMESTAMP '1997-09-03 09:33:30.555555',\n" + "INTERVAL '2-7' YEAR TO MONTH,INTERVAL '96' YEAR,INTERVAL '9' MONTH,INTERVAL '9' DAY,INTERVAL '4-5' YEAR TO MONTH,\n" + "INTERVAL '7 8' DAY TO HOUR,INTERVAL '12' HOUR,INTERVAL '30' MINUTE,INTERVAL '60' SECOND,INTERVAL '2:5' HOUR TO MINUTE,\n" + "INTERVAL '5:4:3' HOUR TO SECOND,INTERVAL '9:2' MINUTE TO SECOND)"; pStmt = conn.prepareStatement(insert); startTime = System.currentTimeMillis(); insert = "insert into " + IN1 + " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; pStmt = conn.prepareStatement(insert); startTime = System.currentTimeMillis(); try { for (int j = 1; j <= total; j++) { pStmt.setInt(1, j); long ix = -2*45; pStmt.setLong(2, ix); pStmt.setString(3, "abc"); float fx = 1234.5678f; pStmt.setFloat(4, fx); //NUMERIC(18,4) fx = -1234.5678f; pStmt.setFloat(5, fx); //NUMERIC(6) SIGNED pStmt.setDouble(6, 123456789.123456789); //NUMERIC(128,30) UNSIGNED pStmt.setInt(7, 12); //DECIMAL pStmt.setInt(8, -123); //DECIMAL(18,4) SIGNED fx = 12.56f; pStmt.setFloat(9, fx); //DECIMAL(9,5) UNSIGNED pStmt.setInt(10, 123456); //INTEGER pStmt.setInt(11, -123456); //INTEGER SIGNED pStmt.setInt(12, 123456); //INTEGER UNSIGNED pStmt.setInt(13, 123); //SMALLINT pStmt.setInt(14, -123); //SMALLINT SIGNED pStmt.setInt(15, 123); //SMALLINT UNSIGNED fx = 0.1234f; pStmt.setFloat(16, fx); //FLOAT(5) fx = 123.0989f; pStmt.setFloat(17, fx); //REAL pStmt.setDouble(18, 12345.67890); //DOUBLE PRECISION pStmt.setString(19, "abcdefghi"); //VARCHAR(1000) Date x = new Date(2000,12,8); pStmt.setDate(20, x); //DATE Time t = new Time(6, 30, 45); pStmt.setTime(21, t); //TIME Timestamp ts = new Timestamp(2000, 12, 8, 6, 30, 45, 10); pStmt.setTimestamp(22, ts); //TIMESTAMP pStmt.setString(23, "2-7"); //INTERVAL YEAR TO MONTH pStmt.setString(24, "96"); //INTERVAL YEAR pStmt.setString(25, "9"); //INTERVAL MONTH pStmt.setString(26, "9"); //INTERVAL DAY pStmt.setString(27, "4-5"); //INTERVAL YEAR TO MONTH pStmt.setString(28, "7 8"); //INTERVAL DAY TO HOUR pStmt.setString(29, "12"); //INTERVAL HOUR pStmt.setString(30, "30"); //INTERVAL MINUTE pStmt.setString(31, "60"); //INTERVAL SECOND pStmt.setString(32, "2:5"); //INTERVAL HOUR TO MINUTE pStmt.setString(33, "5:4:3"); //INTERVAL HOUR TO SECOND pStmt.setString(34, "9:2"); //INTERVAL MINUTE TO SECOND pStmt.addBatch(); } insertCount = pStmt.executeBatch(); for (int i = 0; i < insertCount.length; i++) { if ((insertCount[i] != -2) && (insertCount[i] != 1)) { pass = false; System.out.println("Batch6 : ERROR: Expecting return code for " + i + "th command: -2 or 1, but got : " + insertCount[i]); } } } catch (BatchUpdateException bue) { System.out.println("Batch6 : ERROR: Exception in insert batch mode....."); bue.printStackTrace(); System.out.println(bue.getMessage()); handleBatchUpdateException(bue); } // Check the SQLWarning java.sql.SQLWarning sw = pStmt.getWarnings(); int totalW = 0; while (sw != null) { System.out.println("SQLMessage : " + sw.getMessage()); System.out.println("SQLState : " + sw.getSQLState()); System.out.println("ErrorCode : " + sw.getErrorCode()); totalW++; sw = sw.getNextWarning(); } int updateRowCount = pStmt.getUpdateCount(); if (updateRowCount != TOTALUPDATECOUNT) { System.out.println("Batch6: ERROR: Expecting updateRowCount to be " + TOTALUPDATECOUNT + " but got " + updateRowCount); pass = false; } // Verify the inserted rows stmt = conn.createStatement(); int totalI = 0; rs = stmt.executeQuery("select * from " + IN1); if (rs != null) { ResultSetMetaData rsMD = rs.getMetaData(); while (rs.next()) { totalI++; } rs.close(); } if (totalI != TOTALUPDATECOUNT) { pass = false; System.out.println("Batch6 : ERROR: Expecting total of " + totalI + " rows inserted"); } pStmt.close(); pStmt = null; stmt.close(); conn.close(); }// end of try catch (Exception e) { pass = false; e.printStackTrace(); System.out.println(e.getMessage()); } finally { /**/ if (pass) System.out.println("JDBCBatch6 : Passed"); else System.out.println("JDBCBatch6 : FAILED"); /**/ assertEquals(true, pass); } System.out.println("JDBCBatch6 : Done"); } public static void handleBatchUpdateException(BatchUpdateException e) { int[] bueUpdateCount = e.getUpdateCounts(); Throwable cause = e.getCause(); while (cause != null) cause = cause.getCause(); SQLException nextException = e.getNextException(); while (nextException != null) { cause = nextException.getCause(); while (cause != null) cause = cause.getCause(); nextException = nextException.getNextException(); } } }
googleapis/google-api-java-client-services
37,727
clients/google-api-services-retail/v2alpha/1.31.0/com/google/api/services/retail/v2alpha/model/GoogleCloudRetailV2alphaUserEvent.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.v2alpha.model; /** * UserEvent captures all metadata information Retail API needs to know about how end users interact * with customers' website. * * <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 GoogleCloudRetailV2alphaUserEvent extends com.google.api.client.json.GenericJson { /** * Extra user event features to include in the recommendation model. If you provide custom * attributes for ingested user events, also include them in the user events that you associate * with prediction requests. Custom attribute formatting must be consistent between imported * events and events provided with prediction requests. This lets the Retail API use those custom * attributes when training models and serving predictions, which helps improve recommendation * quality. This field needs to pass all below criteria, otherwise an INVALID_ARGUMENT error is * returned: * The key must be a UTF-8 encoded string with a length limit of 5,000 characters. * * For text attributes, at most 400 values are allowed. Empty values are not allowed. Each value * must be a UTF-8 encoded string with a length limit of 256 characters. * For number attributes, * at most 400 values are allowed. For product recommendations, an example of extra user * information is traffic_channel, which is how a user arrives at the site. Users can arrive at * the site by coming to the site directly, coming through Google search, or in other ways. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, GoogleCloudRetailV2alphaCustomAttribute> attributes; static { // hack to force ProGuard to consider GoogleCloudRetailV2alphaCustomAttribute 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(GoogleCloudRetailV2alphaCustomAttribute.class); } /** * Highly recommended for user events that are the result of PredictionService.Predict. This field * enables accurate attribution of recommendation model performance. The value must be a valid * PredictResponse.attribution_token for user events that are the result of * PredictionService.Predict. The value must be a valid SearchResponse.attribution_token for user * events that are the result of SearchService.Search. This token enables us to accurately * attribute page view or purchase back to the event and the particular predict response * containing this clicked/purchased product. If user clicks on product K in the recommendation * results, pass PredictResponse.attribution_token as a URL parameter to product K's page. When * recording events on product K's page, log the PredictResponse.attribution_token to this field. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String attributionToken; /** * The ID or name of the associated shopping cart. This ID is used to associate multiple items * added or present in the cart before purchase. This can only be set for `add-to-cart`, * `purchase-complete`, or `shopping-cart-page-view` events. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String cartId; /** * The main auto-completion details related to the event. This field should be set for `search` * event when autocomplete function is enabled and the user clicks a suggestion for search. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudRetailV2alphaCompletionDetail completionDetail; /** * Only required for UserEventService.ImportUserEvents method. Timestamp of when the user event * happened. * The value may be {@code null}. */ @com.google.api.client.util.Key private String eventTime; /** * Required. User event type. Allowed values are: * `add-to-cart`: Products being added to cart. * * `category-page-view`: Special pages such as sale or promotion pages viewed. * `detail-page- * view`: Products detail page viewed. * `home-page-view`: Homepage viewed. * `promotion-offered`: * Promotion is offered to a user. * `promotion-not-offered`: Promotion is not offered to a user. * * `purchase-complete`: User finishing a purchase. * `search`: Product search. * `shopping-cart- * page-view`: User viewing a shopping cart. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String eventType; /** * A list of identifiers for the independent experiment groups this user event belongs to. This is * used to distinguish between user events associated with different experiment setups (e.g. using * Retail API, using different recommendation models). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> experimentIds; /** * The filter syntax consists of an expression language for constructing a predicate from one or * more fields of the products being filtered. See SearchRequest.filter for definition and syntax. * The value must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an * INVALID_ARGUMENT error is returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String filter; /** * An integer that specifies the current offset for pagination (the 0-indexed starting location, * amongst the products deemed by the API as relevant). See SearchRequest.offset for definition. * If this field is negative, an INVALID_ARGUMENT is returned. This can only be set for `search` * events. Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error 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. See SearchRequest.order_by for definition and syntax. * The value must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an * INVALID_ARGUMENT error is returned. This can only be set for `search` events. Other event types * should not set this field. Otherwise, an INVALID_ARGUMENT error 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. 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"]. Required for `category-page-view` events. At least one of * search_query or page_categories is required for `search` events. Other event types should not * set this field. Otherwise, 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> pageCategories; /** * A unique ID of a web page view. This should be kept the same for all user events triggered from * the same pageview. For example, an item detail page view could trigger multiple events as the * user is browsing the page. The `pageViewId` property should be kept the same for all these * events so that they can be grouped together properly. When using the client side event * reporting with JavaScript pixel and Google Tag Manager, this value is filled in automatically. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String pageViewId; /** * The main product details related to the event. This field is optional except for the following * event types: * `add-to-cart` * `detail-page-view` * `purchase-complete` In a `search` event, * this field represents the products returned to the end user on the current page (the end user * may have not finished browsing the whole page yet). When a new page is returned to the end * user, after pagination/filtering/ordering even for the same query, a new `search` event with * different product_details is desired. The end user may have not finished browsing the whole * page yet. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudRetailV2alphaProductDetail> productDetails; static { // hack to force ProGuard to consider GoogleCloudRetailV2alphaProductDetail 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(GoogleCloudRetailV2alphaProductDetail.class); } /** * A transaction represents the entire purchase transaction. Required for `purchase-complete` * events. Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is * returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudRetailV2alphaPurchaseTransaction purchaseTransaction; /** * The referrer URL of the current page. When using the client side event reporting with * JavaScript pixel and Google Tag Manager, this value is filled in automatically. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String referrerUri; /** * The user's search query. See SearchRequest.query for definition. The value must be a UTF-8 * encoded string with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is * returned. At least one of search_query or page_categories is required for `search` events. * Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String searchQuery; /** * A unique identifier for tracking a visitor session with a length limit of 128 bytes. A session * is an aggregation of an end user behavior in a time span. A general guideline to populate the * sesion_id: 1. If user has no activity for 30 min, a new session_id should be assigned. 2. The * session_id should be unique across users, suggest use uuid or add visitor_id as prefix. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String sessionId; /** * Complete URL (window.location.href) of the user's current page. When using the client side * event reporting with JavaScript pixel and Google Tag Manager, this value is filled in * automatically. Maximum length 5,000 characters. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String uri; /** * User information. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudRetailV2alphaUserInfo userInfo; /** * 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 log in/out of the website. Don't set * the field to the same fixed ID for different users. This mixes the event history of those users * together, which results in degraded model quality. The field must be a UTF-8 encoded string * with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. The * field should not contain PII or user-data. We recommend to use Google Analytics [Client * ID](https://developers.google.com/analytics/devguides/collection/analyticsjs/field- * reference#clientId) for this field. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String visitorId; /** * Extra user event features to include in the recommendation model. If you provide custom * attributes for ingested user events, also include them in the user events that you associate * with prediction requests. Custom attribute formatting must be consistent between imported * events and events provided with prediction requests. This lets the Retail API use those custom * attributes when training models and serving predictions, which helps improve recommendation * quality. This field needs to pass all below criteria, otherwise an INVALID_ARGUMENT error is * returned: * The key must be a UTF-8 encoded string with a length limit of 5,000 characters. * * For text attributes, at most 400 values are allowed. Empty values are not allowed. Each value * must be a UTF-8 encoded string with a length limit of 256 characters. * For number attributes, * at most 400 values are allowed. For product recommendations, an example of extra user * information is traffic_channel, which is how a user arrives at the site. Users can arrive at * the site by coming to the site directly, coming through Google search, or in other ways. * @return value or {@code null} for none */ public java.util.Map<String, GoogleCloudRetailV2alphaCustomAttribute> getAttributes() { return attributes; } /** * Extra user event features to include in the recommendation model. If you provide custom * attributes for ingested user events, also include them in the user events that you associate * with prediction requests. Custom attribute formatting must be consistent between imported * events and events provided with prediction requests. This lets the Retail API use those custom * attributes when training models and serving predictions, which helps improve recommendation * quality. This field needs to pass all below criteria, otherwise an INVALID_ARGUMENT error is * returned: * The key must be a UTF-8 encoded string with a length limit of 5,000 characters. * * For text attributes, at most 400 values are allowed. Empty values are not allowed. Each value * must be a UTF-8 encoded string with a length limit of 256 characters. * For number attributes, * at most 400 values are allowed. For product recommendations, an example of extra user * information is traffic_channel, which is how a user arrives at the site. Users can arrive at * the site by coming to the site directly, coming through Google search, or in other ways. * @param attributes attributes or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setAttributes(java.util.Map<String, GoogleCloudRetailV2alphaCustomAttribute> attributes) { this.attributes = attributes; return this; } /** * Highly recommended for user events that are the result of PredictionService.Predict. This field * enables accurate attribution of recommendation model performance. The value must be a valid * PredictResponse.attribution_token for user events that are the result of * PredictionService.Predict. The value must be a valid SearchResponse.attribution_token for user * events that are the result of SearchService.Search. This token enables us to accurately * attribute page view or purchase back to the event and the particular predict response * containing this clicked/purchased product. If user clicks on product K in the recommendation * results, pass PredictResponse.attribution_token as a URL parameter to product K's page. When * recording events on product K's page, log the PredictResponse.attribution_token to this field. * @return value or {@code null} for none */ public java.lang.String getAttributionToken() { return attributionToken; } /** * Highly recommended for user events that are the result of PredictionService.Predict. This field * enables accurate attribution of recommendation model performance. The value must be a valid * PredictResponse.attribution_token for user events that are the result of * PredictionService.Predict. The value must be a valid SearchResponse.attribution_token for user * events that are the result of SearchService.Search. This token enables us to accurately * attribute page view or purchase back to the event and the particular predict response * containing this clicked/purchased product. If user clicks on product K in the recommendation * results, pass PredictResponse.attribution_token as a URL parameter to product K's page. When * recording events on product K's page, log the PredictResponse.attribution_token to this field. * @param attributionToken attributionToken or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setAttributionToken(java.lang.String attributionToken) { this.attributionToken = attributionToken; return this; } /** * The ID or name of the associated shopping cart. This ID is used to associate multiple items * added or present in the cart before purchase. This can only be set for `add-to-cart`, * `purchase-complete`, or `shopping-cart-page-view` events. * @return value or {@code null} for none */ public java.lang.String getCartId() { return cartId; } /** * The ID or name of the associated shopping cart. This ID is used to associate multiple items * added or present in the cart before purchase. This can only be set for `add-to-cart`, * `purchase-complete`, or `shopping-cart-page-view` events. * @param cartId cartId or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setCartId(java.lang.String cartId) { this.cartId = cartId; return this; } /** * The main auto-completion details related to the event. This field should be set for `search` * event when autocomplete function is enabled and the user clicks a suggestion for search. * @return value or {@code null} for none */ public GoogleCloudRetailV2alphaCompletionDetail getCompletionDetail() { return completionDetail; } /** * The main auto-completion details related to the event. This field should be set for `search` * event when autocomplete function is enabled and the user clicks a suggestion for search. * @param completionDetail completionDetail or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setCompletionDetail(GoogleCloudRetailV2alphaCompletionDetail completionDetail) { this.completionDetail = completionDetail; return this; } /** * Only required for UserEventService.ImportUserEvents method. Timestamp of when the user event * happened. * @return value or {@code null} for none */ public String getEventTime() { return eventTime; } /** * Only required for UserEventService.ImportUserEvents method. Timestamp of when the user event * happened. * @param eventTime eventTime or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setEventTime(String eventTime) { this.eventTime = eventTime; return this; } /** * Required. User event type. Allowed values are: * `add-to-cart`: Products being added to cart. * * `category-page-view`: Special pages such as sale or promotion pages viewed. * `detail-page- * view`: Products detail page viewed. * `home-page-view`: Homepage viewed. * `promotion-offered`: * Promotion is offered to a user. * `promotion-not-offered`: Promotion is not offered to a user. * * `purchase-complete`: User finishing a purchase. * `search`: Product search. * `shopping-cart- * page-view`: User viewing a shopping cart. * @return value or {@code null} for none */ public java.lang.String getEventType() { return eventType; } /** * Required. User event type. Allowed values are: * `add-to-cart`: Products being added to cart. * * `category-page-view`: Special pages such as sale or promotion pages viewed. * `detail-page- * view`: Products detail page viewed. * `home-page-view`: Homepage viewed. * `promotion-offered`: * Promotion is offered to a user. * `promotion-not-offered`: Promotion is not offered to a user. * * `purchase-complete`: User finishing a purchase. * `search`: Product search. * `shopping-cart- * page-view`: User viewing a shopping cart. * @param eventType eventType or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setEventType(java.lang.String eventType) { this.eventType = eventType; return this; } /** * A list of identifiers for the independent experiment groups this user event belongs to. This is * used to distinguish between user events associated with different experiment setups (e.g. using * Retail API, using different recommendation models). * @return value or {@code null} for none */ public java.util.List<java.lang.String> getExperimentIds() { return experimentIds; } /** * A list of identifiers for the independent experiment groups this user event belongs to. This is * used to distinguish between user events associated with different experiment setups (e.g. using * Retail API, using different recommendation models). * @param experimentIds experimentIds or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setExperimentIds(java.util.List<java.lang.String> experimentIds) { this.experimentIds = experimentIds; return this; } /** * The filter syntax consists of an expression language for constructing a predicate from one or * more fields of the products being filtered. See SearchRequest.filter for definition and syntax. * The value must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an * INVALID_ARGUMENT error 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. See SearchRequest.filter for definition and syntax. * The value must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an * INVALID_ARGUMENT error is returned. * @param filter filter or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setFilter(java.lang.String filter) { this.filter = filter; return this; } /** * An integer that specifies the current offset for pagination (the 0-indexed starting location, * amongst the products deemed by the API as relevant). See SearchRequest.offset for definition. * If this field is negative, an INVALID_ARGUMENT is returned. This can only be set for `search` * events. Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is * returned. * @return value or {@code null} for none */ public java.lang.Integer getOffset() { return offset; } /** * An integer that specifies the current offset for pagination (the 0-indexed starting location, * amongst the products deemed by the API as relevant). See SearchRequest.offset for definition. * If this field is negative, an INVALID_ARGUMENT is returned. This can only be set for `search` * events. Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is * returned. * @param offset offset or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setOffset(java.lang.Integer offset) { this.offset = offset; return this; } /** * The order in which products are returned. See SearchRequest.order_by for definition and syntax. * The value must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an * INVALID_ARGUMENT error is returned. This can only be set for `search` events. Other event types * should not set this field. Otherwise, an INVALID_ARGUMENT error is returned. * @return value or {@code null} for none */ public java.lang.String getOrderBy() { return orderBy; } /** * The order in which products are returned. See SearchRequest.order_by for definition and syntax. * The value must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an * INVALID_ARGUMENT error is returned. This can only be set for `search` events. Other event types * should not set this field. Otherwise, an INVALID_ARGUMENT error is returned. * @param orderBy orderBy or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setOrderBy(java.lang.String orderBy) { this.orderBy = orderBy; return this; } /** * The categories associated with a category page. 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"]. Required for `category-page-view` events. At least one of * search_query or page_categories is required for `search` events. Other event types should not * set this field. Otherwise, an INVALID_ARGUMENT error is returned. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPageCategories() { return pageCategories; } /** * The categories associated with a category page. 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"]. Required for `category-page-view` events. At least one of * search_query or page_categories is required for `search` events. Other event types should not * set this field. Otherwise, an INVALID_ARGUMENT error is returned. * @param pageCategories pageCategories or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setPageCategories(java.util.List<java.lang.String> pageCategories) { this.pageCategories = pageCategories; return this; } /** * A unique ID of a web page view. This should be kept the same for all user events triggered from * the same pageview. For example, an item detail page view could trigger multiple events as the * user is browsing the page. The `pageViewId` property should be kept the same for all these * events so that they can be grouped together properly. When using the client side event * reporting with JavaScript pixel and Google Tag Manager, this value is filled in automatically. * @return value or {@code null} for none */ public java.lang.String getPageViewId() { return pageViewId; } /** * A unique ID of a web page view. This should be kept the same for all user events triggered from * the same pageview. For example, an item detail page view could trigger multiple events as the * user is browsing the page. The `pageViewId` property should be kept the same for all these * events so that they can be grouped together properly. When using the client side event * reporting with JavaScript pixel and Google Tag Manager, this value is filled in automatically. * @param pageViewId pageViewId or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setPageViewId(java.lang.String pageViewId) { this.pageViewId = pageViewId; return this; } /** * The main product details related to the event. This field is optional except for the following * event types: * `add-to-cart` * `detail-page-view` * `purchase-complete` In a `search` event, * this field represents the products returned to the end user on the current page (the end user * may have not finished browsing the whole page yet). When a new page is returned to the end * user, after pagination/filtering/ordering even for the same query, a new `search` event with * different product_details is desired. The end user may have not finished browsing the whole * page yet. * @return value or {@code null} for none */ public java.util.List<GoogleCloudRetailV2alphaProductDetail> getProductDetails() { return productDetails; } /** * The main product details related to the event. This field is optional except for the following * event types: * `add-to-cart` * `detail-page-view` * `purchase-complete` In a `search` event, * this field represents the products returned to the end user on the current page (the end user * may have not finished browsing the whole page yet). When a new page is returned to the end * user, after pagination/filtering/ordering even for the same query, a new `search` event with * different product_details is desired. The end user may have not finished browsing the whole * page yet. * @param productDetails productDetails or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setProductDetails(java.util.List<GoogleCloudRetailV2alphaProductDetail> productDetails) { this.productDetails = productDetails; return this; } /** * A transaction represents the entire purchase transaction. Required for `purchase-complete` * events. Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is * returned. * @return value or {@code null} for none */ public GoogleCloudRetailV2alphaPurchaseTransaction getPurchaseTransaction() { return purchaseTransaction; } /** * A transaction represents the entire purchase transaction. Required for `purchase-complete` * events. Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is * returned. * @param purchaseTransaction purchaseTransaction or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setPurchaseTransaction(GoogleCloudRetailV2alphaPurchaseTransaction purchaseTransaction) { this.purchaseTransaction = purchaseTransaction; return this; } /** * The referrer URL of the current page. When using the client side event reporting with * JavaScript pixel and Google Tag Manager, this value is filled in automatically. * @return value or {@code null} for none */ public java.lang.String getReferrerUri() { return referrerUri; } /** * The referrer URL of the current page. When using the client side event reporting with * JavaScript pixel and Google Tag Manager, this value is filled in automatically. * @param referrerUri referrerUri or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setReferrerUri(java.lang.String referrerUri) { this.referrerUri = referrerUri; return this; } /** * The user's search query. See SearchRequest.query for definition. The value must be a UTF-8 * encoded string with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is * returned. At least one of search_query or page_categories is required for `search` events. * Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is returned. * @return value or {@code null} for none */ public java.lang.String getSearchQuery() { return searchQuery; } /** * The user's search query. See SearchRequest.query for definition. The value must be a UTF-8 * encoded string with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is * returned. At least one of search_query or page_categories is required for `search` events. * Other event types should not set this field. Otherwise, an INVALID_ARGUMENT error is returned. * @param searchQuery searchQuery or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setSearchQuery(java.lang.String searchQuery) { this.searchQuery = searchQuery; return this; } /** * A unique identifier for tracking a visitor session with a length limit of 128 bytes. A session * is an aggregation of an end user behavior in a time span. A general guideline to populate the * sesion_id: 1. If user has no activity for 30 min, a new session_id should be assigned. 2. The * session_id should be unique across users, suggest use uuid or add visitor_id as prefix. * @return value or {@code null} for none */ public java.lang.String getSessionId() { return sessionId; } /** * A unique identifier for tracking a visitor session with a length limit of 128 bytes. A session * is an aggregation of an end user behavior in a time span. A general guideline to populate the * sesion_id: 1. If user has no activity for 30 min, a new session_id should be assigned. 2. The * session_id should be unique across users, suggest use uuid or add visitor_id as prefix. * @param sessionId sessionId or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setSessionId(java.lang.String sessionId) { this.sessionId = sessionId; return this; } /** * Complete URL (window.location.href) of the user's current page. When using the client side * event reporting with JavaScript pixel and Google Tag Manager, this value is filled in * automatically. Maximum length 5,000 characters. * @return value or {@code null} for none */ public java.lang.String getUri() { return uri; } /** * Complete URL (window.location.href) of the user's current page. When using the client side * event reporting with JavaScript pixel and Google Tag Manager, this value is filled in * automatically. Maximum length 5,000 characters. * @param uri uri or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setUri(java.lang.String uri) { this.uri = uri; return this; } /** * User information. * @return value or {@code null} for none */ public GoogleCloudRetailV2alphaUserInfo getUserInfo() { return userInfo; } /** * User information. * @param userInfo userInfo or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setUserInfo(GoogleCloudRetailV2alphaUserInfo userInfo) { this.userInfo = userInfo; 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 log in/out of the website. Don't set * the field to the same fixed ID for different users. This mixes the event history of those users * together, which results in degraded model quality. The field must be a UTF-8 encoded string * with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. The * field should not contain PII or user-data. We recommend to use Google Analytics [Client * ID](https://developers.google.com/analytics/devguides/collection/analyticsjs/field- * reference#clientId) for this field. * @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 log in/out of the website. Don't set * the field to the same fixed ID for different users. This mixes the event history of those users * together, which results in degraded model quality. The field must be a UTF-8 encoded string * with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. The * field should not contain PII or user-data. We recommend to use Google Analytics [Client * ID](https://developers.google.com/analytics/devguides/collection/analyticsjs/field- * reference#clientId) for this field. * @param visitorId visitorId or {@code null} for none */ public GoogleCloudRetailV2alphaUserEvent setVisitorId(java.lang.String visitorId) { this.visitorId = visitorId; return this; } @Override public GoogleCloudRetailV2alphaUserEvent set(String fieldName, Object value) { return (GoogleCloudRetailV2alphaUserEvent) super.set(fieldName, value); } @Override public GoogleCloudRetailV2alphaUserEvent clone() { return (GoogleCloudRetailV2alphaUserEvent) super.clone(); } }
googleapis/google-cloud-java
37,325
java-biglake/proto-google-cloud-biglake-v1/src/main/java/com/google/cloud/bigquery/biglake/v1/CreateTableRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/bigquery/biglake/v1/metastore.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.bigquery.biglake.v1; /** * * * <pre> * Request message for the CreateTable method. * </pre> * * Protobuf type {@code google.cloud.bigquery.biglake.v1.CreateTableRequest} */ public final class CreateTableRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.bigquery.biglake.v1.CreateTableRequest) CreateTableRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateTableRequest.newBuilder() to construct. private CreateTableRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateTableRequest() { parent_ = ""; tableId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateTableRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.biglake.v1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1_CreateTableRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.biglake.v1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1_CreateTableRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.biglake.v1.CreateTableRequest.class, com.google.cloud.bigquery.biglake.v1.CreateTableRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource where this table will be created. * Format: * projects/{project_id_or_number}/locations/{location_id}/catalogs/{catalog_id}/databases/{database_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The parent resource where this table will be created. * Format: * projects/{project_id_or_number}/locations/{location_id}/catalogs/{catalog_id}/databases/{database_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TABLE_FIELD_NUMBER = 2; private com.google.cloud.bigquery.biglake.v1.Table table_; /** * * * <pre> * Required. The table to create. The `name` field does not need to be * provided for the table creation. * </pre> * * <code> * .google.cloud.bigquery.biglake.v1.Table table = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the table field is set. */ @java.lang.Override public boolean hasTable() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The table to create. The `name` field does not need to be * provided for the table creation. * </pre> * * <code> * .google.cloud.bigquery.biglake.v1.Table table = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The table. */ @java.lang.Override public com.google.cloud.bigquery.biglake.v1.Table getTable() { return table_ == null ? com.google.cloud.bigquery.biglake.v1.Table.getDefaultInstance() : table_; } /** * * * <pre> * Required. The table to create. The `name` field does not need to be * provided for the table creation. * </pre> * * <code> * .google.cloud.bigquery.biglake.v1.Table table = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.bigquery.biglake.v1.TableOrBuilder getTableOrBuilder() { return table_ == null ? com.google.cloud.bigquery.biglake.v1.Table.getDefaultInstance() : table_; } public static final int TABLE_ID_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object tableId_ = ""; /** * * * <pre> * Required. The ID to use for the table, which will become the final * component of the table's resource name. * </pre> * * <code>string table_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The tableId. */ @java.lang.Override public java.lang.String getTableId() { java.lang.Object ref = tableId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); tableId_ = s; return s; } } /** * * * <pre> * Required. The ID to use for the table, which will become the final * component of the table's resource name. * </pre> * * <code>string table_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for tableId. */ @java.lang.Override public com.google.protobuf.ByteString getTableIdBytes() { java.lang.Object ref = tableId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); tableId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getTable()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(tableId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, tableId_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getTable()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(tableId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, tableId_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.bigquery.biglake.v1.CreateTableRequest)) { return super.equals(obj); } com.google.cloud.bigquery.biglake.v1.CreateTableRequest other = (com.google.cloud.bigquery.biglake.v1.CreateTableRequest) obj; if (!getParent().equals(other.getParent())) return false; if (hasTable() != other.hasTable()) return false; if (hasTable()) { if (!getTable().equals(other.getTable())) return false; } if (!getTableId().equals(other.getTableId())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); if (hasTable()) { hash = (37 * hash) + TABLE_FIELD_NUMBER; hash = (53 * hash) + getTable().hashCode(); } hash = (37 * hash) + TABLE_ID_FIELD_NUMBER; hash = (53 * hash) + getTableId().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.bigquery.biglake.v1.CreateTableRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.biglake.v1.CreateTableRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.biglake.v1.CreateTableRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.biglake.v1.CreateTableRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.biglake.v1.CreateTableRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.biglake.v1.CreateTableRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.biglake.v1.CreateTableRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.biglake.v1.CreateTableRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.biglake.v1.CreateTableRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.bigquery.biglake.v1.CreateTableRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.biglake.v1.CreateTableRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.biglake.v1.CreateTableRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.bigquery.biglake.v1.CreateTableRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for the CreateTable method. * </pre> * * Protobuf type {@code google.cloud.bigquery.biglake.v1.CreateTableRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.bigquery.biglake.v1.CreateTableRequest) com.google.cloud.bigquery.biglake.v1.CreateTableRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.biglake.v1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1_CreateTableRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.biglake.v1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1_CreateTableRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.biglake.v1.CreateTableRequest.class, com.google.cloud.bigquery.biglake.v1.CreateTableRequest.Builder.class); } // Construct using com.google.cloud.bigquery.biglake.v1.CreateTableRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getTableFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; table_ = null; if (tableBuilder_ != null) { tableBuilder_.dispose(); tableBuilder_ = null; } tableId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.bigquery.biglake.v1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1_CreateTableRequest_descriptor; } @java.lang.Override public com.google.cloud.bigquery.biglake.v1.CreateTableRequest getDefaultInstanceForType() { return com.google.cloud.bigquery.biglake.v1.CreateTableRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.bigquery.biglake.v1.CreateTableRequest build() { com.google.cloud.bigquery.biglake.v1.CreateTableRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.bigquery.biglake.v1.CreateTableRequest buildPartial() { com.google.cloud.bigquery.biglake.v1.CreateTableRequest result = new com.google.cloud.bigquery.biglake.v1.CreateTableRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.bigquery.biglake.v1.CreateTableRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.table_ = tableBuilder_ == null ? table_ : tableBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.tableId_ = tableId_; } 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.bigquery.biglake.v1.CreateTableRequest) { return mergeFrom((com.google.cloud.bigquery.biglake.v1.CreateTableRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.bigquery.biglake.v1.CreateTableRequest other) { if (other == com.google.cloud.bigquery.biglake.v1.CreateTableRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasTable()) { mergeTable(other.getTable()); } if (!other.getTableId().isEmpty()) { tableId_ = other.tableId_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getTableFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { tableId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource where this table will be created. * Format: * projects/{project_id_or_number}/locations/{location_id}/catalogs/{catalog_id}/databases/{database_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The parent resource where this table will be created. * Format: * projects/{project_id_or_number}/locations/{location_id}/catalogs/{catalog_id}/databases/{database_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The parent resource where this table will be created. * Format: * projects/{project_id_or_number}/locations/{location_id}/catalogs/{catalog_id}/databases/{database_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The parent resource where this table will be created. * Format: * projects/{project_id_or_number}/locations/{location_id}/catalogs/{catalog_id}/databases/{database_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The parent resource where this table will be created. * Format: * projects/{project_id_or_number}/locations/{location_id}/catalogs/{catalog_id}/databases/{database_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.cloud.bigquery.biglake.v1.Table table_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.biglake.v1.Table, com.google.cloud.bigquery.biglake.v1.Table.Builder, com.google.cloud.bigquery.biglake.v1.TableOrBuilder> tableBuilder_; /** * * * <pre> * Required. The table to create. The `name` field does not need to be * provided for the table creation. * </pre> * * <code> * .google.cloud.bigquery.biglake.v1.Table table = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the table field is set. */ public boolean hasTable() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The table to create. The `name` field does not need to be * provided for the table creation. * </pre> * * <code> * .google.cloud.bigquery.biglake.v1.Table table = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The table. */ public com.google.cloud.bigquery.biglake.v1.Table getTable() { if (tableBuilder_ == null) { return table_ == null ? com.google.cloud.bigquery.biglake.v1.Table.getDefaultInstance() : table_; } else { return tableBuilder_.getMessage(); } } /** * * * <pre> * Required. The table to create. The `name` field does not need to be * provided for the table creation. * </pre> * * <code> * .google.cloud.bigquery.biglake.v1.Table table = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setTable(com.google.cloud.bigquery.biglake.v1.Table value) { if (tableBuilder_ == null) { if (value == null) { throw new NullPointerException(); } table_ = value; } else { tableBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The table to create. The `name` field does not need to be * provided for the table creation. * </pre> * * <code> * .google.cloud.bigquery.biglake.v1.Table table = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setTable(com.google.cloud.bigquery.biglake.v1.Table.Builder builderForValue) { if (tableBuilder_ == null) { table_ = builderForValue.build(); } else { tableBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The table to create. The `name` field does not need to be * provided for the table creation. * </pre> * * <code> * .google.cloud.bigquery.biglake.v1.Table table = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeTable(com.google.cloud.bigquery.biglake.v1.Table value) { if (tableBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && table_ != null && table_ != com.google.cloud.bigquery.biglake.v1.Table.getDefaultInstance()) { getTableBuilder().mergeFrom(value); } else { table_ = value; } } else { tableBuilder_.mergeFrom(value); } if (table_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The table to create. The `name` field does not need to be * provided for the table creation. * </pre> * * <code> * .google.cloud.bigquery.biglake.v1.Table table = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearTable() { bitField0_ = (bitField0_ & ~0x00000002); table_ = null; if (tableBuilder_ != null) { tableBuilder_.dispose(); tableBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The table to create. The `name` field does not need to be * provided for the table creation. * </pre> * * <code> * .google.cloud.bigquery.biglake.v1.Table table = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.bigquery.biglake.v1.Table.Builder getTableBuilder() { bitField0_ |= 0x00000002; onChanged(); return getTableFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The table to create. The `name` field does not need to be * provided for the table creation. * </pre> * * <code> * .google.cloud.bigquery.biglake.v1.Table table = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.bigquery.biglake.v1.TableOrBuilder getTableOrBuilder() { if (tableBuilder_ != null) { return tableBuilder_.getMessageOrBuilder(); } else { return table_ == null ? com.google.cloud.bigquery.biglake.v1.Table.getDefaultInstance() : table_; } } /** * * * <pre> * Required. The table to create. The `name` field does not need to be * provided for the table creation. * </pre> * * <code> * .google.cloud.bigquery.biglake.v1.Table table = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.biglake.v1.Table, com.google.cloud.bigquery.biglake.v1.Table.Builder, com.google.cloud.bigquery.biglake.v1.TableOrBuilder> getTableFieldBuilder() { if (tableBuilder_ == null) { tableBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.biglake.v1.Table, com.google.cloud.bigquery.biglake.v1.Table.Builder, com.google.cloud.bigquery.biglake.v1.TableOrBuilder>( getTable(), getParentForChildren(), isClean()); table_ = null; } return tableBuilder_; } private java.lang.Object tableId_ = ""; /** * * * <pre> * Required. The ID to use for the table, which will become the final * component of the table's resource name. * </pre> * * <code>string table_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The tableId. */ public java.lang.String getTableId() { java.lang.Object ref = tableId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); tableId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The ID to use for the table, which will become the final * component of the table's resource name. * </pre> * * <code>string table_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for tableId. */ public com.google.protobuf.ByteString getTableIdBytes() { java.lang.Object ref = tableId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); tableId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The ID to use for the table, which will become the final * component of the table's resource name. * </pre> * * <code>string table_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The tableId to set. * @return This builder for chaining. */ public Builder setTableId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } tableId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The ID to use for the table, which will become the final * component of the table's resource name. * </pre> * * <code>string table_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearTableId() { tableId_ = getDefaultInstance().getTableId(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Required. The ID to use for the table, which will become the final * component of the table's resource name. * </pre> * * <code>string table_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for tableId to set. * @return This builder for chaining. */ public Builder setTableIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); tableId_ = 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.bigquery.biglake.v1.CreateTableRequest) } // @@protoc_insertion_point(class_scope:google.cloud.bigquery.biglake.v1.CreateTableRequest) private static final com.google.cloud.bigquery.biglake.v1.CreateTableRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.bigquery.biglake.v1.CreateTableRequest(); } public static com.google.cloud.bigquery.biglake.v1.CreateTableRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateTableRequest> PARSER = new com.google.protobuf.AbstractParser<CreateTableRequest>() { @java.lang.Override public CreateTableRequest 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<CreateTableRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateTableRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.bigquery.biglake.v1.CreateTableRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,355
java-retail/proto-google-cloud-retail-v2beta/src/main/java/com/google/cloud/retail/v2beta/ListServingConfigsResponse.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/serving_config_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.retail.v2beta; /** * * * <pre> * Response for ListServingConfigs method. * </pre> * * Protobuf type {@code google.cloud.retail.v2beta.ListServingConfigsResponse} */ public final class ListServingConfigsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.retail.v2beta.ListServingConfigsResponse) ListServingConfigsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListServingConfigsResponse.newBuilder() to construct. private ListServingConfigsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListServingConfigsResponse() { servingConfigs_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListServingConfigsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.retail.v2beta.ServingConfigServiceProto .internal_static_google_cloud_retail_v2beta_ListServingConfigsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.retail.v2beta.ServingConfigServiceProto .internal_static_google_cloud_retail_v2beta_ListServingConfigsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.retail.v2beta.ListServingConfigsResponse.class, com.google.cloud.retail.v2beta.ListServingConfigsResponse.Builder.class); } public static final int SERVING_CONFIGS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.retail.v2beta.ServingConfig> servingConfigs_; /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.retail.v2beta.ServingConfig> getServingConfigsList() { return servingConfigs_; } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.retail.v2beta.ServingConfigOrBuilder> getServingConfigsOrBuilderList() { return servingConfigs_; } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ @java.lang.Override public int getServingConfigsCount() { return servingConfigs_.size(); } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ @java.lang.Override public com.google.cloud.retail.v2beta.ServingConfig getServingConfigs(int index) { return servingConfigs_.get(index); } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ @java.lang.Override public com.google.cloud.retail.v2beta.ServingConfigOrBuilder getServingConfigsOrBuilder( int index) { return servingConfigs_.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 < servingConfigs_.size(); i++) { output.writeMessage(1, servingConfigs_.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 < servingConfigs_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, servingConfigs_.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.ListServingConfigsResponse)) { return super.equals(obj); } com.google.cloud.retail.v2beta.ListServingConfigsResponse other = (com.google.cloud.retail.v2beta.ListServingConfigsResponse) obj; if (!getServingConfigsList().equals(other.getServingConfigsList())) 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 (getServingConfigsCount() > 0) { hash = (37 * hash) + SERVING_CONFIGS_FIELD_NUMBER; hash = (53 * hash) + getServingConfigsList().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.ListServingConfigsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.retail.v2beta.ListServingConfigsResponse 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.ListServingConfigsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.retail.v2beta.ListServingConfigsResponse 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.ListServingConfigsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.retail.v2beta.ListServingConfigsResponse 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.ListServingConfigsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.retail.v2beta.ListServingConfigsResponse 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.ListServingConfigsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.retail.v2beta.ListServingConfigsResponse 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.ListServingConfigsResponse 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.ListServingConfigsResponse 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.ListServingConfigsResponse 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 ListServingConfigs method. * </pre> * * Protobuf type {@code google.cloud.retail.v2beta.ListServingConfigsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.retail.v2beta.ListServingConfigsResponse) com.google.cloud.retail.v2beta.ListServingConfigsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.retail.v2beta.ServingConfigServiceProto .internal_static_google_cloud_retail_v2beta_ListServingConfigsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.retail.v2beta.ServingConfigServiceProto .internal_static_google_cloud_retail_v2beta_ListServingConfigsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.retail.v2beta.ListServingConfigsResponse.class, com.google.cloud.retail.v2beta.ListServingConfigsResponse.Builder.class); } // Construct using com.google.cloud.retail.v2beta.ListServingConfigsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (servingConfigsBuilder_ == null) { servingConfigs_ = java.util.Collections.emptyList(); } else { servingConfigs_ = null; servingConfigsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.retail.v2beta.ServingConfigServiceProto .internal_static_google_cloud_retail_v2beta_ListServingConfigsResponse_descriptor; } @java.lang.Override public com.google.cloud.retail.v2beta.ListServingConfigsResponse getDefaultInstanceForType() { return com.google.cloud.retail.v2beta.ListServingConfigsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.retail.v2beta.ListServingConfigsResponse build() { com.google.cloud.retail.v2beta.ListServingConfigsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.retail.v2beta.ListServingConfigsResponse buildPartial() { com.google.cloud.retail.v2beta.ListServingConfigsResponse result = new com.google.cloud.retail.v2beta.ListServingConfigsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.retail.v2beta.ListServingConfigsResponse result) { if (servingConfigsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { servingConfigs_ = java.util.Collections.unmodifiableList(servingConfigs_); bitField0_ = (bitField0_ & ~0x00000001); } result.servingConfigs_ = servingConfigs_; } else { result.servingConfigs_ = servingConfigsBuilder_.build(); } } private void buildPartial0(com.google.cloud.retail.v2beta.ListServingConfigsResponse 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.ListServingConfigsResponse) { return mergeFrom((com.google.cloud.retail.v2beta.ListServingConfigsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.retail.v2beta.ListServingConfigsResponse other) { if (other == com.google.cloud.retail.v2beta.ListServingConfigsResponse.getDefaultInstance()) return this; if (servingConfigsBuilder_ == null) { if (!other.servingConfigs_.isEmpty()) { if (servingConfigs_.isEmpty()) { servingConfigs_ = other.servingConfigs_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureServingConfigsIsMutable(); servingConfigs_.addAll(other.servingConfigs_); } onChanged(); } } else { if (!other.servingConfigs_.isEmpty()) { if (servingConfigsBuilder_.isEmpty()) { servingConfigsBuilder_.dispose(); servingConfigsBuilder_ = null; servingConfigs_ = other.servingConfigs_; bitField0_ = (bitField0_ & ~0x00000001); servingConfigsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getServingConfigsFieldBuilder() : null; } else { servingConfigsBuilder_.addAllMessages(other.servingConfigs_); } } } 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.ServingConfig m = input.readMessage( com.google.cloud.retail.v2beta.ServingConfig.parser(), extensionRegistry); if (servingConfigsBuilder_ == null) { ensureServingConfigsIsMutable(); servingConfigs_.add(m); } else { servingConfigsBuilder_.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.ServingConfig> servingConfigs_ = java.util.Collections.emptyList(); private void ensureServingConfigsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { servingConfigs_ = new java.util.ArrayList<com.google.cloud.retail.v2beta.ServingConfig>(servingConfigs_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.retail.v2beta.ServingConfig, com.google.cloud.retail.v2beta.ServingConfig.Builder, com.google.cloud.retail.v2beta.ServingConfigOrBuilder> servingConfigsBuilder_; /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public java.util.List<com.google.cloud.retail.v2beta.ServingConfig> getServingConfigsList() { if (servingConfigsBuilder_ == null) { return java.util.Collections.unmodifiableList(servingConfigs_); } else { return servingConfigsBuilder_.getMessageList(); } } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public int getServingConfigsCount() { if (servingConfigsBuilder_ == null) { return servingConfigs_.size(); } else { return servingConfigsBuilder_.getCount(); } } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public com.google.cloud.retail.v2beta.ServingConfig getServingConfigs(int index) { if (servingConfigsBuilder_ == null) { return servingConfigs_.get(index); } else { return servingConfigsBuilder_.getMessage(index); } } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public Builder setServingConfigs( int index, com.google.cloud.retail.v2beta.ServingConfig value) { if (servingConfigsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureServingConfigsIsMutable(); servingConfigs_.set(index, value); onChanged(); } else { servingConfigsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public Builder setServingConfigs( int index, com.google.cloud.retail.v2beta.ServingConfig.Builder builderForValue) { if (servingConfigsBuilder_ == null) { ensureServingConfigsIsMutable(); servingConfigs_.set(index, builderForValue.build()); onChanged(); } else { servingConfigsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public Builder addServingConfigs(com.google.cloud.retail.v2beta.ServingConfig value) { if (servingConfigsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureServingConfigsIsMutable(); servingConfigs_.add(value); onChanged(); } else { servingConfigsBuilder_.addMessage(value); } return this; } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public Builder addServingConfigs( int index, com.google.cloud.retail.v2beta.ServingConfig value) { if (servingConfigsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureServingConfigsIsMutable(); servingConfigs_.add(index, value); onChanged(); } else { servingConfigsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public Builder addServingConfigs( com.google.cloud.retail.v2beta.ServingConfig.Builder builderForValue) { if (servingConfigsBuilder_ == null) { ensureServingConfigsIsMutable(); servingConfigs_.add(builderForValue.build()); onChanged(); } else { servingConfigsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public Builder addServingConfigs( int index, com.google.cloud.retail.v2beta.ServingConfig.Builder builderForValue) { if (servingConfigsBuilder_ == null) { ensureServingConfigsIsMutable(); servingConfigs_.add(index, builderForValue.build()); onChanged(); } else { servingConfigsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public Builder addAllServingConfigs( java.lang.Iterable<? extends com.google.cloud.retail.v2beta.ServingConfig> values) { if (servingConfigsBuilder_ == null) { ensureServingConfigsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, servingConfigs_); onChanged(); } else { servingConfigsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public Builder clearServingConfigs() { if (servingConfigsBuilder_ == null) { servingConfigs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { servingConfigsBuilder_.clear(); } return this; } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public Builder removeServingConfigs(int index) { if (servingConfigsBuilder_ == null) { ensureServingConfigsIsMutable(); servingConfigs_.remove(index); onChanged(); } else { servingConfigsBuilder_.remove(index); } return this; } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public com.google.cloud.retail.v2beta.ServingConfig.Builder getServingConfigsBuilder( int index) { return getServingConfigsFieldBuilder().getBuilder(index); } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public com.google.cloud.retail.v2beta.ServingConfigOrBuilder getServingConfigsOrBuilder( int index) { if (servingConfigsBuilder_ == null) { return servingConfigs_.get(index); } else { return servingConfigsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public java.util.List<? extends com.google.cloud.retail.v2beta.ServingConfigOrBuilder> getServingConfigsOrBuilderList() { if (servingConfigsBuilder_ != null) { return servingConfigsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(servingConfigs_); } } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public com.google.cloud.retail.v2beta.ServingConfig.Builder addServingConfigsBuilder() { return getServingConfigsFieldBuilder() .addBuilder(com.google.cloud.retail.v2beta.ServingConfig.getDefaultInstance()); } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public com.google.cloud.retail.v2beta.ServingConfig.Builder addServingConfigsBuilder( int index) { return getServingConfigsFieldBuilder() .addBuilder(index, com.google.cloud.retail.v2beta.ServingConfig.getDefaultInstance()); } /** * * * <pre> * All the ServingConfigs for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.ServingConfig serving_configs = 1;</code> */ public java.util.List<com.google.cloud.retail.v2beta.ServingConfig.Builder> getServingConfigsBuilderList() { return getServingConfigsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.retail.v2beta.ServingConfig, com.google.cloud.retail.v2beta.ServingConfig.Builder, com.google.cloud.retail.v2beta.ServingConfigOrBuilder> getServingConfigsFieldBuilder() { if (servingConfigsBuilder_ == null) { servingConfigsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.retail.v2beta.ServingConfig, com.google.cloud.retail.v2beta.ServingConfig.Builder, com.google.cloud.retail.v2beta.ServingConfigOrBuilder>( servingConfigs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); servingConfigs_ = null; } return servingConfigsBuilder_; } 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.ListServingConfigsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.retail.v2beta.ListServingConfigsResponse) private static final com.google.cloud.retail.v2beta.ListServingConfigsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.retail.v2beta.ListServingConfigsResponse(); } public static com.google.cloud.retail.v2beta.ListServingConfigsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListServingConfigsResponse> PARSER = new com.google.protobuf.AbstractParser<ListServingConfigsResponse>() { @java.lang.Override public ListServingConfigsResponse 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<ListServingConfigsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListServingConfigsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.retail.v2beta.ListServingConfigsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
openjdk/jdk8
37,553
jdk/src/share/classes/sun/font/LayoutPathImpl.java
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright IBM Corp. 2005, All Rights Reserved. */ package sun.font; // // This is the 'simple' mapping implementation. It does things the most // straightforward way even if that is a bit slow. It won't // handle complex paths efficiently, and doesn't handle closed paths. // import java.awt.Shape; import java.awt.font.LayoutPath; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.util.Formatter; import java.util.ArrayList; import static java.awt.geom.PathIterator.*; import static java.lang.Math.abs; import static java.lang.Math.sqrt; public abstract class LayoutPathImpl extends LayoutPath { // // Convenience APIs // public Point2D pointToPath(double x, double y) { Point2D.Double pt = new Point2D.Double(x, y); pointToPath(pt, pt); return pt; } public Point2D pathToPoint(double a, double o, boolean preceding) { Point2D.Double pt = new Point2D.Double(a, o); pathToPoint(pt, preceding, pt); return pt; } public void pointToPath(double x, double y, Point2D pt) { pt.setLocation(x, y); pointToPath(pt, pt); } public void pathToPoint(double a, double o, boolean preceding, Point2D pt) { pt.setLocation(a, o); pathToPoint(pt, preceding, pt); } // // extra utility APIs // public abstract double start(); public abstract double end(); public abstract double length(); public abstract Shape mapShape(Shape s); // // debugging flags // private static final boolean LOGMAP = false; private static final Formatter LOG = new Formatter(System.out); /** * Indicate how positions past the start and limit of the * path are treated. PINNED adjusts these positions so * as to be within start and limit. EXTENDED ignores the * start and limit and effectively extends the first and * last segments of the path 'infinitely'. CLOSED wraps * positions around the ends of the path. */ public static enum EndType { PINNED, EXTENDED, CLOSED; public boolean isPinned() { return this == PINNED; } public boolean isExtended() { return this == EXTENDED; } public boolean isClosed() { return this == CLOSED; } }; // // Top level construction. // /** * Return a path representing the path from the origin through the points in order. */ public static LayoutPathImpl getPath(EndType etype, double ... coords) { if ((coords.length & 0x1) != 0) { throw new IllegalArgumentException("odd number of points not allowed"); } return SegmentPath.get(etype, coords); } /** * Use to build a SegmentPath. This takes the data and preanalyzes it for * information that the SegmentPath needs, then constructs a SegmentPath * from that. Mainly, this lets SegmentPath cache the lengths along * the path to each line segment, and so avoid calculating them over and over. */ public static final class SegmentPathBuilder { private double[] data; private int w; private double px; private double py; private double a; private boolean pconnect; /** * Construct a SegmentPathBuilder. */ public SegmentPathBuilder() { } /** * Reset the builder for a new path. Datalen is a hint of how many * points will be in the path, and the working buffer will be sized * to accommodate at least this number of points. If datalen is zero, * the working buffer is freed (it will be allocated on first use). */ public void reset(int datalen) { if (data == null || datalen > data.length) { data = new double[datalen]; } else if (datalen == 0) { data = null; } w = 0; px = py = 0; pconnect = false; } /** * Automatically build from a list of points represented by pairs of * doubles. Initial advance is zero. */ public SegmentPath build(EndType etype, double... pts) { assert(pts.length % 2 == 0); reset(pts.length / 2 * 3); for (int i = 0; i < pts.length; i += 2) { nextPoint(pts[i], pts[i+1], i != 0); } return complete(etype); } /** * Move to a new point. If there is no data, this will become the * first point. If there is data, and the previous call was a lineTo, this * point is checked against the previous point, and if different, this * starts a new segment at the same advance as the end of the last * segment. If there is data, and the previous call was a moveTo, this * replaces the point used for that previous call. * * Calling this is optional, lineTo will suffice and the initial point * will be set to 0, 0. */ public void moveTo(double x, double y) { nextPoint(x, y, false); } /** * Connect to a new point. If there is no data, the previous point * is presumed to be 0, 0. This point is checked against * the previous point, and if different, this point is added to * the path and the advance extended. If this point is the same as the * previous point, the path remains unchanged. */ public void lineTo(double x, double y) { nextPoint(x, y, true); } /** * Add a new point, and increment advance if connect is true. * * This automatically rejects duplicate points and multiple disconnected points. */ private void nextPoint(double x, double y, boolean connect) { // if zero length move or line, ignore if (x == px && y == py) { return; } if (w == 0) { // this is the first point, make sure we have space if (data == null) { data = new double[6]; } if (connect) { w = 3; // default first point to 0, 0 } } // if multiple disconnected move, just update position, leave advance alone if (w != 0 && !connect && !pconnect) { data[w-3] = px = x; data[w-2] = py = y; return; } // grow data to deal with new point if (w == data.length) { double[] t = new double[w * 2]; System.arraycopy(data, 0, t, 0, w); data = t; } if (connect) { double dx = x - px; double dy = y - py; a += sqrt(dx * dx + dy * dy); } // update data data[w++] = x; data[w++] = y; data[w++] = a; // update state px = x; py = y; pconnect = connect; } public SegmentPath complete() { return complete(EndType.EXTENDED); } /** * Complete building a SegmentPath. Once this is called, the builder is restored * to its initial state and information about the previous path is released. The * end type indicates whether to treat the path as closed, extended, or pinned. */ public SegmentPath complete(EndType etype) { SegmentPath result; if (data == null || w < 6) { return null; } if (w == data.length) { result = new SegmentPath(data, etype); reset(0); // releases pointer to data } else { double[] dataToAdopt = new double[w]; System.arraycopy(data, 0, dataToAdopt, 0, w); result = new SegmentPath(dataToAdopt, etype); reset(2); // reuses data, since we held on to it } return result; } } /** * Represents a path built from segments. Each segment is * represented by a triple: x, y, and cumulative advance. * These represent the end point of the segment. The start * point of the first segment is represented by the triple * at position 0. * * The path might have breaks in it, e.g. it is not connected. * These will be represented by pairs of triplets that share the * same advance. * * The path might be extended, pinned, or closed. If extended, * the initial and final segments are considered to extend * 'indefinitely' past the bounds of the advance. If pinned, * they end at the bounds of the advance. If closed, * advances before the start or after the end 'wrap around' the * path. * * The start of the path is the initial triple. This provides * the nominal advance at the given x, y position (typically * zero). The end of the path is the final triple. This provides * the advance at the end, the total length of the path is * thus the ending advance minus the starting advance. * * Note: We might want to cache more auxiliary data than the * advance, but this seems adequate for now. */ public static final class SegmentPath extends LayoutPathImpl { private double[] data; // triplets x, y, a EndType etype; public static SegmentPath get(EndType etype, double... pts) { return new SegmentPathBuilder().build(etype, pts); } /** * Internal, use SegmentPathBuilder or one of the static * helper functions to construct a SegmentPath. */ SegmentPath(double[] data, EndType etype) { this.data = data; this.etype = etype; } // // LayoutPath API // public void pathToPoint(Point2D location, boolean preceding, Point2D point) { locateAndGetIndex(location, preceding, point); } // the path consists of line segments, which i'll call // 'path vectors'. call each run of path vectors a 'path segment'. // no path vector in a path segment is zero length (in the // data, such vectors start a new path segment). // // for each path segment... // // for each path vector... // // we look at the dot product of the path vector and the vector from the // origin of the path vector to the test point. if <0 (case // A), the projection of the test point is before the start of // the path vector. if > the square of the length of the path vector // (case B), the projection is past the end point of the // path vector. otherwise (case C), it lies on the path vector. // determine the closeset point on the path vector. if case A, it // is the start of the path vector. if case B and this is the last // path vector in the path segment, it is the end of the path vector. If // case C, it is the projection onto the path vector. Otherwise // there is no closest point. // // if we have a closest point, compare the distance from it to // the test point against our current closest distance. // (culling should be fast, currently i am using distance // squared, but there's probably better ways). if we're // closer, save the new point as the current closest point, // and record the path vector index so we can determine the final // info if this turns out to be the closest point in the end. // // after we have processed all the segments we will have // tested each path vector and each endpoint. if our point is not on // an endpoint, we're done; we can compute the position and // offset again, or if we saved it off we can just use it. if // we're on an endpoint we need to see which path vector we should // associate with. if we're at the start or end of a path segment, // we're done-- the first or last vector of the segment is the // one we associate with. we project against that vector to // get the offset, and pin to that vector to get the length. // // otherwise, we compute the information as follows. if the // dot product (see above) with the following vector is zero, // we associate with that vector. otherwise, if the dot // product with the previous vector is zero, we associate with // that vector. otherwise we're beyond the end of the // previous vector and before the start of the current vector. // we project against both vectors and get the distance from // the test point to the projection (this will be the offset). // if they are the same, we take the following vector. // otherwise use the vector from which the test point is the // _farthest_ (this is because the point lies most clearly in // the half of the plane defined by extending that vector). // // the returned position is the path length to the (possibly // pinned) point, the offset is the projection onto the line // along the vector, and we have a boolean flag which if false // indicates that we associate with the previous vector at a // junction (which is necessary when projecting such a // location back to a point). public boolean pointToPath(Point2D pt, Point2D result) { double x = pt.getX(); // test point double y = pt.getY(); double bx = data[0]; // previous point double by = data[1]; double bl = data[2]; // start with defaults double cd2 = Double.MAX_VALUE; // current best distance from path, squared double cx = 0; // current best x double cy = 0; // current best y double cl = 0; // current best position along path int ci = 0; // current best index into data for (int i = 3; i < data.length; i += 3) { double nx = data[i]; // current end point double ny = data[i+1]; double nl = data[i+2]; double dx = nx - bx; // vector from previous to current double dy = ny - by; double dl = nl - bl; double px = x - bx; // vector from previous to test point double py = y - by; // determine sign of dot product of vectors from bx, by // if < 0, we're before the start of this vector double dot = dx * px + dy * py; // dot product double vcx, vcy, vcl; // hold closest point on vector as x, y, l int vi; // hold index of line, is data.length if last point on path do { // use break below, lets us avoid initializing vcx, vcy... if (dl == 0 || // moveto, or (dot < 0 && // before path vector and (!etype.isExtended() || i != 3))) { // closest point is start of vector vcx = bx; vcy = by; vcl = bl; vi = i; } else { double l2 = dl * dl; // aka dx * dx + dy * dy, square of length if (dot <= l2 || // closest point is not past end of vector, or (etype.isExtended() && // we're extended and at the last segment i == data.length - 3)) { double p = dot / l2; // get parametric along segment vcx = bx + p * dx; // compute closest point vcy = by + p * dy; vcl = bl + p * dl; vi = i; } else { if (i == data.length - 3) { vcx = nx; // special case, always test last point vcy = ny; vcl = nl; vi = data.length; } else { break; // typical case, skip point, we'll pick it up next iteration } } } double tdx = x - vcx; // compute distance from (usually pinned) projection to test point double tdy = y - vcy; double td2 = tdx * tdx + tdy * tdy; if (td2 <= cd2) { // new closest point, record info on it cd2 = td2; cx = vcx; cy = vcy; cl = vcl; ci = vi; } } while (false); bx = nx; by = ny; bl = nl; } // we have our closest point, get the info bx = data[ci-3]; by = data[ci-2]; if (cx != bx || cy != by) { // not on endpoint, no need to resolve double nx = data[ci]; double ny = data[ci+1]; double co = sqrt(cd2); // have a true perpendicular, so can use distance if ((x-cx)*(ny-by) > (y-cy)*(nx-bx)) { co = -co; // determine sign of offset } result.setLocation(cl, co); return false; } else { // on endpoint, we need to resolve which segment boolean havePrev = ci != 3 && data[ci-1] != data[ci-4]; boolean haveFoll = ci != data.length && data[ci-1] != data[ci+2]; boolean doExtend = etype.isExtended() && (ci == 3 || ci == data.length); if (havePrev && haveFoll) { Point2D.Double pp = new Point2D.Double(x, y); calcoffset(ci - 3, doExtend, pp); Point2D.Double fp = new Point2D.Double(x, y); calcoffset(ci, doExtend, fp); if (abs(pp.y) > abs(fp.y)) { result.setLocation(pp); return true; // associate with previous } else { result.setLocation(fp); return false; // associate with following } } else if (havePrev) { result.setLocation(x, y); calcoffset(ci - 3, doExtend, result); return true; } else { result.setLocation(x, y); calcoffset(ci, doExtend, result); return false; } } } /** * Return the location of the point passed in result as mapped to the * line indicated by index. If doExtend is true, extend the * x value without pinning to the ends of the line. * this assumes that index is valid and references a line that has * non-zero length. */ private void calcoffset(int index, boolean doExtend, Point2D result) { double bx = data[index-3]; double by = data[index-2]; double px = result.getX() - bx; double py = result.getY() - by; double dx = data[index] - bx; double dy = data[index+1] - by; double l = data[index+2] - data[index - 1]; // rx = A dot B / |B| // ry = A dot invB / |B| double rx = (px * dx + py * dy) / l; double ry = (px * -dy + py * dx) / l; if (!doExtend) { if (rx < 0) rx = 0; else if (rx > l) rx = l; } rx += data[index-1]; result.setLocation(rx, ry); } // // LayoutPathImpl API // public Shape mapShape(Shape s) { return new Mapper().mapShape(s); } public double start() { return data[2]; } public double end() { return data[data.length - 1]; } public double length() { return data[data.length-1] - data[2]; } // // Utilities // /** * Get the 'modulus' of an advance on a closed path. */ private double getClosedAdvance(double a, boolean preceding) { if (etype.isClosed()) { a -= data[2]; int count = (int)(a/length()); a -= count * length(); if (a < 0 || (a == 0 && preceding)) { a += length(); } a += data[2]; } return a; } /** * Return the index of the segment associated with advance. This * points to the start of the triple and is a multiple of 3 between * 3 and data.length-3 inclusive. It never points to a 'moveto' triple. * * If the path is closed, 'a' is mapped to * a value between the start and end of the path, inclusive. * If preceding is true, and 'a' lies on a segment boundary, * return the index of the preceding segment, else return the index * of the current segment (if it is not a moveto segment) otherwise * the following segment (which is never a moveto segment). * * Note: if the path is not closed, the advance might not actually * lie on the returned segment-- it might be before the first, or * after the last. The first or last segment (as appropriate) * will be returned in this case. */ private int getSegmentIndexForAdvance(double a, boolean preceding) { // must have local advance a = getClosedAdvance(a, preceding); // note we must avoid 'moveto' segments. the first segment is // always a moveto segment, so we always skip it. int i, lim; for (i = 5, lim = data.length-1; i < lim; i += 3) { double v = data[i]; if (a < v || (a == v && preceding)) { break; } } return i-2; // adjust to start of segment } /** * Map a location based on the provided segment, returning in pt. * Seg must be a valid 'lineto' segment. Note: if the path is * closed, x must be within the start and end of the path. */ private void map(int seg, double a, double o, Point2D pt) { double dx = data[seg] - data[seg-3]; double dy = data[seg+1] - data[seg-2]; double dl = data[seg+2] - data[seg-1]; double ux = dx/dl; // could cache these, but is it worth it? double uy = dy/dl; a -= data[seg-1]; pt.setLocation(data[seg-3] + a * ux - o * uy, data[seg-2] + a * uy + o * ux); } /** * Map the point, and return the segment index. */ private int locateAndGetIndex(Point2D loc, boolean preceding, Point2D result) { double a = loc.getX(); double o = loc.getY(); int seg = getSegmentIndexForAdvance(a, preceding); map(seg, a, o, result); return seg; } // // Mapping classes. // Map the path onto each path segment. // Record points where the advance 'enters' and 'exits' the path segment, and connect successive // points when appropriate. // /** * This represents a line segment from the iterator. Each target segment will * interpret it, and since this process needs slope along the line * segment, this lets us compute it once and pass it around easily. */ class LineInfo { double sx, sy; // start double lx, ly; // limit double m; // slope dy/dx /** * Set the lineinfo to this line */ void set(double sx, double sy, double lx, double ly) { this.sx = sx; this.sy = sy; this.lx = lx; this.ly = ly; double dx = lx - sx; if (dx == 0) { m = 0; // we'll check for this elsewhere } else { double dy = ly - sy; m = dy / dx; } } void set(LineInfo rhs) { this.sx = rhs.sx; this.sy = rhs.sy; this.lx = rhs.lx; this.ly = rhs.ly; this.m = rhs.m; } /** * Return true if we intersect the infinitely tall rectangle with * lo <= x < hi. If we do, also return the pinned portion of ourselves in * result. */ boolean pin(double lo, double hi, LineInfo result) { result.set(this); if (lx >= sx) { if (sx < hi && lx >= lo) { if (sx < lo) { if (m != 0) result.sy = sy + m * (lo - sx); result.sx = lo; } if (lx > hi) { if (m != 0) result.ly = ly + m * (hi - lx); result.lx = hi; } return true; } } else { if (lx < hi && sx >= lo) { if (lx < lo) { if (m != 0) result.ly = ly + m * (lo - lx); result.lx = lo; } if (sx > hi) { if (m != 0) result.sy = sy + m * (hi - sx); result.sx = hi; } return true; } } return false; } /** * Return true if we intersect the segment at ix. This takes * the path end type into account and computes the relevant * parameters to pass to pin(double, double, LineInfo). */ boolean pin(int ix, LineInfo result) { double lo = data[ix-1]; double hi = data[ix+2]; switch (SegmentPath.this.etype) { case PINNED: break; case EXTENDED: if (ix == 3) lo = Double.NEGATIVE_INFINITY; if (ix == data.length - 3) hi = Double.POSITIVE_INFINITY; break; case CLOSED: // not implemented break; } return pin(lo, hi, result); } } /** * Each segment will construct its own general path, mapping the provided lines * into its own simple space. */ class Segment { final int ix; // index into data array for this segment final double ux, uy; // unit vector final LineInfo temp; // working line info boolean broken; // true if a moveto has occurred since we last added to our path double cx, cy; // last point in gp GeneralPath gp; // path built for this segment Segment(int ix) { this.ix = ix; double len = data[ix+2] - data[ix-1]; this.ux = (data[ix] - data[ix-3]) / len; this.uy = (data[ix+1] - data[ix-2]) / len; this.temp = new LineInfo(); } void init() { if (LOGMAP) LOG.format("s(%d) init\n", ix); broken = true; cx = cy = Double.MIN_VALUE; this.gp = new GeneralPath(); } void move() { if (LOGMAP) LOG.format("s(%d) move\n", ix); broken = true; } void close() { if (!broken) { if (LOGMAP) LOG.format("s(%d) close\n[cp]\n", ix); gp.closePath(); } } void line(LineInfo li) { if (LOGMAP) LOG.format("s(%d) line %g, %g to %g, %g\n", ix, li.sx, li.sy, li.lx, li.ly); if (li.pin(ix, temp)) { if (LOGMAP) LOG.format("pin: %g, %g to %g, %g\n", temp.sx, temp.sy, temp.lx, temp.ly); temp.sx -= data[ix-1]; double sx = data[ix-3] + temp.sx * ux - temp.sy * uy; double sy = data[ix-2] + temp.sx * uy + temp.sy * ux; temp.lx -= data[ix-1]; double lx = data[ix-3] + temp.lx * ux - temp.ly * uy; double ly = data[ix-2] + temp.lx * uy + temp.ly * ux; if (LOGMAP) LOG.format("points: %g, %g to %g, %g\n", sx, sy, lx, ly); if (sx != cx || sy != cy) { if (broken) { if (LOGMAP) LOG.format("[mt %g, %g]\n", sx, sy); gp.moveTo((float)sx, (float)sy); } else { if (LOGMAP) LOG.format("[lt %g, %g]\n", sx, sy); gp.lineTo((float)sx, (float)sy); } } if (LOGMAP) LOG.format("[lt %g, %g]\n", lx, ly); gp.lineTo((float)lx, (float)ly); broken = false; cx = lx; cy = ly; } } } class Mapper { final LineInfo li; // working line info final ArrayList<Segment> segments; // cache additional data on segments, working objects final Point2D.Double mpt; // last moveto source point final Point2D.Double cpt; // current source point boolean haveMT; // true when last op was a moveto Mapper() { li = new LineInfo(); segments = new ArrayList<Segment>(); for (int i = 3; i < data.length; i += 3) { if (data[i+2] != data[i-1]) { // a new segment segments.add(new Segment(i)); } } mpt = new Point2D.Double(); cpt = new Point2D.Double(); } void init() { if (LOGMAP) LOG.format("init\n"); haveMT = false; for (Segment s: segments) { s.init(); } } void moveTo(double x, double y) { if (LOGMAP) LOG.format("moveto %g, %g\n", x, y); mpt.x = x; mpt.y = y; haveMT = true; } void lineTo(double x, double y) { if (LOGMAP) LOG.format("lineto %g, %g\n", x, y); if (haveMT) { // prepare previous point for no-op check cpt.x = mpt.x; cpt.y = mpt.y; } if (x == cpt.x && y == cpt.y) { // lineto is a no-op return; } if (haveMT) { // current point is the most recent moveto point haveMT = false; for (Segment s: segments) { s.move(); } } li.set(cpt.x, cpt.y, x, y); for (Segment s: segments) { s.line(li); } cpt.x = x; cpt.y = y; } void close() { if (LOGMAP) LOG.format("close\n"); lineTo(mpt.x, mpt.y); for (Segment s: segments) { s.close(); } } public Shape mapShape(Shape s) { if (LOGMAP) LOG.format("mapshape on path: %s\n", LayoutPathImpl.SegmentPath.this); PathIterator pi = s.getPathIterator(null, 1); // cheap way to handle curves. if (LOGMAP) LOG.format("start\n"); init(); final double[] coords = new double[2]; while (!pi.isDone()) { switch (pi.currentSegment(coords)) { case SEG_CLOSE: close(); break; case SEG_MOVETO: moveTo(coords[0], coords[1]); break; case SEG_LINETO: lineTo(coords[0], coords[1]); break; default: break; } pi.next(); } if (LOGMAP) LOG.format("finish\n\n"); GeneralPath gp = new GeneralPath(); for (Segment seg: segments) { gp.append(seg.gp, false); } return gp; } } // // for debugging // public String toString() { StringBuilder b = new StringBuilder(); b.append("{"); b.append(etype.toString()); b.append(" "); for (int i = 0; i < data.length; i += 3) { if (i > 0) { b.append(","); } float x = ((int)(data[i] * 100))/100.0f; float y = ((int)(data[i+1] * 100))/100.0f; float l = ((int)(data[i+2] * 10))/10.0f; b.append("{"); b.append(x); b.append(","); b.append(y); b.append(","); b.append(l); b.append("}"); } b.append("}"); return b.toString(); } } public static class EmptyPath extends LayoutPathImpl { private AffineTransform tx; public EmptyPath(AffineTransform tx) { this.tx = tx; } public void pathToPoint(Point2D location, boolean preceding, Point2D point) { if (tx != null) { tx.transform(location, point); } else { point.setLocation(location); } } public boolean pointToPath(Point2D pt, Point2D result) { result.setLocation(pt); if (tx != null) { try { tx.inverseTransform(pt, result); } catch (NoninvertibleTransformException ex) { } } return result.getX() > 0; } public double start() { return 0; } public double end() { return 0; } public double length() { return 0; } public Shape mapShape(Shape s) { if (tx != null) { return tx.createTransformedShape(s); } return s; } } }
apache/nifi
37,266
nifi-extension-bundles/nifi-elasticsearch-bundle/nifi-elasticsearch-restapi-processors/src/test/java/org/apache/nifi/processors/elasticsearch/AbstractJsonQueryElasticsearchTest.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.nifi.processors.elasticsearch; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.components.state.Scope; import org.apache.nifi.processors.elasticsearch.api.AggregationResultsFormat; import org.apache.nifi.processors.elasticsearch.api.JsonQueryParameters; import org.apache.nifi.processors.elasticsearch.api.QueryDefinitionType; import org.apache.nifi.processors.elasticsearch.api.ResultOutputStrategy; import org.apache.nifi.processors.elasticsearch.api.SearchResultsFormat; import org.apache.nifi.provenance.ProvenanceEventType; import org.apache.nifi.reporting.InitializationException; import org.apache.nifi.util.MockFlowFile; import org.apache.nifi.util.TestRunner; import org.apache.nifi.util.TestRunners; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.MethodSource; import java.io.IOException; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public abstract class AbstractJsonQueryElasticsearchTest<P extends AbstractJsonQueryElasticsearch<? extends JsonQueryParameters>> { private static final String TEST_DIR = "src/test/resources/AbstractJsonQueryElasticsearchTest"; private static final String TEST_COMMON_DIR = "src/test/resources/common"; private static final String INDEX_NAME = "messages"; static final String RANGE_FIELD_NAME = "msg"; static final String RANGE_SORT_ORDER = "asc"; static final String RANGE_FIELD_VALUE = "123456"; // bool query with range filter as constructed by ConsumeElasticsearch private static final String QUERY_CLAUSE = String.format("{\"bool\": {\"filter\": [{\"range\": {\"%s\": {\"gt\": \"123456\"}}}]}}", RANGE_FIELD_NAME); static final String CONSUME_ELASTICSEARCH_SORT_CLAUSE = String.format("{\"%s\":\"%s\"}", RANGE_FIELD_NAME, RANGE_SORT_ORDER); protected static String matchAllQuery; protected static String matchAllAggregationWithDefaultTermsQuery; static final ObjectMapper TEST_MAPPER = new ObjectMapper(); abstract P getProcessor(); abstract Scope getStateScope(); abstract boolean isInput(); @BeforeAll public static void setUpBeforeClass() throws Exception { matchAllQuery = JsonUtils.readString(Paths.get(TEST_COMMON_DIR, "matchAllQuery.json")); matchAllAggregationWithDefaultTermsQuery = JsonUtils.readString(Paths.get(TEST_DIR, "matchAllAggregationWithDefaultTermsQuery.json")); } @Test void testMandatoryProperties() { final TestRunner runner = createRunner(false); runner.removeProperty(ElasticsearchRestProcessor.CLIENT_SERVICE); runner.removeProperty(ElasticsearchRestProcessor.INDEX); runner.removeProperty(ElasticsearchRestProcessor.TYPE); runner.removeProperty(ElasticsearchRestProcessor.QUERY_DEFINITION_STYLE); runner.removeProperty(ElasticsearchRestProcessor.QUERY); runner.removeProperty(ElasticsearchRestProcessor.QUERY_ATTRIBUTE); runner.removeProperty(ElasticsearchRestProcessor.MAX_JSON_FIELD_STRING_LENGTH); runner.removeProperty(AbstractJsonQueryElasticsearch.AGGREGATION_RESULTS_SPLIT); runner.removeProperty(AbstractJsonQueryElasticsearch.SEARCH_RESULTS_SPLIT); runner.removeProperty(AbstractJsonQueryElasticsearch.OUTPUT_NO_HITS); final AssertionError assertionError = assertThrows(AssertionError.class, runner::run); final String expected = String.format(""" Processor has 2 validation failures: '%s' is invalid because %s is required '%s' is invalid because %s is required """, ElasticsearchRestProcessor.INDEX.getDisplayName(), ElasticsearchRestProcessor.INDEX.getDisplayName(), ElasticsearchRestProcessor.CLIENT_SERVICE.getDisplayName(), ElasticsearchRestProcessor.CLIENT_SERVICE.getDisplayName()); assertEquals(expected, assertionError.getMessage()); } @Test void testInvalidProperties() { final TestRunner runner = createRunner(false); runner.setProperty(ElasticsearchRestProcessor.CLIENT_SERVICE, "not-a-service"); runner.setProperty(ElasticsearchRestProcessor.INDEX, ""); runner.setProperty(ElasticsearchRestProcessor.TYPE, ""); runner.setProperty(ElasticsearchRestProcessor.QUERY_DEFINITION_STYLE, "not-valid"); runner.setProperty(ElasticsearchRestProcessor.MAX_JSON_FIELD_STRING_LENGTH, "not-a-size"); runner.setProperty(AbstractJsonQueryElasticsearch.AGGREGATION_RESULTS_SPLIT, "not-enum"); runner.setProperty(AbstractJsonQueryElasticsearch.SEARCH_RESULTS_SPLIT, "not-enum2"); runner.setProperty(AbstractJsonQueryElasticsearch.OUTPUT_NO_HITS, "not-boolean"); final String nonPaginatedResultOutputStrategies = ResultOutputStrategy.getNonPaginatedResponseOutputStrategies() .stream().map(ResultOutputStrategy::getValue) .collect(Collectors.joining(", ")); final String expectedAllowedSplitHits = getProcessor() instanceof AbstractPaginatedJsonQueryElasticsearch ? Arrays.stream(ResultOutputStrategy.values()) .map(ResultOutputStrategy::getValue) .collect(Collectors.joining(", ")) : nonPaginatedResultOutputStrategies; final AssertionError assertionError = assertThrows(AssertionError.class, runner::run); String expected; if (runner.getProcessor() instanceof ConsumeElasticsearch) { expected = "Processor has 8 validation failures:\n"; } else { expected = String.format(""" Processor has 9 validation failures: '%s' validated against 'not-valid' is invalid because Given value not found in allowed set '%s' """, ElasticsearchRestProcessor.QUERY_DEFINITION_STYLE.getName(), Arrays.stream(QueryDefinitionType.values()).map(QueryDefinitionType::getValue).collect(Collectors.joining(", "))); } expected += String.format( """ '%s' validated against '' is invalid because %s cannot be empty '%s' validated against '' is invalid because %s cannot be empty '%s' validated against 'not-a-size' is invalid because Must be of format <Data Size> <Data Unit> where <Data Size> is a non-negative integer \ and <Data Unit> is a supported Data Unit, such as: B, KB, MB, GB, TB '%s' validated against 'not-a-service' is invalid because Property references a Controller Service that does not exist '%s' validated against 'not-enum2' is invalid because Given value not found in allowed set '%s' '%s' validated against 'not-enum' is invalid because Given value not found in allowed set '%s' '%s' validated against 'not-boolean' is invalid because Given value not found in allowed set 'true, false' '%s' validated against 'not-a-service' is invalid because Invalid Controller Service: not-a-service is not a valid Controller Service Identifier """, ElasticsearchRestProcessor.INDEX.getName(), ElasticsearchRestProcessor.INDEX.getName(), ElasticsearchRestProcessor.TYPE.getName(), ElasticsearchRestProcessor.TYPE.getName(), ElasticsearchRestProcessor.MAX_JSON_FIELD_STRING_LENGTH.getName(), ElasticsearchRestProcessor.CLIENT_SERVICE.getDisplayName(), AbstractJsonQueryElasticsearch.SEARCH_RESULTS_SPLIT.getName(), expectedAllowedSplitHits, AbstractJsonQueryElasticsearch.AGGREGATION_RESULTS_SPLIT.getName(), nonPaginatedResultOutputStrategies, AbstractJsonQueryElasticsearch.OUTPUT_NO_HITS.getName(), ElasticsearchRestProcessor.CLIENT_SERVICE.getDisplayName()); assertEquals(expected, assertionError.getMessage()); } @Test void testInvalidQueryProperty() { final TestRunner runner = createRunner(false); runner.setProperty(ElasticsearchRestProcessor.QUERY_DEFINITION_STYLE, QueryDefinitionType.FULL_QUERY.getValue()); final PropertyDescriptor queryPropertyDescriptor; if (runner.getProcessor() instanceof SearchElasticsearch) { queryPropertyDescriptor = SearchElasticsearch.QUERY; } else { queryPropertyDescriptor = ElasticsearchRestProcessor.QUERY; } runner.setProperty(queryPropertyDescriptor, "not-json"); if (runner.getProcessor() instanceof ConsumeElasticsearch) { // ConsumeElasticsearch does not use the QUERY property runner.assertValid(); } else { final AssertionError assertionError = assertThrows(AssertionError.class, runner::run); assertTrue(assertionError.getMessage().contains("not-json")); } } @Test void testInvalidQueryBuilderProperties() { final TestRunner runner = createRunner(false); runner.setProperty(ElasticsearchRestProcessor.QUERY_DEFINITION_STYLE, QueryDefinitionType.BUILD_QUERY); runner.setProperty(ElasticsearchRestProcessor.QUERY_CLAUSE, "not-json"); runner.setProperty(ElasticsearchRestProcessor.SIZE, "-1"); runner.setProperty(ElasticsearchRestProcessor.AGGREGATIONS, "not-json-aggs"); runner.setProperty(ElasticsearchRestProcessor.SORT, "not-json-sort"); runner.setProperty(ElasticsearchRestProcessor.FIELDS, "not-json-fields"); runner.setProperty(ElasticsearchRestProcessor.SCRIPT_FIELDS, "not-json-script_fields"); final AssertionError assertionError = assertThrows(AssertionError.class, runner::run); assertTrue(assertionError.getMessage().contains("not-json")); } @Test void testBasicQuery() { // test hits (no splitting) - full hit format final TestRunner runner = createRunner(false); runner.setProperty(AbstractJsonQueryElasticsearch.QUERY, matchAllQuery); runner.setProperty(AbstractJsonQueryElasticsearch.SEARCH_RESULTS_FORMAT, SearchResultsFormat.FULL); runOnce(runner); testCounts(runner, isInput() ? 1 : 0, 1, 0, 0); final MockFlowFile hits = runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_HITS).getFirst(); hits.assertAttributeEquals("hit.count", "10"); assertOutputContent(hits.getContent(), 10, false); final List<Map<String, Object>> result = JsonUtils.readListOfMaps(hits.getContent()); result.forEach(hit -> { assertFalse(hit.isEmpty()); assertTrue(hit.containsKey("_source")); assertTrue(hit.containsKey("_index")); }); assertEquals(1L, runner.getProvenanceEvents().stream() .filter(pe -> ProvenanceEventType.RECEIVE.equals(pe.getEventType()) && pe.getAttribute("uuid").equals(hits.getAttribute("uuid"))) .count()); reset(runner); // test splitting hits - _source only format runner.setProperty(AbstractJsonQueryElasticsearch.SEARCH_RESULTS_SPLIT, ResultOutputStrategy.PER_HIT); runner.setProperty(AbstractJsonQueryElasticsearch.SEARCH_RESULTS_FORMAT, SearchResultsFormat.SOURCE_ONLY); runOnce(runner); testCounts(runner, isInput() ? 1 : 0, 10, 0, 0); runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_HITS).forEach(hit -> { hit.assertAttributeEquals("hit.count", "1"); assertOutputContent(hit.getContent(), 1, false); final Map<String, Object> h = JsonUtils.readMap(hit.getContent()); assertFalse(h.isEmpty()); assertFalse(h.containsKey("_source")); assertFalse(h.containsKey("_index")); // should be the _source content only assertTrue(h.containsKey("msg")); assertEquals(1L, runner.getProvenanceEvents().stream() .filter(pe -> pe.getEventType() == ProvenanceEventType.RECEIVE && pe.getAttribute("uuid").equals(hit.getAttribute("uuid"))) .count()); }); reset(runner); // test splitting hits - metadata only format runner.setProperty(AbstractJsonQueryElasticsearch.SEARCH_RESULTS_SPLIT, ResultOutputStrategy.PER_HIT); runner.setProperty(AbstractJsonQueryElasticsearch.SEARCH_RESULTS_FORMAT, SearchResultsFormat.METADATA_ONLY); runOnce(runner); testCounts(runner, isInput() ? 1 : 0, 10, 0, 0); runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_HITS).forEach(hit -> { hit.assertAttributeEquals("hit.count", "1"); assertOutputContent(hit.getContent(), 1, false); final Map<String, Object> h = JsonUtils.readMap(hit.getContent()); assertFalse(h.isEmpty()); assertFalse(h.containsKey("_source")); assertTrue(h.containsKey("_index")); assertEquals(1L, runner.getProvenanceEvents().stream() .filter(pe -> ProvenanceEventType.RECEIVE.equals(pe.getEventType()) && pe.getAttribute("uuid").equals(hit.getAttribute("uuid"))) .count()); }); } @Test void testNoHits() { // test no hits (no output) final TestRunner runner = createRunner(false); final TestElasticsearchClientService service = getService(runner); service.setMaxPages(0); runner.setProperty(AbstractJsonQueryElasticsearch.QUERY, matchAllQuery); runner.setProperty(AbstractJsonQueryElasticsearch.OUTPUT_NO_HITS, "false"); runOnce(runner); testCounts(runner, isInput() ? 1 : 0, 0, 0, 0); assertEquals(0L, runner.getProvenanceEvents().stream() .filter(pe -> ProvenanceEventType.RECEIVE.equals(pe.getEventType())) .count()); reset(runner); // test not hits (with output) runner.setProperty(AbstractJsonQueryElasticsearch.OUTPUT_NO_HITS, "true"); runOnce(runner); testCounts(runner, isInput() ? 1 : 0, 1, 0, 0); runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_HITS).forEach( hit -> { hit.assertAttributeEquals("hit.count", "0"); assertOutputContent(hit.getContent(), 0, false); assertEquals(1L, runner.getProvenanceEvents().stream() .filter(pe -> ProvenanceEventType.RECEIVE.equals(pe.getEventType()) && pe.getAttribute("uuid").equals(hit.getAttribute("uuid"))) .count()); }); } @SuppressWarnings("unchecked") @Test void testAggregationsFullFormat() { final TestRunner runner = createRunner(true); runner.setProperty(AbstractJsonQueryElasticsearch.QUERY, matchAllAggregationWithDefaultTermsQuery); runner.setProperty(AbstractJsonQueryElasticsearch.AGGREGATION_RESULTS_FORMAT, AggregationResultsFormat.FULL); runOnce(runner); testCounts(runner, isInput() ? 1 : 0, 1, 0, 1); runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_HITS).getFirst().assertAttributeEquals("hit.count", "10"); final MockFlowFile aggregations = runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_AGGREGATIONS).getFirst(); aggregations.assertAttributeNotExists("aggregation.number"); aggregations.assertAttributeNotExists("aggregation.name"); // count == 1 because aggregations is a single Map rather than a List of Maps, even when there are multiple aggs assertOutputContent(aggregations.getContent(), 1, false); final Map<String, Object> agg = JsonUtils.readMap(aggregations.getContent()); // agg Map of 2 Maps (buckets and metadata) assertEquals(2, agg.size()); agg.keySet().forEach(aggName -> { final Map<String, Object> termAgg = (Map<String, Object>) agg.get(aggName); assertInstanceOf(List.class, termAgg.get("buckets")); assertTrue(termAgg.containsKey("doc_count_error_upper_bound")); }); } @SuppressWarnings("unchecked") @Test void testWithQueryParameterNoIncomingConnectionAndBucketsAggregationFormat() { final TestRunner runner = createRunner(true); runner.setProperty(AbstractJsonQueryElasticsearch.QUERY, matchAllAggregationWithDefaultTermsQuery); runner.setIncomingConnection(false); runner.setProperty(AbstractJsonQueryElasticsearch.AGGREGATION_RESULTS_FORMAT, AggregationResultsFormat.BUCKETS_ONLY); runner.run(1, true, true); testCounts(runner, 0, 1, 0, 1); runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_HITS).getFirst().assertAttributeEquals("hit.count", "10"); final MockFlowFile singleAgg = runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_AGGREGATIONS).getFirst(); singleAgg.assertAttributeNotExists("aggregation.number"); singleAgg.assertAttributeNotExists("aggregation.name"); final Map<String, Object> agg2 = JsonUtils.readMap(singleAgg.getContent()); // agg Map of 2 Lists (bucket contents only) assertEquals(2, agg2.size()); agg2.keySet().forEach(aggName -> { final List<Map<String, Object>> termAgg = (List<Map<String, Object>>) agg2.get(aggName); assertEquals(5, termAgg.size()); termAgg.forEach(a -> { assertTrue(a.containsKey("key")); assertTrue(a.containsKey("doc_count")); }); }); } @Test void testSplittingAggregationsMetadataOnlyFormat() { final TestRunner runner = createRunner(true); runner.setProperty(AbstractJsonQueryElasticsearch.QUERY, matchAllAggregationWithDefaultTermsQuery); runner.setProperty(AbstractJsonQueryElasticsearch.AGGREGATION_RESULTS_SPLIT, ResultOutputStrategy.PER_HIT); runner.setProperty(AbstractJsonQueryElasticsearch.AGGREGATION_RESULTS_FORMAT, AggregationResultsFormat.METADATA_ONLY); runOnce(runner); testCounts(runner, isInput() ? 1 : 0, 1, 0, 2); runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_HITS).getFirst().assertAttributeEquals("hit.count", "10"); int a = 0; for (final MockFlowFile termAgg : runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_AGGREGATIONS)) { termAgg.assertAttributeEquals("aggregation.name", a == 0 ? "term_agg" : "term_agg2"); termAgg.assertAttributeEquals("aggregation.number", Integer.toString(++a)); assertOutputContent(termAgg.getContent(), 1, false); final Map<String, Object> aggContent = JsonUtils.readMap(termAgg.getContent()); // agg Map (metadata, no buckets) assertTrue(aggContent.containsKey("doc_count_error_upper_bound")); assertFalse(aggContent.containsKey("buckets")); } } @Test void testAggregationsUsingExpressionLanguage() throws Exception { final TestRunner runner = createRunner(true); final String query = JsonUtils.readString(Paths.get(TEST_DIR, "matchAllAggregationWithDefaultTermsInExpressionLanguageQuery.json")); runner.setEnvironmentVariableValue("fieldValue", "msg"); runner.setEnvironmentVariableValue("es.index", INDEX_NAME); runner.setEnvironmentVariableValue("es.type", "msg"); runner.setProperty(AbstractJsonQueryElasticsearch.QUERY, query); runner.setProperty(AbstractJsonQueryElasticsearch.INDEX, "${es.index}"); runner.setProperty(AbstractJsonQueryElasticsearch.TYPE, "${es.type}"); runner.setProperty(AbstractJsonQueryElasticsearch.AGGREGATION_RESULTS_SPLIT, ResultOutputStrategy.PER_HIT); runner.setProperty(AbstractJsonQueryElasticsearch.AGGREGATION_RESULTS_FORMAT, AggregationResultsFormat.FULL); runOnce(runner); testCounts(runner, isInput() ? 1 : 0, 1, 0, 2); runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_HITS).getFirst().assertAttributeEquals("hit.count", "10"); int a = 0; for (final MockFlowFile termAgg : runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_AGGREGATIONS)) { termAgg.assertAttributeEquals("aggregation.name", a == 0 ? "term_agg" : "term_agg2"); termAgg.assertAttributeEquals("aggregation.number", Integer.toString(++a)); assertOutputContent(termAgg.getContent(), 1, false); } } @Test void testErrorDuringSearch() { final TestRunner runner = createRunner(true); getService(runner).setThrowErrorInSearch(true); runner.setProperty(AbstractJsonQueryElasticsearch.QUERY, matchAllAggregationWithDefaultTermsQuery); runOnce(runner); testCounts(runner, 0, 0, isInput() ? 1 : 0, 0); } @ParameterizedTest @EnumSource(QueryDefinitionType.class) void testQueryAttribute(final QueryDefinitionType queryDefinitionType) throws JsonProcessingException { Assumptions.assumeFalse(QueryDefinitionType.FULL_QUERY.equals(queryDefinitionType) && getProcessor() instanceof ConsumeElasticsearch, "ConsumeElasticsearch doesn't use the FULL_QUERY definition type"); final String query = matchAllAggregationWithDefaultTermsQuery; final String queryAttr = "es.query"; final TestRunner runner = createRunner(true); runner.setProperty(AbstractJsonQueryElasticsearch.QUERY_ATTRIBUTE, queryAttr); runner.setProperty(ElasticsearchRestProcessor.QUERY_DEFINITION_STYLE, queryDefinitionType); setQuery(runner, query); runOnce(runner); testCounts(runner, isInput() ? 1 : 0, 1, 0, 1); final List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_AGGREGATIONS); flowFiles.addAll(runner.getFlowFilesForRelationship(AbstractJsonQueryElasticsearch.REL_HITS)); for (final MockFlowFile mockFlowFile : flowFiles) { final String attr = mockFlowFile.getAttribute(queryAttr); assertNotNull(attr, "Missing query attribute"); final ObjectNode expected = TEST_MAPPER.readValue(query, ObjectNode.class); if (runner.getProcessor() instanceof ConsumeElasticsearch) { // no "query" will be defined with Range Field but no initial value provided expected.remove("query"); addExpectedSort(expected); } assertEquals(expected, TEST_MAPPER.readTree(attr), "Query had wrong value."); } } @Test void testInputHandling() { final TestRunner runner = createRunner(false); runner.setProperty(AbstractJsonQueryElasticsearch.QUERY, matchAllQuery); runner.setIncomingConnection(true); runner.run(); testCounts(runner, 0, 0, 0, 0); reset(runner); runner.setIncomingConnection(false); runner.run(); testCounts(runner, 0, 1, 0, 0); } @Test void testRequestParameters() { final TestRunner runner = createRunner(false); if (!(runner.getProcessor() instanceof ConsumeElasticsearch)) { runner.setProperty(AbstractJsonQueryElasticsearch.QUERY, matchAllQuery); } runner.setProperty("refresh", "true"); runner.setProperty("slices", "${slices}"); runner.setProperty(ElasticsearchRestProcessor.DYNAMIC_PROPERTY_PREFIX_REQUEST_HEADER + "Accept", "${accept}"); runner.setEnvironmentVariableValue("slices", "auto"); runner.setEnvironmentVariableValue("accept", "application/json"); runOnce(runner); final TestElasticsearchClientService service = getService(runner); if (runner.getProcessor() instanceof AbstractPaginatedJsonQueryElasticsearch) { assertEquals(3, service.getElasticsearchRequestOptions().getRequestParameters().size()); assertEquals("600s", service.getElasticsearchRequestOptions().getRequestParameters().get("scroll")); } else { assertEquals(2, service.getElasticsearchRequestOptions().getRequestParameters().size()); } assertEquals("true", service.getElasticsearchRequestOptions().getRequestParameters().get("refresh")); assertEquals("auto", service.getElasticsearchRequestOptions().getRequestParameters().get("slices")); assertEquals(1, service.getElasticsearchRequestOptions().getRequestHeaders().size()); assertEquals("application/json", service.getElasticsearchRequestOptions().getRequestHeaders().get("Accept")); } @ParameterizedTest @MethodSource void testQueryBuilder(final String queryClause, final Integer size, final String aggs, final String sort, final String fields, final String scriptFields, final String expectedQuery) throws Exception { final TestRunner runner = createRunner(false); if (runner.getProcessor() instanceof ConsumeElasticsearch) { // test Range Field and initial value defined runner.setProperty(ConsumeElasticsearch.RANGE_FIELD, RANGE_FIELD_NAME); runner.setProperty(ConsumeElasticsearch.RANGE_INITIAL_VALUE, RANGE_FIELD_VALUE); // as onScheduled won't run (the processor will not actually br triggered), set these fields directly ((ConsumeElasticsearch) runner.getProcessor()).trackingRangeField = RANGE_FIELD_NAME; ((ConsumeElasticsearch) runner.getProcessor()).trackingSortOrder = RANGE_SORT_ORDER; } else { runner.setProperty(ElasticsearchRestProcessor.QUERY_DEFINITION_STYLE, QueryDefinitionType.BUILD_QUERY); } if (queryClause != null) { runner.setProperty(ElasticsearchRestProcessor.QUERY_CLAUSE, queryClause); } if (size != null) { runner.setProperty(ElasticsearchRestProcessor.SIZE, String.valueOf(size)); } if (aggs != null) { runner.setProperty(ElasticsearchRestProcessor.AGGREGATIONS, aggs); } if (sort != null) { runner.setProperty(ElasticsearchRestProcessor.SORT, sort); } if (fields != null) { runner.setProperty(ElasticsearchRestProcessor.FIELDS, fields); } if (scriptFields != null) { runner.setProperty(ElasticsearchRestProcessor.SCRIPT_FIELDS, scriptFields); } @SuppressWarnings("unchecked") final String query = ((P) runner.getProcessor()).getQuery(null, runner.getProcessContext(), null, TEST_MAPPER); assertNotNull(query); final ObjectNode expected = TEST_MAPPER.readValue(expectedQuery, ObjectNode.class); if (runner.getProcessor() instanceof ConsumeElasticsearch) { // ConsumeElasticsearch should build the "query" based upon the Range Field and initial value expected.set("query", TEST_MAPPER.readTree(QUERY_CLAUSE)); addExpectedSort(expected); } assertEquals(expected, TEST_MAPPER.readTree(query)); } private void addExpectedSort(final ObjectNode expected) throws JsonProcessingException { // ConsumeElasticsearch should add the "sort" for the Range field final ArrayNode expectedSort; if (expected.has("sort")) { expectedSort = expected.withArray("sort"); } else { expectedSort = TEST_MAPPER.getNodeFactory().arrayNode(1); expected.set("sort", expectedSort); } expectedSort.insert(0, TEST_MAPPER.readTree(CONSUME_ELASTICSEARCH_SORT_CLAUSE)); } private static Stream<Arguments> testQueryBuilder() { final int size = 123; final String aggs = "{\"foo_terms\": {\"terms\": {\"field\": \"foo.keyword\"}}}"; final String sort = "[{\"price\" : {\"order\" : \"asc\", \"mode\" : \"avg\"}}, {\"post_date\" : {\"format\": \"strict_date_optional_time_nanos\"}}]"; final String fields = "[\"user.id\", \"http.response.*\", {\"field\": \"@timestamp\", \"format\": \"epoch_millis\"}]"; final String scriptFields = "{\"test1\": {\"script\": {\"lang\": \"painless\", \"source\": \"doc['price'].value * 2\"}}}"; return Stream.of( Arguments.of(null, null, null, null, null, null, "{}"), Arguments.of(QUERY_CLAUSE, null, null, null, null, null, String.format("{\"query\": %s}", QUERY_CLAUSE)), Arguments.of(null, size, null, null, null, null, String.format("{\"size\": %d}", size)), Arguments.of(null, null, aggs, null, null, null, String.format("{\"aggs\": %s}", aggs)), Arguments.of(null, null, null, sort, null, null, String.format("{\"sort\": %s}", sort)), Arguments.of(null, null, null, null, fields, null, String.format("{\"fields\": %s}", fields)), Arguments.of(null, null, null, null, null, scriptFields, String.format("{\"script_fields\": %s}", scriptFields)), Arguments.of(QUERY_CLAUSE, size, null, null, null, null, String.format("{\"query\": %s, \"size\": %d}", QUERY_CLAUSE, size)), Arguments.of(QUERY_CLAUSE, size, aggs, sort, fields, scriptFields, String.format("{\"query\": %s, \"size\": %d, \"aggs\": %s, \"sort\": %s, \"fields\": %s, \"script_fields\": %s}", QUERY_CLAUSE, size, aggs, sort, fields, scriptFields) ) ); } @Test void testDefaultQuery() { final TestRunner runner = createRunner(false); runner.removeProperty(ElasticsearchRestProcessor.QUERY); runner.removeProperty(ElasticsearchRestProcessor.QUERY_CLAUSE); final String expected; if (runner.getProcessor() instanceof ConsumeElasticsearch) { // test Range Field defined but no initial value runner.setProperty(ConsumeElasticsearch.QUERY_DEFINITION_STYLE, QueryDefinitionType.BUILD_QUERY); runner.setProperty(ConsumeElasticsearch.RANGE_FIELD, RANGE_FIELD_NAME); // should be no "query" (with no initial value) but "sort" added expected = String.format("{\"sort\":[%s]}", CONSUME_ELASTICSEARCH_SORT_CLAUSE); } else { expected = "{}"; } runOnce(runner, ""); assertEquals(expected, getService(runner).getQuery()); } void setQuery(final TestRunner runner, final String query) throws JsonProcessingException { if (runner.getProcessor() instanceof ConsumeElasticsearch) { runner.setProperty(ElasticsearchRestProcessor.QUERY_DEFINITION_STYLE, QueryDefinitionType.BUILD_QUERY); } if (QueryDefinitionType.BUILD_QUERY.getValue().equals(runner.getProcessContext().getProperty(ElasticsearchRestProcessor.QUERY_DEFINITION_STYLE).getValue())) { final Map<String, Object> queryMap = TEST_MAPPER.readValue(query, new TypeReference<>() { }); if (queryMap.containsKey("query")) { if (runner.getProcessor() instanceof ConsumeElasticsearch) { runner.setProperty(ConsumeElasticsearch.RANGE_FIELD, RANGE_FIELD_NAME); } else { runner.setProperty(ElasticsearchRestProcessor.QUERY_CLAUSE, TEST_MAPPER.writeValueAsString(queryMap.get("query"))); } } if (queryMap.containsKey("size")) { runner.setProperty(ElasticsearchRestProcessor.SIZE, TEST_MAPPER.writeValueAsString(queryMap.get("size"))); } if (queryMap.containsKey("aggs")) { runner.setProperty(ElasticsearchRestProcessor.AGGREGATIONS, TEST_MAPPER.writeValueAsString(queryMap.get("aggs"))); } if (queryMap.containsKey("sort")) { runner.setProperty(ElasticsearchRestProcessor.SORT, TEST_MAPPER.writeValueAsString(queryMap.get("sort"))); } } else { runner.setProperty(ElasticsearchRestProcessor.QUERY, query); } } static void testCounts(final TestRunner runner, final int original, final int hits, final int failure, final int aggregations) { runner.assertTransferCount(AbstractJsonQueryElasticsearch.REL_ORIGINAL, original); runner.assertTransferCount(AbstractJsonQueryElasticsearch.REL_HITS, hits); runner.assertTransferCount(AbstractJsonQueryElasticsearch.REL_FAILURE, failure); runner.assertTransferCount(AbstractJsonQueryElasticsearch.REL_AGGREGATIONS, aggregations); runner.assertTransferCount(AbstractJsonQueryElasticsearch.REL_RETRY, 0); } static void assertOutputContent(final String content, final int count, final boolean ndjson) { if (ndjson) { assertEquals(count, (content.split("\n").length)); } else { if (count == 0) { assertEquals("", content); } else if (count == 1) { assertTrue(content.startsWith("{") && content.endsWith("}")); } else { assertTrue(content.startsWith("[") && content.endsWith("]")); } } } TestRunner createRunner(final boolean returnAggs) { final P processor = getProcessor(); final TestRunner runner = TestRunners.newTestRunner(processor); final TestElasticsearchClientService service = new TestElasticsearchClientService(returnAggs); try { runner.addControllerService("esService", service); } catch (final InitializationException e) { throw new RuntimeException(e); } runner.enableControllerService(service); runner.setProperty(AbstractJsonQueryElasticsearch.CLIENT_SERVICE, "esService"); runner.setProperty(AbstractJsonQueryElasticsearch.INDEX, INDEX_NAME); runner.setProperty(AbstractJsonQueryElasticsearch.TYPE, "message"); runner.setValidateExpressionUsage(true); return runner; } MockFlowFile runOnce(final TestRunner runner) { return runOnce(runner, "test"); } MockFlowFile runOnce(final TestRunner runner, final String data) { final MockFlowFile ff; if (isInput()) { runner.setIncomingConnection(true); ff = runner.enqueue(data); } else { runner.setIncomingConnection(false); ff = null; } runner.run(1, true, true); return ff; } static TestElasticsearchClientService getService(final TestRunner runner) { return runner.getControllerService("esService", TestElasticsearchClientService.class); } void reset(final TestRunner runner) { runner.clearProvenanceEvents(); runner.clearTransferState(); if (getStateScope() != null) { try { runner.getStateManager().clear(getStateScope()); } catch (final IOException e) { throw new RuntimeException(e); } } getService(runner).resetPageCount(); } }
apache/ozhera
37,354
ozhera-tspandata/src/main/java/org/apache/ozhera/tspandata/TValue.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. */ // // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package org.apache.ozhera.tspandata; import java.io.Serializable; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.thrift.TBase; import org.apache.thrift.TBaseHelper; import org.apache.thrift.TException; import org.apache.thrift.TFieldIdEnum; import org.apache.thrift.meta_data.FieldMetaData; import org.apache.thrift.meta_data.FieldValueMetaData; import org.apache.thrift.meta_data.ListMetaData; import org.apache.thrift.protocol.TField; import org.apache.thrift.protocol.TList; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolUtil; import org.apache.thrift.protocol.TStruct; public class TValue implements TBase<TValue, TValue._Fields>, Serializable, Cloneable { private static final TStruct STRUCT_DESC = new TStruct("TValue"); private static final TField STRING_VALUE_FIELD_DESC = new TField("stringValue", (byte)11, (short)1); private static final TField BOOL_VALUE_FIELD_DESC = new TField("boolValue", (byte)2, (short)2); private static final TField LONG_VALUE_FIELD_DESC = new TField("longValue", (byte)10, (short)3); private static final TField DOUBLE_VALUE_FIELD_DESC = new TField("doubleValue", (byte)4, (short)4); private static final TField STRING_ARRAY_VALUE_FIELD_DESC = new TField("stringArrayValue", (byte)15, (short)5); private static final TField BOOL_ARRAY_VALUE_FIELD_DESC = new TField("boolArrayValue", (byte)15, (short)6); private static final TField LONG_ARRAY_VALUE_FIELD_DESC = new TField("longArrayValue", (byte)15, (short)7); private static final TField DOUBLE_ARRAY_VALUE_FIELD_DESC = new TField("doubleArrayValue", (byte)15, (short)8); public String stringValue; public boolean boolValue; public long longValue; public double doubleValue; public List<String> stringArrayValue; public List<Boolean> boolArrayValue; public List<Long> longArrayValue; public List<Double> doubleArrayValue; private static final int __BOOLVALUE_ISSET_ID = 0; private static final int __LONGVALUE_ISSET_ID = 1; private static final int __DOUBLEVALUE_ISSET_ID = 2; private BitSet __isset_bit_vector = new BitSet(3); public static final Map<TValue._Fields, FieldMetaData> metaDataMap; public TValue() { } public TValue(TValue var1) { this.__isset_bit_vector.clear(); this.__isset_bit_vector.or(var1.__isset_bit_vector); if (var1.isSetStringValue()) { this.stringValue = var1.stringValue; } this.boolValue = var1.boolValue; this.longValue = var1.longValue; this.doubleValue = var1.doubleValue; ArrayList var2; Iterator var3; if (var1.isSetStringArrayValue()) { var2 = new ArrayList(); var3 = var1.stringArrayValue.iterator(); while(var3.hasNext()) { String var4 = (String)var3.next(); var2.add(var4); } this.stringArrayValue = var2; } if (var1.isSetBoolArrayValue()) { var2 = new ArrayList(); var3 = var1.boolArrayValue.iterator(); while(var3.hasNext()) { Boolean var5 = (Boolean)var3.next(); var2.add(var5); } this.boolArrayValue = var2; } if (var1.isSetLongArrayValue()) { var2 = new ArrayList(); var3 = var1.longArrayValue.iterator(); while(var3.hasNext()) { Long var6 = (Long)var3.next(); var2.add(var6); } this.longArrayValue = var2; } if (var1.isSetDoubleArrayValue()) { var2 = new ArrayList(); var3 = var1.doubleArrayValue.iterator(); while(var3.hasNext()) { Double var7 = (Double)var3.next(); var2.add(var7); } this.doubleArrayValue = var2; } } public TValue deepCopy() { return new TValue(this); } public void clear() { this.stringValue = null; this.setBoolValueIsSet(false); this.boolValue = false; this.setLongValueIsSet(false); this.longValue = 0L; this.setDoubleValueIsSet(false); this.doubleValue = 0.0D; this.stringArrayValue = null; this.boolArrayValue = null; this.longArrayValue = null; this.doubleArrayValue = null; } public String getStringValue() { return this.stringValue; } public TValue setStringValue(String var1) { this.stringValue = var1; return this; } public void unsetStringValue() { this.stringValue = null; } public boolean isSetStringValue() { return this.stringValue != null; } public void setStringValueIsSet(boolean var1) { if (!var1) { this.stringValue = null; } } public boolean isBoolValue() { return this.boolValue; } public TValue setBoolValue(boolean var1) { this.boolValue = var1; this.setBoolValueIsSet(true); return this; } public void unsetBoolValue() { this.__isset_bit_vector.clear(0); } public boolean isSetBoolValue() { return this.__isset_bit_vector.get(0); } public void setBoolValueIsSet(boolean var1) { this.__isset_bit_vector.set(0, var1); } public long getLongValue() { return this.longValue; } public TValue setLongValue(long var1) { this.longValue = var1; this.setLongValueIsSet(true); return this; } public void unsetLongValue() { this.__isset_bit_vector.clear(1); } public boolean isSetLongValue() { return this.__isset_bit_vector.get(1); } public void setLongValueIsSet(boolean var1) { this.__isset_bit_vector.set(1, var1); } public double getDoubleValue() { return this.doubleValue; } public TValue setDoubleValue(double var1) { this.doubleValue = var1; this.setDoubleValueIsSet(true); return this; } public void unsetDoubleValue() { this.__isset_bit_vector.clear(2); } public boolean isSetDoubleValue() { return this.__isset_bit_vector.get(2); } public void setDoubleValueIsSet(boolean var1) { this.__isset_bit_vector.set(2, var1); } public int getStringArrayValueSize() { return this.stringArrayValue == null ? 0 : this.stringArrayValue.size(); } public Iterator<String> getStringArrayValueIterator() { return this.stringArrayValue == null ? null : this.stringArrayValue.iterator(); } public void addToStringArrayValue(String var1) { if (this.stringArrayValue == null) { this.stringArrayValue = new ArrayList(); } this.stringArrayValue.add(var1); } public List<String> getStringArrayValue() { return this.stringArrayValue; } public TValue setStringArrayValue(List<String> var1) { this.stringArrayValue = var1; return this; } public void unsetStringArrayValue() { this.stringArrayValue = null; } public boolean isSetStringArrayValue() { return this.stringArrayValue != null; } public void setStringArrayValueIsSet(boolean var1) { if (!var1) { this.stringArrayValue = null; } } public int getBoolArrayValueSize() { return this.boolArrayValue == null ? 0 : this.boolArrayValue.size(); } public Iterator<Boolean> getBoolArrayValueIterator() { return this.boolArrayValue == null ? null : this.boolArrayValue.iterator(); } public void addToBoolArrayValue(boolean var1) { if (this.boolArrayValue == null) { this.boolArrayValue = new ArrayList(); } this.boolArrayValue.add(var1); } public List<Boolean> getBoolArrayValue() { return this.boolArrayValue; } public TValue setBoolArrayValue(List<Boolean> var1) { this.boolArrayValue = var1; return this; } public void unsetBoolArrayValue() { this.boolArrayValue = null; } public boolean isSetBoolArrayValue() { return this.boolArrayValue != null; } public void setBoolArrayValueIsSet(boolean var1) { if (!var1) { this.boolArrayValue = null; } } public int getLongArrayValueSize() { return this.longArrayValue == null ? 0 : this.longArrayValue.size(); } public Iterator<Long> getLongArrayValueIterator() { return this.longArrayValue == null ? null : this.longArrayValue.iterator(); } public void addToLongArrayValue(long var1) { if (this.longArrayValue == null) { this.longArrayValue = new ArrayList(); } this.longArrayValue.add(var1); } public List<Long> getLongArrayValue() { return this.longArrayValue; } public TValue setLongArrayValue(List<Long> var1) { this.longArrayValue = var1; return this; } public void unsetLongArrayValue() { this.longArrayValue = null; } public boolean isSetLongArrayValue() { return this.longArrayValue != null; } public void setLongArrayValueIsSet(boolean var1) { if (!var1) { this.longArrayValue = null; } } public int getDoubleArrayValueSize() { return this.doubleArrayValue == null ? 0 : this.doubleArrayValue.size(); } public Iterator<Double> getDoubleArrayValueIterator() { return this.doubleArrayValue == null ? null : this.doubleArrayValue.iterator(); } public void addToDoubleArrayValue(double var1) { if (this.doubleArrayValue == null) { this.doubleArrayValue = new ArrayList(); } this.doubleArrayValue.add(var1); } public List<Double> getDoubleArrayValue() { return this.doubleArrayValue; } public TValue setDoubleArrayValue(List<Double> var1) { this.doubleArrayValue = var1; return this; } public void unsetDoubleArrayValue() { this.doubleArrayValue = null; } public boolean isSetDoubleArrayValue() { return this.doubleArrayValue != null; } public void setDoubleArrayValueIsSet(boolean var1) { if (!var1) { this.doubleArrayValue = null; } } public void setFieldValue(TValue._Fields var1, Object var2) { switch(var1) { case STRING_VALUE: if (var2 == null) { this.unsetStringValue(); } else { this.setStringValue((String)var2); } break; case BOOL_VALUE: if (var2 == null) { this.unsetBoolValue(); } else { this.setBoolValue((Boolean)var2); } break; case LONG_VALUE: if (var2 == null) { this.unsetLongValue(); } else { this.setLongValue((Long)var2); } break; case DOUBLE_VALUE: if (var2 == null) { this.unsetDoubleValue(); } else { this.setDoubleValue((Double)var2); } break; case STRING_ARRAY_VALUE: if (var2 == null) { this.unsetStringArrayValue(); } else { this.setStringArrayValue((List)var2); } break; case BOOL_ARRAY_VALUE: if (var2 == null) { this.unsetBoolArrayValue(); } else { this.setBoolArrayValue((List)var2); } break; case LONG_ARRAY_VALUE: if (var2 == null) { this.unsetLongArrayValue(); } else { this.setLongArrayValue((List)var2); } break; case DOUBLE_ARRAY_VALUE: if (var2 == null) { this.unsetDoubleArrayValue(); } else { this.setDoubleArrayValue((List)var2); } } } public Object getFieldValue(TValue._Fields var1) { switch(var1) { case STRING_VALUE: return this.getStringValue(); case BOOL_VALUE: return new Boolean(this.isBoolValue()); case LONG_VALUE: return new Long(this.getLongValue()); case DOUBLE_VALUE: return new Double(this.getDoubleValue()); case STRING_ARRAY_VALUE: return this.getStringArrayValue(); case BOOL_ARRAY_VALUE: return this.getBoolArrayValue(); case LONG_ARRAY_VALUE: return this.getLongArrayValue(); case DOUBLE_ARRAY_VALUE: return this.getDoubleArrayValue(); default: throw new IllegalStateException(); } } public boolean isSet(TValue._Fields var1) { if (var1 == null) { throw new IllegalArgumentException(); } else { switch(var1) { case STRING_VALUE: return this.isSetStringValue(); case BOOL_VALUE: return this.isSetBoolValue(); case LONG_VALUE: return this.isSetLongValue(); case DOUBLE_VALUE: return this.isSetDoubleValue(); case STRING_ARRAY_VALUE: return this.isSetStringArrayValue(); case BOOL_ARRAY_VALUE: return this.isSetBoolArrayValue(); case LONG_ARRAY_VALUE: return this.isSetLongArrayValue(); case DOUBLE_ARRAY_VALUE: return this.isSetDoubleArrayValue(); default: throw new IllegalStateException(); } } } public boolean equals(Object var1) { if (var1 == null) { return false; } else { return var1 instanceof TValue ? this.equals((TValue)var1) : false; } } public boolean equals(TValue var1) { if (var1 == null) { return false; } else { boolean var2 = this.isSetStringValue(); boolean var3 = var1.isSetStringValue(); if (var2 || var3) { if (!var2 || !var3) { return false; } if (!this.stringValue.equals(var1.stringValue)) { return false; } } boolean var4 = this.isSetBoolValue(); boolean var5 = var1.isSetBoolValue(); if (var4 || var5) { if (!var4 || !var5) { return false; } if (this.boolValue != var1.boolValue) { return false; } } boolean var6 = this.isSetLongValue(); boolean var7 = var1.isSetLongValue(); if (var6 || var7) { if (!var6 || !var7) { return false; } if (this.longValue != var1.longValue) { return false; } } boolean var8 = this.isSetDoubleValue(); boolean var9 = var1.isSetDoubleValue(); if (var8 || var9) { if (!var8 || !var9) { return false; } if (this.doubleValue != var1.doubleValue) { return false; } } boolean var10 = this.isSetStringArrayValue(); boolean var11 = var1.isSetStringArrayValue(); if (var10 || var11) { if (!var10 || !var11) { return false; } if (!this.stringArrayValue.equals(var1.stringArrayValue)) { return false; } } boolean var12 = this.isSetBoolArrayValue(); boolean var13 = var1.isSetBoolArrayValue(); if (var12 || var13) { if (!var12 || !var13) { return false; } if (!this.boolArrayValue.equals(var1.boolArrayValue)) { return false; } } boolean var14 = this.isSetLongArrayValue(); boolean var15 = var1.isSetLongArrayValue(); if (var14 || var15) { if (!var14 || !var15) { return false; } if (!this.longArrayValue.equals(var1.longArrayValue)) { return false; } } boolean var16 = this.isSetDoubleArrayValue(); boolean var17 = var1.isSetDoubleArrayValue(); if (var16 || var17) { if (!var16 || !var17) { return false; } if (!this.doubleArrayValue.equals(var1.doubleArrayValue)) { return false; } } return true; } } public int hashCode() { return 0; } public int compareTo(TValue var1) { if (!this.getClass().equals(var1.getClass())) { return this.getClass().getName().compareTo(var1.getClass().getName()); } else { boolean var2 = false; int var4 = Boolean.valueOf(this.isSetStringValue()).compareTo(var1.isSetStringValue()); if (var4 != 0) { return var4; } else { if (this.isSetStringValue()) { var4 = TBaseHelper.compareTo(this.stringValue, var1.stringValue); if (var4 != 0) { return var4; } } var4 = Boolean.valueOf(this.isSetBoolValue()).compareTo(var1.isSetBoolValue()); if (var4 != 0) { return var4; } else { if (this.isSetBoolValue()) { var4 = TBaseHelper.compareTo(this.boolValue, var1.boolValue); if (var4 != 0) { return var4; } } var4 = Boolean.valueOf(this.isSetLongValue()).compareTo(var1.isSetLongValue()); if (var4 != 0) { return var4; } else { if (this.isSetLongValue()) { var4 = TBaseHelper.compareTo(this.longValue, var1.longValue); if (var4 != 0) { return var4; } } var4 = Boolean.valueOf(this.isSetDoubleValue()).compareTo(var1.isSetDoubleValue()); if (var4 != 0) { return var4; } else { if (this.isSetDoubleValue()) { var4 = TBaseHelper.compareTo(this.doubleValue, var1.doubleValue); if (var4 != 0) { return var4; } } var4 = Boolean.valueOf(this.isSetStringArrayValue()).compareTo(var1.isSetStringArrayValue()); if (var4 != 0) { return var4; } else { if (this.isSetStringArrayValue()) { var4 = TBaseHelper.compareTo(this.stringArrayValue, var1.stringArrayValue); if (var4 != 0) { return var4; } } var4 = Boolean.valueOf(this.isSetBoolArrayValue()).compareTo(var1.isSetBoolArrayValue()); if (var4 != 0) { return var4; } else { if (this.isSetBoolArrayValue()) { var4 = TBaseHelper.compareTo(this.boolArrayValue, var1.boolArrayValue); if (var4 != 0) { return var4; } } var4 = Boolean.valueOf(this.isSetLongArrayValue()).compareTo(var1.isSetLongArrayValue()); if (var4 != 0) { return var4; } else { if (this.isSetLongArrayValue()) { var4 = TBaseHelper.compareTo(this.longArrayValue, var1.longArrayValue); if (var4 != 0) { return var4; } } var4 = Boolean.valueOf(this.isSetDoubleArrayValue()).compareTo(var1.isSetDoubleArrayValue()); if (var4 != 0) { return var4; } else { if (this.isSetDoubleArrayValue()) { var4 = TBaseHelper.compareTo(this.doubleArrayValue, var1.doubleArrayValue); if (var4 != 0) { return var4; } } return 0; } } } } } } } } } } public TValue._Fields fieldForId(int var1) { return TValue._Fields.findByThriftId(var1); } public void read(TProtocol var1) throws TException { var1.readStructBegin(); while(true) { TField var2 = var1.readFieldBegin(); if (var2.type == 0) { var1.readStructEnd(); this.validate(); return; } TList var3; int var4; switch(var2.id) { case 1: if (var2.type == 11) { this.stringValue = var1.readString(); } else { TProtocolUtil.skip(var1, var2.type); } break; case 2: if (var2.type == 2) { this.boolValue = var1.readBool(); this.setBoolValueIsSet(true); } else { TProtocolUtil.skip(var1, var2.type); } break; case 3: if (var2.type == 10) { this.longValue = var1.readI64(); this.setLongValueIsSet(true); } else { TProtocolUtil.skip(var1, var2.type); } break; case 4: if (var2.type == 4) { this.doubleValue = var1.readDouble(); this.setDoubleValueIsSet(true); } else { TProtocolUtil.skip(var1, var2.type); } break; case 5: if (var2.type != 15) { TProtocolUtil.skip(var1, var2.type); break; } var3 = var1.readListBegin(); this.stringArrayValue = new ArrayList(var3.size); for(var4 = 0; var4 < var3.size; ++var4) { String var9 = var1.readString(); this.stringArrayValue.add(var9); } var1.readListEnd(); break; case 6: if (var2.type != 15) { TProtocolUtil.skip(var1, var2.type); break; } var3 = var1.readListBegin(); this.boolArrayValue = new ArrayList(var3.size); for(var4 = 0; var4 < var3.size; ++var4) { boolean var8 = var1.readBool(); this.boolArrayValue.add(var8); } var1.readListEnd(); break; case 7: if (var2.type != 15) { TProtocolUtil.skip(var1, var2.type); break; } var3 = var1.readListBegin(); this.longArrayValue = new ArrayList(var3.size); for(var4 = 0; var4 < var3.size; ++var4) { long var7 = var1.readI64(); this.longArrayValue.add(var7); } var1.readListEnd(); break; case 8: if (var2.type != 15) { TProtocolUtil.skip(var1, var2.type); break; } var3 = var1.readListBegin(); this.doubleArrayValue = new ArrayList(var3.size); for(var4 = 0; var4 < var3.size; ++var4) { double var5 = var1.readDouble(); this.doubleArrayValue.add(var5); } var1.readListEnd(); break; default: TProtocolUtil.skip(var1, var2.type); } var1.readFieldEnd(); } } public void write(TProtocol var1) throws TException { this.validate(); var1.writeStructBegin(STRUCT_DESC); if (this.stringValue != null && this.isSetStringValue()) { var1.writeFieldBegin(STRING_VALUE_FIELD_DESC); var1.writeString(this.stringValue); var1.writeFieldEnd(); } if (this.isSetBoolValue()) { var1.writeFieldBegin(BOOL_VALUE_FIELD_DESC); var1.writeBool(this.boolValue); var1.writeFieldEnd(); } if (this.isSetLongValue()) { var1.writeFieldBegin(LONG_VALUE_FIELD_DESC); var1.writeI64(this.longValue); var1.writeFieldEnd(); } if (this.isSetDoubleValue()) { var1.writeFieldBegin(DOUBLE_VALUE_FIELD_DESC); var1.writeDouble(this.doubleValue); var1.writeFieldEnd(); } Iterator var2; if (this.stringArrayValue != null && this.isSetStringArrayValue()) { var1.writeFieldBegin(STRING_ARRAY_VALUE_FIELD_DESC); var1.writeListBegin(new TList((byte)11, this.stringArrayValue.size())); var2 = this.stringArrayValue.iterator(); while(var2.hasNext()) { String var3 = (String)var2.next(); var1.writeString(var3); } var1.writeListEnd(); var1.writeFieldEnd(); } if (this.boolArrayValue != null && this.isSetBoolArrayValue()) { var1.writeFieldBegin(BOOL_ARRAY_VALUE_FIELD_DESC); var1.writeListBegin(new TList((byte)2, this.boolArrayValue.size())); var2 = this.boolArrayValue.iterator(); while(var2.hasNext()) { boolean var5 = (Boolean)var2.next(); var1.writeBool(var5); } var1.writeListEnd(); var1.writeFieldEnd(); } if (this.longArrayValue != null && this.isSetLongArrayValue()) { var1.writeFieldBegin(LONG_ARRAY_VALUE_FIELD_DESC); var1.writeListBegin(new TList((byte)10, this.longArrayValue.size())); var2 = this.longArrayValue.iterator(); while(var2.hasNext()) { long var6 = (Long)var2.next(); var1.writeI64(var6); } var1.writeListEnd(); var1.writeFieldEnd(); } if (this.doubleArrayValue != null && this.isSetDoubleArrayValue()) { var1.writeFieldBegin(DOUBLE_ARRAY_VALUE_FIELD_DESC); var1.writeListBegin(new TList((byte)4, this.doubleArrayValue.size())); var2 = this.doubleArrayValue.iterator(); while(var2.hasNext()) { double var7 = (Double)var2.next(); var1.writeDouble(var7); } var1.writeListEnd(); var1.writeFieldEnd(); } var1.writeFieldStop(); var1.writeStructEnd(); } public String toString() { StringBuilder var1 = new StringBuilder("TValue("); boolean var2 = true; if (this.isSetStringValue()) { var1.append("stringValue:"); if (this.stringValue == null) { var1.append("null"); } else { var1.append(this.stringValue); } var2 = false; } if (this.isSetBoolValue()) { if (!var2) { var1.append(", "); } var1.append("boolValue:"); var1.append(this.boolValue); var2 = false; } if (this.isSetLongValue()) { if (!var2) { var1.append(", "); } var1.append("longValue:"); var1.append(this.longValue); var2 = false; } if (this.isSetDoubleValue()) { if (!var2) { var1.append(", "); } var1.append("doubleValue:"); var1.append(this.doubleValue); var2 = false; } if (this.isSetStringArrayValue()) { if (!var2) { var1.append(", "); } var1.append("stringArrayValue:"); if (this.stringArrayValue == null) { var1.append("null"); } else { var1.append(this.stringArrayValue); } var2 = false; } if (this.isSetBoolArrayValue()) { if (!var2) { var1.append(", "); } var1.append("boolArrayValue:"); if (this.boolArrayValue == null) { var1.append("null"); } else { var1.append(this.boolArrayValue); } var2 = false; } if (this.isSetLongArrayValue()) { if (!var2) { var1.append(", "); } var1.append("longArrayValue:"); if (this.longArrayValue == null) { var1.append("null"); } else { var1.append(this.longArrayValue); } var2 = false; } if (this.isSetDoubleArrayValue()) { if (!var2) { var1.append(", "); } var1.append("doubleArrayValue:"); if (this.doubleArrayValue == null) { var1.append("null"); } else { var1.append(this.doubleArrayValue); } var2 = false; } var1.append(")"); return var1.toString(); } public void validate() throws TException { } static { EnumMap var0 = new EnumMap(TValue._Fields.class); var0.put(TValue._Fields.STRING_VALUE, new FieldMetaData("stringValue", (byte)2, new FieldValueMetaData((byte)11))); var0.put(TValue._Fields.BOOL_VALUE, new FieldMetaData("boolValue", (byte)2, new FieldValueMetaData((byte)2))); var0.put(TValue._Fields.LONG_VALUE, new FieldMetaData("longValue", (byte)2, new FieldValueMetaData((byte)10))); var0.put(TValue._Fields.DOUBLE_VALUE, new FieldMetaData("doubleValue", (byte)2, new FieldValueMetaData((byte)4))); var0.put(TValue._Fields.STRING_ARRAY_VALUE, new FieldMetaData("stringArrayValue", (byte)2, new ListMetaData((byte)15, new FieldValueMetaData((byte)11)))); var0.put(TValue._Fields.BOOL_ARRAY_VALUE, new FieldMetaData("boolArrayValue", (byte)2, new ListMetaData((byte)15, new FieldValueMetaData((byte)2)))); var0.put(TValue._Fields.LONG_ARRAY_VALUE, new FieldMetaData("longArrayValue", (byte)2, new ListMetaData((byte)15, new FieldValueMetaData((byte)10)))); var0.put(TValue._Fields.DOUBLE_ARRAY_VALUE, new FieldMetaData("doubleArrayValue", (byte)2, new ListMetaData((byte)15, new FieldValueMetaData((byte)4)))); metaDataMap = Collections.unmodifiableMap(var0); FieldMetaData.addStructMetaDataMap(TValue.class, metaDataMap); } public static enum _Fields implements TFieldIdEnum { STRING_VALUE((short)1, "stringValue"), BOOL_VALUE((short)2, "boolValue"), LONG_VALUE((short)3, "longValue"), DOUBLE_VALUE((short)4, "doubleValue"), STRING_ARRAY_VALUE((short)5, "stringArrayValue"), BOOL_ARRAY_VALUE((short)6, "boolArrayValue"), LONG_ARRAY_VALUE((short)7, "longArrayValue"), DOUBLE_ARRAY_VALUE((short)8, "doubleArrayValue"); private static final Map<String, TValue._Fields> byName = new HashMap(); private final short _thriftId; private final String _fieldName; public static TValue._Fields findByThriftId(int var0) { switch(var0) { case 1: return STRING_VALUE; case 2: return BOOL_VALUE; case 3: return LONG_VALUE; case 4: return DOUBLE_VALUE; case 5: return STRING_ARRAY_VALUE; case 6: return BOOL_ARRAY_VALUE; case 7: return LONG_ARRAY_VALUE; case 8: return DOUBLE_ARRAY_VALUE; default: return null; } } public static TValue._Fields findByThriftIdOrThrow(int var0) { TValue._Fields var1 = findByThriftId(var0); if (var1 == null) { throw new IllegalArgumentException("Field " + var0 + " doesn't exist!"); } else { return var1; } } public static TValue._Fields findByName(String var0) { return (TValue._Fields)byName.get(var0); } private _Fields(short var3, String var4) { this._thriftId = var3; this._fieldName = var4; } public short getThriftFieldId() { return this._thriftId; } public String getFieldName() { return this._fieldName; } static { Iterator var0 = EnumSet.allOf(TValue._Fields.class).iterator(); while(var0.hasNext()) { TValue._Fields var1 = (TValue._Fields)var0.next(); byName.put(var1.getFieldName(), var1); } } } }
googleapis/google-cloud-java
37,325
java-shopping-merchant-lfp/proto-google-shopping-merchant-lfp-v1beta/src/main/java/com/google/shopping/merchant/lfp/v1beta/ListLfpStoresResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/shopping/merchant/lfp/v1beta/lfpstore.proto // Protobuf Java Version: 3.25.8 package com.google.shopping.merchant.lfp.v1beta; /** * * * <pre> * Response message for the ListLfpStores method. * </pre> * * Protobuf type {@code google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse} */ public final class ListLfpStoresResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse) ListLfpStoresResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListLfpStoresResponse.newBuilder() to construct. private ListLfpStoresResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListLfpStoresResponse() { lfpStores_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListLfpStoresResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.lfp.v1beta.LfpStoreProto .internal_static_google_shopping_merchant_lfp_v1beta_ListLfpStoresResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.lfp.v1beta.LfpStoreProto .internal_static_google_shopping_merchant_lfp_v1beta_ListLfpStoresResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse.class, com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse.Builder.class); } public static final int LFP_STORES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.shopping.merchant.lfp.v1beta.LfpStore> lfpStores_; /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ @java.lang.Override public java.util.List<com.google.shopping.merchant.lfp.v1beta.LfpStore> getLfpStoresList() { return lfpStores_; } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.shopping.merchant.lfp.v1beta.LfpStoreOrBuilder> getLfpStoresOrBuilderList() { return lfpStores_; } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ @java.lang.Override public int getLfpStoresCount() { return lfpStores_.size(); } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ @java.lang.Override public com.google.shopping.merchant.lfp.v1beta.LfpStore getLfpStores(int index) { return lfpStores_.get(index); } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ @java.lang.Override public com.google.shopping.merchant.lfp.v1beta.LfpStoreOrBuilder getLfpStoresOrBuilder( int index) { return lfpStores_.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 `pageToken` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token, which can be sent as `pageToken` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < lfpStores_.size(); i++) { output.writeMessage(1, lfpStores_.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 < lfpStores_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, lfpStores_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse)) { return super.equals(obj); } com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse other = (com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse) obj; if (!getLfpStoresList().equals(other.getLfpStoresList())) 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 (getLfpStoresCount() > 0) { hash = (37 * hash) + LFP_STORES_FIELD_NUMBER; hash = (53 * hash) + getLfpStoresList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse 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 ListLfpStores method. * </pre> * * Protobuf type {@code google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse) com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.lfp.v1beta.LfpStoreProto .internal_static_google_shopping_merchant_lfp_v1beta_ListLfpStoresResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.lfp.v1beta.LfpStoreProto .internal_static_google_shopping_merchant_lfp_v1beta_ListLfpStoresResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse.class, com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse.Builder.class); } // Construct using com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (lfpStoresBuilder_ == null) { lfpStores_ = java.util.Collections.emptyList(); } else { lfpStores_ = null; lfpStoresBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.shopping.merchant.lfp.v1beta.LfpStoreProto .internal_static_google_shopping_merchant_lfp_v1beta_ListLfpStoresResponse_descriptor; } @java.lang.Override public com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse getDefaultInstanceForType() { return com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse.getDefaultInstance(); } @java.lang.Override public com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse build() { com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse buildPartial() { com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse result = new com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse result) { if (lfpStoresBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { lfpStores_ = java.util.Collections.unmodifiableList(lfpStores_); bitField0_ = (bitField0_ & ~0x00000001); } result.lfpStores_ = lfpStores_; } else { result.lfpStores_ = lfpStoresBuilder_.build(); } } private void buildPartial0( com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse) { return mergeFrom((com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse other) { if (other == com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse.getDefaultInstance()) return this; if (lfpStoresBuilder_ == null) { if (!other.lfpStores_.isEmpty()) { if (lfpStores_.isEmpty()) { lfpStores_ = other.lfpStores_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureLfpStoresIsMutable(); lfpStores_.addAll(other.lfpStores_); } onChanged(); } } else { if (!other.lfpStores_.isEmpty()) { if (lfpStoresBuilder_.isEmpty()) { lfpStoresBuilder_.dispose(); lfpStoresBuilder_ = null; lfpStores_ = other.lfpStores_; bitField0_ = (bitField0_ & ~0x00000001); lfpStoresBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getLfpStoresFieldBuilder() : null; } else { lfpStoresBuilder_.addAllMessages(other.lfpStores_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.shopping.merchant.lfp.v1beta.LfpStore m = input.readMessage( com.google.shopping.merchant.lfp.v1beta.LfpStore.parser(), extensionRegistry); if (lfpStoresBuilder_ == null) { ensureLfpStoresIsMutable(); lfpStores_.add(m); } else { lfpStoresBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.shopping.merchant.lfp.v1beta.LfpStore> lfpStores_ = java.util.Collections.emptyList(); private void ensureLfpStoresIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { lfpStores_ = new java.util.ArrayList<com.google.shopping.merchant.lfp.v1beta.LfpStore>(lfpStores_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.merchant.lfp.v1beta.LfpStore, com.google.shopping.merchant.lfp.v1beta.LfpStore.Builder, com.google.shopping.merchant.lfp.v1beta.LfpStoreOrBuilder> lfpStoresBuilder_; /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public java.util.List<com.google.shopping.merchant.lfp.v1beta.LfpStore> getLfpStoresList() { if (lfpStoresBuilder_ == null) { return java.util.Collections.unmodifiableList(lfpStores_); } else { return lfpStoresBuilder_.getMessageList(); } } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public int getLfpStoresCount() { if (lfpStoresBuilder_ == null) { return lfpStores_.size(); } else { return lfpStoresBuilder_.getCount(); } } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public com.google.shopping.merchant.lfp.v1beta.LfpStore getLfpStores(int index) { if (lfpStoresBuilder_ == null) { return lfpStores_.get(index); } else { return lfpStoresBuilder_.getMessage(index); } } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public Builder setLfpStores(int index, com.google.shopping.merchant.lfp.v1beta.LfpStore value) { if (lfpStoresBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLfpStoresIsMutable(); lfpStores_.set(index, value); onChanged(); } else { lfpStoresBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public Builder setLfpStores( int index, com.google.shopping.merchant.lfp.v1beta.LfpStore.Builder builderForValue) { if (lfpStoresBuilder_ == null) { ensureLfpStoresIsMutable(); lfpStores_.set(index, builderForValue.build()); onChanged(); } else { lfpStoresBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public Builder addLfpStores(com.google.shopping.merchant.lfp.v1beta.LfpStore value) { if (lfpStoresBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLfpStoresIsMutable(); lfpStores_.add(value); onChanged(); } else { lfpStoresBuilder_.addMessage(value); } return this; } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public Builder addLfpStores(int index, com.google.shopping.merchant.lfp.v1beta.LfpStore value) { if (lfpStoresBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLfpStoresIsMutable(); lfpStores_.add(index, value); onChanged(); } else { lfpStoresBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public Builder addLfpStores( com.google.shopping.merchant.lfp.v1beta.LfpStore.Builder builderForValue) { if (lfpStoresBuilder_ == null) { ensureLfpStoresIsMutable(); lfpStores_.add(builderForValue.build()); onChanged(); } else { lfpStoresBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public Builder addLfpStores( int index, com.google.shopping.merchant.lfp.v1beta.LfpStore.Builder builderForValue) { if (lfpStoresBuilder_ == null) { ensureLfpStoresIsMutable(); lfpStores_.add(index, builderForValue.build()); onChanged(); } else { lfpStoresBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public Builder addAllLfpStores( java.lang.Iterable<? extends com.google.shopping.merchant.lfp.v1beta.LfpStore> values) { if (lfpStoresBuilder_ == null) { ensureLfpStoresIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, lfpStores_); onChanged(); } else { lfpStoresBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public Builder clearLfpStores() { if (lfpStoresBuilder_ == null) { lfpStores_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { lfpStoresBuilder_.clear(); } return this; } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public Builder removeLfpStores(int index) { if (lfpStoresBuilder_ == null) { ensureLfpStoresIsMutable(); lfpStores_.remove(index); onChanged(); } else { lfpStoresBuilder_.remove(index); } return this; } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public com.google.shopping.merchant.lfp.v1beta.LfpStore.Builder getLfpStoresBuilder(int index) { return getLfpStoresFieldBuilder().getBuilder(index); } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public com.google.shopping.merchant.lfp.v1beta.LfpStoreOrBuilder getLfpStoresOrBuilder( int index) { if (lfpStoresBuilder_ == null) { return lfpStores_.get(index); } else { return lfpStoresBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public java.util.List<? extends com.google.shopping.merchant.lfp.v1beta.LfpStoreOrBuilder> getLfpStoresOrBuilderList() { if (lfpStoresBuilder_ != null) { return lfpStoresBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(lfpStores_); } } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public com.google.shopping.merchant.lfp.v1beta.LfpStore.Builder addLfpStoresBuilder() { return getLfpStoresFieldBuilder() .addBuilder(com.google.shopping.merchant.lfp.v1beta.LfpStore.getDefaultInstance()); } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public com.google.shopping.merchant.lfp.v1beta.LfpStore.Builder addLfpStoresBuilder(int index) { return getLfpStoresFieldBuilder() .addBuilder(index, com.google.shopping.merchant.lfp.v1beta.LfpStore.getDefaultInstance()); } /** * * * <pre> * The stores from the specified merchant. * </pre> * * <code>repeated .google.shopping.merchant.lfp.v1beta.LfpStore lfp_stores = 1;</code> */ public java.util.List<com.google.shopping.merchant.lfp.v1beta.LfpStore.Builder> getLfpStoresBuilderList() { return getLfpStoresFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.merchant.lfp.v1beta.LfpStore, com.google.shopping.merchant.lfp.v1beta.LfpStore.Builder, com.google.shopping.merchant.lfp.v1beta.LfpStoreOrBuilder> getLfpStoresFieldBuilder() { if (lfpStoresBuilder_ == null) { lfpStoresBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.merchant.lfp.v1beta.LfpStore, com.google.shopping.merchant.lfp.v1beta.LfpStore.Builder, com.google.shopping.merchant.lfp.v1beta.LfpStoreOrBuilder>( lfpStores_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); lfpStores_ = null; } return lfpStoresBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `pageToken` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as `pageToken` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as `pageToken` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `pageToken` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `pageToken` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse) } // @@protoc_insertion_point(class_scope:google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse) private static final com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse(); } public static com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListLfpStoresResponse> PARSER = new com.google.protobuf.AbstractParser<ListLfpStoresResponse>() { @java.lang.Override public ListLfpStoresResponse 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<ListLfpStoresResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListLfpStoresResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.shopping.merchant.lfp.v1beta.ListLfpStoresResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/felix-dev
37,422
healthcheck/core/src/test/java/org/apache/felix/hc/core/impl/scheduling/cron/embedded/EmbeddedCronParserTest.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 SF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.apache.felix.hc.core.impl.scheduling.cron.embedded; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.TimeZone; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class EmbeddedCronParserTest { private final Calendar calendar = new GregorianCalendar(); private final Date date; private final TimeZone timeZone; public EmbeddedCronParserTest(final Date date, final TimeZone timeZone) { this.date = date; this.timeZone = timeZone; } @Parameters(name = "date [{0}], time zone [{1}]") public static List<Object[]> getParameters() { final List<Object[]> list = new ArrayList<>(); list.add(new Object[] { new Date(), TimeZone.getTimeZone("PST") }); list.add(new Object[] { new Date(), TimeZone.getTimeZone("CET") }); return list; } private static void roundup(final Calendar calendar) { calendar.add(Calendar.SECOND, 1); calendar.set(Calendar.MILLISECOND, 0); } @Before public void setUp() { calendar.setTimeZone(timeZone); calendar.setTime(date); roundup(calendar); } @Test public void testAt0And15And45Seconds() { final EmbeddedCronParser trigger = new EmbeddedCronParser("*/15 * 1-4 * * *", timeZone); calendar.set(Calendar.DAY_OF_MONTH, 2); calendar.set(Calendar.HOUR_OF_DAY, 9); calendar.set(Calendar.MINUTE, 53); calendar.set(Calendar.SECOND, 50); Date intialTime = calendar.getTime(); calendar.set(Calendar.DAY_OF_MONTH, 3); calendar.set(Calendar.HOUR_OF_DAY, 1); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); assertEquals(calendar.getTime().getTime(), trigger.next(intialTime.getTime())); intialTime = calendar.getTime(); calendar.set(Calendar.SECOND, 15); assertEquals(calendar.getTime().getTime(), trigger.next(intialTime.getTime())); intialTime = calendar.getTime(); calendar.set(Calendar.SECOND, 30); assertEquals(calendar.getTime().getTime(), trigger.next(intialTime.getTime())); intialTime = calendar.getTime(); calendar.set(Calendar.SECOND, 45); assertEquals(calendar.getTime().getTime(), trigger.next(intialTime.getTime())); } @Test public void testAt0Minutes() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 */2 1-4 * * *", timeZone); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 9); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); Date intialTime = calendar.getTime(); calendar.set(Calendar.DAY_OF_MONTH, 2); calendar.set(Calendar.HOUR_OF_DAY, 1); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); long next = trigger.next(intialTime.getTime()); assertEquals(calendar.getTime().getTime(), next); } @Test(expected = IllegalArgumentException.class) public void testWith0Increment() { new EmbeddedCronParser("*/0 * * * * *").next(calendar.getTime().getTime()); } @Test(expected = IllegalArgumentException.class) public void testWithNegativeIncrement() { new EmbeddedCronParser("*/-1 * * * * *").next(calendar.getTime().getTime()); } @Test public void testMatchAll() { final EmbeddedCronParser trigger = new EmbeddedCronParser("* * * * * *", timeZone); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testMatchLastSecond() { final EmbeddedCronParser trigger = new EmbeddedCronParser("* * * * * *", timeZone); calendar.set(Calendar.SECOND, 58); assertMatchesNextSecond(trigger, calendar); } @Test public void testMatchSpecificSecond() { final EmbeddedCronParser trigger = new EmbeddedCronParser("10 * * * * *", timeZone); calendar.set(Calendar.SECOND, 9); assertMatchesNextSecond(trigger, calendar); } @Test public void testIncrementSecondByOne() { final EmbeddedCronParser trigger = new EmbeddedCronParser("11 * * * * *", timeZone); calendar.set(Calendar.SECOND, 10); final Date date = calendar.getTime(); calendar.add(Calendar.SECOND, 1); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testIncrementSecondWithPreviousExecutionTooEarly() { final EmbeddedCronParser trigger = new EmbeddedCronParser("11 * * * * *", timeZone); calendar.set(Calendar.SECOND, 11); final Date date = calendar.getTime(); calendar.add(Calendar.MINUTE, 1); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testIncrementSecondAndRollover() { final EmbeddedCronParser trigger = new EmbeddedCronParser("10 * * * * *", timeZone); calendar.set(Calendar.SECOND, 11); final Date date = calendar.getTime(); calendar.add(Calendar.SECOND, 59); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testSecondRange() { final EmbeddedCronParser trigger = new EmbeddedCronParser("10-15 * * * * *", timeZone); calendar.set(Calendar.SECOND, 9); assertMatchesNextSecond(trigger, calendar); calendar.set(Calendar.SECOND, 14); assertMatchesNextSecond(trigger, calendar); } @Test public void testIncrementMinute() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 * * * * *", timeZone); calendar.set(Calendar.MINUTE, 10); Date date = calendar.getTime(); calendar.add(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 0); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.add(Calendar.MINUTE, 1); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); } @Test public void testIncrementMinuteByOne() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 11 * * * *", timeZone); calendar.set(Calendar.MINUTE, 10); final Date date = calendar.getTime(); calendar.add(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 0); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testIncrementMinuteAndRollover() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 10 * * * *", timeZone); calendar.set(Calendar.MINUTE, 11); calendar.set(Calendar.SECOND, 0); final Date date = calendar.getTime(); calendar.add(Calendar.MINUTE, 59); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testIncrementHour() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 * * * *", timeZone); calendar.set(Calendar.MONTH, 9); calendar.set(Calendar.DAY_OF_MONTH, 30); calendar.set(Calendar.HOUR_OF_DAY, 11); calendar.set(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 0); Date date = calendar.getTime(); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 12); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.set(Calendar.HOUR_OF_DAY, 13); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testIncrementHourAndRollover() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 * * * *", timeZone); calendar.set(Calendar.MONTH, 9); calendar.set(Calendar.DAY_OF_MONTH, 10); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 0); Date date = calendar.getTime(); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.DAY_OF_MONTH, 11); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.set(Calendar.HOUR_OF_DAY, 1); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testIncrementDayOfMonth() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 0 * * *", timeZone); calendar.set(Calendar.DAY_OF_MONTH, 1); Date date = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); assertEquals(2, calendar.get(Calendar.DAY_OF_MONTH)); calendar.add(Calendar.DAY_OF_MONTH, 1); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); assertEquals(3, calendar.get(Calendar.DAY_OF_MONTH)); } @Test public void testIncrementDayOfMonthByOne() { final EmbeddedCronParser trigger = new EmbeddedCronParser("* * * 10 * *", timeZone); calendar.set(Calendar.DAY_OF_MONTH, 9); final Date date = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testIncrementDayOfMonthAndRollover() { final EmbeddedCronParser trigger = new EmbeddedCronParser("* * * 10 * *", timeZone); calendar.set(Calendar.DAY_OF_MONTH, 11); final Date date = calendar.getTime(); calendar.add(Calendar.MONTH, 1); calendar.set(Calendar.DAY_OF_MONTH, 10); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testDailyTriggerInShortMonth() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 0 * * *", timeZone); calendar.set(Calendar.MONTH, 8); // September: 30 days calendar.set(Calendar.DAY_OF_MONTH, 30); Date date = calendar.getTime(); calendar.set(Calendar.MONTH, 9); // October calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.DAY_OF_MONTH, 1); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.set(Calendar.DAY_OF_MONTH, 2); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testDailyTriggerInLongMonth() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 0 * * *", timeZone); calendar.set(Calendar.MONTH, 7); // August: 31 days and not a daylight saving boundary calendar.set(Calendar.DAY_OF_MONTH, 30); Date date = calendar.getTime(); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.DAY_OF_MONTH, 31); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.set(Calendar.MONTH, 8); // September calendar.set(Calendar.DAY_OF_MONTH, 1); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testDailyTriggerOnDaylightSavingBoundary() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 0 * * *", timeZone); calendar.set(Calendar.MONTH, 9); // October: 31 days and a daylight saving boundary in CET calendar.set(Calendar.DAY_OF_MONTH, 30); Date date = calendar.getTime(); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.DAY_OF_MONTH, 31); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.set(Calendar.MONTH, 10); // November calendar.set(Calendar.DAY_OF_MONTH, 1); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testIncrementMonth() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 0 1 * *", timeZone); calendar.set(Calendar.MONTH, 9); calendar.set(Calendar.DAY_OF_MONTH, 30); Date date = calendar.getTime(); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MONTH, 10); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.set(Calendar.MONTH, 11); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testIncrementMonthAndRollover() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 0 1 * *", timeZone); calendar.set(Calendar.MONTH, 11); calendar.set(Calendar.DAY_OF_MONTH, 31); calendar.set(Calendar.YEAR, 2010); Date date = calendar.getTime(); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MONTH, 0); calendar.set(Calendar.YEAR, 2011); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.set(Calendar.MONTH, 1); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testMonthlyTriggerInLongMonth() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 0 31 * *", timeZone); calendar.set(Calendar.MONTH, 9); calendar.set(Calendar.DAY_OF_MONTH, 30); final Date date = calendar.getTime(); calendar.set(Calendar.DAY_OF_MONTH, 31); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testMonthlyTriggerInShortMonth() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 0 1 * *", timeZone); calendar.set(Calendar.MONTH, 9); calendar.set(Calendar.DAY_OF_MONTH, 30); final Date date = calendar.getTime(); calendar.set(Calendar.MONTH, 10); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testIncrementDayOfWeekByOne() { final EmbeddedCronParser trigger = new EmbeddedCronParser("* * * * * 2", timeZone); calendar.set(Calendar.DAY_OF_WEEK, 2); final Date date = calendar.getTime(); calendar.add(Calendar.DAY_OF_WEEK, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); assertEquals(Calendar.TUESDAY, calendar.get(Calendar.DAY_OF_WEEK)); } @Test public void testIncrementDayOfWeekAndRollover() { final EmbeddedCronParser trigger = new EmbeddedCronParser("* * * * * 2", timeZone); calendar.set(Calendar.DAY_OF_WEEK, 4); final Date date = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, 6); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); assertEquals(Calendar.TUESDAY, calendar.get(Calendar.DAY_OF_WEEK)); } @Test public void testSpecificMinuteSecond() { final EmbeddedCronParser trigger = new EmbeddedCronParser("55 5 * * * *", timeZone); calendar.set(Calendar.MINUTE, 4); calendar.set(Calendar.SECOND, 54); Date date = calendar.getTime(); calendar.add(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 55); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.add(Calendar.HOUR, 1); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testSpecificHourSecond() { final EmbeddedCronParser trigger = new EmbeddedCronParser("55 * 10 * * *", timeZone); calendar.set(Calendar.HOUR_OF_DAY, 9); calendar.set(Calendar.SECOND, 54); Date date = calendar.getTime(); calendar.add(Calendar.HOUR_OF_DAY, 1); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 55); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.add(Calendar.MINUTE, 1); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testSpecificMinuteHour() { final EmbeddedCronParser trigger = new EmbeddedCronParser("* 5 10 * * *", timeZone); calendar.set(Calendar.MINUTE, 4); calendar.set(Calendar.HOUR_OF_DAY, 9); Date date = calendar.getTime(); calendar.add(Calendar.MINUTE, 1); calendar.add(Calendar.HOUR_OF_DAY, 1); calendar.set(Calendar.SECOND, 0); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); // next trigger is in one second because second is wildcard calendar.add(Calendar.SECOND, 1); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testSpecificDayOfMonthSecond() { final EmbeddedCronParser trigger = new EmbeddedCronParser("55 * * 3 * *", timeZone); calendar.set(Calendar.DAY_OF_MONTH, 2); calendar.set(Calendar.SECOND, 54); Date date = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 55); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.add(Calendar.MINUTE, 1); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testSpecificDate() { final EmbeddedCronParser trigger = new EmbeddedCronParser("* * * 3 11 *", timeZone); calendar.set(Calendar.DAY_OF_MONTH, 2); calendar.set(Calendar.MONTH, 9); Date date = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MONTH, 10); // 10=November calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.add(Calendar.SECOND, 1); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); } @Test(expected = IllegalArgumentException.class) public void testNonExistentSpecificDate() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 0 31 6 *", timeZone); calendar.set(Calendar.DAY_OF_MONTH, 10); calendar.set(Calendar.MONTH, 2); final Date date = calendar.getTime(); trigger.next(date.getTime()); } @Test public void testLeapYearSpecificDate() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 0 29 2 *", timeZone); calendar.set(Calendar.YEAR, 2007); calendar.set(Calendar.DAY_OF_MONTH, 10); calendar.set(Calendar.MONTH, 1); // 2=February Date date = calendar.getTime(); calendar.set(Calendar.YEAR, 2008); calendar.set(Calendar.DAY_OF_MONTH, 29); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.add(Calendar.YEAR, 4); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); } @Test public void testWeekDaySequence() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 7 ? * MON-FRI", timeZone); // This is a Saturday calendar.set(2009, Calendar.SEPTEMBER, 26); Date date = calendar.getTime(); // 7 am is the trigger time calendar.set(Calendar.HOUR_OF_DAY, 7); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); // Add two days because we start on Saturday calendar.add(Calendar.DAY_OF_MONTH, 2); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); // Next day is a week day so add one calendar.add(Calendar.DAY_OF_MONTH, 1); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); calendar.add(Calendar.DAY_OF_MONTH, 1); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTimeInMillis(), date.getTime()); } @Test public void testDayOfWeekIndifferent() { final EmbeddedCronParser trigger1 = new EmbeddedCronParser("* * * 2 * *", timeZone); final EmbeddedCronParser trigger2 = new EmbeddedCronParser("* * * 2 * ?", timeZone); assertEquals(trigger1, trigger2); } @Test public void testSecondIncrementer() { final EmbeddedCronParser trigger1 = new EmbeddedCronParser("57,59 * * * * *", timeZone); final EmbeddedCronParser trigger2 = new EmbeddedCronParser("57/2 * * * * *", timeZone); assertEquals(trigger1, trigger2); } @Test public void testSecondIncrementerWithRange() { final EmbeddedCronParser trigger1 = new EmbeddedCronParser("1,3,5 * * * * *", timeZone); final EmbeddedCronParser trigger2 = new EmbeddedCronParser("1-6/2 * * * * *", timeZone); assertEquals(trigger1, trigger2); } @Test public void testHourIncrementer() { final EmbeddedCronParser trigger1 = new EmbeddedCronParser("* * 4,8,12,16,20 * * *", timeZone); final EmbeddedCronParser trigger2 = new EmbeddedCronParser("* * 4/4 * * *", timeZone); assertEquals(trigger1, trigger2); } @Test public void testDayNames() { final EmbeddedCronParser trigger1 = new EmbeddedCronParser("* * * * * 0-6", timeZone); final EmbeddedCronParser trigger2 = new EmbeddedCronParser("* * * * * TUE,WED,THU,FRI,SAT,SUN,MON", timeZone); assertEquals(trigger1, trigger2); } @Test public void testSundayIsZero() { final EmbeddedCronParser trigger1 = new EmbeddedCronParser("* * * * * 0", timeZone); final EmbeddedCronParser trigger2 = new EmbeddedCronParser("* * * * * SUN", timeZone); assertEquals(trigger1, trigger2); } @Test public void testSundaySynonym() { final EmbeddedCronParser trigger1 = new EmbeddedCronParser("* * * * * 0", timeZone); final EmbeddedCronParser trigger2 = new EmbeddedCronParser("* * * * * 7", timeZone); assertEquals(trigger1, trigger2); } @Test public void testMonthNames() { final EmbeddedCronParser trigger1 = new EmbeddedCronParser("* * * * 1-12 *", timeZone); final EmbeddedCronParser trigger2 = new EmbeddedCronParser( "* * * * FEB,JAN,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC *", timeZone); assertEquals(trigger1, trigger2); } @Test public void testMonthNamesMixedCase() { final EmbeddedCronParser trigger1 = new EmbeddedCronParser("* * * * 2 *", timeZone); final EmbeddedCronParser trigger2 = new EmbeddedCronParser("* * * * Feb *", timeZone); assertEquals(trigger1, trigger2); } @Test(expected = IllegalArgumentException.class) public void testSecondInvalid() { new EmbeddedCronParser("77 * * * * *", timeZone); } @Test(expected = IllegalArgumentException.class) public void testSecondRangeInvalid() { new EmbeddedCronParser("44-77 * * * * *", timeZone); } @Test(expected = IllegalArgumentException.class) public void testMinuteInvalid() { new EmbeddedCronParser("* 77 * * * *", timeZone); } @Test(expected = IllegalArgumentException.class) public void testMinuteRangeInvalid() { new EmbeddedCronParser("* 44-77 * * * *", timeZone); } @Test(expected = IllegalArgumentException.class) public void testHourInvalid() { new EmbeddedCronParser("* * 27 * * *", timeZone); } @Test(expected = IllegalArgumentException.class) public void testHourRangeInvalid() { new EmbeddedCronParser("* * 23-28 * * *", timeZone); } @Test(expected = IllegalArgumentException.class) public void testDayInvalid() { new EmbeddedCronParser("* * * 45 * *", timeZone); } @Test(expected = IllegalArgumentException.class) public void testDayRangeInvalid() { new EmbeddedCronParser("* * * 28-45 * *", timeZone); } @Test(expected = IllegalArgumentException.class) public void testMonthInvalid() { new EmbeddedCronParser("0 0 0 25 13 ?", timeZone); } @Test(expected = IllegalArgumentException.class) public void testMonthInvalidTooSmall() { new EmbeddedCronParser("0 0 0 25 0 ?", timeZone); } @Test(expected = IllegalArgumentException.class) public void testDayOfMonthInvalid() { new EmbeddedCronParser("0 0 0 32 12 ?", timeZone); } @Test(expected = IllegalArgumentException.class) public void testMonthRangeInvalid() { new EmbeddedCronParser("* * * * 11-13 *", timeZone); } @Test public void testWhitespace() { final EmbeddedCronParser trigger1 = new EmbeddedCronParser("* * * * 1 *", timeZone); final EmbeddedCronParser trigger2 = new EmbeddedCronParser("* * * * 1 *", timeZone); assertEquals(trigger1, trigger2); } @Test public void testMonthSequence() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 30 23 30 1/3 ?", timeZone); calendar.set(2010, Calendar.DECEMBER, 30); Date date = calendar.getTime(); // set expected next trigger time calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 30); calendar.set(Calendar.SECOND, 0); calendar.add(Calendar.MONTH, 1); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTime(), date); // Next trigger is 3 months latter calendar.add(Calendar.MONTH, 3); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTime(), date); // Next trigger is 3 months latter calendar.add(Calendar.MONTH, 3); date = new Date(trigger.next(date.getTime())); assertEquals(calendar.getTime(), date); } @Test public void testDaylightSavingMissingHour() { // This trigger has to be somewhere in between 2am and 3am final EmbeddedCronParser trigger = new EmbeddedCronParser("0 10 2 * * *", timeZone); calendar.set(Calendar.DAY_OF_MONTH, 31); calendar.set(Calendar.MONTH, Calendar.MARCH); calendar.set(Calendar.YEAR, 2013); calendar.set(Calendar.HOUR_OF_DAY, 1); calendar.set(Calendar.SECOND, 54); final Date date = calendar.getTime(); if (timeZone.equals(TimeZone.getTimeZone("CET"))) { // Clocks go forward an hour so 2am doesn't exist in CET for this date calendar.add(Calendar.DAY_OF_MONTH, 1); } calendar.add(Calendar.HOUR_OF_DAY, 1); calendar.set(Calendar.MINUTE, 10); calendar.set(Calendar.SECOND, 0); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } @Test public void testYearFieldSetToStar() { final EmbeddedCronParser trigger = new EmbeddedCronParser("30 30 7 * * * *", timeZone); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 2); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); Date intialTime = calendar.getTime(); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 7); calendar.set(Calendar.MINUTE, 30); calendar.set(Calendar.SECOND, 30); long next = trigger.next(intialTime.getTime()); assertEquals(calendar.getTime().getTime(), next); } @Test public void testYearInThePast() { final EmbeddedCronParser trigger = new EmbeddedCronParser("* * * * * * 1977", timeZone); calendar.set(Calendar.YEAR, 2020); calendar.set(Calendar.MONTH, 0); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); Date intialTime = calendar.getTime(); calendar.set(Calendar.YEAR, calendar.getMaximum(Calendar.YEAR)); long next = trigger.next(intialTime.getTime()); assertEquals(calendar.getTime().getTime(), next); } @Test public void testJumpToCronYear() { final EmbeddedCronParser trigger = new EmbeddedCronParser("* * * * * * 2022", timeZone); calendar.set(Calendar.YEAR, 2020); calendar.set(Calendar.MONTH, 5); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 3); calendar.set(Calendar.MINUTE, 4); calendar.set(Calendar.SECOND, 33); Date intialTime = calendar.getTime(); calendar.set(Calendar.YEAR, 2022); calendar.set(Calendar.MONTH, Calendar.JANUARY); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); long next = trigger.next(intialTime.getTime()); assertEquals(calendar.getTime().getTime(), next); final EmbeddedCronParser triggerWithRange = new EmbeddedCronParser("* * * * * * 2024-2030", timeZone); calendar.set(Calendar.YEAR, 2024); calendar.set(Calendar.MONTH, 0); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); long nextForRange = triggerWithRange.next(intialTime.getTime()); assertEquals(calendar.getTime().getTime(), nextForRange); } @Test public void testCronYearStayOnSameYear() { final EmbeddedCronParser trigger = new EmbeddedCronParser("* * * * * * 2022", timeZone); calendar.set(Calendar.YEAR, 2022); calendar.set(Calendar.MONTH, Calendar.MAY); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 3); calendar.set(Calendar.MINUTE, 4); calendar.set(Calendar.SECOND, 33); Date intialTime = calendar.getTime(); calendar.set(Calendar.SECOND, 34); long next = trigger.next(intialTime.getTime()); assertEquals(calendar.getTime().getTime(), next); final EmbeddedCronParser triggerWithRange = new EmbeddedCronParser("* * * * * * 2022-2030", timeZone); calendar.set(Calendar.SECOND, 34); long nextForRange = triggerWithRange.next(intialTime.getTime()); assertEquals(calendar.getTime().getTime(), nextForRange); final EmbeddedCronParser triggerWithDayAndTime = new EmbeddedCronParser("0 0 7 15 * * 2022-2030", timeZone); calendar.set(Calendar.DAY_OF_MONTH, 15); calendar.set(Calendar.HOUR_OF_DAY, 7); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); long nextForTriggerWithDayAndTime = triggerWithDayAndTime.next(intialTime.getTime()); assertEquals(calendar.getTime().getTime(), nextForTriggerWithDayAndTime); } @Test public void testJumpToNextYearWithinRange() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 7 15 * * 2020-2025", timeZone); calendar.set(Calendar.YEAR, 2023); calendar.set(Calendar.MONTH, Calendar.DECEMBER); calendar.set(Calendar.DAY_OF_MONTH, 24); calendar.set(Calendar.HOUR_OF_DAY, 18); calendar.set(Calendar.MINUTE, 4); calendar.set(Calendar.SECOND, 33); Date intialTime = calendar.getTime(); calendar.set(Calendar.YEAR, 2024); calendar.set(Calendar.MONTH, Calendar.JANUARY); calendar.set(Calendar.DAY_OF_MONTH, 15); calendar.set(Calendar.HOUR_OF_DAY, 7); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); long next = trigger.next(intialTime.getTime()); assertEquals(calendar.getTime().getTime(), next); } @Test public void testJumpToNextYearLeavingRange() { final EmbeddedCronParser trigger = new EmbeddedCronParser("0 0 7 15 * * 2020-2023", timeZone); calendar.set(Calendar.YEAR, 2023); calendar.set(Calendar.MONTH, Calendar.DECEMBER); calendar.set(Calendar.DAY_OF_MONTH, 24); calendar.set(Calendar.HOUR_OF_DAY, 18); calendar.set(Calendar.MINUTE, 4); calendar.set(Calendar.SECOND, 33); Date intialTime = calendar.getTime(); calendar.set(Calendar.YEAR, calendar.getMaximum(Calendar.YEAR)); calendar.set(Calendar.MONTH, Calendar.JANUARY); calendar.set(Calendar.DAY_OF_MONTH, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); long next = trigger.next(intialTime.getTime()); assertTrue(next > calendar.getTime().getTime()); } @Test public void testPreDeclared() { assertEquals("0 0 0 1 1 *", new EmbeddedCronParser("@annually", timeZone).getExpression()); assertEquals("0 0 0 1 1 *", new EmbeddedCronParser("@yearly", timeZone).getExpression()); assertEquals("0 0 0 1 * *", new EmbeddedCronParser("@monthly", timeZone).getExpression()); assertEquals("0 0 0 ? * MON", new EmbeddedCronParser("@weekly", timeZone).getExpression()); assertEquals("0 0 0 * * ?", new EmbeddedCronParser("@daily", timeZone).getExpression()); assertEquals("0 0 * * * ?", new EmbeddedCronParser("@hourly", timeZone).getExpression()); } private void assertMatchesNextSecond(final EmbeddedCronParser trigger, final Calendar calendar) { final Date date = calendar.getTime(); roundup(calendar); assertEquals(calendar.getTimeInMillis(), trigger.next(date.getTime())); } }
googleapis/google-cloud-java
37,440
java-confidentialcomputing/proto-google-cloud-confidentialcomputing-v1/src/main/java/com/google/cloud/confidentialcomputing/v1/SignedEntity.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/confidentialcomputing/v1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.confidentialcomputing.v1; /** * * * <pre> * SignedEntity represents an OCI image object containing everything necessary * to verify container image signatures. * </pre> * * Protobuf type {@code google.cloud.confidentialcomputing.v1.SignedEntity} */ public final class SignedEntity extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.confidentialcomputing.v1.SignedEntity) SignedEntityOrBuilder { private static final long serialVersionUID = 0L; // Use SignedEntity.newBuilder() to construct. private SignedEntity(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SignedEntity() { containerImageSignatures_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SignedEntity(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.confidentialcomputing.v1.ServiceProto .internal_static_google_cloud_confidentialcomputing_v1_SignedEntity_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.confidentialcomputing.v1.ServiceProto .internal_static_google_cloud_confidentialcomputing_v1_SignedEntity_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.confidentialcomputing.v1.SignedEntity.class, com.google.cloud.confidentialcomputing.v1.SignedEntity.Builder.class); } public static final int CONTAINER_IMAGE_SIGNATURES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.confidentialcomputing.v1.ContainerImageSignature> containerImageSignatures_; /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public java.util.List<com.google.cloud.confidentialcomputing.v1.ContainerImageSignature> getContainerImageSignaturesList() { return containerImageSignatures_; } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public java.util.List< ? extends com.google.cloud.confidentialcomputing.v1.ContainerImageSignatureOrBuilder> getContainerImageSignaturesOrBuilderList() { return containerImageSignatures_; } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public int getContainerImageSignaturesCount() { return containerImageSignatures_.size(); } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public com.google.cloud.confidentialcomputing.v1.ContainerImageSignature getContainerImageSignatures(int index) { return containerImageSignatures_.get(index); } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public com.google.cloud.confidentialcomputing.v1.ContainerImageSignatureOrBuilder getContainerImageSignaturesOrBuilder(int index) { return containerImageSignatures_.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 < containerImageSignatures_.size(); i++) { output.writeMessage(1, containerImageSignatures_.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 < containerImageSignatures_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 1, containerImageSignatures_.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.confidentialcomputing.v1.SignedEntity)) { return super.equals(obj); } com.google.cloud.confidentialcomputing.v1.SignedEntity other = (com.google.cloud.confidentialcomputing.v1.SignedEntity) obj; if (!getContainerImageSignaturesList().equals(other.getContainerImageSignaturesList())) 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 (getContainerImageSignaturesCount() > 0) { hash = (37 * hash) + CONTAINER_IMAGE_SIGNATURES_FIELD_NUMBER; hash = (53 * hash) + getContainerImageSignaturesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.confidentialcomputing.v1.SignedEntity parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.confidentialcomputing.v1.SignedEntity 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.confidentialcomputing.v1.SignedEntity parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.confidentialcomputing.v1.SignedEntity 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.confidentialcomputing.v1.SignedEntity parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.confidentialcomputing.v1.SignedEntity parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.confidentialcomputing.v1.SignedEntity parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.confidentialcomputing.v1.SignedEntity 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.confidentialcomputing.v1.SignedEntity parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.confidentialcomputing.v1.SignedEntity 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.confidentialcomputing.v1.SignedEntity parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.confidentialcomputing.v1.SignedEntity 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.confidentialcomputing.v1.SignedEntity 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> * SignedEntity represents an OCI image object containing everything necessary * to verify container image signatures. * </pre> * * Protobuf type {@code google.cloud.confidentialcomputing.v1.SignedEntity} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.confidentialcomputing.v1.SignedEntity) com.google.cloud.confidentialcomputing.v1.SignedEntityOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.confidentialcomputing.v1.ServiceProto .internal_static_google_cloud_confidentialcomputing_v1_SignedEntity_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.confidentialcomputing.v1.ServiceProto .internal_static_google_cloud_confidentialcomputing_v1_SignedEntity_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.confidentialcomputing.v1.SignedEntity.class, com.google.cloud.confidentialcomputing.v1.SignedEntity.Builder.class); } // Construct using com.google.cloud.confidentialcomputing.v1.SignedEntity.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (containerImageSignaturesBuilder_ == null) { containerImageSignatures_ = java.util.Collections.emptyList(); } else { containerImageSignatures_ = null; containerImageSignaturesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.confidentialcomputing.v1.ServiceProto .internal_static_google_cloud_confidentialcomputing_v1_SignedEntity_descriptor; } @java.lang.Override public com.google.cloud.confidentialcomputing.v1.SignedEntity getDefaultInstanceForType() { return com.google.cloud.confidentialcomputing.v1.SignedEntity.getDefaultInstance(); } @java.lang.Override public com.google.cloud.confidentialcomputing.v1.SignedEntity build() { com.google.cloud.confidentialcomputing.v1.SignedEntity result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.confidentialcomputing.v1.SignedEntity buildPartial() { com.google.cloud.confidentialcomputing.v1.SignedEntity result = new com.google.cloud.confidentialcomputing.v1.SignedEntity(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.confidentialcomputing.v1.SignedEntity result) { if (containerImageSignaturesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { containerImageSignatures_ = java.util.Collections.unmodifiableList(containerImageSignatures_); bitField0_ = (bitField0_ & ~0x00000001); } result.containerImageSignatures_ = containerImageSignatures_; } else { result.containerImageSignatures_ = containerImageSignaturesBuilder_.build(); } } private void buildPartial0(com.google.cloud.confidentialcomputing.v1.SignedEntity 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.confidentialcomputing.v1.SignedEntity) { return mergeFrom((com.google.cloud.confidentialcomputing.v1.SignedEntity) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.confidentialcomputing.v1.SignedEntity other) { if (other == com.google.cloud.confidentialcomputing.v1.SignedEntity.getDefaultInstance()) return this; if (containerImageSignaturesBuilder_ == null) { if (!other.containerImageSignatures_.isEmpty()) { if (containerImageSignatures_.isEmpty()) { containerImageSignatures_ = other.containerImageSignatures_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureContainerImageSignaturesIsMutable(); containerImageSignatures_.addAll(other.containerImageSignatures_); } onChanged(); } } else { if (!other.containerImageSignatures_.isEmpty()) { if (containerImageSignaturesBuilder_.isEmpty()) { containerImageSignaturesBuilder_.dispose(); containerImageSignaturesBuilder_ = null; containerImageSignatures_ = other.containerImageSignatures_; bitField0_ = (bitField0_ & ~0x00000001); containerImageSignaturesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getContainerImageSignaturesFieldBuilder() : null; } else { containerImageSignaturesBuilder_.addAllMessages(other.containerImageSignatures_); } } } 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.confidentialcomputing.v1.ContainerImageSignature m = input.readMessage( com.google.cloud.confidentialcomputing.v1.ContainerImageSignature.parser(), extensionRegistry); if (containerImageSignaturesBuilder_ == null) { ensureContainerImageSignaturesIsMutable(); containerImageSignatures_.add(m); } else { containerImageSignaturesBuilder_.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.confidentialcomputing.v1.ContainerImageSignature> containerImageSignatures_ = java.util.Collections.emptyList(); private void ensureContainerImageSignaturesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { containerImageSignatures_ = new java.util.ArrayList< com.google.cloud.confidentialcomputing.v1.ContainerImageSignature>( containerImageSignatures_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.confidentialcomputing.v1.ContainerImageSignature, com.google.cloud.confidentialcomputing.v1.ContainerImageSignature.Builder, com.google.cloud.confidentialcomputing.v1.ContainerImageSignatureOrBuilder> containerImageSignaturesBuilder_; /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public java.util.List<com.google.cloud.confidentialcomputing.v1.ContainerImageSignature> getContainerImageSignaturesList() { if (containerImageSignaturesBuilder_ == null) { return java.util.Collections.unmodifiableList(containerImageSignatures_); } else { return containerImageSignaturesBuilder_.getMessageList(); } } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public int getContainerImageSignaturesCount() { if (containerImageSignaturesBuilder_ == null) { return containerImageSignatures_.size(); } else { return containerImageSignaturesBuilder_.getCount(); } } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.confidentialcomputing.v1.ContainerImageSignature getContainerImageSignatures(int index) { if (containerImageSignaturesBuilder_ == null) { return containerImageSignatures_.get(index); } else { return containerImageSignaturesBuilder_.getMessage(index); } } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setContainerImageSignatures( int index, com.google.cloud.confidentialcomputing.v1.ContainerImageSignature value) { if (containerImageSignaturesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureContainerImageSignaturesIsMutable(); containerImageSignatures_.set(index, value); onChanged(); } else { containerImageSignaturesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setContainerImageSignatures( int index, com.google.cloud.confidentialcomputing.v1.ContainerImageSignature.Builder builderForValue) { if (containerImageSignaturesBuilder_ == null) { ensureContainerImageSignaturesIsMutable(); containerImageSignatures_.set(index, builderForValue.build()); onChanged(); } else { containerImageSignaturesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder addContainerImageSignatures( com.google.cloud.confidentialcomputing.v1.ContainerImageSignature value) { if (containerImageSignaturesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureContainerImageSignaturesIsMutable(); containerImageSignatures_.add(value); onChanged(); } else { containerImageSignaturesBuilder_.addMessage(value); } return this; } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder addContainerImageSignatures( int index, com.google.cloud.confidentialcomputing.v1.ContainerImageSignature value) { if (containerImageSignaturesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureContainerImageSignaturesIsMutable(); containerImageSignatures_.add(index, value); onChanged(); } else { containerImageSignaturesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder addContainerImageSignatures( com.google.cloud.confidentialcomputing.v1.ContainerImageSignature.Builder builderForValue) { if (containerImageSignaturesBuilder_ == null) { ensureContainerImageSignaturesIsMutable(); containerImageSignatures_.add(builderForValue.build()); onChanged(); } else { containerImageSignaturesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder addContainerImageSignatures( int index, com.google.cloud.confidentialcomputing.v1.ContainerImageSignature.Builder builderForValue) { if (containerImageSignaturesBuilder_ == null) { ensureContainerImageSignaturesIsMutable(); containerImageSignatures_.add(index, builderForValue.build()); onChanged(); } else { containerImageSignaturesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder addAllContainerImageSignatures( java.lang.Iterable< ? extends com.google.cloud.confidentialcomputing.v1.ContainerImageSignature> values) { if (containerImageSignaturesBuilder_ == null) { ensureContainerImageSignaturesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, containerImageSignatures_); onChanged(); } else { containerImageSignaturesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder clearContainerImageSignatures() { if (containerImageSignaturesBuilder_ == null) { containerImageSignatures_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { containerImageSignaturesBuilder_.clear(); } return this; } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder removeContainerImageSignatures(int index) { if (containerImageSignaturesBuilder_ == null) { ensureContainerImageSignaturesIsMutable(); containerImageSignatures_.remove(index); onChanged(); } else { containerImageSignaturesBuilder_.remove(index); } return this; } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.confidentialcomputing.v1.ContainerImageSignature.Builder getContainerImageSignaturesBuilder(int index) { return getContainerImageSignaturesFieldBuilder().getBuilder(index); } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.confidentialcomputing.v1.ContainerImageSignatureOrBuilder getContainerImageSignaturesOrBuilder(int index) { if (containerImageSignaturesBuilder_ == null) { return containerImageSignatures_.get(index); } else { return containerImageSignaturesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public java.util.List< ? extends com.google.cloud.confidentialcomputing.v1.ContainerImageSignatureOrBuilder> getContainerImageSignaturesOrBuilderList() { if (containerImageSignaturesBuilder_ != null) { return containerImageSignaturesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(containerImageSignatures_); } } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.confidentialcomputing.v1.ContainerImageSignature.Builder addContainerImageSignaturesBuilder() { return getContainerImageSignaturesFieldBuilder() .addBuilder( com.google.cloud.confidentialcomputing.v1.ContainerImageSignature .getDefaultInstance()); } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.confidentialcomputing.v1.ContainerImageSignature.Builder addContainerImageSignaturesBuilder(int index) { return getContainerImageSignaturesFieldBuilder() .addBuilder( index, com.google.cloud.confidentialcomputing.v1.ContainerImageSignature .getDefaultInstance()); } /** * * * <pre> * Optional. A list of container image signatures attached to an OCI image * object. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.ContainerImageSignature container_image_signatures = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public java.util.List<com.google.cloud.confidentialcomputing.v1.ContainerImageSignature.Builder> getContainerImageSignaturesBuilderList() { return getContainerImageSignaturesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.confidentialcomputing.v1.ContainerImageSignature, com.google.cloud.confidentialcomputing.v1.ContainerImageSignature.Builder, com.google.cloud.confidentialcomputing.v1.ContainerImageSignatureOrBuilder> getContainerImageSignaturesFieldBuilder() { if (containerImageSignaturesBuilder_ == null) { containerImageSignaturesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.confidentialcomputing.v1.ContainerImageSignature, com.google.cloud.confidentialcomputing.v1.ContainerImageSignature.Builder, com.google.cloud.confidentialcomputing.v1.ContainerImageSignatureOrBuilder>( containerImageSignatures_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); containerImageSignatures_ = null; } return containerImageSignaturesBuilder_; } @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.confidentialcomputing.v1.SignedEntity) } // @@protoc_insertion_point(class_scope:google.cloud.confidentialcomputing.v1.SignedEntity) private static final com.google.cloud.confidentialcomputing.v1.SignedEntity DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.confidentialcomputing.v1.SignedEntity(); } public static com.google.cloud.confidentialcomputing.v1.SignedEntity getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SignedEntity> PARSER = new com.google.protobuf.AbstractParser<SignedEntity>() { @java.lang.Override public SignedEntity 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<SignedEntity> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SignedEntity> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.confidentialcomputing.v1.SignedEntity getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
openjdk/jtreg
37,454
src/share/classes/com/sun/javatest/regtest/exec/CompileAction.java
/* * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.javatest.regtest.exec; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringReader; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import com.sun.javatest.Status; import com.sun.javatest.regtest.TimeoutHandler; import com.sun.javatest.regtest.agent.AStatus; import com.sun.javatest.regtest.agent.CompileActionHelper; import com.sun.javatest.regtest.agent.JDK_Version; import com.sun.javatest.regtest.agent.SearchPath; import com.sun.javatest.regtest.config.ExecMode; import com.sun.javatest.regtest.config.JDK; import com.sun.javatest.regtest.config.JDKOpts; import com.sun.javatest.regtest.config.Locations; import com.sun.javatest.regtest.config.Locations.LibLocn; import com.sun.javatest.regtest.config.Modules; import com.sun.javatest.regtest.config.ParseException; import com.sun.javatest.regtest.exec.RegressionScript.PathKind; import com.sun.javatest.regtest.util.StringUtils; import static com.sun.javatest.regtest.RStatus.createStatus; import static com.sun.javatest.regtest.RStatus.error; import static com.sun.javatest.regtest.RStatus.failed; import static com.sun.javatest.regtest.RStatus.normalize; import static com.sun.javatest.regtest.RStatus.passed; /** * This class implements the "compile" action as described by the JDK tag * specification. It is also invoked implicitly as needed by the "build" * action. * * @see Action * @see com.sun.javatest.regtest.agent.MainActionHelper */ public class CompileAction extends Action { public static final String NAME = "compile"; /** * {@inheritDoc} * @return "compile" */ @Override public String getName() { return NAME; } /** * A method used by sibling classes to run both the init() and run() * method of CompileAction. * * @param libLocn details for where to place the compiled classes * @param opts The options for the action. * @param args The arguments for the actions. * @param reason Indication of why this action was invoked. * @param script The script. * @return The result of the action. * @throws TestRunException if an error occurs while executing this action * @see #init * @see #run */ Status compile(LibLocn libLocn, Map<String,String> opts, List<String> args, String reason, RegressionScript script) throws TestRunException { this.libLocn = libLocn; init(opts, args, reason, script); return run(); } // compile() /** * This method does initial processing of the options and arguments for the * action. Processing is determined by the requirements of run() and * getSourceFiles(). If run will be called, script.hasEnv() will be true. * If script.hasEnv() is false, there is no context available to determine * any class directories. * * Verify that the options are valid for the "compile" action. * * Verify that there is at least one argument. Find the class names to * compile (via presence of ".java") and modify to contain fully qualified * path. * * If one of the JVM options is "-classpath" or "-cp", add the test classes * and test sources directory to the provided path. * * @param opts The options for the action. * @param args The arguments for the actions. * @param reason Indication of why this action was invoked. * @param script The script. * @exception ParseException If the options or arguments are not expected * for the action or are improperly formated. */ @Override public void init(Map<String,String> opts, List<String> args, String reason, RegressionScript script) throws ParseException { super.init(opts, args, reason, script); if (reason.startsWith(SREASON_USER_SPECIFIED)) addDebugOpts = true; if (args.isEmpty()) throw new ParseException(COMPILE_NO_CLASSNAME); for (Map.Entry<String,String> e: opts.entrySet()) { String optName = e.getKey(); String optValue = e.getValue(); switch (optName) { case "fail": reverseStatus = parseFail(optValue); break; case "timeout": timeout = parseTimeout(optValue); break; case "ref": ref = parseRef(optValue); break; case "process": process = true; break; case "module": module = parseModule(optValue); modules = Collections.singleton(module); break; case "modules": if (optValue != null) throw new ParseException(COMPILE_MODULES_UEXPECT + optValue); multiModule = true; modules = new LinkedHashSet<>(); break; default: throw new ParseException(COMPILE_BAD_OPT + optName); } } if (module != null && multiModule) { throw new ParseException("Bad combination of options: /module=" + module + ", /modules"); } if (module == null && !multiModule) modules = Collections.emptySet(); if (timeout < 0) timeout = script.getActionTimeout(-1); // add absolute path name to all the .java files create appropriate // class directories Locations locations = script.locations; if (libLocn == null) { destDir = multiModule ? locations.absTestModulesDir().toFile() : locations.absTestClsDir(module).toFile(); } else { destDir = ((module == null) ? libLocn.absClsDir : libLocn.absClsDir.resolve(module)).toFile(); } if (!script.isCheck()) mkdirs(destDir); boolean foundJavaFile = false; boolean foundAsmFile = false; for (int i = 0; i < args.size(); i++) { // note: in the following code, some args are overwritten in place String currArg = args.get(i); boolean isSourceFile = false; if (currArg.endsWith(".java")) { foundJavaFile = true; isSourceFile = true; } else if (currArg.endsWith(".jasm") || currArg.endsWith(".jcod")) { foundAsmFile = true; isSourceFile = true; } if (isSourceFile) { File sourceFile = new File(currArg.replace('/', File.separatorChar)); if (!sourceFile.isAbsolute()) { // User must have used @compile, so file must be // in the same directory as the defining file. if (multiModule) addModule(currArg); Path absSourceFile = locations.absTestSrcFile(module, sourceFile); if (!Files.exists(absSourceFile)) throw new ParseException(CANT_FIND_SRC + currArg); args.set(i, absSourceFile.toString()); } } if (currArg.equals("-classpath") || currArg.equals("-cp") || currArg.equals("--class-path") || currArg.startsWith("--class-path=")) { if (module != null || multiModule) { throw new ParseException(COMPILE_OPT_DISALLOW); } classpathp = true; if (!currArg.startsWith("--class-path=")) { i++; } } else if (currArg.equals("-sourcepath") || currArg.equals("--source-path") || currArg.startsWith("--source-path=")) { if (module != null || multiModule) { throw new ParseException(COMPILE_OPT_DISALLOW); } sourcepathp = true; if (!currArg.startsWith("--source-path=")) { i++; } } else if (currArg.equals("-d")) { throw new ParseException(COMPILE_OPT_DISALLOW); } } if (!foundJavaFile && !process && !foundAsmFile) { throw new ParseException(COMPILE_NO_DOT_JAVA); } if (foundAsmFile) { if (sourcepathp || classpathp || process) { throw new ParseException(COMPILE_OPT_DISALLOW); } if (reverseStatus || ref != null) { throw new ParseException(COMPILE_OPT_DISALLOW); } } } // init() @Override public Set<File> getSourceFiles() { Set<File> files = new LinkedHashSet<>(); for (String currArg : args) { if (currArg.endsWith(".java") || currArg.endsWith(".jasm") || currArg.endsWith(".jcod")) { files.add(new File(currArg)); } } return files; } @Override public Set<String> getModules() { return modules; } /** * The method that does the work of the action. The necessary work for the * given action is defined by the tag specification. * * Invoke the compiler on the given arguments which may possibly include * compiler options. Equivalent to "javac arg+". * * Each named class will be compiled if its corresponding class file doesn't * exist or is older than its source file. The class name is fully * qualified as necessary and the ".java" extension is added before * compilation. * * Build is allowed to search anywhere in the library-list. Compile is * allowed to search only in the directory containing the defining file of * the test. Thus, compile will always make files absolute by adding the * directory path of the defining file to the passed filename. * Build must pass an absolute filename to handle files found in the * library-list. * * @return The result of the action. * @throws TestRunException If an unexpected error occurs while executing * the action. */ @Override public Status run() throws TestRunException { startAction(true); List<String> javacArgs = new ArrayList<>(); List<String> jasmArgs = new ArrayList<>(); List<String> jcodArgs = new ArrayList<>(); boolean runJavac = process; String sourceOrReleaseVersion = null; boolean seenSourceOrRelease = false; boolean seenEnablePreview = false; for (int i = 0; i < args.size(); i++) { String currArg = args.get(i); if (currArg.endsWith(".java")) { if (!(new File(currArg)).exists()) throw new TestRunException(CANT_FIND_SRC + currArg); javacArgs.add(currArg); runJavac = true; } else if (currArg.endsWith(".jasm")) { jasmArgs.add(currArg); } else if (currArg.endsWith(".jcod")) { jcodArgs.add(currArg); } else { int eq = currArg.indexOf("="); switch (eq == -1 ? currArg : currArg.substring(0, eq)) { case "--enable-preview": seenEnablePreview = true; break; // switch case "-source": case "--source": case "--release": seenSourceOrRelease = true; if (eq != -1) { sourceOrReleaseVersion = currArg.substring(eq + 1).trim(); } else { sourceOrReleaseVersion = args.size() > i + 1 ? args.get(i + 1) : null; } break; // switch } javacArgs.add(currArg); } } if (runJavac && script.enablePreview() && !seenEnablePreview) { String version = script.getTestJDKVersion().name(); // always prepend in order to not mess with variadic arguments if (!seenSourceOrRelease) { javacArgs.add(0, version); javacArgs.add(0, "-source"); } // 7903809: prevent invalid source release errors if (!seenSourceOrRelease || version.equals(sourceOrReleaseVersion)) { javacArgs.add(0, "--enable-preview"); } } Status status; if (script.isCheck()) { status = passed(CHECK_PASS); } else { // run jasm and jcod first (if needed) in case the resulting class // files will be required when compiling the .java files. status = passed("Not yet run"); if (status.isPassed() && !jasmArgs.isEmpty()) status = jasm(jasmArgs); if (status.isPassed() && !jcodArgs.isEmpty()) status = jcod(jcodArgs); if (status.isPassed() && runJavac) { javacArgs = getJavacCommandArgs(javacArgs); for (String arg: javacArgs) { if (arg.startsWith("-J")) { othervmOverrideReasons.add("JVM options specified for compiler"); break; } } if (explicitAnnotationProcessingRequested(javacArgs) && !getExtraModuleConfigOptions(Modules.Phase.DYNAMIC).isEmpty()) { othervmOverrideReasons.add("additional runtime exports needed for annotation processing"); } switch (!othervmOverrideReasons.isEmpty() ? ExecMode.OTHERVM : script.getExecMode()) { case AGENTVM: showMode(ExecMode.AGENTVM); status = runAgentJVM(javacArgs); break; case OTHERVM: showMode(ExecMode.OTHERVM, othervmOverrideReasons); status = runOtherJVM(javacArgs); break; default: throw new AssertionError(); } } } endAction(status); return status; } // run() //----------internal methods------------------------------------------------ private Status jasm(List<String> files) { return asmtools("jasm", files); } private Status jcod(List<String> files) { return asmtools("jcoder", files); } private Status asmtools(String toolName, List<String> files) { if (files.isEmpty()) return Status.passed(toolName + ": no files"); List<String> toolArgs = new ArrayList<>(); toolArgs.add("-d"); toolArgs.add(destDir.getPath()); toolArgs.addAll(files); try { String toolClassName = "org.openjdk.asmtools." + toolName + ".Main"; recorder.asmtools(toolClassName, toolArgs); Class<?> toolClass = Class.forName(toolClassName); Constructor<?> constr = toolClass.getConstructor(PrintStream.class, String.class); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); try { Object tool = constr.newInstance(ps, toolName); Method m = toolClass.getMethod("compile", String[].class); Object r = m.invoke(tool, new Object[] { toolArgs.toArray(new String[0]) }); if (r instanceof Boolean) { boolean ok = (Boolean) r; return ok ? Status.passed(toolName + " OK") : Status.failed(toolName + " failed"); } else return Status.error("unexpected result from " + toolName + ": " + r.toString()); } finally { try (PrintWriter out = section.createOutput(toolName)) { out.write(baos.toString()); } } } catch (ClassNotFoundException e) { return Status.error("can't find " + toolName); } catch (ReflectiveOperationException t) { return Status.error("error invoking " + toolName + ": " + t); } } /** * Determine the arguments for the compilation. * Three different types of compilation are supported. * <ul> * <li>Compilation of classes in the unnamed module. * This is the default "classic" compilation. * The output directory should be a package-oriented directory. * Sources and classes for the unnamed module are put on the * sourcepath and classpath. * <li>Compilation of classes in a single named user module. * This mode is indicated by the option /module=module-name * where module-name is not the name of a system module. * The output directory should be the appropriate subdirectory * of a module-oriented directory. * The output directory should appear on the classpath. * Sources and classes for the unnamed module are <i>not</i> available. * <li>Compilation of classes to patch those in a system module. * This mode is indicated by the option /module=module-name * where module-name is the name of a system module. * <li>Compilation of classes in one or more named user modules. * This mode is indicated by the option /modules. * The output directory should be a module-oriented directory. * Sources and classes for the unnamed module are put on the * sourcepath and classpath. * </ul> */ private List<String> getJavacCommandArgs(List<String> args) throws TestRunException { Map<PathKind, SearchPath> compilePaths = script.getCompilePaths(libLocn, multiModule, module); JDKOpts javacArgs = new JDKOpts(); javacArgs.addAll(script.getTestCompilerOptions()); if (isModuleOptionsAllowed(args)) { javacArgs.addAll(getExtraModuleConfigOptions(Modules.Phase.STATIC)); } if (destDir != null) { javacArgs.add("-d"); javacArgs.add(destDir.toString()); } // modulesourcepath and sourcepath are mutually exclusive if (multiModule) { javacArgs.addPath("--module-source-path", compilePaths.get(PathKind.MODULESOURCEPATH)); } else if (module != null) { // Note: any additional patches for this module will be // automatically merged with this one. javacArgs.addAll("--patch-module", module + "=" + compilePaths.get(PathKind.SOURCEPATH)); } else { javacArgs.addPath("--source-path", compilePaths.get(PathKind.SOURCEPATH)); } // Need to refine what it means to put absTestClsDir unconditionally on the compilePath SearchPath cp = compilePaths.get(PathKind.CLASSPATH); javacArgs.addPath("--class-path", cp); javacArgs.addPath("--module-path", compilePaths.get(PathKind.MODULEPATH)); SearchPath pp = compilePaths.get(PathKind.PATCHPATH); javacArgs.addAllPatchModules(pp); // will merge as needed with any similar preceding options if (pp != null && !pp.isEmpty() && cp != null && !cp.isEmpty()) { // provide addReads from patch modules to unnamed module(s). for (String s: getModules(pp)) { javacArgs.add("--add-reads=" + s + "=ALL-UNNAMED"); } } Set<String> userMods = getModules(compilePaths.get(PathKind.MODULEPATH)); if (!userMods.isEmpty()) { javacArgs.add("--add-modules"); javacArgs.add(StringUtils.join(userMods, ",")); } javacArgs.addAll(args); return javacArgs.toList(); } private boolean isModuleOptionsAllowed(List<String> args) { Iterator<String> iter = args.iterator(); while (iter.hasNext()) { String option = iter.next(); switch (option) { case "-source": case "-target": case "--release": if (iter.hasNext()) { JDK_Version v = JDK_Version.forName(iter.next()); return v != null && v.compareTo(JDK_Version.V9) >= 0; } break; default: if (option.startsWith("--release=")) { JDK_Version v = JDK_Version.forName( option.substring(option.indexOf("=") + 1)); return v != null && v.compareTo(JDK_Version.V9) >= 0; } break; } } return true; } private Status runOtherJVM(List<String> javacArgs) throws TestRunException { Status status; // Set test.src and test.classes for the benefit of annotation processors Map<String, String> javacProps = script.getTestProperties(); // CONSTRUCT THE COMMAND LINE Map<String, String> env = script.getEnvVars(); Path javacCmd = script.getJavacProg(); JDKOpts javacVMOpts = new JDKOpts(); javacVMOpts.addAll(script.getTestVMOptions()); if (addDebugOpts && script.getCompileJDK().equals(script.getTestJDK())) javacVMOpts.addAll(script.getTestDebugOptions()); if (explicitAnnotationProcessingRequested(javacArgs)) { javacVMOpts.addAll(getExtraModuleConfigOptions(Modules.Phase.DYNAMIC)); } // WRITE ARGUMENT FILE List<String> fullJavacArgs = javacArgs; if (javacArgs.size() >= 10) { File argFile = getArgFile(); try (BufferedWriter w = new BufferedWriter(new FileWriter(argFile))) { for (String arg: javacArgs) { if (arg.startsWith("-J")) { // remove -J for now; it will be added back later javacVMOpts.add(arg.substring(2)); } else { w.write(arg); w.newLine(); } } } catch (IOException e) { return error(COMPILE_CANT_WRITE_ARGS); } catch (SecurityException e) { // shouldn't happen since JavaTestSecurityManager allows file ops return error(COMPILE_SECMGR_FILEOPS); } javacArgs = List.of("@" + argFile); } List<String> command = new ArrayList<>(); command.add(javacCmd.toString()); for (String opt: javacVMOpts.toList()) command.add("-J" + opt); for (Map.Entry<String,String> e: javacProps.entrySet()) command.add("-J-D" + e.getKey() + "=" + e.getValue()); command.addAll(javacArgs); if (showMode) showMode("compile", ExecMode.OTHERVM, section); if (showCmd) showCmd("compile", command, section); new ModuleConfig("Boot Layer (javac runtime environment)") .setFromOpts(javacVMOpts) .write(configWriter); new ModuleConfig("javac compilation environment") .setFromOpts(fullJavacArgs) .write(configWriter); recorder.javac(env, javacCmd, javacVMOpts.toList(), javacProps, javacArgs); // PASS TO PROCESSCOMMAND PrintStringWriter stdOut = new PrintStringWriter(); PrintStringWriter stdErr = new PrintStringWriter(); ProcessCommand cmd = new ProcessCommand() { @Override protected Status getStatus(int exitCode, Status logStatus) { // logStatus is never used by javac, so ignore it JDK_Version v = script.getCompileJDKVersion(); AStatus aStatus = CompileActionHelper.getStatusForJavacExitCode(v, exitCode); return new Status(aStatus.getType(), aStatus.getReason()); } }; cmd.setMessageWriter(section.getMessageWriter()); TimeoutHandler timeoutHandler = script.getTimeoutHandlerProvider().createHandler(this.getClass(), script, section); cmd.setExecDir(script.absTestScratchDir().toFile()) .setCommand(command) .setEnvironment(env) .setStreams(stdOut, stdErr) .setTimeout(timeout, TimeUnit.SECONDS) .setTimeoutHandler(timeoutHandler); status = normalize(cmd.exec()); try (PrintWriter sysOut = section.createOutput("System.out")) { sysOut.write(stdOut.getOutput()); } try (PrintWriter sysErr = section.createOutput("System.err")) { sysErr.write(stdErr.getOutput()); } // EVALUATE THE RESULTS status = checkReverse(status, reverseStatus); // COMPARE OUTPUT TO GOLDENFILE IF REQUIRED // tag-spec says that "standard error is redirected to standard out // so that /ref can be used." Simulate this by concatenating streams. if ((ref != null) && status.isPassed()) { String combined = stdOut.getOutput() + stdErr.getOutput(); status = checkGoldenFile(combined, status); } return status; } // runOtherJVM() private Status runAgentJVM(List<String> javacArgs) throws TestRunException { // TAG-SPEC: "The source and class directories of a test are made // available to main and applet actions via the system properties // "test.src" and "test.classes", respectively" Map<String, String> javacProps = script.getTestProperties(); if (showMode) showMode("compile", ExecMode.AGENTVM, section); if (showCmd) showCmd("compile", javacArgs, section); Path javacProg = script.getJavacProg(); List<String> javacVMOpts = script.getTestVMOptions(); recorder.javac(script.getEnvVars(), javacProg, javacVMOpts, javacProps, javacArgs); Agent agent; try { JDK jdk = script.getCompileJDK(); SearchPath agentClasspath = new SearchPath(jdk.getJDKClassPath(), script.getJavaTestClassPath()); List<String> vmOpts = addDebugOpts && jdk.equals(script.getTestJDK()) ? join(script.getTestVMOptions(), script.getTestDebugOptions()) : script.getTestVMOptions(); agent = script.getAgent(jdk, agentClasspath, vmOpts, null, null); section.getMessageWriter().println("Agent id: " + agent.getId()); final long pid = agent.getAgentServerPid(); section.getMessageWriter().println("Process id: " + ((pid == -1) ? "unknown" : pid)); new ModuleConfig("Boot Layer (javac runtime environment)") .setFromOpts(agent.vmOpts) .write(configWriter); } catch (Agent.Fault e) { return error(AGENTVM_CANT_GET_VM + ": " + e.getCause()); } TimeoutHandler timeoutHandler = script.getTimeoutHandlerProvider().createHandler(this.getClass(), script, section); Status status; try { new ModuleConfig("javac compilation environment") .setFromOpts(javacArgs) .write(configWriter); status = agent.doCompileAction( script.getTestResult().getTestName(), javacProps, javacArgs, timeout, timeoutHandler, section); } catch (Agent.ActionTimeout te) { String msg = "\"" + getName() + "\" action timed out with a timeout of " + timeout + " seconds on agent " + agent.id; if (te.getSuppressedStatus().isPresent()) { Status suppressed = te.getSuppressedStatus().get(); msg += "; but completed after timeout - suppressed status: \"" + suppressed + "\""; } status = error(msg); } catch (Agent.Fault e) { if (e.getCause() instanceof IOException) status = error(String.format(AGENTVM_IO_EXCEPTION, e.getCause())); else status = error(String.format(AGENTVM_EXCEPTION, e.getCause())); } if (status.isError()) { script.closeAgent(agent); } // EVALUATE THE RESULTS status = checkReverse(status, reverseStatus); // COMPARE OUTPUT TO GOLDENFILE IF REQUIRED // tag-spec says that "standard error is redirected to standard out // so that /ref can be used." Simulate this by concatenating streams. if ((ref != null) && status.isPassed()) { String outString = getOutput(OutputHandler.OutputKind.DIRECT); String errString = getOutput(OutputHandler.OutputKind.DIRECT_LOG); String stdOutString = getOutput(OutputHandler.OutputKind.STDOUT); String stdErrString = getOutput(OutputHandler.OutputKind.STDERR); String combined = (outString + errString + stdOutString + stdErrString); status = checkGoldenFile(combined, status); } return status; } // runAgentJVM() private String getOutput(OutputHandler.OutputKind kind) { String s = section.getOutput(kind.name); return (s == null) ? "" : s; } // See JavaCompiler.explicitAnnotationProcessingRequested private boolean explicitAnnotationProcessingRequested(List<String> javacArgs) { for (String arg: javacArgs) { if (arg.equals("-processor") || arg.equals("-processorpath") || arg.equals("-processormodulepath") || arg.equals("-proc:only") || arg.equals("-Xprint")) { return true; } } return false; } //----------internal methods------------------------------------------------ /** * This method parses the <em>ref</em> action option used by the compile * action. It verifies that the indicated reference file exists in the * directory containing the defining file of the test. * * @param value The proposed filename for the reference file. * @return A string indicating the name of the reference file for the * test. * @exception ParseException If the passed filename is null, the empty * string, or does not exist. */ private String parseRef(String value) throws ParseException { if ((value == null) || (value.equals(""))) throw new ParseException(COMPILE_NO_REF_NAME); File refFile = script.absTestSrcDir().resolve(value).toFile(); if (!refFile.exists()) throw new ParseException(COMPILE_CANT_FIND_REF + refFile); return value; } // parseRef() private Status checkReverse(Status status, boolean reverseStatus) { if (!status.isError()) { boolean ok = status.isPassed(); int st = status.getType(); String sr; if (ok && reverseStatus) { sr = COMPILE_PASS_UNEXPECT; st = Status.FAILED; } else if (ok && !reverseStatus) { sr = COMPILE_PASS; } else if (!ok && reverseStatus) { sr = COMPILE_FAIL_EXPECT; st = Status.PASSED; } else { /* !ok && !reverseStatus */ sr = COMPILE_FAIL; } if ((st == Status.FAILED) && ! (status.getReason() == null) && !status.getReason().equals(EXEC_PASS)) sr += ": " + status.getReason(); status = createStatus(st, sr); } return status; } /** * Compare output against a reference file. * @param status default result if no differences found * @param actual the text to be compared against the reference file * @return a status indicating the first difference, or the default status * if no differences found * @throws TestRunException if the reference file can't be found */ private Status checkGoldenFile(String actual, Status status) throws TestRunException { File refFile = script.absTestSrcDir().resolve(ref).toFile(); try (BufferedReader actualReader = new BufferedReader(new StringReader(actual)); BufferedReader refReader = new BufferedReader(new FileReader(refFile)) ) { int lineNum; if ((lineNum = compareGoldenFile(actualReader, refReader)) != 0) { return failed(COMPILE_GOLD_FAIL + ref + COMPILE_GOLD_LINE + lineNum); } return status; } catch (FileNotFoundException e) { throw new TestRunException(COMPILE_CANT_FIND_REF + refFile); } catch (IOException e) { throw new TestRunException(COMPILE_CANT_READ_REF + refFile); } } /** * Line by line comparison of compile output and a reference file. If no * differences are found, then 0 is returned. Otherwise, the line number * where differences are first detected is returned. * * @param actualReader the reader for the output actually found * @param refReader the reader for the reference (expected) content * @return the line number where differences were first detected, * or 0 if no differences were detected */ private int compareGoldenFile(BufferedReader actualReader, BufferedReader refReader) throws TestRunException { Pattern ignoreLinesPattern = script.getIgnoreRefLinesPattern(); try { int lineNum = 0; for ( ; ; ) { String s1 = actualReader.readLine(); if (ignoreLinesPattern != null) { while (s1 != null && ignoreLinesPattern.matcher(s1).matches()) { section.getMessageWriter().println("Ignoring line: " + s1); s1 = actualReader.readLine(); } } String s2 = refReader.readLine(); lineNum++; if ((s1 == null) && (s2 == null)) return 0; if ((s1 == null) || (s2 == null) || !s1.equals(s2)) { return lineNum; } } } catch (IOException e) { Path refFile = script.absTestSrcDir().resolve(ref); throw new TestRunException(COMPILE_GOLD_READ_PROB + refFile); } } // compareGoldenFile() private void addModule(String file) { int sep = file.indexOf('/'); if (sep > 0) modules.add(file.substring(0, sep)); } //----------member variables------------------------------------------------ private LibLocn libLocn; private File destDir; private boolean reverseStatus = false; private String ref = null; private int timeout = -1; private boolean classpathp = false; private boolean sourcepathp = false; private boolean process = false; private String module = null; private boolean multiModule = false; private Set<String> modules; private boolean addDebugOpts = false; protected Set<String> othervmOverrideReasons = new LinkedHashSet<>(); }
googleapis/google-cloud-java
37,347
java-apigee-registry/proto-google-cloud-apigee-registry-v1/src/main/java/com/google/cloud/apigeeregistry/v1/ListApiVersionsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/apigeeregistry/v1/registry_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.apigeeregistry.v1; /** * * * <pre> * Response message for ListApiVersions. * </pre> * * Protobuf type {@code google.cloud.apigeeregistry.v1.ListApiVersionsResponse} */ public final class ListApiVersionsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.apigeeregistry.v1.ListApiVersionsResponse) ListApiVersionsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListApiVersionsResponse.newBuilder() to construct. private ListApiVersionsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListApiVersionsResponse() { apiVersions_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListApiVersionsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.apigeeregistry.v1.RegistryServiceProto .internal_static_google_cloud_apigeeregistry_v1_ListApiVersionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.apigeeregistry.v1.RegistryServiceProto .internal_static_google_cloud_apigeeregistry_v1_ListApiVersionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse.class, com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse.Builder.class); } public static final int API_VERSIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.apigeeregistry.v1.ApiVersion> apiVersions_; /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.apigeeregistry.v1.ApiVersion> getApiVersionsList() { return apiVersions_; } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.apigeeregistry.v1.ApiVersionOrBuilder> getApiVersionsOrBuilderList() { return apiVersions_; } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ @java.lang.Override public int getApiVersionsCount() { return apiVersions_.size(); } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ @java.lang.Override public com.google.cloud.apigeeregistry.v1.ApiVersion getApiVersions(int index) { return apiVersions_.get(index); } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ @java.lang.Override public com.google.cloud.apigeeregistry.v1.ApiVersionOrBuilder getApiVersionsOrBuilder(int index) { return apiVersions_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < apiVersions_.size(); i++) { output.writeMessage(1, apiVersions_.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 < apiVersions_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, apiVersions_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse)) { return super.equals(obj); } com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse other = (com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse) obj; if (!getApiVersionsList().equals(other.getApiVersionsList())) 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 (getApiVersionsCount() > 0) { hash = (37 * hash) + API_VERSIONS_FIELD_NUMBER; hash = (53 * hash) + getApiVersionsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse 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 ListApiVersions. * </pre> * * Protobuf type {@code google.cloud.apigeeregistry.v1.ListApiVersionsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.apigeeregistry.v1.ListApiVersionsResponse) com.google.cloud.apigeeregistry.v1.ListApiVersionsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.apigeeregistry.v1.RegistryServiceProto .internal_static_google_cloud_apigeeregistry_v1_ListApiVersionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.apigeeregistry.v1.RegistryServiceProto .internal_static_google_cloud_apigeeregistry_v1_ListApiVersionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse.class, com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse.Builder.class); } // Construct using com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (apiVersionsBuilder_ == null) { apiVersions_ = java.util.Collections.emptyList(); } else { apiVersions_ = null; apiVersionsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.apigeeregistry.v1.RegistryServiceProto .internal_static_google_cloud_apigeeregistry_v1_ListApiVersionsResponse_descriptor; } @java.lang.Override public com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse getDefaultInstanceForType() { return com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse build() { com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse buildPartial() { com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse result = new com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse result) { if (apiVersionsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { apiVersions_ = java.util.Collections.unmodifiableList(apiVersions_); bitField0_ = (bitField0_ & ~0x00000001); } result.apiVersions_ = apiVersions_; } else { result.apiVersions_ = apiVersionsBuilder_.build(); } } private void buildPartial0(com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse) { return mergeFrom((com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse other) { if (other == com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse.getDefaultInstance()) return this; if (apiVersionsBuilder_ == null) { if (!other.apiVersions_.isEmpty()) { if (apiVersions_.isEmpty()) { apiVersions_ = other.apiVersions_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureApiVersionsIsMutable(); apiVersions_.addAll(other.apiVersions_); } onChanged(); } } else { if (!other.apiVersions_.isEmpty()) { if (apiVersionsBuilder_.isEmpty()) { apiVersionsBuilder_.dispose(); apiVersionsBuilder_ = null; apiVersions_ = other.apiVersions_; bitField0_ = (bitField0_ & ~0x00000001); apiVersionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getApiVersionsFieldBuilder() : null; } else { apiVersionsBuilder_.addAllMessages(other.apiVersions_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.apigeeregistry.v1.ApiVersion m = input.readMessage( com.google.cloud.apigeeregistry.v1.ApiVersion.parser(), extensionRegistry); if (apiVersionsBuilder_ == null) { ensureApiVersionsIsMutable(); apiVersions_.add(m); } else { apiVersionsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.apigeeregistry.v1.ApiVersion> apiVersions_ = java.util.Collections.emptyList(); private void ensureApiVersionsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { apiVersions_ = new java.util.ArrayList<com.google.cloud.apigeeregistry.v1.ApiVersion>(apiVersions_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.apigeeregistry.v1.ApiVersion, com.google.cloud.apigeeregistry.v1.ApiVersion.Builder, com.google.cloud.apigeeregistry.v1.ApiVersionOrBuilder> apiVersionsBuilder_; /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public java.util.List<com.google.cloud.apigeeregistry.v1.ApiVersion> getApiVersionsList() { if (apiVersionsBuilder_ == null) { return java.util.Collections.unmodifiableList(apiVersions_); } else { return apiVersionsBuilder_.getMessageList(); } } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public int getApiVersionsCount() { if (apiVersionsBuilder_ == null) { return apiVersions_.size(); } else { return apiVersionsBuilder_.getCount(); } } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public com.google.cloud.apigeeregistry.v1.ApiVersion getApiVersions(int index) { if (apiVersionsBuilder_ == null) { return apiVersions_.get(index); } else { return apiVersionsBuilder_.getMessage(index); } } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public Builder setApiVersions(int index, com.google.cloud.apigeeregistry.v1.ApiVersion value) { if (apiVersionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureApiVersionsIsMutable(); apiVersions_.set(index, value); onChanged(); } else { apiVersionsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public Builder setApiVersions( int index, com.google.cloud.apigeeregistry.v1.ApiVersion.Builder builderForValue) { if (apiVersionsBuilder_ == null) { ensureApiVersionsIsMutable(); apiVersions_.set(index, builderForValue.build()); onChanged(); } else { apiVersionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public Builder addApiVersions(com.google.cloud.apigeeregistry.v1.ApiVersion value) { if (apiVersionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureApiVersionsIsMutable(); apiVersions_.add(value); onChanged(); } else { apiVersionsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public Builder addApiVersions(int index, com.google.cloud.apigeeregistry.v1.ApiVersion value) { if (apiVersionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureApiVersionsIsMutable(); apiVersions_.add(index, value); onChanged(); } else { apiVersionsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public Builder addApiVersions( com.google.cloud.apigeeregistry.v1.ApiVersion.Builder builderForValue) { if (apiVersionsBuilder_ == null) { ensureApiVersionsIsMutable(); apiVersions_.add(builderForValue.build()); onChanged(); } else { apiVersionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public Builder addApiVersions( int index, com.google.cloud.apigeeregistry.v1.ApiVersion.Builder builderForValue) { if (apiVersionsBuilder_ == null) { ensureApiVersionsIsMutable(); apiVersions_.add(index, builderForValue.build()); onChanged(); } else { apiVersionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public Builder addAllApiVersions( java.lang.Iterable<? extends com.google.cloud.apigeeregistry.v1.ApiVersion> values) { if (apiVersionsBuilder_ == null) { ensureApiVersionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, apiVersions_); onChanged(); } else { apiVersionsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public Builder clearApiVersions() { if (apiVersionsBuilder_ == null) { apiVersions_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { apiVersionsBuilder_.clear(); } return this; } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public Builder removeApiVersions(int index) { if (apiVersionsBuilder_ == null) { ensureApiVersionsIsMutable(); apiVersions_.remove(index); onChanged(); } else { apiVersionsBuilder_.remove(index); } return this; } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public com.google.cloud.apigeeregistry.v1.ApiVersion.Builder getApiVersionsBuilder(int index) { return getApiVersionsFieldBuilder().getBuilder(index); } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public com.google.cloud.apigeeregistry.v1.ApiVersionOrBuilder getApiVersionsOrBuilder( int index) { if (apiVersionsBuilder_ == null) { return apiVersions_.get(index); } else { return apiVersionsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public java.util.List<? extends com.google.cloud.apigeeregistry.v1.ApiVersionOrBuilder> getApiVersionsOrBuilderList() { if (apiVersionsBuilder_ != null) { return apiVersionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(apiVersions_); } } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public com.google.cloud.apigeeregistry.v1.ApiVersion.Builder addApiVersionsBuilder() { return getApiVersionsFieldBuilder() .addBuilder(com.google.cloud.apigeeregistry.v1.ApiVersion.getDefaultInstance()); } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public com.google.cloud.apigeeregistry.v1.ApiVersion.Builder addApiVersionsBuilder(int index) { return getApiVersionsFieldBuilder() .addBuilder(index, com.google.cloud.apigeeregistry.v1.ApiVersion.getDefaultInstance()); } /** * * * <pre> * The versions from the specified publisher. * </pre> * * <code>repeated .google.cloud.apigeeregistry.v1.ApiVersion api_versions = 1;</code> */ public java.util.List<com.google.cloud.apigeeregistry.v1.ApiVersion.Builder> getApiVersionsBuilderList() { return getApiVersionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.apigeeregistry.v1.ApiVersion, com.google.cloud.apigeeregistry.v1.ApiVersion.Builder, com.google.cloud.apigeeregistry.v1.ApiVersionOrBuilder> getApiVersionsFieldBuilder() { if (apiVersionsBuilder_ == null) { apiVersionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.apigeeregistry.v1.ApiVersion, com.google.cloud.apigeeregistry.v1.ApiVersion.Builder, com.google.cloud.apigeeregistry.v1.ApiVersionOrBuilder>( apiVersions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); apiVersions_ = null; } return apiVersionsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.apigeeregistry.v1.ListApiVersionsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.apigeeregistry.v1.ListApiVersionsResponse) private static final com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse(); } public static com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListApiVersionsResponse> PARSER = new com.google.protobuf.AbstractParser<ListApiVersionsResponse>() { @java.lang.Override public ListApiVersionsResponse 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<ListApiVersionsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListApiVersionsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.apigeeregistry.v1.ListApiVersionsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/ignite-3
37,652
modules/system-disaster-recovery/src/test/java/org/apache/ignite/internal/disaster/system/SystemDisasterRecoveryManagerImplTest.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.disaster.system; import static java.util.UUID.randomUUID; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.concurrent.CompletableFuture.failedFuture; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.toSet; import static org.apache.ignite.internal.cluster.management.ClusterTag.clusterTag; import static org.apache.ignite.internal.cluster.management.ClusterTag.randomClusterTag; import static org.apache.ignite.internal.testframework.IgniteTestUtils.waitForCondition; import static org.apache.ignite.internal.testframework.asserts.CompletableFutureAssert.assertWillThrow; import static org.apache.ignite.internal.testframework.matchers.CompletableFutureMatcher.willCompleteSuccessfully; import static org.apache.ignite.internal.util.ArrayUtils.BYTE_EMPTY_ARRAY; import static org.apache.ignite.internal.util.ByteUtils.uuidToBytes; import static org.apache.ignite.internal.util.CompletableFutures.nullCompletedFuture; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.nio.file.Path; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.IntStream; import org.apache.ignite.internal.cluster.management.ClusterManagementGroupManager; import org.apache.ignite.internal.cluster.management.ClusterState; import org.apache.ignite.internal.cluster.management.ClusterStatePersistentSerializer; import org.apache.ignite.internal.cluster.management.network.messages.CmgMessagesFactory; import org.apache.ignite.internal.cluster.management.network.messages.SuccessResponseMessage; import org.apache.ignite.internal.disaster.system.exception.ClusterResetException; import org.apache.ignite.internal.disaster.system.exception.MigrateException; import org.apache.ignite.internal.disaster.system.message.BecomeMetastorageLeaderMessage; import org.apache.ignite.internal.disaster.system.message.ResetClusterMessage; import org.apache.ignite.internal.disaster.system.message.ResetClusterMessageBuilder; import org.apache.ignite.internal.disaster.system.message.StartMetastorageRepairRequest; import org.apache.ignite.internal.disaster.system.message.StartMetastorageRepairResponse; import org.apache.ignite.internal.disaster.system.message.SystemDisasterRecoveryMessageGroup; import org.apache.ignite.internal.disaster.system.message.SystemDisasterRecoveryMessagesFactory; import org.apache.ignite.internal.lang.ByteArray; import org.apache.ignite.internal.manager.ComponentContext; import org.apache.ignite.internal.metastorage.impl.MetastorageGroupMaintenance; import org.apache.ignite.internal.network.ClusterNodeImpl; import org.apache.ignite.internal.network.ConstantClusterIdSupplier; import org.apache.ignite.internal.network.InternalClusterNode; import org.apache.ignite.internal.network.MessagingService; import org.apache.ignite.internal.network.NetworkMessage; import org.apache.ignite.internal.network.NetworkMessageHandler; import org.apache.ignite.internal.network.TopologyService; import org.apache.ignite.internal.properties.IgniteProductVersion; import org.apache.ignite.internal.raft.IndexWithTerm; import org.apache.ignite.internal.testframework.BaseIgniteAbstractTest; import org.apache.ignite.internal.testframework.WorkDirectory; import org.apache.ignite.internal.testframework.WorkDirectoryExtension; import org.apache.ignite.internal.vault.VaultEntry; import org.apache.ignite.internal.vault.VaultManager; import org.apache.ignite.internal.vault.persistence.PersistentVaultService; import org.apache.ignite.internal.versioned.VersionedSerialization; import org.apache.ignite.network.NetworkAddress; import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; import org.junitpioneer.jupiter.cartesian.CartesianTest; import org.junitpioneer.jupiter.cartesian.CartesianTest.Values; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) @ExtendWith(WorkDirectoryExtension.class) class SystemDisasterRecoveryManagerImplTest extends BaseIgniteAbstractTest { private static final String CLUSTER_NAME = "cluster"; private static final ByteArray INIT_CONFIG_APPLIED_VAULT_KEY = new ByteArray("systemRecovery.initConfigApplied"); private static final ByteArray CLUSTER_STATE_VAULT_KEY = new ByteArray("systemRecovery.clusterState"); private static final ByteArray RESET_CLUSTER_MESSAGE_VAULT_KEY = new ByteArray("systemRecovery.resetClusterMessage"); private static final ByteArray WITNESSED_METASTORAGE_REPAIR_CLUSTER_ID_VAULT_KEY = new ByteArray("systemRecovery.witnessedMetastorageRepairClusterId"); private static final String INITIAL_CONFIGURATION = "initial-config"; @WorkDirectory private Path workDir; private static final String thisNodeName = "node1"; @Mock private TopologyService topologyService; @Mock private MessagingService messagingService; private VaultManager vaultManager; @Mock private ServerRestarter restarter; @Mock private MetastorageGroupMaintenance metastorageMaintenance; private SystemDisasterRecoveryManagerImpl manager; private final ComponentContext componentContext = new ComponentContext(); private final InternalClusterNode thisNode = new ClusterNodeImpl(randomUUID(), thisNodeName, new NetworkAddress("host", 1001)); private final InternalClusterNode node2 = new ClusterNodeImpl(randomUUID(), "node2", new NetworkAddress("host", 1002)); private final InternalClusterNode node3 = new ClusterNodeImpl(randomUUID(), "node3", new NetworkAddress("host", 1003)); private final InternalClusterNode node4 = new ClusterNodeImpl(randomUUID(), "node4", new NetworkAddress("host", 1004)); private final InternalClusterNode node5 = new ClusterNodeImpl(randomUUID(), "node5", new NetworkAddress("host", 1005)); private final UUID clusterId = new UUID(1, 2); private final CmgMessagesFactory cmgMessagesFactory = new CmgMessagesFactory(); private final SystemDisasterRecoveryMessagesFactory messagesFactory = new SystemDisasterRecoveryMessagesFactory(); private final ClusterState usualClusterState = cmgMessagesFactory.clusterState() .cmgNodes(Set.of(thisNodeName)) .metaStorageNodes(Set.of(node2.name())) .version(IgniteProductVersion.CURRENT_VERSION.toString()) .clusterTag(randomClusterTag(cmgMessagesFactory, CLUSTER_NAME)) .initialClusterConfiguration(INITIAL_CONFIGURATION) .build(); private final SuccessResponseMessage successResponseMessage = cmgMessagesFactory.successResponseMessage().build(); @BeforeEach void init() { vaultManager = spy(new VaultManager(new PersistentVaultService(workDir.resolve("vault")))); assertThat(vaultManager.startAsync(componentContext), willCompleteSuccessfully()); lenient().when(messagingService.respond(any(InternalClusterNode.class), any(NetworkMessage.class), anyLong())) .thenReturn(nullCompletedFuture()); ClusterManagementGroupManager cmgManager = mock(ClusterManagementGroupManager.class); lenient().when(cmgManager.clusterState()).thenReturn(completedFuture(usualClusterState)); manager = new SystemDisasterRecoveryManagerImpl( thisNodeName, topologyService, messagingService, vaultManager, restarter, metastorageMaintenance, cmgManager, new ConstantClusterIdSupplier(clusterId) ); assertThat(manager.startAsync(componentContext), willCompleteSuccessfully()); } @AfterEach void cleanup() { assertThat(vaultManager.stopAsync(), willCompleteSuccessfully()); assertThat(manager.stopAsync(), willCompleteSuccessfully()); } @Test void marksInitConfigApplied() { manager.markInitConfigApplied(); VaultEntry entry = vaultManager.get(INIT_CONFIG_APPLIED_VAULT_KEY); assertThat(entry, is(notNullValue())); assertThat(entry.value(), is(notNullValue())); } @Test void savesClusterState() { manager.saveClusterState(usualClusterState); VaultEntry entry = vaultManager.get(CLUSTER_STATE_VAULT_KEY); assertThat(entry, is(notNullValue())); ClusterState savedState = VersionedSerialization.fromBytes(entry.value(), ClusterStatePersistentSerializer.INSTANCE); assertThat(savedState, is(equalTo(usualClusterState))); } @ParameterizedTest @EnumSource(ResetCluster.class) void resetClusterRejectsDuplicateNodeNames(ResetCluster action) { ClusterResetException ex = assertWillThrow( action.resetCluster(manager, List.of(thisNodeName, thisNodeName)), ClusterResetException.class ); assertThat(ex.getMessage(), is("New CMG node names have repetitions: [node1, node1].")); } @ParameterizedTest @EnumSource(ResetCluster.class) void resetClusterRequiresThisNodeToBeNewCmg(ResetCluster action) { ClusterResetException ex = assertWillThrow(action.resetCluster(manager, List.of("abc")), ClusterResetException.class); assertThat(ex.getMessage(), is("Current node is not contained in the new CMG, so it cannot conduct a cluster reset.")); } @ParameterizedTest @EnumSource(ResetCluster.class) void resetClusterRequiresNewCmgNodesToBeOnline(ResetCluster action) { when(topologyService.allMembers()).thenReturn(List.of(thisNode)); ClusterResetException ex = assertWillThrow(action.resetCluster(manager, List.of(thisNodeName, "abc")), ClusterResetException.class); assertThat(ex.getMessage(), is("Some of proposed CMG nodes are not online: [abc].")); } @Test void resetClusterRepairingMgUsesCurrentCmgNodesIfNotSpecified() { int replicationFactor = 1; ArgumentCaptor<ResetClusterMessage> messageCaptor = ArgumentCaptor.forClass(ResetClusterMessage.class); when(topologyService.allMembers()).thenReturn(List.of(thisNode, node3, node4)); prepareNodeStateForClusterReset(); when(messagingService.invoke(any(InternalClusterNode.class), any(ResetClusterMessage.class), anyLong())) .thenReturn(completedFuture(successResponseMessage)); CompletableFuture<Void> future = manager.resetClusterRepairingMetastorage(null, replicationFactor); assertThat(future, willCompleteSuccessfully()); verify(messagingService).invoke(eq(thisNode), messageCaptor.capture(), anyLong()); assertThat(messageCaptor.getValue().newCmgNodes(), is(usualClusterState.cmgNodes())); } @ParameterizedTest @EnumSource(ResetCluster.class) void resetClusterRequiresClusterState(ResetCluster action) { when(topologyService.allMembers()).thenReturn(List.of(thisNode)); markInitConfigApplied(); ClusterResetException ex = assertWillThrow(action.resetCluster(manager, List.of(thisNodeName)), ClusterResetException.class); assertThat(ex.getMessage(), is("Node does not have cluster state.")); } @ParameterizedTest @EnumSource(ResetCluster.class) void resetClusterRequiresInitConfigToBeApplied(ResetCluster action) { when(topologyService.allMembers()).thenReturn(List.of(thisNode)); putClusterState(); ClusterResetException ex = assertWillThrow(action.resetCluster(manager, List.of(thisNodeName)), ClusterResetException.class); assertThat(ex.getMessage(), is("Initial configuration is not applied, so the node cannot serve as a cluster reset conductor.")); } private void putClusterState() { vaultManager.put( CLUSTER_STATE_VAULT_KEY, VersionedSerialization.toBytes(usualClusterState, ClusterStatePersistentSerializer.INSTANCE) ); } private void markInitConfigApplied() { vaultManager.put(INIT_CONFIG_APPLIED_VAULT_KEY, BYTE_EMPTY_ARRAY); } @ParameterizedTest @EnumSource(ResetCluster.class) void resetClusterSendsMessages(ResetCluster action) { ArgumentCaptor<ResetClusterMessage> messageCaptor = ArgumentCaptor.forClass(ResetClusterMessage.class); when(topologyService.allMembers()).thenReturn(List.of(thisNode, node3, node4)); prepareNodeStateForClusterReset(); when(messagingService.invoke(any(InternalClusterNode.class), any(ResetClusterMessage.class), anyLong())) .thenReturn(completedFuture(successResponseMessage)); CompletableFuture<Void> future = action.resetCluster(manager, List.of(thisNodeName, node3.name())); assertThat(future, willCompleteSuccessfully()); verify(messagingService).invoke(eq(thisNode), messageCaptor.capture(), anyLong()); ResetClusterMessage messageToSelf = messageCaptor.getValue(); assertThatResetClusterMessageIsAsExpected(messageToSelf, action.mgRepair()); verify(messagingService).invoke(eq(node3), messageCaptor.capture(), anyLong()); ResetClusterMessage messageToOtherNewCmgNode = messageCaptor.getValue(); assertThatResetClusterMessageIsAsExpected(messageToOtherNewCmgNode, action.mgRepair()); verify(messagingService).invoke(eq(node4), messageCaptor.capture(), anyLong()); ResetClusterMessage messageToOtherNonCmgNode = messageCaptor.getValue(); assertThatResetClusterMessageIsAsExpected(messageToOtherNonCmgNode, action.mgRepair()); assertThat(messageToSelf.clusterId(), is(messageToOtherNewCmgNode.clusterId())); assertThat(messageToSelf.clusterId(), is(messageToOtherNonCmgNode.clusterId())); } private void prepareNodeStateForClusterReset() { markInitConfigApplied(); putClusterState(); } private void assertThatResetClusterMessageIsAsExpected(ResetClusterMessage message, boolean mgRepair) { assertThatResetClusterMessageContentIsAsExpected(message, mgRepair); } private void assertThatResetClusterMessageContentIsAsExpected(@Nullable ResetClusterMessage message, boolean mgRepair) { assertThat(message, is(notNullValue())); assertThat(message.newCmgNodes(), containsInAnyOrder(thisNodeName, node3.name())); assertThat(message.currentMetaStorageNodes(), is(usualClusterState.metaStorageNodes())); assertThat(message.clusterName(), is(CLUSTER_NAME)); assertThat(message.clusterId(), is(not(usualClusterState.clusterTag().clusterId()))); assertThat(message.formerClusterIds(), contains(usualClusterState.clusterTag().clusterId())); assertThat(message.initialClusterConfiguration(), is(INITIAL_CONFIGURATION)); if (mgRepair) { assertThat(message.metastorageReplicationFactor(), is(1)); assertThat(message.conductor(), is(thisNodeName)); assertThat(message.participatingNodes(), containsInAnyOrder(thisNodeName, node3.name(), node4.name())); } } @ParameterizedTest @EnumSource(ResetCluster.class) void resetClusterInitiatesRestartOnSuccess(ResetCluster action) { when(topologyService.allMembers()).thenReturn(List.of(thisNode, node3)); prepareNodeStateForClusterReset(); when(messagingService.invoke(any(InternalClusterNode.class), any(ResetClusterMessage.class), anyLong())) .thenReturn(completedFuture(successResponseMessage)); CompletableFuture<Void> future = action.resetCluster(manager, List.of(thisNodeName, node3.name())); assertThat(future, willCompleteSuccessfully()); verify(restarter).initiateRestart(); } @Test void repairCmgInitiatesRestartWhenMajorityOfCmgNodesRespondsWithOk() { when(topologyService.allMembers()).thenReturn(List.of(thisNode, node2, node3, node4, node5)); prepareNodeStateForClusterReset(); respondSuccessfullyFrom(thisNode, node2); respondWithExceptionFrom(node3, node4, node5); CompletableFuture<Void> future = manager.resetCluster(List.of(thisNodeName, node2.name(), node3.name())); assertThat(future, willCompleteSuccessfully()); verify(restarter).initiateRestart(); } @Test void repairMgInitiatesRestartWhenAllParticipatingNodesRespondWithOk() { when(topologyService.allMembers()).thenReturn(List.of(thisNode, node3, node4, node5)); prepareNodeStateForClusterReset(); respondSuccessfullyFrom(thisNode, node3, node4, node5); CompletableFuture<Void> future = manager.resetClusterRepairingMetastorage(List.of(thisNodeName, node3.name()), 1); assertThat(future, willCompleteSuccessfully()); verify(restarter).initiateRestart(); } private void respondSuccessfullyFrom(InternalClusterNode... nodes) { for (InternalClusterNode node : nodes) { respondSuccessfullyFrom(node); } } private void respondSuccessfullyFrom(InternalClusterNode node) { when(messagingService.invoke(eq(node), any(ResetClusterMessage.class), anyLong())) .thenReturn(completedFuture(successResponseMessage)); } private void respondWithExceptionFrom(InternalClusterNode... nodes) { for (InternalClusterNode node : nodes) { respondWithExceptionFrom(node); } } private void respondWithExceptionFrom(InternalClusterNode node) { when(messagingService.invoke(eq(node), any(), anyLong())) .thenReturn(failedFuture(new TimeoutException())); } @Test @DisplayName("resetCluster() fails and does not restart node when majority of new CMG nodes do not respond") void repairCmgFailsWhenNewCmgMajorityDoesNotRespond() { when(topologyService.allMembers()).thenReturn(List.of(thisNode, node2, node3, node4, node5)); prepareNodeStateForClusterReset(); respondSuccessfullyFrom(thisNode, node4, node5); respondWithExceptionFrom(node2, node3); CompletableFuture<Void> future = manager.resetCluster(List.of(thisNodeName, node2.name(), node3.name())); ClusterResetException ex = assertWillThrow(future, ClusterResetException.class); assertThat(ex.getMessage(), is("Did not get successful responses from new CMG majority, failing cluster reset.")); verify(restarter, never()).initiateRestart(); } @Test @DisplayName("resetClusterRepairingMetastorage() fails and does not restart node when any participating node does not respond") void resetClusterFailsWhenNewCmgMajorityDoesNotRespond() { when(topologyService.allMembers()).thenReturn(List.of(thisNode, node3, node4, node5)); prepareNodeStateForClusterReset(); respondSuccessfullyFrom(thisNode, node4, node5); respondWithExceptionFrom(node3); CompletableFuture<Void> future = manager.resetClusterRepairingMetastorage(List.of(thisNodeName, node3.name()), 1); ClusterResetException ex = assertWillThrow(future, ClusterResetException.class); assertThat( ex.getMessage(), is("Did not get successful response from at least one node, failing cluster reset [failedNode=node3].") ); verify(restarter, never()).initiateRestart(); } @CartesianTest void savesToVaultWhenGetsMessage(@Values(booleans = {false, true}) boolean fromSelf, @Values(booleans = {false, true}) boolean mgRepair) throws Exception { NetworkMessageHandler handler = extractMessageHandler(); InternalClusterNode conductor = fromSelf ? thisNode : node3; handler.onReceived(resetClusterMessageOn2Nodes(mgRepair), conductor, 0L); waitTillResetClusterMessageGetsSavedToVault(); VaultEntry entry = vaultManager.get(RESET_CLUSTER_MESSAGE_VAULT_KEY); assertThat(entry, is(notNullValue())); ResetClusterMessage savedMessage = VersionedSerialization.fromBytes( entry.value(), ResetClusterMessagePersistentSerializer.INSTANCE ); assertThatResetClusterMessageContentIsAsExpected(savedMessage, mgRepair); } private void waitTillResetClusterMessageGetsSavedToVault() throws InterruptedException { assertTrue(waitForCondition(() -> vaultManager.get(RESET_CLUSTER_MESSAGE_VAULT_KEY) != null, 10_000)); } private NetworkMessageHandler extractMessageHandler() { assertThat(manager.stopAsync(), willCompleteSuccessfully()); var handlerRef = new AtomicReference<NetworkMessageHandler>(); doAnswer(invocation -> { handlerRef.set(invocation.getArgument(1)); return null; }).when(messagingService).addMessageHandler(eq(SystemDisasterRecoveryMessageGroup.class), any()); assertThat(manager.startAsync(componentContext), willCompleteSuccessfully()); NetworkMessageHandler handler = handlerRef.get(); assertThat("Handler was not installed", handler, is(notNullValue())); return handler; } private ResetClusterMessage resetClusterMessageOn2Nodes() { return resetClusterMessageOn2Nodes(false); } private ResetClusterMessage resetClusterMessageOn2Nodes(boolean mgRepair) { ResetClusterMessageBuilder builder = messagesFactory.resetClusterMessage() .newCmgNodes(Set.of(thisNodeName, node3.name())) .currentMetaStorageNodes(usualClusterState.metaStorageNodes()) .clusterName(CLUSTER_NAME) .clusterId(randomUUID()) .formerClusterIds(List.of(usualClusterState.clusterTag().clusterId())) .initialClusterConfiguration(INITIAL_CONFIGURATION); if (mgRepair) { builder.metastorageReplicationFactor(1); builder.conductor(thisNodeName); builder.participatingNodes(Set.of(thisNodeName, node3.name(), node4.name())); } return builder.build(); } @Test void respondsWhenGetsMessageFromSelf() { ArgumentCaptor<NetworkMessage> messageCaptor = ArgumentCaptor.forClass(NetworkMessage.class); NetworkMessageHandler handler = extractMessageHandler(); InternalClusterNode conductor = thisNode; handler.onReceived(resetClusterMessageOn2Nodes(), conductor, 123L); InOrder inOrder = inOrder(messagingService, vaultManager); inOrder.verify(vaultManager, timeout(SECONDS.toMillis(10))).put(eq(RESET_CLUSTER_MESSAGE_VAULT_KEY), any()); inOrder.verify(messagingService, timeout(SECONDS.toMillis(10))).respond(eq(conductor), messageCaptor.capture(), eq(123L)); assertThat(messageCaptor.getValue(), instanceOf(SuccessResponseMessage.class)); } @Test void respondsWhenGetsMessageFromOtherNode() { ArgumentCaptor<NetworkMessage> messageCaptor = ArgumentCaptor.forClass(NetworkMessage.class); NetworkMessageHandler handler = extractMessageHandler(); InternalClusterNode conductor = node2; handler.onReceived(resetClusterMessageOn2Nodes(), conductor, 123L); InOrder inOrder = inOrder(messagingService, vaultManager, restarter); inOrder.verify(vaultManager, timeout(SECONDS.toMillis(10))).put(eq(RESET_CLUSTER_MESSAGE_VAULT_KEY), any()); inOrder.verify(messagingService, timeout(SECONDS.toMillis(10))).respond(eq(conductor), messageCaptor.capture(), eq(123L)); inOrder.verify(restarter, timeout(SECONDS.toMillis(10))).initiateRestart(); assertThat(messageCaptor.getValue(), instanceOf(SuccessResponseMessage.class)); } @Test void initiatesRestartWhenGetsMessageFromOtherNode() throws Exception { NetworkMessageHandler handler = extractMessageHandler(); handler.onReceived(resetClusterMessageOn2Nodes(), node2, 0L); verify(restarter, timeout(SECONDS.toMillis(10))).initiateRestart(); // Wait till it gets saved to Vault to avoid an attempt to write to it after the after-each method stops the Vault. // TODO: IGNITE-23144 - remove when busy locks are added to VaultManager. waitTillResetClusterMessageGetsSavedToVault(); } @Test void doesNotInitiateRestartWhenGetsMessageFromSelf() throws Exception { NetworkMessageHandler handler = extractMessageHandler(); handler.onReceived(resetClusterMessageOn2Nodes(), thisNode, 0L); verify(restarter, never()).initiateRestart(); // Wait till it gets saved to Vault to avoid an attempt to write to it after the after-each method stops the Vault. // TODO: IGNITE-23144 - remove when busy locks are added to VaultManager. waitTillResetClusterMessageGetsSavedToVault(); } @Test void migrateRequiresFormerClusterIdsToBePresent() { ClusterState stateWithoutFormerClusterIds = cmgMessagesFactory.clusterState() .cmgNodes(Set.of("node5")) .metaStorageNodes(Set.of("node6")) .version(IgniteProductVersion.CURRENT_VERSION.toString()) .clusterTag(randomClusterTag(cmgMessagesFactory, CLUSTER_NAME)) .formerClusterIds(null) .build(); MigrateException ex = assertWillThrow(manager.migrate(stateWithoutFormerClusterIds), MigrateException.class); assertThat(ex.getMessage(), is("Migration can only happen using cluster state from a node that saw a cluster reset")); } @Test void migrateSendsMessagesToAllNodes() { putClusterState(); ClusterState newState = newClusterState(); ArgumentCaptor<ResetClusterMessage> messageCaptor = ArgumentCaptor.forClass(ResetClusterMessage.class); when(topologyService.allMembers()).thenReturn(List.of(thisNode, node2, node3)); when(messagingService.invoke(any(InternalClusterNode.class), any(ResetClusterMessage.class), anyLong())) .thenReturn(completedFuture(successResponseMessage)); assertThat(manager.migrate(newState), willCompleteSuccessfully()); verify(messagingService).invoke(eq(thisNode), messageCaptor.capture(), anyLong()); ResetClusterMessage messageToSelf = messageCaptor.getValue(); assertThatResetClusterMessageContentIsAsExpectedAfterMigrate(messageToSelf, newState); verify(messagingService).invoke(eq(node2), messageCaptor.capture(), anyLong()); ResetClusterMessage messageToOtherNewCmgNode = messageCaptor.getValue(); assertThatResetClusterMessageContentIsAsExpectedAfterMigrate(messageToOtherNewCmgNode, newState); verify(messagingService).invoke(eq(node3), messageCaptor.capture(), anyLong()); ResetClusterMessage messageToOtherNonCmgNode = messageCaptor.getValue(); assertThatResetClusterMessageContentIsAsExpectedAfterMigrate(messageToOtherNonCmgNode, newState); } private ClusterState newClusterState() { return cmgMessagesFactory.clusterState() .cmgNodes(Set.of("node5")) .metaStorageNodes(Set.of("node6")) .version(IgniteProductVersion.CURRENT_VERSION.toString()) .clusterTag(randomClusterTag(cmgMessagesFactory, CLUSTER_NAME)) .formerClusterIds(List.of(randomUUID(), randomUUID())) .initialClusterConfiguration(INITIAL_CONFIGURATION) .build(); } private static void assertThatResetClusterMessageContentIsAsExpectedAfterMigrate( ResetClusterMessage message, ClusterState clusterState ) { assertThat(message, is(notNullValue())); assertThat(message.newCmgNodes(), is(clusterState.cmgNodes())); assertThat(message.currentMetaStorageNodes(), is(clusterState.metaStorageNodes())); assertThat(message.clusterName(), is(clusterState.clusterTag().clusterName())); assertThat(message.clusterId(), is(clusterState.clusterTag().clusterId())); assertThat(message.formerClusterIds(), is(clusterState.formerClusterIds())); assertThat(message.initialClusterConfiguration(), is(clusterState.initialClusterConfiguration())); } @Test void migrateInitiatesRestart() { putClusterState(); ClusterState newState = newClusterState(); when(topologyService.allMembers()).thenReturn(List.of(thisNode, node2, node3)); respondSuccessfullyFrom(thisNode, node2); respondWithExceptionFrom(node3); assertThat(manager.migrate(newState), willCompleteSuccessfully()); verify(restarter).initiateRestart(); } @Test void migrationInWrongDirectionIsProhibited() { UUID clusterId1 = randomUUID(); UUID clusterId2 = randomUUID(); UUID clusterId3 = randomUUID(); ClusterState oldClusterState = cmgMessagesFactory.clusterState() .cmgNodes(Set.of(thisNodeName)) .metaStorageNodes(Set.of(thisNodeName)) .version(IgniteProductVersion.CURRENT_VERSION.toString()) .clusterTag(clusterTag(cmgMessagesFactory, CLUSTER_NAME, clusterId2)) .initialClusterConfiguration(INITIAL_CONFIGURATION) .formerClusterIds(List.of(clusterId1)) .build(); ClusterState newClusterState = cmgMessagesFactory.clusterState() .cmgNodes(Set.of(thisNodeName)) .metaStorageNodes(Set.of(thisNodeName)) .version(IgniteProductVersion.CURRENT_VERSION.toString()) .clusterTag(clusterTag(cmgMessagesFactory, CLUSTER_NAME, clusterId3)) .initialClusterConfiguration(INITIAL_CONFIGURATION) .formerClusterIds(List.of(clusterId1, clusterId2)) .build(); manager.saveClusterState(newClusterState); MigrateException ex = assertWillThrow(manager.migrate(oldClusterState), MigrateException.class); assertThat(ex.getMessage(), is("Migration can only happen from old cluster to new one, not the other way around")); } @ParameterizedTest @ValueSource(ints = {0, -1}) void resetClusterWithMgRequiresPositiveMgReplicationFactor(int metastorageReplicationFactor) { when(topologyService.allMembers()).thenReturn(List.of(thisNode, node2, node3)); ClusterResetException ex = assertWillThrow( manager.resetClusterRepairingMetastorage(List.of(thisNodeName), metastorageReplicationFactor), ClusterResetException.class ); assertThat(ex.getMessage(), is("Metastorage replication factor must be positive.")); } @Test void resetClusterWithMgRequiresCurrentTopologyBeEnoughForMgReplicationFactor() { when(topologyService.allMembers()).thenReturn(List.of(thisNode)); ClusterResetException ex = assertWillThrow( manager.resetClusterRepairingMetastorage(List.of(thisNodeName), 2), ClusterResetException.class ); assertThat(ex.getMessage(), is("Metastorage replication factor cannot exceed size of current physical topology (1).")); } @Test void startMetastorageRepairReturnsIndexAndTerm() { when(metastorageMaintenance.raftNodeIndex()).thenReturn(completedFuture(new IndexWithTerm(234, 2))); NetworkMessageHandler handler = extractMessageHandler(); handler.onReceived(startMetastorageRepairRequest(), thisNode, 123L); ArgumentCaptor<StartMetastorageRepairResponse> captor = ArgumentCaptor.forClass(StartMetastorageRepairResponse.class); verify(messagingService).respond(eq(thisNode), captor.capture(), eq(123L)); StartMetastorageRepairResponse response = captor.getValue(); assertThat(response.raftIndex(), is(234L)); assertThat(response.raftTerm(), is(2L)); } @Test void startsMetastorageRepairSavesClusterIdToVaultAsWitnessed() { when(metastorageMaintenance.raftNodeIndex()).thenReturn(completedFuture(new IndexWithTerm(234, 2))); NetworkMessageHandler handler = extractMessageHandler(); handler.onReceived(startMetastorageRepairRequest(), thisNode, 123L); VaultEntry entry = vaultManager.get(WITNESSED_METASTORAGE_REPAIR_CLUSTER_ID_VAULT_KEY); assertThat(entry, is(notNullValue())); assertThat(entry.value(), is(uuidToBytes(clusterId))); } private StartMetastorageRepairRequest startMetastorageRepairRequest() { return messagesFactory.startMetastorageRepairRequest().build(); } @ParameterizedTest @ValueSource(ints = {1, 3}) void initiatesBecomingMetastorageLeader(int targetVotingSetSize) { Set<String> targetSet = IntStream.range(0, targetVotingSetSize) .mapToObj(n -> "node" + n) .collect(toSet()); NetworkMessageHandler handler = extractMessageHandler(); BecomeMetastorageLeaderMessage message = messagesFactory.becomeMetastorageLeaderMessage() .termBeforeChange(1) .targetVotingSet(targetSet) .build(); handler.onReceived(message, thisNode, 123L); ArgumentCaptor<SuccessResponseMessage> captor = ArgumentCaptor.forClass(SuccessResponseMessage.class); verify(messagingService).respond(eq(thisNode), captor.capture(), eq(123L)); } @Test void allowsClusterResetWhenCmgMajorityIsOnline() { when(topologyService.allMembers()).thenReturn(List.of(thisNode, node2, node3)); prepareNodeStateForClusterReset(); when(messagingService.invoke(any(InternalClusterNode.class), any(ResetClusterMessage.class), anyLong())) .thenReturn(completedFuture(successResponseMessage)); CompletableFuture<Void> future = manager.resetCluster(List.of(thisNodeName, node2.name(), node3.name())); assertThat(future, willCompleteSuccessfully()); } @Test void prohibitsMetastorageRepairWhenMgMajorityIsOnline() { when(topologyService.allMembers()).thenReturn(List.of(thisNode, node2, node3)); prepareNodeStateForClusterReset(); ClusterResetException ex = assertWillThrow( manager.resetClusterRepairingMetastorage(List.of(thisNodeName, node2.name(), node3.name()), 3), ClusterResetException.class ); assertThat( ex.getMessage(), is("Majority repair is rejected because majority of Metastorage nodes are online [metastorageNodes=[node2], " + "onlineNodes=[node2, node3, node1]].") ); } private enum ResetCluster { CMG_ONLY { @Override CompletableFuture<Void> resetCluster(SystemDisasterRecoveryManager manager, List<String> proposedCmgConsistentIds) { return manager.resetCluster(proposedCmgConsistentIds); } }, CMG_AND_METASTORAGE { @Override CompletableFuture<Void> resetCluster(SystemDisasterRecoveryManager manager, List<String> proposedCmgConsistentIds) { return manager.resetClusterRepairingMetastorage(proposedCmgConsistentIds, 1); } }; abstract CompletableFuture<Void> resetCluster(SystemDisasterRecoveryManager manager, List<String> proposedCmgConsistentIds); boolean mgRepair() { return this == CMG_AND_METASTORAGE; } } }
googleapis/google-cloud-java
37,373
java-modelarmor/proto-google-cloud-modelarmor-v1beta/src/main/java/com/google/cloud/modelarmor/v1beta/SdpFilterResult.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/modelarmor/v1beta/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.modelarmor.v1beta; /** * * * <pre> * Sensitive Data Protection filter result. * </pre> * * Protobuf type {@code google.cloud.modelarmor.v1beta.SdpFilterResult} */ public final class SdpFilterResult extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.modelarmor.v1beta.SdpFilterResult) SdpFilterResultOrBuilder { private static final long serialVersionUID = 0L; // Use SdpFilterResult.newBuilder() to construct. private SdpFilterResult(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SdpFilterResult() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SdpFilterResult(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.modelarmor.v1beta.V1mainProto .internal_static_google_cloud_modelarmor_v1beta_SdpFilterResult_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.modelarmor.v1beta.V1mainProto .internal_static_google_cloud_modelarmor_v1beta_SdpFilterResult_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.modelarmor.v1beta.SdpFilterResult.class, com.google.cloud.modelarmor.v1beta.SdpFilterResult.Builder.class); } private int resultCase_ = 0; @SuppressWarnings("serial") private java.lang.Object result_; public enum ResultCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { INSPECT_RESULT(1), DEIDENTIFY_RESULT(2), RESULT_NOT_SET(0); private final int value; private ResultCase(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 ResultCase valueOf(int value) { return forNumber(value); } public static ResultCase forNumber(int value) { switch (value) { case 1: return INSPECT_RESULT; case 2: return DEIDENTIFY_RESULT; case 0: return RESULT_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public ResultCase getResultCase() { return ResultCase.forNumber(resultCase_); } public static final int INSPECT_RESULT_FIELD_NUMBER = 1; /** * * * <pre> * Sensitive Data Protection Inspection result if inspection is performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpInspectResult inspect_result = 1;</code> * * @return Whether the inspectResult field is set. */ @java.lang.Override public boolean hasInspectResult() { return resultCase_ == 1; } /** * * * <pre> * Sensitive Data Protection Inspection result if inspection is performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpInspectResult inspect_result = 1;</code> * * @return The inspectResult. */ @java.lang.Override public com.google.cloud.modelarmor.v1beta.SdpInspectResult getInspectResult() { if (resultCase_ == 1) { return (com.google.cloud.modelarmor.v1beta.SdpInspectResult) result_; } return com.google.cloud.modelarmor.v1beta.SdpInspectResult.getDefaultInstance(); } /** * * * <pre> * Sensitive Data Protection Inspection result if inspection is performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpInspectResult inspect_result = 1;</code> */ @java.lang.Override public com.google.cloud.modelarmor.v1beta.SdpInspectResultOrBuilder getInspectResultOrBuilder() { if (resultCase_ == 1) { return (com.google.cloud.modelarmor.v1beta.SdpInspectResult) result_; } return com.google.cloud.modelarmor.v1beta.SdpInspectResult.getDefaultInstance(); } public static final int DEIDENTIFY_RESULT_FIELD_NUMBER = 2; /** * * * <pre> * Sensitive Data Protection Deidentification result if deidentification is * performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpDeidentifyResult deidentify_result = 2;</code> * * @return Whether the deidentifyResult field is set. */ @java.lang.Override public boolean hasDeidentifyResult() { return resultCase_ == 2; } /** * * * <pre> * Sensitive Data Protection Deidentification result if deidentification is * performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpDeidentifyResult deidentify_result = 2;</code> * * @return The deidentifyResult. */ @java.lang.Override public com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult getDeidentifyResult() { if (resultCase_ == 2) { return (com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult) result_; } return com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult.getDefaultInstance(); } /** * * * <pre> * Sensitive Data Protection Deidentification result if deidentification is * performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpDeidentifyResult deidentify_result = 2;</code> */ @java.lang.Override public com.google.cloud.modelarmor.v1beta.SdpDeidentifyResultOrBuilder getDeidentifyResultOrBuilder() { if (resultCase_ == 2) { return (com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult) result_; } return com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult.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 (resultCase_ == 1) { output.writeMessage(1, (com.google.cloud.modelarmor.v1beta.SdpInspectResult) result_); } if (resultCase_ == 2) { output.writeMessage(2, (com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult) result_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (resultCase_ == 1) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 1, (com.google.cloud.modelarmor.v1beta.SdpInspectResult) result_); } if (resultCase_ == 2) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 2, (com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult) result_); } 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.modelarmor.v1beta.SdpFilterResult)) { return super.equals(obj); } com.google.cloud.modelarmor.v1beta.SdpFilterResult other = (com.google.cloud.modelarmor.v1beta.SdpFilterResult) obj; if (!getResultCase().equals(other.getResultCase())) return false; switch (resultCase_) { case 1: if (!getInspectResult().equals(other.getInspectResult())) return false; break; case 2: if (!getDeidentifyResult().equals(other.getDeidentifyResult())) 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 (resultCase_) { case 1: hash = (37 * hash) + INSPECT_RESULT_FIELD_NUMBER; hash = (53 * hash) + getInspectResult().hashCode(); break; case 2: hash = (37 * hash) + DEIDENTIFY_RESULT_FIELD_NUMBER; hash = (53 * hash) + getDeidentifyResult().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.modelarmor.v1beta.SdpFilterResult parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.modelarmor.v1beta.SdpFilterResult 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.modelarmor.v1beta.SdpFilterResult parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.modelarmor.v1beta.SdpFilterResult 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.modelarmor.v1beta.SdpFilterResult parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.modelarmor.v1beta.SdpFilterResult parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.modelarmor.v1beta.SdpFilterResult parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.modelarmor.v1beta.SdpFilterResult 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.modelarmor.v1beta.SdpFilterResult parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.modelarmor.v1beta.SdpFilterResult 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.modelarmor.v1beta.SdpFilterResult parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.modelarmor.v1beta.SdpFilterResult 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.modelarmor.v1beta.SdpFilterResult 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> * Sensitive Data Protection filter result. * </pre> * * Protobuf type {@code google.cloud.modelarmor.v1beta.SdpFilterResult} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.modelarmor.v1beta.SdpFilterResult) com.google.cloud.modelarmor.v1beta.SdpFilterResultOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.modelarmor.v1beta.V1mainProto .internal_static_google_cloud_modelarmor_v1beta_SdpFilterResult_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.modelarmor.v1beta.V1mainProto .internal_static_google_cloud_modelarmor_v1beta_SdpFilterResult_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.modelarmor.v1beta.SdpFilterResult.class, com.google.cloud.modelarmor.v1beta.SdpFilterResult.Builder.class); } // Construct using com.google.cloud.modelarmor.v1beta.SdpFilterResult.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (inspectResultBuilder_ != null) { inspectResultBuilder_.clear(); } if (deidentifyResultBuilder_ != null) { deidentifyResultBuilder_.clear(); } resultCase_ = 0; result_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.modelarmor.v1beta.V1mainProto .internal_static_google_cloud_modelarmor_v1beta_SdpFilterResult_descriptor; } @java.lang.Override public com.google.cloud.modelarmor.v1beta.SdpFilterResult getDefaultInstanceForType() { return com.google.cloud.modelarmor.v1beta.SdpFilterResult.getDefaultInstance(); } @java.lang.Override public com.google.cloud.modelarmor.v1beta.SdpFilterResult build() { com.google.cloud.modelarmor.v1beta.SdpFilterResult result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.modelarmor.v1beta.SdpFilterResult buildPartial() { com.google.cloud.modelarmor.v1beta.SdpFilterResult result = new com.google.cloud.modelarmor.v1beta.SdpFilterResult(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.cloud.modelarmor.v1beta.SdpFilterResult result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs(com.google.cloud.modelarmor.v1beta.SdpFilterResult result) { result.resultCase_ = resultCase_; result.result_ = this.result_; if (resultCase_ == 1 && inspectResultBuilder_ != null) { result.result_ = inspectResultBuilder_.build(); } if (resultCase_ == 2 && deidentifyResultBuilder_ != null) { result.result_ = deidentifyResultBuilder_.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.modelarmor.v1beta.SdpFilterResult) { return mergeFrom((com.google.cloud.modelarmor.v1beta.SdpFilterResult) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.modelarmor.v1beta.SdpFilterResult other) { if (other == com.google.cloud.modelarmor.v1beta.SdpFilterResult.getDefaultInstance()) return this; switch (other.getResultCase()) { case INSPECT_RESULT: { mergeInspectResult(other.getInspectResult()); break; } case DEIDENTIFY_RESULT: { mergeDeidentifyResult(other.getDeidentifyResult()); break; } case RESULT_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(getInspectResultFieldBuilder().getBuilder(), extensionRegistry); resultCase_ = 1; break; } // case 10 case 18: { input.readMessage( getDeidentifyResultFieldBuilder().getBuilder(), extensionRegistry); resultCase_ = 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 resultCase_ = 0; private java.lang.Object result_; public ResultCase getResultCase() { return ResultCase.forNumber(resultCase_); } public Builder clearResult() { resultCase_ = 0; result_ = null; onChanged(); return this; } private int bitField0_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.modelarmor.v1beta.SdpInspectResult, com.google.cloud.modelarmor.v1beta.SdpInspectResult.Builder, com.google.cloud.modelarmor.v1beta.SdpInspectResultOrBuilder> inspectResultBuilder_; /** * * * <pre> * Sensitive Data Protection Inspection result if inspection is performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpInspectResult inspect_result = 1;</code> * * @return Whether the inspectResult field is set. */ @java.lang.Override public boolean hasInspectResult() { return resultCase_ == 1; } /** * * * <pre> * Sensitive Data Protection Inspection result if inspection is performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpInspectResult inspect_result = 1;</code> * * @return The inspectResult. */ @java.lang.Override public com.google.cloud.modelarmor.v1beta.SdpInspectResult getInspectResult() { if (inspectResultBuilder_ == null) { if (resultCase_ == 1) { return (com.google.cloud.modelarmor.v1beta.SdpInspectResult) result_; } return com.google.cloud.modelarmor.v1beta.SdpInspectResult.getDefaultInstance(); } else { if (resultCase_ == 1) { return inspectResultBuilder_.getMessage(); } return com.google.cloud.modelarmor.v1beta.SdpInspectResult.getDefaultInstance(); } } /** * * * <pre> * Sensitive Data Protection Inspection result if inspection is performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpInspectResult inspect_result = 1;</code> */ public Builder setInspectResult(com.google.cloud.modelarmor.v1beta.SdpInspectResult value) { if (inspectResultBuilder_ == null) { if (value == null) { throw new NullPointerException(); } result_ = value; onChanged(); } else { inspectResultBuilder_.setMessage(value); } resultCase_ = 1; return this; } /** * * * <pre> * Sensitive Data Protection Inspection result if inspection is performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpInspectResult inspect_result = 1;</code> */ public Builder setInspectResult( com.google.cloud.modelarmor.v1beta.SdpInspectResult.Builder builderForValue) { if (inspectResultBuilder_ == null) { result_ = builderForValue.build(); onChanged(); } else { inspectResultBuilder_.setMessage(builderForValue.build()); } resultCase_ = 1; return this; } /** * * * <pre> * Sensitive Data Protection Inspection result if inspection is performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpInspectResult inspect_result = 1;</code> */ public Builder mergeInspectResult(com.google.cloud.modelarmor.v1beta.SdpInspectResult value) { if (inspectResultBuilder_ == null) { if (resultCase_ == 1 && result_ != com.google.cloud.modelarmor.v1beta.SdpInspectResult.getDefaultInstance()) { result_ = com.google.cloud.modelarmor.v1beta.SdpInspectResult.newBuilder( (com.google.cloud.modelarmor.v1beta.SdpInspectResult) result_) .mergeFrom(value) .buildPartial(); } else { result_ = value; } onChanged(); } else { if (resultCase_ == 1) { inspectResultBuilder_.mergeFrom(value); } else { inspectResultBuilder_.setMessage(value); } } resultCase_ = 1; return this; } /** * * * <pre> * Sensitive Data Protection Inspection result if inspection is performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpInspectResult inspect_result = 1;</code> */ public Builder clearInspectResult() { if (inspectResultBuilder_ == null) { if (resultCase_ == 1) { resultCase_ = 0; result_ = null; onChanged(); } } else { if (resultCase_ == 1) { resultCase_ = 0; result_ = null; } inspectResultBuilder_.clear(); } return this; } /** * * * <pre> * Sensitive Data Protection Inspection result if inspection is performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpInspectResult inspect_result = 1;</code> */ public com.google.cloud.modelarmor.v1beta.SdpInspectResult.Builder getInspectResultBuilder() { return getInspectResultFieldBuilder().getBuilder(); } /** * * * <pre> * Sensitive Data Protection Inspection result if inspection is performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpInspectResult inspect_result = 1;</code> */ @java.lang.Override public com.google.cloud.modelarmor.v1beta.SdpInspectResultOrBuilder getInspectResultOrBuilder() { if ((resultCase_ == 1) && (inspectResultBuilder_ != null)) { return inspectResultBuilder_.getMessageOrBuilder(); } else { if (resultCase_ == 1) { return (com.google.cloud.modelarmor.v1beta.SdpInspectResult) result_; } return com.google.cloud.modelarmor.v1beta.SdpInspectResult.getDefaultInstance(); } } /** * * * <pre> * Sensitive Data Protection Inspection result if inspection is performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpInspectResult inspect_result = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.modelarmor.v1beta.SdpInspectResult, com.google.cloud.modelarmor.v1beta.SdpInspectResult.Builder, com.google.cloud.modelarmor.v1beta.SdpInspectResultOrBuilder> getInspectResultFieldBuilder() { if (inspectResultBuilder_ == null) { if (!(resultCase_ == 1)) { result_ = com.google.cloud.modelarmor.v1beta.SdpInspectResult.getDefaultInstance(); } inspectResultBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.modelarmor.v1beta.SdpInspectResult, com.google.cloud.modelarmor.v1beta.SdpInspectResult.Builder, com.google.cloud.modelarmor.v1beta.SdpInspectResultOrBuilder>( (com.google.cloud.modelarmor.v1beta.SdpInspectResult) result_, getParentForChildren(), isClean()); result_ = null; } resultCase_ = 1; onChanged(); return inspectResultBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult, com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult.Builder, com.google.cloud.modelarmor.v1beta.SdpDeidentifyResultOrBuilder> deidentifyResultBuilder_; /** * * * <pre> * Sensitive Data Protection Deidentification result if deidentification is * performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpDeidentifyResult deidentify_result = 2;</code> * * @return Whether the deidentifyResult field is set. */ @java.lang.Override public boolean hasDeidentifyResult() { return resultCase_ == 2; } /** * * * <pre> * Sensitive Data Protection Deidentification result if deidentification is * performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpDeidentifyResult deidentify_result = 2;</code> * * @return The deidentifyResult. */ @java.lang.Override public com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult getDeidentifyResult() { if (deidentifyResultBuilder_ == null) { if (resultCase_ == 2) { return (com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult) result_; } return com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult.getDefaultInstance(); } else { if (resultCase_ == 2) { return deidentifyResultBuilder_.getMessage(); } return com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult.getDefaultInstance(); } } /** * * * <pre> * Sensitive Data Protection Deidentification result if deidentification is * performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpDeidentifyResult deidentify_result = 2;</code> */ public Builder setDeidentifyResult( com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult value) { if (deidentifyResultBuilder_ == null) { if (value == null) { throw new NullPointerException(); } result_ = value; onChanged(); } else { deidentifyResultBuilder_.setMessage(value); } resultCase_ = 2; return this; } /** * * * <pre> * Sensitive Data Protection Deidentification result if deidentification is * performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpDeidentifyResult deidentify_result = 2;</code> */ public Builder setDeidentifyResult( com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult.Builder builderForValue) { if (deidentifyResultBuilder_ == null) { result_ = builderForValue.build(); onChanged(); } else { deidentifyResultBuilder_.setMessage(builderForValue.build()); } resultCase_ = 2; return this; } /** * * * <pre> * Sensitive Data Protection Deidentification result if deidentification is * performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpDeidentifyResult deidentify_result = 2;</code> */ public Builder mergeDeidentifyResult( com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult value) { if (deidentifyResultBuilder_ == null) { if (resultCase_ == 2 && result_ != com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult.getDefaultInstance()) { result_ = com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult.newBuilder( (com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult) result_) .mergeFrom(value) .buildPartial(); } else { result_ = value; } onChanged(); } else { if (resultCase_ == 2) { deidentifyResultBuilder_.mergeFrom(value); } else { deidentifyResultBuilder_.setMessage(value); } } resultCase_ = 2; return this; } /** * * * <pre> * Sensitive Data Protection Deidentification result if deidentification is * performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpDeidentifyResult deidentify_result = 2;</code> */ public Builder clearDeidentifyResult() { if (deidentifyResultBuilder_ == null) { if (resultCase_ == 2) { resultCase_ = 0; result_ = null; onChanged(); } } else { if (resultCase_ == 2) { resultCase_ = 0; result_ = null; } deidentifyResultBuilder_.clear(); } return this; } /** * * * <pre> * Sensitive Data Protection Deidentification result if deidentification is * performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpDeidentifyResult deidentify_result = 2;</code> */ public com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult.Builder getDeidentifyResultBuilder() { return getDeidentifyResultFieldBuilder().getBuilder(); } /** * * * <pre> * Sensitive Data Protection Deidentification result if deidentification is * performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpDeidentifyResult deidentify_result = 2;</code> */ @java.lang.Override public com.google.cloud.modelarmor.v1beta.SdpDeidentifyResultOrBuilder getDeidentifyResultOrBuilder() { if ((resultCase_ == 2) && (deidentifyResultBuilder_ != null)) { return deidentifyResultBuilder_.getMessageOrBuilder(); } else { if (resultCase_ == 2) { return (com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult) result_; } return com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult.getDefaultInstance(); } } /** * * * <pre> * Sensitive Data Protection Deidentification result if deidentification is * performed. * </pre> * * <code>.google.cloud.modelarmor.v1beta.SdpDeidentifyResult deidentify_result = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult, com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult.Builder, com.google.cloud.modelarmor.v1beta.SdpDeidentifyResultOrBuilder> getDeidentifyResultFieldBuilder() { if (deidentifyResultBuilder_ == null) { if (!(resultCase_ == 2)) { result_ = com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult.getDefaultInstance(); } deidentifyResultBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult, com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult.Builder, com.google.cloud.modelarmor.v1beta.SdpDeidentifyResultOrBuilder>( (com.google.cloud.modelarmor.v1beta.SdpDeidentifyResult) result_, getParentForChildren(), isClean()); result_ = null; } resultCase_ = 2; onChanged(); return deidentifyResultBuilder_; } @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.modelarmor.v1beta.SdpFilterResult) } // @@protoc_insertion_point(class_scope:google.cloud.modelarmor.v1beta.SdpFilterResult) private static final com.google.cloud.modelarmor.v1beta.SdpFilterResult DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.modelarmor.v1beta.SdpFilterResult(); } public static com.google.cloud.modelarmor.v1beta.SdpFilterResult getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SdpFilterResult> PARSER = new com.google.protobuf.AbstractParser<SdpFilterResult>() { @java.lang.Override public SdpFilterResult 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<SdpFilterResult> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SdpFilterResult> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.modelarmor.v1beta.SdpFilterResult getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hive
37,386
standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/DropDatabaseRequest.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 DropDatabaseRequest implements org.apache.thrift.TBase<DropDatabaseRequest, DropDatabaseRequest._Fields>, java.io.Serializable, Cloneable, Comparable<DropDatabaseRequest> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("DropDatabaseRequest"); private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField CATALOG_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("catalogName", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField IGNORE_UNKNOWN_DB_FIELD_DESC = new org.apache.thrift.protocol.TField("ignoreUnknownDb", org.apache.thrift.protocol.TType.BOOL, (short)3); private static final org.apache.thrift.protocol.TField DELETE_DATA_FIELD_DESC = new org.apache.thrift.protocol.TField("deleteData", org.apache.thrift.protocol.TType.BOOL, (short)4); private static final org.apache.thrift.protocol.TField CASCADE_FIELD_DESC = new org.apache.thrift.protocol.TField("cascade", org.apache.thrift.protocol.TType.BOOL, (short)5); private static final org.apache.thrift.protocol.TField SOFT_DELETE_FIELD_DESC = new org.apache.thrift.protocol.TField("softDelete", org.apache.thrift.protocol.TType.BOOL, (short)6); private static final org.apache.thrift.protocol.TField TXN_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("txnId", org.apache.thrift.protocol.TType.I64, (short)7); private static final org.apache.thrift.protocol.TField DELETE_MANAGED_DIR_FIELD_DESC = new org.apache.thrift.protocol.TField("deleteManagedDir", org.apache.thrift.protocol.TType.BOOL, (short)8); private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new DropDatabaseRequestStandardSchemeFactory(); private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new DropDatabaseRequestTupleSchemeFactory(); private @org.apache.thrift.annotation.Nullable java.lang.String name; // required private @org.apache.thrift.annotation.Nullable java.lang.String catalogName; // optional private boolean ignoreUnknownDb; // required private boolean deleteData; // required private boolean cascade; // required private boolean softDelete; // optional private long txnId; // optional private boolean deleteManagedDir; // 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 { NAME((short)1, "name"), CATALOG_NAME((short)2, "catalogName"), IGNORE_UNKNOWN_DB((short)3, "ignoreUnknownDb"), DELETE_DATA((short)4, "deleteData"), CASCADE((short)5, "cascade"), SOFT_DELETE((short)6, "softDelete"), TXN_ID((short)7, "txnId"), DELETE_MANAGED_DIR((short)8, "deleteManagedDir"); 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: // NAME return NAME; case 2: // CATALOG_NAME return CATALOG_NAME; case 3: // IGNORE_UNKNOWN_DB return IGNORE_UNKNOWN_DB; case 4: // DELETE_DATA return DELETE_DATA; case 5: // CASCADE return CASCADE; case 6: // SOFT_DELETE return SOFT_DELETE; case 7: // TXN_ID return TXN_ID; case 8: // DELETE_MANAGED_DIR return DELETE_MANAGED_DIR; 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 __IGNOREUNKNOWNDB_ISSET_ID = 0; private static final int __DELETEDATA_ISSET_ID = 1; private static final int __CASCADE_ISSET_ID = 2; private static final int __SOFTDELETE_ISSET_ID = 3; private static final int __TXNID_ISSET_ID = 4; private static final int __DELETEMANAGEDDIR_ISSET_ID = 5; private byte __isset_bitfield = 0; private static final _Fields optionals[] = {_Fields.CATALOG_NAME,_Fields.SOFT_DELETE,_Fields.TXN_ID,_Fields.DELETE_MANAGED_DIR}; 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.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.CATALOG_NAME, new org.apache.thrift.meta_data.FieldMetaData("catalogName", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.IGNORE_UNKNOWN_DB, new org.apache.thrift.meta_data.FieldMetaData("ignoreUnknownDb", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.DELETE_DATA, new org.apache.thrift.meta_data.FieldMetaData("deleteData", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.CASCADE, new org.apache.thrift.meta_data.FieldMetaData("cascade", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.SOFT_DELETE, new org.apache.thrift.meta_data.FieldMetaData("softDelete", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.TXN_ID, new org.apache.thrift.meta_data.FieldMetaData("txnId", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); tmpMap.put(_Fields.DELETE_MANAGED_DIR, new org.apache.thrift.meta_data.FieldMetaData("deleteManagedDir", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(DropDatabaseRequest.class, metaDataMap); } public DropDatabaseRequest() { this.softDelete = false; this.txnId = 0L; this.deleteManagedDir = true; } public DropDatabaseRequest( java.lang.String name, boolean ignoreUnknownDb, boolean deleteData, boolean cascade) { this(); this.name = name; this.ignoreUnknownDb = ignoreUnknownDb; setIgnoreUnknownDbIsSet(true); this.deleteData = deleteData; setDeleteDataIsSet(true); this.cascade = cascade; setCascadeIsSet(true); } /** * Performs a deep copy on <i>other</i>. */ public DropDatabaseRequest(DropDatabaseRequest other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetName()) { this.name = other.name; } if (other.isSetCatalogName()) { this.catalogName = other.catalogName; } this.ignoreUnknownDb = other.ignoreUnknownDb; this.deleteData = other.deleteData; this.cascade = other.cascade; this.softDelete = other.softDelete; this.txnId = other.txnId; this.deleteManagedDir = other.deleteManagedDir; } public DropDatabaseRequest deepCopy() { return new DropDatabaseRequest(this); } @Override public void clear() { this.name = null; this.catalogName = null; setIgnoreUnknownDbIsSet(false); this.ignoreUnknownDb = false; setDeleteDataIsSet(false); this.deleteData = false; setCascadeIsSet(false); this.cascade = false; this.softDelete = false; this.txnId = 0L; this.deleteManagedDir = true; } @org.apache.thrift.annotation.Nullable public java.lang.String getName() { return this.name; } public void setName(@org.apache.thrift.annotation.Nullable java.lang.String name) { this.name = name; } public void unsetName() { this.name = null; } /** Returns true if field name is set (has been assigned a value) and false otherwise */ public boolean isSetName() { return this.name != null; } public void setNameIsSet(boolean value) { if (!value) { this.name = null; } } @org.apache.thrift.annotation.Nullable public java.lang.String getCatalogName() { return this.catalogName; } public void setCatalogName(@org.apache.thrift.annotation.Nullable java.lang.String catalogName) { this.catalogName = catalogName; } public void unsetCatalogName() { this.catalogName = null; } /** Returns true if field catalogName is set (has been assigned a value) and false otherwise */ public boolean isSetCatalogName() { return this.catalogName != null; } public void setCatalogNameIsSet(boolean value) { if (!value) { this.catalogName = null; } } public boolean isIgnoreUnknownDb() { return this.ignoreUnknownDb; } public void setIgnoreUnknownDb(boolean ignoreUnknownDb) { this.ignoreUnknownDb = ignoreUnknownDb; setIgnoreUnknownDbIsSet(true); } public void unsetIgnoreUnknownDb() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __IGNOREUNKNOWNDB_ISSET_ID); } /** Returns true if field ignoreUnknownDb is set (has been assigned a value) and false otherwise */ public boolean isSetIgnoreUnknownDb() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __IGNOREUNKNOWNDB_ISSET_ID); } public void setIgnoreUnknownDbIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __IGNOREUNKNOWNDB_ISSET_ID, value); } public boolean isDeleteData() { return this.deleteData; } public void setDeleteData(boolean deleteData) { this.deleteData = deleteData; setDeleteDataIsSet(true); } public void unsetDeleteData() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __DELETEDATA_ISSET_ID); } /** Returns true if field deleteData is set (has been assigned a value) and false otherwise */ public boolean isSetDeleteData() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __DELETEDATA_ISSET_ID); } public void setDeleteDataIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __DELETEDATA_ISSET_ID, value); } public boolean isCascade() { return this.cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; setCascadeIsSet(true); } public void unsetCascade() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __CASCADE_ISSET_ID); } /** Returns true if field cascade is set (has been assigned a value) and false otherwise */ public boolean isSetCascade() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __CASCADE_ISSET_ID); } public void setCascadeIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __CASCADE_ISSET_ID, value); } public boolean isSoftDelete() { return this.softDelete; } public void setSoftDelete(boolean softDelete) { this.softDelete = softDelete; setSoftDeleteIsSet(true); } public void unsetSoftDelete() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __SOFTDELETE_ISSET_ID); } /** Returns true if field softDelete is set (has been assigned a value) and false otherwise */ public boolean isSetSoftDelete() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __SOFTDELETE_ISSET_ID); } public void setSoftDeleteIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __SOFTDELETE_ISSET_ID, value); } public long getTxnId() { return this.txnId; } public void setTxnId(long txnId) { this.txnId = txnId; setTxnIdIsSet(true); } public void unsetTxnId() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __TXNID_ISSET_ID); } /** Returns true if field txnId is set (has been assigned a value) and false otherwise */ public boolean isSetTxnId() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __TXNID_ISSET_ID); } public void setTxnIdIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __TXNID_ISSET_ID, value); } public boolean isDeleteManagedDir() { return this.deleteManagedDir; } public void setDeleteManagedDir(boolean deleteManagedDir) { this.deleteManagedDir = deleteManagedDir; setDeleteManagedDirIsSet(true); } public void unsetDeleteManagedDir() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __DELETEMANAGEDDIR_ISSET_ID); } /** Returns true if field deleteManagedDir is set (has been assigned a value) and false otherwise */ public boolean isSetDeleteManagedDir() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __DELETEMANAGEDDIR_ISSET_ID); } public void setDeleteManagedDirIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __DELETEMANAGEDDIR_ISSET_ID, value); } public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) { switch (field) { case NAME: if (value == null) { unsetName(); } else { setName((java.lang.String)value); } break; case CATALOG_NAME: if (value == null) { unsetCatalogName(); } else { setCatalogName((java.lang.String)value); } break; case IGNORE_UNKNOWN_DB: if (value == null) { unsetIgnoreUnknownDb(); } else { setIgnoreUnknownDb((java.lang.Boolean)value); } break; case DELETE_DATA: if (value == null) { unsetDeleteData(); } else { setDeleteData((java.lang.Boolean)value); } break; case CASCADE: if (value == null) { unsetCascade(); } else { setCascade((java.lang.Boolean)value); } break; case SOFT_DELETE: if (value == null) { unsetSoftDelete(); } else { setSoftDelete((java.lang.Boolean)value); } break; case TXN_ID: if (value == null) { unsetTxnId(); } else { setTxnId((java.lang.Long)value); } break; case DELETE_MANAGED_DIR: if (value == null) { unsetDeleteManagedDir(); } else { setDeleteManagedDir((java.lang.Boolean)value); } break; } } @org.apache.thrift.annotation.Nullable public java.lang.Object getFieldValue(_Fields field) { switch (field) { case NAME: return getName(); case CATALOG_NAME: return getCatalogName(); case IGNORE_UNKNOWN_DB: return isIgnoreUnknownDb(); case DELETE_DATA: return isDeleteData(); case CASCADE: return isCascade(); case SOFT_DELETE: return isSoftDelete(); case TXN_ID: return getTxnId(); case DELETE_MANAGED_DIR: return isDeleteManagedDir(); } 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 NAME: return isSetName(); case CATALOG_NAME: return isSetCatalogName(); case IGNORE_UNKNOWN_DB: return isSetIgnoreUnknownDb(); case DELETE_DATA: return isSetDeleteData(); case CASCADE: return isSetCascade(); case SOFT_DELETE: return isSetSoftDelete(); case TXN_ID: return isSetTxnId(); case DELETE_MANAGED_DIR: return isSetDeleteManagedDir(); } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that instanceof DropDatabaseRequest) return this.equals((DropDatabaseRequest)that); return false; } public boolean equals(DropDatabaseRequest that) { if (that == null) return false; if (this == that) return true; boolean this_present_name = true && this.isSetName(); boolean that_present_name = true && that.isSetName(); if (this_present_name || that_present_name) { if (!(this_present_name && that_present_name)) return false; if (!this.name.equals(that.name)) return false; } boolean this_present_catalogName = true && this.isSetCatalogName(); boolean that_present_catalogName = true && that.isSetCatalogName(); if (this_present_catalogName || that_present_catalogName) { if (!(this_present_catalogName && that_present_catalogName)) return false; if (!this.catalogName.equals(that.catalogName)) return false; } boolean this_present_ignoreUnknownDb = true; boolean that_present_ignoreUnknownDb = true; if (this_present_ignoreUnknownDb || that_present_ignoreUnknownDb) { if (!(this_present_ignoreUnknownDb && that_present_ignoreUnknownDb)) return false; if (this.ignoreUnknownDb != that.ignoreUnknownDb) return false; } boolean this_present_deleteData = true; boolean that_present_deleteData = true; if (this_present_deleteData || that_present_deleteData) { if (!(this_present_deleteData && that_present_deleteData)) return false; if (this.deleteData != that.deleteData) return false; } boolean this_present_cascade = true; boolean that_present_cascade = true; if (this_present_cascade || that_present_cascade) { if (!(this_present_cascade && that_present_cascade)) return false; if (this.cascade != that.cascade) return false; } boolean this_present_softDelete = true && this.isSetSoftDelete(); boolean that_present_softDelete = true && that.isSetSoftDelete(); if (this_present_softDelete || that_present_softDelete) { if (!(this_present_softDelete && that_present_softDelete)) return false; if (this.softDelete != that.softDelete) return false; } boolean this_present_txnId = true && this.isSetTxnId(); boolean that_present_txnId = true && that.isSetTxnId(); if (this_present_txnId || that_present_txnId) { if (!(this_present_txnId && that_present_txnId)) return false; if (this.txnId != that.txnId) return false; } boolean this_present_deleteManagedDir = true && this.isSetDeleteManagedDir(); boolean that_present_deleteManagedDir = true && that.isSetDeleteManagedDir(); if (this_present_deleteManagedDir || that_present_deleteManagedDir) { if (!(this_present_deleteManagedDir && that_present_deleteManagedDir)) return false; if (this.deleteManagedDir != that.deleteManagedDir) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetName()) ? 131071 : 524287); if (isSetName()) hashCode = hashCode * 8191 + name.hashCode(); hashCode = hashCode * 8191 + ((isSetCatalogName()) ? 131071 : 524287); if (isSetCatalogName()) hashCode = hashCode * 8191 + catalogName.hashCode(); hashCode = hashCode * 8191 + ((ignoreUnknownDb) ? 131071 : 524287); hashCode = hashCode * 8191 + ((deleteData) ? 131071 : 524287); hashCode = hashCode * 8191 + ((cascade) ? 131071 : 524287); hashCode = hashCode * 8191 + ((isSetSoftDelete()) ? 131071 : 524287); if (isSetSoftDelete()) hashCode = hashCode * 8191 + ((softDelete) ? 131071 : 524287); hashCode = hashCode * 8191 + ((isSetTxnId()) ? 131071 : 524287); if (isSetTxnId()) hashCode = hashCode * 8191 + org.apache.thrift.TBaseHelper.hashCode(txnId); hashCode = hashCode * 8191 + ((isSetDeleteManagedDir()) ? 131071 : 524287); if (isSetDeleteManagedDir()) hashCode = hashCode * 8191 + ((deleteManagedDir) ? 131071 : 524287); return hashCode; } @Override public int compareTo(DropDatabaseRequest other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.compare(isSetName(), other.isSetName()); if (lastComparison != 0) { return lastComparison; } if (isSetName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetCatalogName(), other.isSetCatalogName()); if (lastComparison != 0) { return lastComparison; } if (isSetCatalogName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.catalogName, other.catalogName); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetIgnoreUnknownDb(), other.isSetIgnoreUnknownDb()); if (lastComparison != 0) { return lastComparison; } if (isSetIgnoreUnknownDb()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ignoreUnknownDb, other.ignoreUnknownDb); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetDeleteData(), other.isSetDeleteData()); if (lastComparison != 0) { return lastComparison; } if (isSetDeleteData()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.deleteData, other.deleteData); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetCascade(), other.isSetCascade()); if (lastComparison != 0) { return lastComparison; } if (isSetCascade()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.cascade, other.cascade); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetSoftDelete(), other.isSetSoftDelete()); if (lastComparison != 0) { return lastComparison; } if (isSetSoftDelete()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.softDelete, other.softDelete); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetTxnId(), other.isSetTxnId()); if (lastComparison != 0) { return lastComparison; } if (isSetTxnId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.txnId, other.txnId); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetDeleteManagedDir(), other.isSetDeleteManagedDir()); if (lastComparison != 0) { return lastComparison; } if (isSetDeleteManagedDir()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.deleteManagedDir, other.deleteManagedDir); 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("DropDatabaseRequest("); boolean first = true; sb.append("name:"); if (this.name == null) { sb.append("null"); } else { sb.append(this.name); } first = false; if (isSetCatalogName()) { if (!first) sb.append(", "); sb.append("catalogName:"); if (this.catalogName == null) { sb.append("null"); } else { sb.append(this.catalogName); } first = false; } if (!first) sb.append(", "); sb.append("ignoreUnknownDb:"); sb.append(this.ignoreUnknownDb); first = false; if (!first) sb.append(", "); sb.append("deleteData:"); sb.append(this.deleteData); first = false; if (!first) sb.append(", "); sb.append("cascade:"); sb.append(this.cascade); first = false; if (isSetSoftDelete()) { if (!first) sb.append(", "); sb.append("softDelete:"); sb.append(this.softDelete); first = false; } if (isSetTxnId()) { if (!first) sb.append(", "); sb.append("txnId:"); sb.append(this.txnId); first = false; } if (isSetDeleteManagedDir()) { if (!first) sb.append(", "); sb.append("deleteManagedDir:"); sb.append(this.deleteManagedDir); first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (!isSetName()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'name' is unset! Struct:" + toString()); } if (!isSetIgnoreUnknownDb()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'ignoreUnknownDb' is unset! Struct:" + toString()); } if (!isSetDeleteData()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'deleteData' is unset! Struct:" + toString()); } if (!isSetCascade()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'cascade' is unset! Struct:" + toString()); } // 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 DropDatabaseRequestStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public DropDatabaseRequestStandardScheme getScheme() { return new DropDatabaseRequestStandardScheme(); } } private static class DropDatabaseRequestStandardScheme extends org.apache.thrift.scheme.StandardScheme<DropDatabaseRequest> { public void read(org.apache.thrift.protocol.TProtocol iprot, DropDatabaseRequest 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: // NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.name = iprot.readString(); struct.setNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // CATALOG_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.catalogName = iprot.readString(); struct.setCatalogNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // IGNORE_UNKNOWN_DB if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.ignoreUnknownDb = iprot.readBool(); struct.setIgnoreUnknownDbIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DELETE_DATA if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.deleteData = iprot.readBool(); struct.setDeleteDataIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // CASCADE if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.cascade = iprot.readBool(); struct.setCascadeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // SOFT_DELETE if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.softDelete = iprot.readBool(); struct.setSoftDeleteIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 7: // TXN_ID if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.txnId = iprot.readI64(); struct.setTxnIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 8: // DELETE_MANAGED_DIR if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.deleteManagedDir = iprot.readBool(); struct.setDeleteManagedDirIsSet(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, DropDatabaseRequest struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.name != null) { oprot.writeFieldBegin(NAME_FIELD_DESC); oprot.writeString(struct.name); oprot.writeFieldEnd(); } if (struct.catalogName != null) { if (struct.isSetCatalogName()) { oprot.writeFieldBegin(CATALOG_NAME_FIELD_DESC); oprot.writeString(struct.catalogName); oprot.writeFieldEnd(); } } oprot.writeFieldBegin(IGNORE_UNKNOWN_DB_FIELD_DESC); oprot.writeBool(struct.ignoreUnknownDb); oprot.writeFieldEnd(); oprot.writeFieldBegin(DELETE_DATA_FIELD_DESC); oprot.writeBool(struct.deleteData); oprot.writeFieldEnd(); oprot.writeFieldBegin(CASCADE_FIELD_DESC); oprot.writeBool(struct.cascade); oprot.writeFieldEnd(); if (struct.isSetSoftDelete()) { oprot.writeFieldBegin(SOFT_DELETE_FIELD_DESC); oprot.writeBool(struct.softDelete); oprot.writeFieldEnd(); } if (struct.isSetTxnId()) { oprot.writeFieldBegin(TXN_ID_FIELD_DESC); oprot.writeI64(struct.txnId); oprot.writeFieldEnd(); } if (struct.isSetDeleteManagedDir()) { oprot.writeFieldBegin(DELETE_MANAGED_DIR_FIELD_DESC); oprot.writeBool(struct.deleteManagedDir); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class DropDatabaseRequestTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public DropDatabaseRequestTupleScheme getScheme() { return new DropDatabaseRequestTupleScheme(); } } private static class DropDatabaseRequestTupleScheme extends org.apache.thrift.scheme.TupleScheme<DropDatabaseRequest> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, DropDatabaseRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; oprot.writeString(struct.name); oprot.writeBool(struct.ignoreUnknownDb); oprot.writeBool(struct.deleteData); oprot.writeBool(struct.cascade); java.util.BitSet optionals = new java.util.BitSet(); if (struct.isSetCatalogName()) { optionals.set(0); } if (struct.isSetSoftDelete()) { optionals.set(1); } if (struct.isSetTxnId()) { optionals.set(2); } if (struct.isSetDeleteManagedDir()) { optionals.set(3); } oprot.writeBitSet(optionals, 4); if (struct.isSetCatalogName()) { oprot.writeString(struct.catalogName); } if (struct.isSetSoftDelete()) { oprot.writeBool(struct.softDelete); } if (struct.isSetTxnId()) { oprot.writeI64(struct.txnId); } if (struct.isSetDeleteManagedDir()) { oprot.writeBool(struct.deleteManagedDir); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, DropDatabaseRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; struct.name = iprot.readString(); struct.setNameIsSet(true); struct.ignoreUnknownDb = iprot.readBool(); struct.setIgnoreUnknownDbIsSet(true); struct.deleteData = iprot.readBool(); struct.setDeleteDataIsSet(true); struct.cascade = iprot.readBool(); struct.setCascadeIsSet(true); java.util.BitSet incoming = iprot.readBitSet(4); if (incoming.get(0)) { struct.catalogName = iprot.readString(); struct.setCatalogNameIsSet(true); } if (incoming.get(1)) { struct.softDelete = iprot.readBool(); struct.setSoftDeleteIsSet(true); } if (incoming.get(2)) { struct.txnId = iprot.readI64(); struct.setTxnIdIsSet(true); } if (incoming.get(3)) { struct.deleteManagedDir = iprot.readBool(); struct.setDeleteManagedDirIsSet(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(); } }
google/flatbuffers
37,266
java/src/main/java/com/google/flatbuffers/FlexBuffers.java
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.flatbuffers; import static com.google.flatbuffers.FlexBuffers.Unsigned.byteToUnsignedInt; import static com.google.flatbuffers.FlexBuffers.Unsigned.intToUnsignedLong; import static com.google.flatbuffers.FlexBuffers.Unsigned.shortToUnsignedInt; import java.nio.ByteBuffer; /// @file /// @addtogroup flatbuffers_java_api /// @{ /** * This class can be used to parse FlexBuffer messages. * * <p>For generating FlexBuffer messages, use {@link FlexBuffersBuilder}. * * <p>Example of usage: * * <pre> * ReadBuf bb = ... // load message from file or network * FlexBuffers.Reference r = FlexBuffers.getRoot(bb); // Reads the root element * FlexBuffers.Map map = r.asMap(); // We assumed root object is a map * System.out.println(map.get("name").asString()); // prints element with key "name" * </pre> */ public class FlexBuffers { // These are used as the upper 6 bits of a type field to indicate the actual // type. /** Represent a null type */ public static final int FBT_NULL = 0; /** Represent a signed integer type */ public static final int FBT_INT = 1; /** Represent a unsigned type */ public static final int FBT_UINT = 2; /** Represent a float type */ public static final int FBT_FLOAT = 3; // Types above stored inline, types below store an offset. /** Represent a key to a map type */ public static final int FBT_KEY = 4; /** Represent a string type */ public static final int FBT_STRING = 5; /** Represent a indirect signed integer type */ public static final int FBT_INDIRECT_INT = 6; /** Represent a indirect unsigned integer type */ public static final int FBT_INDIRECT_UINT = 7; /** Represent a indirect float type */ public static final int FBT_INDIRECT_FLOAT = 8; /** Represent a map type */ public static final int FBT_MAP = 9; /** Represent a vector type */ public static final int FBT_VECTOR = 10; // Untyped. /** Represent a vector of signed integers type */ public static final int FBT_VECTOR_INT = 11; // Typed any size = stores no type table). /** Represent a vector of unsigned integers type */ public static final int FBT_VECTOR_UINT = 12; /** Represent a vector of floats type */ public static final int FBT_VECTOR_FLOAT = 13; /** Represent a vector of keys type */ public static final int FBT_VECTOR_KEY = 14; /** Represent a vector of strings type */ // DEPRECATED, use FBT_VECTOR or FBT_VECTOR_KEY instead. // more info on thttps://github.com/google/flatbuffers/issues/5627. public static final int FBT_VECTOR_STRING_DEPRECATED = 15; /// @cond FLATBUFFERS_INTERNAL public static final int FBT_VECTOR_INT2 = 16; // Typed tuple = no type table; no size field). public static final int FBT_VECTOR_UINT2 = 17; public static final int FBT_VECTOR_FLOAT2 = 18; public static final int FBT_VECTOR_INT3 = 19; // Typed triple = no type table; no size field). public static final int FBT_VECTOR_UINT3 = 20; public static final int FBT_VECTOR_FLOAT3 = 21; public static final int FBT_VECTOR_INT4 = 22; // Typed quad = no type table; no size field). public static final int FBT_VECTOR_UINT4 = 23; public static final int FBT_VECTOR_FLOAT4 = 24; /// @endcond FLATBUFFERS_INTERNAL /** Represent a blob type */ public static final int FBT_BLOB = 25; /** Represent a boolean type */ public static final int FBT_BOOL = 26; /** Represent a vector of booleans type */ public static final int FBT_VECTOR_BOOL = 36; // To Allow the same type of conversion of type to vector type private static final ReadBuf EMPTY_BB = new ArrayReadWriteBuf(new byte[] {0}, 1); /** * Checks where a type is a typed vector * * @param type type to be checked * @return true if typed vector */ static boolean isTypedVector(int type) { return (type >= FBT_VECTOR_INT && type <= FBT_VECTOR_STRING_DEPRECATED) || type == FBT_VECTOR_BOOL; } /** * Check whether you can access type directly (no indirection) or not. * * @param type type to be checked * @return true if inline type */ static boolean isTypeInline(int type) { return type <= FBT_FLOAT || type == FBT_BOOL; } static int toTypedVectorElementType(int original_type) { return original_type - FBT_VECTOR_INT + FBT_INT; } /** * Return a vector type our of a original element type * * @param type element type * @param fixedLength size of element * @return typed vector type */ static int toTypedVector(int type, int fixedLength) { assert (isTypedVectorElementType(type)); switch (fixedLength) { case 0: return type - FBT_INT + FBT_VECTOR_INT; case 2: return type - FBT_INT + FBT_VECTOR_INT2; case 3: return type - FBT_INT + FBT_VECTOR_INT3; case 4: return type - FBT_INT + FBT_VECTOR_INT4; default: assert (false); return FBT_NULL; } } static boolean isTypedVectorElementType(int type) { return (type >= FBT_INT && type <= FBT_KEY) || type == FBT_BOOL; } // return position of the element that the offset is pointing to private static int indirect(ReadBuf bb, int offset, int byteWidth) { // we assume all offset fits on a int, since ReadBuf operates with that assumption return (int) (offset - readUInt(bb, offset, byteWidth)); } // read unsigned int with size byteWidth and return as a 64-bit integer private static long readUInt(ReadBuf buff, int end, int byteWidth) { switch (byteWidth) { case 1: return byteToUnsignedInt(buff.get(end)); case 2: return shortToUnsignedInt(buff.getShort(end)); case 4: return intToUnsignedLong(buff.getInt(end)); case 8: return buff.getLong( end); // We are passing signed long here. Losing information (user should know) default: return -1; // we should never reach here } } // read signed int of size byteWidth and return as 32-bit int private static int readInt(ReadBuf buff, int end, int byteWidth) { return (int) readLong(buff, end, byteWidth); } // read signed int of size byteWidth and return as 64-bit int private static long readLong(ReadBuf buff, int end, int byteWidth) { switch (byteWidth) { case 1: return buff.get(end); case 2: return buff.getShort(end); case 4: return buff.getInt(end); case 8: return buff.getLong(end); default: return -1; // we should never reach here } } private static double readDouble(ReadBuf buff, int end, int byteWidth) { switch (byteWidth) { case 4: return buff.getFloat(end); case 8: return buff.getDouble(end); default: return -1; // we should never reach here } } /** * Reads a FlexBuffer message in ReadBuf and returns {@link Reference} to the root element. * * @param buffer ReadBuf containing FlexBuffer message * @return {@link Reference} to the root object */ @Deprecated public static Reference getRoot(ByteBuffer buffer) { return getRoot( buffer.hasArray() ? new ArrayReadWriteBuf(buffer.array(), buffer.limit()) : new ByteBufferReadWriteBuf(buffer)); } /** * Reads a FlexBuffer message in ReadBuf and returns {@link Reference} to the root element. * * @param buffer ReadBuf containing FlexBuffer message * @return {@link Reference} to the root object */ public static Reference getRoot(ReadBuf buffer) { // See Finish() below for the serialization counterpart of this. // The root ends at the end of the buffer, so we parse backwards from there. int end = buffer.limit(); int byteWidth = buffer.get(--end); int packetType = byteToUnsignedInt(buffer.get(--end)); end -= byteWidth; // The root data item. return new Reference(buffer, end, byteWidth, packetType); } /** Represents an generic element in the buffer. */ public static class Reference { private static final Reference NULL_REFERENCE = new Reference(EMPTY_BB, 0, 1, 0); private ReadBuf bb; private int end; private int parentWidth; private int byteWidth; private int type; Reference(ReadBuf bb, int end, int parentWidth, int packedType) { this(bb, end, parentWidth, (1 << (packedType & 3)), packedType >> 2); } Reference(ReadBuf bb, int end, int parentWidth, int byteWidth, int type) { this.bb = bb; this.end = end; this.parentWidth = parentWidth; this.byteWidth = byteWidth; this.type = type; } /** * Return element type * * @return element type as integer */ public int getType() { return type; } /** * Checks whether the element is null type * * @return true if null type */ public boolean isNull() { return type == FBT_NULL; } /** * Checks whether the element is boolean type * * @return true if boolean type */ public boolean isBoolean() { return type == FBT_BOOL; } /** * Checks whether the element type is numeric (signed/unsigned integers and floats) * * @return true if numeric type */ public boolean isNumeric() { return isIntOrUInt() || isFloat(); } /** * Checks whether the element type is signed or unsigned integers * * @return true if an integer type */ public boolean isIntOrUInt() { return isInt() || isUInt(); } /** * Checks whether the element type is float * * @return true if a float type */ public boolean isFloat() { return type == FBT_FLOAT || type == FBT_INDIRECT_FLOAT; } /** * Checks whether the element type is signed integer * * @return true if a signed integer type */ public boolean isInt() { return type == FBT_INT || type == FBT_INDIRECT_INT; } /** * Checks whether the element type is signed integer * * @return true if a signed integer type */ public boolean isUInt() { return type == FBT_UINT || type == FBT_INDIRECT_UINT; } /** * Checks whether the element type is string * * @return true if a string type */ public boolean isString() { return type == FBT_STRING; } /** * Checks whether the element type is key * * @return true if a key type */ public boolean isKey() { return type == FBT_KEY; } /** * Checks whether the element type is vector * * @return true if a vector type */ public boolean isVector() { return type == FBT_VECTOR || type == FBT_MAP; } /** * Checks whether the element type is typed vector * * @return true if a typed vector type */ public boolean isTypedVector() { return FlexBuffers.isTypedVector(type); } /** * Checks whether the element type is a map * * @return true if a map type */ public boolean isMap() { return type == FBT_MAP; } /** * Checks whether the element type is a blob * * @return true if a blob type */ public boolean isBlob() { return type == FBT_BLOB; } /** * Returns element as 32-bit integer. * * <p>For vector element, it will return size of the vector * * <p>For String element, it will type to be parsed as integer * * <p>Unsigned elements will become negative * * <p>Float elements will be casted to integer * * @return 32-bit integer or 0 if fail to convert element to integer. */ public int asInt() { if (type == FBT_INT) { // A fast path for the common case. return readInt(bb, end, parentWidth); } else switch (type) { case FBT_INDIRECT_INT: return readInt(bb, indirect(bb, end, parentWidth), byteWidth); case FBT_UINT: return (int) readUInt(bb, end, parentWidth); case FBT_INDIRECT_UINT: return (int) readUInt(bb, indirect(bb, end, parentWidth), parentWidth); case FBT_FLOAT: return (int) readDouble(bb, end, parentWidth); case FBT_INDIRECT_FLOAT: return (int) readDouble(bb, indirect(bb, end, parentWidth), byteWidth); case FBT_NULL: return 0; case FBT_STRING: return Integer.parseInt(asString()); case FBT_VECTOR: return asVector().size(); case FBT_BOOL: return readInt(bb, end, parentWidth); default: // Convert other things to int. return 0; } } /** * Returns element as unsigned 64-bit integer. * * <p>For vector element, it will return size of the vector * * <p>For String element, it will type to be parsed as integer * * <p>Negative signed elements will become unsigned counterpart * * <p>Float elements will be casted to integer * * @return 64-bit integer or 0 if fail to convert element to integer. */ public long asUInt() { if (type == FBT_UINT) { // A fast path for the common case. return readUInt(bb, end, parentWidth); } else switch (type) { case FBT_INDIRECT_UINT: return readUInt(bb, indirect(bb, end, parentWidth), byteWidth); case FBT_INT: return readLong(bb, end, parentWidth); case FBT_INDIRECT_INT: return readLong(bb, indirect(bb, end, parentWidth), byteWidth); case FBT_FLOAT: return (long) readDouble(bb, end, parentWidth); case FBT_INDIRECT_FLOAT: return (long) readDouble(bb, indirect(bb, end, parentWidth), parentWidth); case FBT_NULL: return 0; case FBT_STRING: return Long.parseLong(asString()); case FBT_VECTOR: return asVector().size(); case FBT_BOOL: return readInt(bb, end, parentWidth); default: // Convert other things to uint. return 0; } } /** * Returns element as 64-bit integer. * * <p>For vector element, it will return size of the vector * * <p>For String element, it will type to be parsed as integer * * <p>Unsigned elements will become negative * * <p>Float elements will be casted to integer * * @return 64-bit integer or 0 if fail to convert element to long. */ public long asLong() { if (type == FBT_INT) { // A fast path for the common case. return readLong(bb, end, parentWidth); } else switch (type) { case FBT_INDIRECT_INT: return readLong(bb, indirect(bb, end, parentWidth), byteWidth); case FBT_UINT: return readUInt(bb, end, parentWidth); case FBT_INDIRECT_UINT: return readUInt(bb, indirect(bb, end, parentWidth), parentWidth); case FBT_FLOAT: return (long) readDouble(bb, end, parentWidth); case FBT_INDIRECT_FLOAT: return (long) readDouble(bb, indirect(bb, end, parentWidth), byteWidth); case FBT_NULL: return 0; case FBT_STRING: { try { return Long.parseLong(asString()); } catch (NumberFormatException nfe) { return 0; // same as C++ implementation } } case FBT_VECTOR: return asVector().size(); case FBT_BOOL: return readInt(bb, end, parentWidth); default: // Convert other things to int. return 0; } } /** * Returns element as 64-bit integer. * * <p>For vector element, it will return size of the vector * * <p>For String element, it will type to be parsed as integer * * @return 64-bit integer or 0 if fail to convert element to long. */ public double asFloat() { if (type == FBT_FLOAT) { // A fast path for the common case. return readDouble(bb, end, parentWidth); } else switch (type) { case FBT_INDIRECT_FLOAT: return readDouble(bb, indirect(bb, end, parentWidth), byteWidth); case FBT_INT: return readInt(bb, end, parentWidth); case FBT_UINT: case FBT_BOOL: return readUInt(bb, end, parentWidth); case FBT_INDIRECT_INT: return readInt(bb, indirect(bb, end, parentWidth), byteWidth); case FBT_INDIRECT_UINT: return readUInt(bb, indirect(bb, end, parentWidth), byteWidth); case FBT_NULL: return 0.0; case FBT_STRING: return Double.parseDouble(asString()); case FBT_VECTOR: return asVector().size(); default: // Convert strings and other things to float. return 0; } } /** * Returns element as a {@link Key} * * @return key or {@link Key#empty()} if element is not a key */ public Key asKey() { if (isKey()) { return new Key(bb, indirect(bb, end, parentWidth), byteWidth); } else { return Key.empty(); } } /** * Returns element as a `String` * * @return element as `String` or empty `String` if fail */ public String asString() { if (isString()) { int start = indirect(bb, end, parentWidth); int size = (int) readUInt(bb, start - byteWidth, byteWidth); return bb.getString(start, size); } else if (isKey()) { int start = indirect(bb, end, byteWidth); for (int i = start; ; i++) { if (bb.get(i) == 0) { return bb.getString(start, i - start); } } } else { return ""; } } /** * Returns element as a {@link Map} * * @return element as {@link Map} or empty {@link Map} if fail */ public Map asMap() { if (isMap()) { return new Map(bb, indirect(bb, end, parentWidth), byteWidth); } else { return Map.empty(); } } /** * Returns element as a {@link Vector} * * @return element as {@link Vector} or empty {@link Vector} if fail */ public Vector asVector() { if (isVector()) { return new Vector(bb, indirect(bb, end, parentWidth), byteWidth); } else if (type == FlexBuffers.FBT_VECTOR_STRING_DEPRECATED) { // deprecated. Should be treated as key vector return new TypedVector(bb, indirect(bb, end, parentWidth), byteWidth, FlexBuffers.FBT_KEY); } else if (FlexBuffers.isTypedVector(type)) { return new TypedVector( bb, indirect(bb, end, parentWidth), byteWidth, FlexBuffers.toTypedVectorElementType(type)); } else { return Vector.empty(); } } /** * Returns element as a {@link Blob} * * @return element as {@link Blob} or empty {@link Blob} if fail */ public Blob asBlob() { if (isBlob() || isString()) { return new Blob(bb, indirect(bb, end, parentWidth), byteWidth); } else { return Blob.empty(); } } /** * Returns element as a boolean * * <p>If element type is not boolean, it will be casted to integer and compared against 0 * * @return element as boolean */ public boolean asBoolean() { if (isBoolean()) { return bb.get(end) != 0; } return asUInt() != 0; } /** * Returns text representation of the element (JSON) * * @return String containing text representation of the element */ @Override public String toString() { return toString(new StringBuilder(128)).toString(); } /** Appends a text(JSON) representation to a `StringBuilder` */ StringBuilder toString(StringBuilder sb) { // TODO: Original C++ implementation escape strings. // probably we should do it as well. switch (type) { case FBT_NULL: return sb.append("null"); case FBT_INT: case FBT_INDIRECT_INT: return sb.append(asLong()); case FBT_UINT: case FBT_INDIRECT_UINT: return sb.append(asUInt()); case FBT_INDIRECT_FLOAT: case FBT_FLOAT: return sb.append(asFloat()); case FBT_KEY: return asKey().toString(sb.append('"')).append('"'); case FBT_STRING: return sb.append('"').append(asString()).append('"'); case FBT_MAP: return asMap().toString(sb); case FBT_VECTOR: return asVector().toString(sb); case FBT_BLOB: return asBlob().toString(sb); case FBT_BOOL: return sb.append(asBoolean()); case FBT_VECTOR_INT: case FBT_VECTOR_UINT: case FBT_VECTOR_FLOAT: case FBT_VECTOR_KEY: case FBT_VECTOR_STRING_DEPRECATED: case FBT_VECTOR_BOOL: return sb.append(asVector()); case FBT_VECTOR_INT2: case FBT_VECTOR_UINT2: case FBT_VECTOR_FLOAT2: case FBT_VECTOR_INT3: case FBT_VECTOR_UINT3: case FBT_VECTOR_FLOAT3: case FBT_VECTOR_INT4: case FBT_VECTOR_UINT4: case FBT_VECTOR_FLOAT4: throw new FlexBufferException("not_implemented:" + type); default: return sb; } } } /** Base class of all types below. Points into the data buffer and allows access to one type. */ private abstract static class Object { ReadBuf bb; int end; int byteWidth; Object(ReadBuf buff, int end, int byteWidth) { this.bb = buff; this.end = end; this.byteWidth = byteWidth; } @Override public String toString() { return toString(new StringBuilder(128)).toString(); } public abstract StringBuilder toString(StringBuilder sb); } // Stores size in `byte_width_` bytes before end position. private abstract static class Sized extends Object { protected final int size; Sized(ReadBuf buff, int end, int byteWidth) { super(buff, end, byteWidth); size = (int) readUInt(bb, end - byteWidth, byteWidth); } public int size() { return size; } } /** * Represents a array of bytes element in the buffer * * <p>It can be converted to `ReadBuf` using {@link data()}, copied into a byte[] using {@link * getBytes()} or have individual bytes accessed individually using {@link get(int)} */ public static class Blob extends Sized { static final Blob EMPTY = new Blob(EMPTY_BB, 1, 1); Blob(ReadBuf buff, int end, int byteWidth) { super(buff, end, byteWidth); } /** Return an empty {@link Blob} */ public static Blob empty() { return EMPTY; } /** * Return {@link Blob} as `ReadBuf` * * @return blob as `ReadBuf` */ public ByteBuffer data() { ByteBuffer dup = ByteBuffer.wrap(bb.data()); dup.position(end); dup.limit(end + size()); return dup.asReadOnlyBuffer().slice(); } /** * Copy blob into a byte[] * * @return blob as a byte[] */ public byte[] getBytes() { int size = size(); byte[] result = new byte[size]; for (int i = 0; i < size; i++) { result[i] = bb.get(end + i); } return result; } /** * Return individual byte at a given position * * @param pos position of the byte to be read */ public byte get(int pos) { assert pos >= 0 && pos <= size(); return bb.get(end + pos); } /** Returns a text(JSON) representation of the {@link Blob} */ @Override public String toString() { return bb.getString(end, size()); } /** Append a text(JSON) representation of the {@link Blob} into a `StringBuilder` */ @Override public StringBuilder toString(StringBuilder sb) { sb.append('"'); sb.append(bb.getString(end, size())); return sb.append('"'); } } /** Represents a key element in the buffer. Keys are used to reference objects in a {@link Map} */ public static class Key extends Object { private static final Key EMPTY = new Key(EMPTY_BB, 0, 0); Key(ReadBuf buff, int end, int byteWidth) { super(buff, end, byteWidth); } /** * Return an empty {@link Key} * * @return empty {@link Key} */ public static Key empty() { return Key.EMPTY; } /** Appends a text(JSON) representation to a `StringBuilder` */ @Override public StringBuilder toString(StringBuilder sb) { return sb.append(toString()); } @Override public String toString() { int size; for (int i = end; ; i++) { if (bb.get(i) == 0) { size = i - end; break; } } return bb.getString(end, size); } int compareTo(byte[] other) { int ia = end; int io = 0; byte c1, c2; do { c1 = bb.get(ia); c2 = other[io]; if (c1 == '\0') return c1 - c2; ia++; io++; if (io == other.length) { // in our buffer we have an additional \0 byte // but this does not exist in regular Java strings, so we return now int cmp = c1 - c2; if (cmp != 0 || bb.get(ia) == '\0') { return cmp; } else { return 1; } } } while (c1 == c2); return c1 - c2; } /** * Compare keys * * @param obj other key to compare * @return true if keys are the same */ @Override public boolean equals(java.lang.Object obj) { if (!(obj instanceof Key)) return false; return ((Key) obj).end == end && ((Key) obj).byteWidth == byteWidth; } public int hashCode() { return end ^ byteWidth; } } /** Map object representing a set of key-value pairs. */ public static class Map extends Vector { private static final Map EMPTY_MAP = new Map(EMPTY_BB, 1, 1); // cache for converting UTF-8 codepoints into // Java chars. Used to speed up String comparison private final byte[] comparisonBuffer = new byte[4]; Map(ReadBuf bb, int end, int byteWidth) { super(bb, end, byteWidth); } /** * Returns an empty {@link Map} * * @return an empty {@link Map} */ public static Map empty() { return EMPTY_MAP; } /** * @param key access key to element on map * @return reference to value in map */ public Reference get(String key) { int index = binarySearch(key); if (index >= 0 && index < size) { return get(index); } return Reference.NULL_REFERENCE; } /** * @param key access key to element on map. Keys are assumed to be encoded in UTF-8 * @return reference to value in map */ public Reference get(byte[] key) { int index = binarySearch(key); if (index >= 0 && index < size) { return get(index); } return Reference.NULL_REFERENCE; } /** * Get a vector or keys in the map * * @return vector of keys */ public KeyVector keys() { final int num_prefixed_fields = 3; int keysOffset = end - (byteWidth * num_prefixed_fields); return new KeyVector( new TypedVector( bb, indirect(bb, keysOffset, byteWidth), readInt(bb, keysOffset + byteWidth, byteWidth), FBT_KEY)); } /** * @return {@code Vector} of values from map */ public Vector values() { return new Vector(bb, end, byteWidth); } /** * Writes text (json) representation of map in a {@code StringBuilder}. * * @param builder {@code StringBuilder} to be appended to * @return Same {@code StringBuilder} with appended text */ public StringBuilder toString(StringBuilder builder) { builder.append("{ "); KeyVector keys = keys(); int size = size(); Vector vals = values(); for (int i = 0; i < size; i++) { builder.append('"').append(keys.get(i).toString()).append("\" : "); builder.append(vals.get(i).toString()); if (i != size - 1) builder.append(", "); } builder.append(" }"); return builder; } // Performs a binary search on a key vector and return index of the key in key vector private int binarySearch(CharSequence searchedKey) { int low = 0; int high = size - 1; final int num_prefixed_fields = 3; int keysOffset = end - (byteWidth * num_prefixed_fields); int keysStart = indirect(bb, keysOffset, byteWidth); int keyByteWidth = readInt(bb, keysOffset + byteWidth, byteWidth); while (low <= high) { int mid = (low + high) >>> 1; int keyPos = indirect(bb, keysStart + mid * keyByteWidth, keyByteWidth); int cmp = compareCharSequence(keyPos, searchedKey); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } private int binarySearch(byte[] searchedKey) { int low = 0; int high = size - 1; final int num_prefixed_fields = 3; int keysOffset = end - (byteWidth * num_prefixed_fields); int keysStart = indirect(bb, keysOffset, byteWidth); int keyByteWidth = readInt(bb, keysOffset + byteWidth, byteWidth); while (low <= high) { int mid = (low + high) >>> 1; int keyPos = indirect(bb, keysStart + mid * keyByteWidth, keyByteWidth); int cmp = compareBytes(bb, keyPos, searchedKey); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } // compares a byte[] against a FBT_KEY private int compareBytes(ReadBuf bb, int start, byte[] other) { int l1 = start; int l2 = 0; byte c1, c2; do { c1 = bb.get(l1); c2 = other[l2]; if (c1 == '\0') return c1 - c2; l1++; l2++; if (l2 == other.length) { // in our buffer we have an additional \0 byte // but this does not exist in regular Java strings, so we return now int cmp = c1 - c2; if (cmp != 0 || bb.get(l1) == '\0') { return cmp; } else { return 1; } } } while (c1 == c2); return c1 - c2; } // compares a CharSequence against a FBT_KEY private int compareCharSequence(int start, CharSequence other) { int bufferPos = start; int otherPos = 0; int limit = bb.limit(); int otherLimit = other.length(); // special loop for ASCII characters. Most of keys should be ASCII only, so this // loop should be optimized for that. // breaks if a multi-byte character is found while (otherPos < otherLimit) { char c2 = other.charAt(otherPos); if (c2 >= 0x80) { // not a single byte codepoint break; } byte b = bb.get(bufferPos); if (b == 0) { return -c2; } else if (b < 0) { break; } else if ((char) b != c2) { return b - c2; } ++bufferPos; ++otherPos; } while (bufferPos < limit) { int sizeInBuff = Utf8.encodeUtf8CodePoint(other, otherPos, comparisonBuffer); if (sizeInBuff == 0) { // That means we finish with other and there are not more chars to // compare. String in the buffer is bigger. return bb.get(bufferPos); } for (int i = 0; i < sizeInBuff; i++) { byte bufferByte = bb.get(bufferPos++); byte otherByte = comparisonBuffer[i]; if (bufferByte == 0) { // Our key is finished, so other is bigger return -otherByte; } else if (bufferByte != otherByte) { return bufferByte - otherByte; } } otherPos += sizeInBuff == 4 ? 2 : 1; } return 0; } } /** Object that represents a set of elements in the buffer */ public static class Vector extends Sized { private static final Vector EMPTY_VECTOR = new Vector(EMPTY_BB, 1, 1); Vector(ReadBuf bb, int end, int byteWidth) { super(bb, end, byteWidth); } /** * Returns an empty {@link Map} * * @return an empty {@link Map} */ public static Vector empty() { return EMPTY_VECTOR; } /** * Checks if the vector is empty * * @return true if vector is empty */ public boolean isEmpty() { return this == EMPTY_VECTOR; } /** Appends a text(JSON) representation to a `StringBuilder` */ @Override public StringBuilder toString(StringBuilder sb) { sb.append("[ "); int size = size(); for (int i = 0; i < size; i++) { get(i).toString(sb); if (i != size - 1) { sb.append(", "); } } sb.append(" ]"); return sb; } /** * Get a element in a vector by index * * @param index position of the element * @return {@code Reference} to the element */ public Reference get(int index) { long len = size(); if (index >= len) { return Reference.NULL_REFERENCE; } int packedType = byteToUnsignedInt(bb.get((int) (end + (len * byteWidth) + index))); int obj_end = end + index * byteWidth; return new Reference(bb, obj_end, byteWidth, packedType); } } /** Object that represents a set of elements with the same type */ public static class TypedVector extends Vector { private static final TypedVector EMPTY_VECTOR = new TypedVector(EMPTY_BB, 1, 1, FBT_INT); private final int elemType; TypedVector(ReadBuf bb, int end, int byteWidth, int elemType) { super(bb, end, byteWidth); this.elemType = elemType; } public static TypedVector empty() { return EMPTY_VECTOR; } /** * Returns whether the vector is empty * * @return true if empty */ public boolean isEmptyVector() { return this == EMPTY_VECTOR; } /** * Return element type for all elements in the vector * * @return element type */ public int getElemType() { return elemType; } /** * Get reference to an object in the {@code Vector} * * @param pos position of the object in {@code Vector} * @return reference to element */ @Override public Reference get(int pos) { int len = size(); if (pos >= len) return Reference.NULL_REFERENCE; int childPos = end + pos * byteWidth; return new Reference(bb, childPos, byteWidth, 1, elemType); } } /** Represent a vector of keys in a map */ public static class KeyVector { private final TypedVector vec; KeyVector(TypedVector vec) { this.vec = vec; } /** * Return key * * @param pos position of the key in key vector * @return key */ public Key get(int pos) { int len = size(); if (pos >= len) return Key.EMPTY; int childPos = vec.end + pos * vec.byteWidth; return new Key(vec.bb, indirect(vec.bb, childPos, vec.byteWidth), 1); } /** * Returns size of key vector * * @return size */ public int size() { return vec.size(); } /** Returns a text(JSON) representation */ public String toString() { StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; i < vec.size(); i++) { vec.get(i).toString(b); if (i != vec.size() - 1) { b.append(", "); } } return b.append("]").toString(); } } public static class FlexBufferException extends RuntimeException { FlexBufferException(String msg) { super(msg); } } static class Unsigned { static int byteToUnsignedInt(byte x) { return ((int) x) & 0xff; } static int shortToUnsignedInt(short x) { return ((int) x) & 0xffff; } static long intToUnsignedLong(int x) { return ((long) x) & 0xffffffffL; } } } /// @}
googleapis/google-cloud-java
37,315
java-geminidataanalytics/proto-google-cloud-geminidataanalytics-v1beta/src/main/java/com/google/cloud/geminidataanalytics/v1beta/ListMessagesResponse.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/data_chat_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.geminidataanalytics.v1beta; /** * * * <pre> * Response for listing chat messages. * </pre> * * Protobuf type {@code google.cloud.geminidataanalytics.v1beta.ListMessagesResponse} */ public final class ListMessagesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.geminidataanalytics.v1beta.ListMessagesResponse) ListMessagesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListMessagesResponse.newBuilder() to construct. private ListMessagesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListMessagesResponse() { messages_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListMessagesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.geminidataanalytics.v1beta.DataChatServiceProto .internal_static_google_cloud_geminidataanalytics_v1beta_ListMessagesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.geminidataanalytics.v1beta.DataChatServiceProto .internal_static_google_cloud_geminidataanalytics_v1beta_ListMessagesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse.class, com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse.Builder.class); } public static final int MESSAGES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.geminidataanalytics.v1beta.StorageMessage> messages_; /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.geminidataanalytics.v1beta.StorageMessage> getMessagesList() { return messages_; } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ @java.lang.Override public java.util.List< ? extends com.google.cloud.geminidataanalytics.v1beta.StorageMessageOrBuilder> getMessagesOrBuilderList() { return messages_; } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ @java.lang.Override public int getMessagesCount() { return messages_.size(); } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ @java.lang.Override public com.google.cloud.geminidataanalytics.v1beta.StorageMessage getMessages(int index) { return messages_.get(index); } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ @java.lang.Override public com.google.cloud.geminidataanalytics.v1beta.StorageMessageOrBuilder getMessagesOrBuilder( int index) { return messages_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token identifying a page of results the server should 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> * A token identifying a page of results the server should 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 < messages_.size(); i++) { output.writeMessage(1, messages_.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 < messages_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, messages_.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.geminidataanalytics.v1beta.ListMessagesResponse)) { return super.equals(obj); } com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse other = (com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse) obj; if (!getMessagesList().equals(other.getMessagesList())) 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 (getMessagesCount() > 0) { hash = (37 * hash) + MESSAGES_FIELD_NUMBER; hash = (53 * hash) + getMessagesList().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.geminidataanalytics.v1beta.ListMessagesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse 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.ListMessagesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse 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.ListMessagesResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse 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.ListMessagesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse 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.ListMessagesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse 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.ListMessagesResponse 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.ListMessagesResponse 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.ListMessagesResponse 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 listing chat messages. * </pre> * * Protobuf type {@code google.cloud.geminidataanalytics.v1beta.ListMessagesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.geminidataanalytics.v1beta.ListMessagesResponse) com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.geminidataanalytics.v1beta.DataChatServiceProto .internal_static_google_cloud_geminidataanalytics_v1beta_ListMessagesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.geminidataanalytics.v1beta.DataChatServiceProto .internal_static_google_cloud_geminidataanalytics_v1beta_ListMessagesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse.class, com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse.Builder.class); } // Construct using com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (messagesBuilder_ == null) { messages_ = java.util.Collections.emptyList(); } else { messages_ = null; messagesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.geminidataanalytics.v1beta.DataChatServiceProto .internal_static_google_cloud_geminidataanalytics_v1beta_ListMessagesResponse_descriptor; } @java.lang.Override public com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse getDefaultInstanceForType() { return com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse build() { com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse buildPartial() { com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse result = new com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse result) { if (messagesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { messages_ = java.util.Collections.unmodifiableList(messages_); bitField0_ = (bitField0_ & ~0x00000001); } result.messages_ = messages_; } else { result.messages_ = messagesBuilder_.build(); } } private void buildPartial0( com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse 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.geminidataanalytics.v1beta.ListMessagesResponse) { return mergeFrom((com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse other) { if (other == com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse.getDefaultInstance()) return this; if (messagesBuilder_ == null) { if (!other.messages_.isEmpty()) { if (messages_.isEmpty()) { messages_ = other.messages_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureMessagesIsMutable(); messages_.addAll(other.messages_); } onChanged(); } } else { if (!other.messages_.isEmpty()) { if (messagesBuilder_.isEmpty()) { messagesBuilder_.dispose(); messagesBuilder_ = null; messages_ = other.messages_; bitField0_ = (bitField0_ & ~0x00000001); messagesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getMessagesFieldBuilder() : null; } else { messagesBuilder_.addAllMessages(other.messages_); } } } 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.geminidataanalytics.v1beta.StorageMessage m = input.readMessage( com.google.cloud.geminidataanalytics.v1beta.StorageMessage.parser(), extensionRegistry); if (messagesBuilder_ == null) { ensureMessagesIsMutable(); messages_.add(m); } else { messagesBuilder_.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.geminidataanalytics.v1beta.StorageMessage> messages_ = java.util.Collections.emptyList(); private void ensureMessagesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { messages_ = new java.util.ArrayList<com.google.cloud.geminidataanalytics.v1beta.StorageMessage>( messages_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.geminidataanalytics.v1beta.StorageMessage, com.google.cloud.geminidataanalytics.v1beta.StorageMessage.Builder, com.google.cloud.geminidataanalytics.v1beta.StorageMessageOrBuilder> messagesBuilder_; /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public java.util.List<com.google.cloud.geminidataanalytics.v1beta.StorageMessage> getMessagesList() { if (messagesBuilder_ == null) { return java.util.Collections.unmodifiableList(messages_); } else { return messagesBuilder_.getMessageList(); } } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public int getMessagesCount() { if (messagesBuilder_ == null) { return messages_.size(); } else { return messagesBuilder_.getCount(); } } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public com.google.cloud.geminidataanalytics.v1beta.StorageMessage getMessages(int index) { if (messagesBuilder_ == null) { return messages_.get(index); } else { return messagesBuilder_.getMessage(index); } } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public Builder setMessages( int index, com.google.cloud.geminidataanalytics.v1beta.StorageMessage value) { if (messagesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMessagesIsMutable(); messages_.set(index, value); onChanged(); } else { messagesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public Builder setMessages( int index, com.google.cloud.geminidataanalytics.v1beta.StorageMessage.Builder builderForValue) { if (messagesBuilder_ == null) { ensureMessagesIsMutable(); messages_.set(index, builderForValue.build()); onChanged(); } else { messagesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public Builder addMessages(com.google.cloud.geminidataanalytics.v1beta.StorageMessage value) { if (messagesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMessagesIsMutable(); messages_.add(value); onChanged(); } else { messagesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public Builder addMessages( int index, com.google.cloud.geminidataanalytics.v1beta.StorageMessage value) { if (messagesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMessagesIsMutable(); messages_.add(index, value); onChanged(); } else { messagesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public Builder addMessages( com.google.cloud.geminidataanalytics.v1beta.StorageMessage.Builder builderForValue) { if (messagesBuilder_ == null) { ensureMessagesIsMutable(); messages_.add(builderForValue.build()); onChanged(); } else { messagesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public Builder addMessages( int index, com.google.cloud.geminidataanalytics.v1beta.StorageMessage.Builder builderForValue) { if (messagesBuilder_ == null) { ensureMessagesIsMutable(); messages_.add(index, builderForValue.build()); onChanged(); } else { messagesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public Builder addAllMessages( java.lang.Iterable<? extends com.google.cloud.geminidataanalytics.v1beta.StorageMessage> values) { if (messagesBuilder_ == null) { ensureMessagesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, messages_); onChanged(); } else { messagesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public Builder clearMessages() { if (messagesBuilder_ == null) { messages_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { messagesBuilder_.clear(); } return this; } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public Builder removeMessages(int index) { if (messagesBuilder_ == null) { ensureMessagesIsMutable(); messages_.remove(index); onChanged(); } else { messagesBuilder_.remove(index); } return this; } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public com.google.cloud.geminidataanalytics.v1beta.StorageMessage.Builder getMessagesBuilder( int index) { return getMessagesFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public com.google.cloud.geminidataanalytics.v1beta.StorageMessageOrBuilder getMessagesOrBuilder( int index) { if (messagesBuilder_ == null) { return messages_.get(index); } else { return messagesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public java.util.List< ? extends com.google.cloud.geminidataanalytics.v1beta.StorageMessageOrBuilder> getMessagesOrBuilderList() { if (messagesBuilder_ != null) { return messagesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(messages_); } } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public com.google.cloud.geminidataanalytics.v1beta.StorageMessage.Builder addMessagesBuilder() { return getMessagesFieldBuilder() .addBuilder( com.google.cloud.geminidataanalytics.v1beta.StorageMessage.getDefaultInstance()); } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public com.google.cloud.geminidataanalytics.v1beta.StorageMessage.Builder addMessagesBuilder( int index) { return getMessagesFieldBuilder() .addBuilder( index, com.google.cloud.geminidataanalytics.v1beta.StorageMessage.getDefaultInstance()); } /** * * * <pre> * The list of chat messages. * </pre> * * <code>repeated .google.cloud.geminidataanalytics.v1beta.StorageMessage messages = 1;</code> */ public java.util.List<com.google.cloud.geminidataanalytics.v1beta.StorageMessage.Builder> getMessagesBuilderList() { return getMessagesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.geminidataanalytics.v1beta.StorageMessage, com.google.cloud.geminidataanalytics.v1beta.StorageMessage.Builder, com.google.cloud.geminidataanalytics.v1beta.StorageMessageOrBuilder> getMessagesFieldBuilder() { if (messagesBuilder_ == null) { messagesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.geminidataanalytics.v1beta.StorageMessage, com.google.cloud.geminidataanalytics.v1beta.StorageMessage.Builder, com.google.cloud.geminidataanalytics.v1beta.StorageMessageOrBuilder>( messages_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); messages_ = null; } return messagesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token identifying a page of results the server should 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> * A token identifying a page of results the server should 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> * A token identifying a page of results the server should 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> * A token identifying a page of results the server should 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> * A token identifying a page of results the server should 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.cloud.geminidataanalytics.v1beta.ListMessagesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.geminidataanalytics.v1beta.ListMessagesResponse) private static final com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse(); } public static com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListMessagesResponse> PARSER = new com.google.protobuf.AbstractParser<ListMessagesResponse>() { @java.lang.Override public ListMessagesResponse 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<ListMessagesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListMessagesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.geminidataanalytics.v1beta.ListMessagesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,444
java-netapp/proto-google-cloud-netapp-v1/src/main/java/com/google/cloud/netapp/v1/UpdateActiveDirectoryRequest.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/active_directory.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.netapp.v1; /** * * * <pre> * UpdateActiveDirectoryRequest for updating an active directory. * </pre> * * Protobuf type {@code google.cloud.netapp.v1.UpdateActiveDirectoryRequest} */ public final class UpdateActiveDirectoryRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.netapp.v1.UpdateActiveDirectoryRequest) UpdateActiveDirectoryRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateActiveDirectoryRequest.newBuilder() to construct. private UpdateActiveDirectoryRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateActiveDirectoryRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateActiveDirectoryRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.netapp.v1.ActiveDirectoryProto .internal_static_google_cloud_netapp_v1_UpdateActiveDirectoryRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.netapp.v1.ActiveDirectoryProto .internal_static_google_cloud_netapp_v1_UpdateActiveDirectoryRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest.class, com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest.Builder.class); } private int bitField0_; public static final int UPDATE_MASK_FIELD_NUMBER = 1; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * Active Directory resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. If the * user does not provide a mask then all fields will be overwritten. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * Active Directory resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. If the * user does not provide a mask then all fields will be overwritten. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * Active Directory resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. If the * user does not provide a mask then all fields will be overwritten. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } public static final int ACTIVE_DIRECTORY_FIELD_NUMBER = 2; private com.google.cloud.netapp.v1.ActiveDirectory activeDirectory_; /** * * * <pre> * Required. The volume being updated * </pre> * * <code> * .google.cloud.netapp.v1.ActiveDirectory active_directory = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the activeDirectory field is set. */ @java.lang.Override public boolean hasActiveDirectory() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The volume being updated * </pre> * * <code> * .google.cloud.netapp.v1.ActiveDirectory active_directory = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The activeDirectory. */ @java.lang.Override public com.google.cloud.netapp.v1.ActiveDirectory getActiveDirectory() { return activeDirectory_ == null ? com.google.cloud.netapp.v1.ActiveDirectory.getDefaultInstance() : activeDirectory_; } /** * * * <pre> * Required. The volume being updated * </pre> * * <code> * .google.cloud.netapp.v1.ActiveDirectory active_directory = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.netapp.v1.ActiveDirectoryOrBuilder getActiveDirectoryOrBuilder() { return activeDirectory_ == null ? com.google.cloud.netapp.v1.ActiveDirectory.getDefaultInstance() : activeDirectory_; } 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, getActiveDirectory()); } 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, getActiveDirectory()); } 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.UpdateActiveDirectoryRequest)) { return super.equals(obj); } com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest other = (com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest) obj; if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (hasActiveDirectory() != other.hasActiveDirectory()) return false; if (hasActiveDirectory()) { if (!getActiveDirectory().equals(other.getActiveDirectory())) 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 (hasActiveDirectory()) { hash = (37 * hash) + ACTIVE_DIRECTORY_FIELD_NUMBER; hash = (53 * hash) + getActiveDirectory().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest 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.UpdateActiveDirectoryRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest 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.UpdateActiveDirectoryRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest 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.UpdateActiveDirectoryRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest 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.UpdateActiveDirectoryRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest 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.UpdateActiveDirectoryRequest 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.UpdateActiveDirectoryRequest 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.UpdateActiveDirectoryRequest 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> * UpdateActiveDirectoryRequest for updating an active directory. * </pre> * * Protobuf type {@code google.cloud.netapp.v1.UpdateActiveDirectoryRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.netapp.v1.UpdateActiveDirectoryRequest) com.google.cloud.netapp.v1.UpdateActiveDirectoryRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.netapp.v1.ActiveDirectoryProto .internal_static_google_cloud_netapp_v1_UpdateActiveDirectoryRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.netapp.v1.ActiveDirectoryProto .internal_static_google_cloud_netapp_v1_UpdateActiveDirectoryRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest.class, com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest.Builder.class); } // Construct using com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest.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(); getActiveDirectoryFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } activeDirectory_ = null; if (activeDirectoryBuilder_ != null) { activeDirectoryBuilder_.dispose(); activeDirectoryBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.netapp.v1.ActiveDirectoryProto .internal_static_google_cloud_netapp_v1_UpdateActiveDirectoryRequest_descriptor; } @java.lang.Override public com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest getDefaultInstanceForType() { return com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest build() { com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest buildPartial() { com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest result = new com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest 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.activeDirectory_ = activeDirectoryBuilder_ == null ? activeDirectory_ : activeDirectoryBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest) { return mergeFrom((com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest other) { if (other == com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest.getDefaultInstance()) return this; if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } if (other.hasActiveDirectory()) { mergeActiveDirectory(other.getActiveDirectory()); } 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(getActiveDirectoryFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * Active Directory resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. If the * user does not provide a mask then all fields will be overwritten. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * Active Directory resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. If the * user does not provide a mask then all fields will be overwritten. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * Active Directory resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. If the * user does not provide a mask then all fields will be overwritten. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * Active Directory resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. If the * user does not provide a mask then all fields will be overwritten. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * Active Directory resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. If the * user does not provide a mask then all fields will be overwritten. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * Active Directory resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. If the * user does not provide a mask then all fields will be overwritten. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000001); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * Active Directory resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. If the * user does not provide a mask then all fields will be overwritten. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000001; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * Active Directory resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. If the * user does not provide a mask then all fields will be overwritten. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * Active Directory resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. If the * user does not provide a mask then all fields will be overwritten. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } private com.google.cloud.netapp.v1.ActiveDirectory activeDirectory_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.netapp.v1.ActiveDirectory, com.google.cloud.netapp.v1.ActiveDirectory.Builder, com.google.cloud.netapp.v1.ActiveDirectoryOrBuilder> activeDirectoryBuilder_; /** * * * <pre> * Required. The volume being updated * </pre> * * <code> * .google.cloud.netapp.v1.ActiveDirectory active_directory = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the activeDirectory field is set. */ public boolean hasActiveDirectory() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The volume being updated * </pre> * * <code> * .google.cloud.netapp.v1.ActiveDirectory active_directory = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The activeDirectory. */ public com.google.cloud.netapp.v1.ActiveDirectory getActiveDirectory() { if (activeDirectoryBuilder_ == null) { return activeDirectory_ == null ? com.google.cloud.netapp.v1.ActiveDirectory.getDefaultInstance() : activeDirectory_; } else { return activeDirectoryBuilder_.getMessage(); } } /** * * * <pre> * Required. The volume being updated * </pre> * * <code> * .google.cloud.netapp.v1.ActiveDirectory active_directory = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setActiveDirectory(com.google.cloud.netapp.v1.ActiveDirectory value) { if (activeDirectoryBuilder_ == null) { if (value == null) { throw new NullPointerException(); } activeDirectory_ = value; } else { activeDirectoryBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The volume being updated * </pre> * * <code> * .google.cloud.netapp.v1.ActiveDirectory active_directory = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setActiveDirectory( com.google.cloud.netapp.v1.ActiveDirectory.Builder builderForValue) { if (activeDirectoryBuilder_ == null) { activeDirectory_ = builderForValue.build(); } else { activeDirectoryBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The volume being updated * </pre> * * <code> * .google.cloud.netapp.v1.ActiveDirectory active_directory = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeActiveDirectory(com.google.cloud.netapp.v1.ActiveDirectory value) { if (activeDirectoryBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && activeDirectory_ != null && activeDirectory_ != com.google.cloud.netapp.v1.ActiveDirectory.getDefaultInstance()) { getActiveDirectoryBuilder().mergeFrom(value); } else { activeDirectory_ = value; } } else { activeDirectoryBuilder_.mergeFrom(value); } if (activeDirectory_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The volume being updated * </pre> * * <code> * .google.cloud.netapp.v1.ActiveDirectory active_directory = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearActiveDirectory() { bitField0_ = (bitField0_ & ~0x00000002); activeDirectory_ = null; if (activeDirectoryBuilder_ != null) { activeDirectoryBuilder_.dispose(); activeDirectoryBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The volume being updated * </pre> * * <code> * .google.cloud.netapp.v1.ActiveDirectory active_directory = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.netapp.v1.ActiveDirectory.Builder getActiveDirectoryBuilder() { bitField0_ |= 0x00000002; onChanged(); return getActiveDirectoryFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The volume being updated * </pre> * * <code> * .google.cloud.netapp.v1.ActiveDirectory active_directory = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.netapp.v1.ActiveDirectoryOrBuilder getActiveDirectoryOrBuilder() { if (activeDirectoryBuilder_ != null) { return activeDirectoryBuilder_.getMessageOrBuilder(); } else { return activeDirectory_ == null ? com.google.cloud.netapp.v1.ActiveDirectory.getDefaultInstance() : activeDirectory_; } } /** * * * <pre> * Required. The volume being updated * </pre> * * <code> * .google.cloud.netapp.v1.ActiveDirectory active_directory = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.netapp.v1.ActiveDirectory, com.google.cloud.netapp.v1.ActiveDirectory.Builder, com.google.cloud.netapp.v1.ActiveDirectoryOrBuilder> getActiveDirectoryFieldBuilder() { if (activeDirectoryBuilder_ == null) { activeDirectoryBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.netapp.v1.ActiveDirectory, com.google.cloud.netapp.v1.ActiveDirectory.Builder, com.google.cloud.netapp.v1.ActiveDirectoryOrBuilder>( getActiveDirectory(), getParentForChildren(), isClean()); activeDirectory_ = null; } return activeDirectoryBuilder_; } @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.UpdateActiveDirectoryRequest) } // @@protoc_insertion_point(class_scope:google.cloud.netapp.v1.UpdateActiveDirectoryRequest) private static final com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest(); } public static com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateActiveDirectoryRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateActiveDirectoryRequest>() { @java.lang.Override public UpdateActiveDirectoryRequest 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<UpdateActiveDirectoryRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateActiveDirectoryRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.netapp.v1.UpdateActiveDirectoryRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
hibernate/hibernate-reactive
35,273
hibernate-reactive-core/src/main/java/org/hibernate/reactive/adaptor/impl/ResultSetAdaptor.java
/* Hibernate, Relational Persistence for Idiomatic Java * * SPDX-License-Identifier: Apache-2.0 * Copyright: Red Hat Inc. and Hibernate Authors */ package org.hibernate.reactive.adaptor.impl; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.JDBCType; import java.sql.NClob; import java.sql.Ref; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.RowId; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.function.Function; import org.hibernate.engine.jdbc.proxy.BlobProxy; import org.hibernate.engine.jdbc.proxy.ClobProxy; import org.hibernate.reactive.logging.impl.Log; import org.hibernate.type.descriptor.jdbc.JdbcType; import io.vertx.core.buffer.Buffer; import io.vertx.sqlclient.PropertyKind; import io.vertx.sqlclient.Row; import io.vertx.sqlclient.RowSet; import io.vertx.sqlclient.Tuple; import io.vertx.sqlclient.desc.ColumnDescriptor; import io.vertx.sqlclient.impl.RowBase; import static java.lang.invoke.MethodHandles.lookup; import static java.util.Collections.emptyList; import static java.util.Objects.requireNonNull; import static org.hibernate.reactive.logging.impl.LoggerFactory.make; /** * An adaptor that allows Hibernate core code which expects a JDBC * {@code ResultSet} to read values from Vert.x's {@code RowSet}. */ public class ResultSetAdaptor implements ResultSet { private static final Log LOG = make( Log.class, lookup() ); private final Iterator<? extends Row> iterator; private final List<ColumnDescriptor> columnDescriptors; private final List<String> columnNames; private Row row; private boolean wasNull; public ResultSetAdaptor(Object id, Class<?> idClass, String columnName) { requireNonNull( id ); this.iterator = List.of( new RowAdaptor( id, idClass, columnName ) ).iterator(); this.columnNames = columnName == null ? emptyList() : List.of( columnName ); this.columnDescriptors = List.of( toColumnDescriptor( idClass, columnName ) ); } private static class RowAdaptor implements Row { private final Object id; private final Class<?> idClass; private final String columnName; public RowAdaptor(Object id, Class<?> idClass, String columnName) { this.id = id; this.idClass = idClass; this.columnName = columnName; } @Override public Object getValue(String column) { return id; } @Override public String getColumnName(int pos) { return columnName; } @Override public int getColumnIndex(String column) { return 0; } @Override public Object getValue(int pos) { return id; } @Override public Tuple addValue(Object value) { return null; } @Override public int size() { return 1; } @Override public void clear() { } @Override public List<Class<?>> types() { return List.of( idClass ); } } public ResultSetAdaptor(RowSet<Row> rows) { requireNonNull( rows ); this.iterator = rows.iterator(); this.columnNames = rows.columnsNames() == null ? emptyList() : rows.columnsNames(); this.columnDescriptors = rows.columnDescriptors(); } public ResultSetAdaptor(RowSet<Row> rows, PropertyKind<Row> propertyKind, List<String> generatedColumnNames, List<Class<?>> generatedColumnClasses) { this( rows, rows.property( propertyKind ), generatedColumnNames, generatedColumnClasses ); } public ResultSetAdaptor(RowSet<Row> rows, Collection<?> ids, String idColumnName, Class<?> idClass) { this( rows, new RowFromId( ids, idColumnName ), idColumnName, idClass ); } private ResultSetAdaptor(RowSet<Row> rows, Row row, String idColumnName, Class<?> idClass) { this( rows, row, List.of( idColumnName ), List.of( idClass ) ); } private ResultSetAdaptor(RowSet<Row> rows, Row row, List<String> columnNames, List<Class<?>> columnClasses) { requireNonNull( rows ); requireNonNull( columnNames ); this.iterator = List.of( row ).iterator(); this.columnNames = columnNames ; this.columnDescriptors = new ArrayList<>(columnNames.size()); for (int i =0; i < columnNames.size(); i++) { columnDescriptors.add( toColumnDescriptor( columnClasses.get( i ), columnNames.get(i) ) ); } } private static ColumnDescriptor toColumnDescriptor(Class<?> idClass, String idColumnName) { return new ColumnDescriptor() { @Override public String name() { return idColumnName; } @Override public boolean isArray() { return idClass.isArray(); } @Override public String typeName() { return idClass.getName(); } @Override public JDBCType jdbcType() { return null; } }; } private static class RowFromId extends RowBase { private final List<String> columns; public RowFromId(Collection<?> ids, String columnName) { super( ids ); this.columns = List.of( requireNonNull( columnName ) ); } @Override public String getColumnName(int pos) { return pos > 0 ? null : columns.get( pos ); } @Override public int getColumnIndex(String column) { return columns.indexOf( column ); } } @Override public boolean next() { if ( iterator.hasNext() ) { row = iterator.next(); return true; } return false; } @Override public void close() { } @Override public boolean wasNull() { return wasNull; } @Override public String getString(int columnIndex) { String string = row.getString( columnIndex - 1 ); return ( wasNull = string == null ) ? null : string; } @Override public boolean getBoolean(int columnIndex) { try { Boolean bool = row.getBoolean( columnIndex - 1 ); wasNull = bool == null; return !wasNull && bool; } catch (ClassCastException cce) { // Oracle doesn't support an actual boolean/Boolean datatype. // Oracle8iDialect in ORM registers the BOOLEAN type as a 'number( 1, 0 )' // so we need to convert the int to a boolean try { return getInt( columnIndex ) != 0; } catch (Exception e) { // ignore second exception and throw first cce throw cce; } } } @Override public byte getByte(int columnIndex) { Integer integer = row.getInteger( columnIndex - 1 ); wasNull = integer == null; return wasNull ? 0 : integer.byteValue(); } @Override public short getShort(int columnIndex) { Short aShort = row.getShort( columnIndex - 1 ); wasNull = aShort == null; return wasNull ? 0 : aShort; } @Override public int getInt(int columnIndex) { Integer integer = row.getInteger( columnIndex - 1 ); wasNull = integer == null; return wasNull ? 0 : integer; } @Override public long getLong(int columnIndex) { Long aLong = row.getLong( columnIndex - 1 ); wasNull = aLong == null; return wasNull ? 0 : aLong; } @Override public float getFloat(int columnIndex) { Float real = row.getFloat( columnIndex - 1 ); wasNull = real == null; return wasNull ? 0 : real; } @Override public double getDouble(int columnIndex) { Double real = row.getDouble( columnIndex - 1 ); wasNull = real == null; return wasNull ? 0 : real; } @Override public BigDecimal getBigDecimal(int columnIndex, int scale) { throw new UnsupportedOperationException(); } @Override public byte[] getBytes(int columnIndex) { Buffer buffer = row.getBuffer( columnIndex - 1 ); wasNull = buffer == null; return wasNull ? null : buffer.getBytes(); } @Override public Date getDate(int columnIndex) { LocalDate localDate = row.getLocalDate( columnIndex - 1 ); return ( wasNull = localDate == null ) ? null : Date.valueOf( localDate ); } @Override public Time getTime(int columnIndex) { LocalTime localTime = row.getLocalTime( columnIndex - 1 ); return ( wasNull = localTime == null ) ? null : Time.valueOf( localTime ); } @Override public Time getTime(int columnIndex, Calendar cal) { LocalTime localTime = row.getLocalTime( columnIndex - 1 ); return ( wasNull = localTime == null ) ? null : Time.valueOf( localTime ); } @Override public InputStream getAsciiStream(int columnIndex) { throw new UnsupportedOperationException( "This type hasn't been implemented yet" ); } @Override public InputStream getUnicodeStream(int columnIndex) { throw new UnsupportedOperationException( "This type hasn't been implemented yet" ); } @Override public InputStream getBinaryStream(int columnIndex) { throw new UnsupportedOperationException( "This type hasn't been implemented yet" ); } @Override public String getString(String columnLabel) { String result = caseInsensitiveGet( columnLabel, row::getString ); wasNull = result == null; return result; } private <T> T caseInsensitiveGet(String columnLabel, Function<String, T> produce) { for ( String columnName : getColumnsNames() ) { if ( columnName.equalsIgnoreCase( columnLabel ) ) { return produce.apply( columnName ); } } // Same error thrown by io.vertx.sqlclient.Row when it doesn't find the label throw new NoSuchElementException( "Column " + columnLabel + " does not exist" ); } /** * rows.columnsNames() might return null for some databases. * For example, when creating a stored procedure in PostgreSQL using a native query. * * @return A list of column names or an empty list. */ private List<String> getColumnsNames() { return this.columnNames; } @Override public boolean getBoolean(String columnLabel) { try { Boolean bool = row.getBoolean( columnLabel ); wasNull = bool == null; return !wasNull && bool; } catch (ClassCastException cce) { // Oracle doesn't support an actual boolean/Boolean datatype. // Oracle8iDialect in ORM registers the BOOLEAN type as a 'number( 1, 0 )' // so we need to convert the int to a boolean try { return getInt( columnLabel ) != 0; } catch (Exception e) { // ignore second exception and throw first cce throw cce; } } } @Override public byte getByte(String columnLabel) { Integer integer = row.getInteger( columnLabel ); wasNull = integer == null; return wasNull ? 0 : integer.byteValue(); } @Override public short getShort(String columnLabel) { Short aShort = row.getShort( columnLabel ); wasNull = aShort == null; return wasNull ? 0 : aShort; } @Override public int getInt(String columnLabel) { Integer integer = row.getInteger( columnLabel ); wasNull = integer == null; return wasNull ? 0 : integer; } @Override public long getLong(String columnLabel) { Long aLong = caseInsensitiveGet( columnLabel, row::getLong ); wasNull = aLong == null; return wasNull ? 0 : aLong; } @Override public float getFloat(String columnLabel) { Float real = row.getFloat( columnLabel ); wasNull = real == null; return wasNull ? 0 : real; } @Override public double getDouble(String columnLabel) { Double real = row.getDouble( columnLabel ); wasNull = real == null; return wasNull ? 0 : real; } @Override public BigDecimal getBigDecimal(String columnLabel, int scale) { throw new UnsupportedOperationException(); } @Override public byte[] getBytes(String columnLabel) { Buffer buffer = row.getBuffer( columnLabel ); wasNull = buffer == null; return wasNull ? null : buffer.getBytes(); } @Override public Date getDate(String columnLabel) { LocalDate localDate = row.getLocalDate( columnLabel ); return ( wasNull = localDate == null ) ? null : Date.valueOf( localDate ); } @Override public Time getTime(String columnLabel) { LocalTime localTime = row.getLocalTime( columnLabel ); return ( wasNull = localTime == null ) ? null : Time.valueOf( localTime ); } @Override public Time getTime(String columnLabel, Calendar cal) { LocalTime localTime = row.getLocalTime( columnLabel ); return ( wasNull = localTime == null ) ? null : Time.valueOf( localTime ); } @Override public Timestamp getTimestamp(String columnLabel) { LocalDateTime rawValue = row.getLocalDateTime( columnLabel ); return ( wasNull = rawValue == null ) ? null : Timestamp.valueOf( rawValue ); } @Override public Timestamp getTimestamp(String columnLabel, Calendar cal) { LocalDateTime localDateTime = row.getLocalDateTime( columnLabel ); return ( wasNull = localDateTime == null ) ? null : toTimestamp( localDateTime, cal ); } private static Timestamp toTimestamp(LocalDateTime localDateTime, Calendar cal) { return Timestamp.from( localDateTime.atZone( cal.getTimeZone().toZoneId() ).toInstant() ); } @Override public int getHoldability() { return CLOSE_CURSORS_AT_COMMIT; } @Override public boolean isClosed() { return false; } @Override public <T> T getObject(int columnIndex, Class<T> type) { T object = row.get( type, columnIndex - 1 ); return ( wasNull = object == null ) ? null : object; } @Override public <T> T getObject(String columnLabel, Class<T> type) { T object = row.get( type, row.getColumnIndex( columnLabel ) ); return ( wasNull = object == null ) ? null : object; } @Override public <T> T unwrap(Class<T> iface) { return null; } @Override public boolean isWrapperFor(Class<?> iface) { return false; } @Override public SQLWarning getWarnings() { return null; } @Override public void clearWarnings() { } @Override public String getCursorName() { return null; } @Override public Object getObject(int columnIndex) { Object object = row.getValue( columnIndex - 1 ); return ( wasNull = object == null ) ? null : object; } @Override public Object getObject(String columnLabel) { Object object = row.getValue( columnLabel ); return ( wasNull = object == null ) ? null : object; } @Override public int findColumn(String columnLabel) { // JDBC parameters index start from 1 int index = 1; for ( String column : getColumnsNames() ) { // Some dbs, like Oracle and Db2, return the column names always in uppercase if ( column.equalsIgnoreCase( columnLabel ) ) { return index; } index++; } return -1; } @Override public BigDecimal getBigDecimal(int columnIndex) { BigDecimal decimal = row.getBigDecimal( columnIndex - 1 ); return ( wasNull = decimal == null ) ? null : decimal; } @Override public BigDecimal getBigDecimal(String columnLabel) { BigDecimal decimal = row.getBigDecimal( columnLabel ); return ( wasNull = decimal == null ) ? null : decimal; } @Override public void setFetchDirection(int direction) { } @Override public int getFetchDirection() { return FETCH_FORWARD; } @Override public void setFetchSize(int rows) { } @Override public int getFetchSize() { return 0; } @Override public int getType() { return TYPE_FORWARD_ONLY; } @Override public int getConcurrency() { return CONCUR_READ_ONLY; } @Override public boolean rowUpdated() { return false; } @Override public boolean rowInserted() { return false; } @Override public boolean rowDeleted() { return false; } @Override public boolean isBeforeFirst() { throw new UnsupportedOperationException(); } @Override public boolean isAfterLast() { throw new UnsupportedOperationException(); } @Override public boolean isFirst() { throw new UnsupportedOperationException(); } @Override public boolean isLast() { throw new UnsupportedOperationException(); } @Override public void beforeFirst() { throw new UnsupportedOperationException(); } @Override public void afterLast() { throw new UnsupportedOperationException(); } @Override public boolean first() { throw new UnsupportedOperationException(); } @Override public boolean last() { throw new UnsupportedOperationException(); } @Override public boolean absolute(int row) { throw new UnsupportedOperationException(); } @Override public boolean relative(int rows) { throw new UnsupportedOperationException(); } @Override public boolean previous() { throw new UnsupportedOperationException(); } @Override public int getRow() { throw new UnsupportedOperationException(); } @Override public void insertRow() { throw new UnsupportedOperationException(); } @Override public void updateRow() { throw new UnsupportedOperationException(); } @Override public void deleteRow() { throw new UnsupportedOperationException(); } @Override public void refreshRow() { throw new UnsupportedOperationException(); } @Override public void cancelRowUpdates() { throw new UnsupportedOperationException(); } @Override public void moveToInsertRow() { throw new UnsupportedOperationException(); } @Override public void moveToCurrentRow() { throw new UnsupportedOperationException(); } @Override public Statement getStatement() { return new PreparedStatementAdaptor(); } @Override public InputStream getAsciiStream(String columnLabel) { throw new UnsupportedOperationException(); } @Override public InputStream getUnicodeStream(String columnLabel) { throw new UnsupportedOperationException(); } @Override public InputStream getBinaryStream(String columnLabel) { throw new UnsupportedOperationException(); } @Override public Reader getCharacterStream(int columnIndex) { throw new UnsupportedOperationException(); } @Override public Reader getCharacterStream(String columnLabel) { throw new UnsupportedOperationException(); } @Override public Object getObject(int columnIndex, Map<String, Class<?>> map) { throw new UnsupportedOperationException(); } @Override public Ref getRef(int columnIndex) { throw new UnsupportedOperationException(); } @Override public Blob getBlob(int columnIndex) { Blob blob = blob( row -> row.getValue( columnIndex - 1 ), row -> row.getBuffer( columnIndex - 1 ) ); wasNull = blob == null; return blob; } @Override public Clob getClob(int columnIndex) { Clob clob = clob( row -> row.getString( columnIndex - 1 ) ); wasNull = clob == null; if ( wasNull ) { return null; } return clob; } private Clob clob(Function<Row, String> getString) { String value = getString.apply( row ); if ( value == null ) { return null; } return ClobProxy.generateProxy( ( value ) ); } @Override public Array getArray(int columnIndex) { throw new UnsupportedOperationException(); } public Array getArray(int columnIndex, JdbcType elementJdbcType) { Object[] objects = (Object[]) row.getValue( columnIndex - 1 ); wasNull = objects == null; if ( objects == null ) { return null; } return new ArrayAdaptor( elementJdbcType, objects ); } @Override public Object getObject(String columnLabel, Map<String, Class<?>> map) { throw new UnsupportedOperationException(); } @Override public Ref getRef(String columnLabel) { throw new UnsupportedOperationException(); } @Override public Blob getBlob(String columnLabel) { Blob blob = blob( row -> row.getValue( columnLabel ), row -> row.getBuffer( columnLabel ) ); wasNull = blob == null; return blob; } private Blob blob(Function<Row, Object> getValue, Function<Row, Buffer> getBuffer) { Object value = getValue.apply( row ); if ( value == null ) { return null; } if ( value instanceof String ) { return BlobProxy.generateProxy( ( (String) value ).getBytes() ); } if ( value instanceof byte[] ) { return BlobProxy.generateProxy( (byte[]) value ); } return BlobProxy.generateProxy( getBuffer.apply( row ).getBytes() ); } @Override public Clob getClob(String columnLabel) { throw new UnsupportedOperationException(); } @Override public Array getArray(String columnLabel) { throw new UnsupportedOperationException(); } @Override public Date getDate(int columnIndex, Calendar cal) { throw new UnsupportedOperationException(); } @Override public Date getDate(String columnLabel, Calendar cal) { throw new UnsupportedOperationException(); } @Override public Timestamp getTimestamp(int columnIndex) { LocalDateTime localDateTime = row.getLocalDateTime( columnIndex - 1 ); return ( wasNull = localDateTime == null ) ? null : Timestamp.valueOf( localDateTime ); } @Override public Timestamp getTimestamp(int columnIndex, Calendar cal) { LocalDateTime localDateTime = row.getLocalDateTime( columnIndex - 1 ); return ( wasNull = localDateTime == null ) ? null : toTimestamp( localDateTime, cal ); } @Override public URL getURL(int columnIndex) { throw new UnsupportedOperationException(); } @Override public URL getURL(String columnLabel) { throw new UnsupportedOperationException(); } @Override public String getNString(int columnIndex) { return getString( columnIndex ); } @Override public String getNString(String columnLabel) { return getString( columnLabel ); } @Override public Reader getNCharacterStream(int columnIndex) { throw new UnsupportedOperationException(); } @Override public Reader getNCharacterStream(String columnLabel) { throw new UnsupportedOperationException(); } @Override public NClob getNClob(int columnIndex) { throw new UnsupportedOperationException(); } @Override public NClob getNClob(String columnLabel) { throw new UnsupportedOperationException(); } @Override public SQLXML getSQLXML(int columnIndex) { throw LOG.unsupportedXmlType(); } @Override public SQLXML getSQLXML(String columnLabel) { throw LOG.unsupportedXmlType(); } @Override public RowId getRowId(int columnIndex) { Buffer buffer = row.getBuffer( columnIndex - 1 ); wasNull = buffer == null; return wasNull ? null : new RowIdAdaptor( buffer ); } @Override public RowId getRowId(String columnLabel) { Buffer buffer = row.getBuffer( columnLabel ); wasNull = buffer == null; return wasNull ? null : new RowIdAdaptor( buffer ); } private static class RowIdAdaptor implements RowId { private final Buffer buffer; private RowIdAdaptor(Buffer buffer) { requireNonNull( buffer ); this.buffer = buffer; } @Override public byte[] getBytes() { return buffer.getBytes(); } } @Override public void updateNull(int columnIndex) { throw new UnsupportedOperationException(); } @Override public void updateBoolean(int columnIndex, boolean x) { throw new UnsupportedOperationException(); } @Override public void updateByte(int columnIndex, byte x) { throw new UnsupportedOperationException(); } @Override public void updateShort(int columnIndex, short x) { throw new UnsupportedOperationException(); } @Override public void updateInt(int columnIndex, int x) { throw new UnsupportedOperationException(); } @Override public void updateLong(int columnIndex, long x) { throw new UnsupportedOperationException(); } @Override public void updateFloat(int columnIndex, float x) { throw new UnsupportedOperationException(); } @Override public void updateDouble(int columnIndex, double x) { throw new UnsupportedOperationException(); } @Override public void updateBigDecimal(int columnIndex, BigDecimal x) { throw new UnsupportedOperationException(); } @Override public void updateString(int columnIndex, String x) { throw new UnsupportedOperationException(); } @Override public void updateBytes(int columnIndex, byte[] x) { throw new UnsupportedOperationException(); } @Override public void updateDate(int columnIndex, Date x) { throw new UnsupportedOperationException(); } @Override public void updateTime(int columnIndex, Time x) { throw new UnsupportedOperationException(); } @Override public void updateTimestamp(int columnIndex, Timestamp x) { throw new UnsupportedOperationException(); } @Override public void updateAsciiStream(int columnIndex, InputStream x, int length) { throw new UnsupportedOperationException(); } @Override public void updateBinaryStream(int columnIndex, InputStream x, int length) { throw new UnsupportedOperationException(); } @Override public void updateCharacterStream(int columnIndex, Reader x, int length) { throw new UnsupportedOperationException(); } @Override public void updateObject(int columnIndex, Object x, int scaleOrLength) { throw new UnsupportedOperationException(); } @Override public void updateObject(int columnIndex, Object x) { throw new UnsupportedOperationException(); } @Override public void updateNull(String columnLabel) { throw new UnsupportedOperationException(); } @Override public void updateBoolean(String columnLabel, boolean x) { throw new UnsupportedOperationException(); } @Override public void updateByte(String columnLabel, byte x) { throw new UnsupportedOperationException(); } @Override public void updateShort(String columnLabel, short x) { throw new UnsupportedOperationException(); } @Override public void updateInt(String columnLabel, int x) { throw new UnsupportedOperationException(); } @Override public void updateLong(String columnLabel, long x) { throw new UnsupportedOperationException(); } @Override public void updateFloat(String columnLabel, float x) { throw new UnsupportedOperationException(); } @Override public void updateDouble(String columnLabel, double x) { throw new UnsupportedOperationException(); } @Override public void updateBigDecimal(String columnLabel, BigDecimal x) { throw new UnsupportedOperationException(); } @Override public void updateString(String columnLabel, String x) { throw new UnsupportedOperationException(); } @Override public void updateBytes(String columnLabel, byte[] x) { throw new UnsupportedOperationException(); } @Override public void updateDate(String columnLabel, Date x) { throw new UnsupportedOperationException(); } @Override public void updateTime(String columnLabel, Time x) { throw new UnsupportedOperationException(); } @Override public void updateTimestamp(String columnLabel, Timestamp x) { throw new UnsupportedOperationException(); } @Override public void updateAsciiStream(String columnLabel, InputStream x, int length) { throw new UnsupportedOperationException(); } @Override public void updateBinaryStream(String columnLabel, InputStream x, int length) { throw new UnsupportedOperationException(); } @Override public void updateCharacterStream(String columnLabel, Reader reader, int length) { throw new UnsupportedOperationException(); } @Override public void updateObject(String columnLabel, Object x, int scaleOrLength) { throw new UnsupportedOperationException(); } @Override public void updateObject(String columnLabel, Object x) { throw new UnsupportedOperationException(); } @Override public void updateRef(int columnIndex, Ref x) { throw new UnsupportedOperationException(); } @Override public void updateRef(String columnLabel, Ref x) { throw new UnsupportedOperationException(); } @Override public void updateBlob(int columnIndex, Blob x) { throw new UnsupportedOperationException(); } @Override public void updateBlob(String columnLabel, Blob x) { throw new UnsupportedOperationException(); } @Override public void updateClob(int columnIndex, Clob x) { throw new UnsupportedOperationException(); } @Override public void updateClob(String columnLabel, Clob x) { throw new UnsupportedOperationException(); } @Override public void updateArray(int columnIndex, Array x) { throw new UnsupportedOperationException(); } @Override public void updateArray(String columnLabel, Array x) { throw new UnsupportedOperationException(); } @Override public void updateRowId(int columnIndex, RowId x) { throw new UnsupportedOperationException(); } @Override public void updateRowId(String columnLabel, RowId x) { throw new UnsupportedOperationException(); } @Override public void updateNString(int columnIndex, String nString) { throw new UnsupportedOperationException(); } @Override public void updateNString(String columnLabel, String nString) { throw new UnsupportedOperationException(); } @Override public void updateNClob(int columnIndex, NClob nClob) { throw new UnsupportedOperationException(); } @Override public void updateNClob(String columnLabel, NClob nClob) { throw new UnsupportedOperationException(); } @Override public void updateSQLXML(int columnIndex, SQLXML xmlObject) { throw new UnsupportedOperationException(); } @Override public void updateSQLXML(String columnLabel, SQLXML xmlObject) { throw new UnsupportedOperationException(); } @Override public void updateNCharacterStream(int columnIndex, Reader x, long length) { throw new UnsupportedOperationException(); } @Override public void updateNCharacterStream(String columnLabel, Reader reader, long length) { throw new UnsupportedOperationException(); } @Override public void updateAsciiStream(int columnIndex, InputStream x, long length) { throw new UnsupportedOperationException(); } @Override public void updateBinaryStream(int columnIndex, InputStream x, long length) { throw new UnsupportedOperationException(); } @Override public void updateCharacterStream(int columnIndex, Reader x, long length) { throw new UnsupportedOperationException(); } @Override public void updateAsciiStream(String columnLabel, InputStream x, long length) { throw new UnsupportedOperationException(); } @Override public void updateBinaryStream(String columnLabel, InputStream x, long length) { throw new UnsupportedOperationException(); } @Override public void updateCharacterStream(String columnLabel, Reader reader, long length) { throw new UnsupportedOperationException(); } @Override public void updateBlob(int columnIndex, InputStream inputStream, long length) { throw new UnsupportedOperationException(); } @Override public void updateBlob(String columnLabel, InputStream inputStream, long length) { throw new UnsupportedOperationException(); } @Override public void updateClob(int columnIndex, Reader reader, long length) { throw new UnsupportedOperationException(); } @Override public void updateClob(String columnLabel, Reader reader, long length) { throw new UnsupportedOperationException(); } @Override public void updateNClob(int columnIndex, Reader reader, long length) { throw new UnsupportedOperationException(); } @Override public void updateNClob(String columnLabel, Reader reader, long length) { throw new UnsupportedOperationException(); } @Override public void updateNCharacterStream(int columnIndex, Reader x) { throw new UnsupportedOperationException(); } @Override public void updateNCharacterStream(String columnLabel, Reader reader) { throw new UnsupportedOperationException(); } @Override public void updateAsciiStream(int columnIndex, InputStream x) { throw new UnsupportedOperationException(); } @Override public void updateBinaryStream(int columnIndex, InputStream x) { throw new UnsupportedOperationException(); } @Override public void updateCharacterStream(int columnIndex, Reader x) { throw new UnsupportedOperationException(); } @Override public void updateAsciiStream(String columnLabel, InputStream x) { throw new UnsupportedOperationException(); } @Override public void updateBinaryStream(String columnLabel, InputStream x) { throw new UnsupportedOperationException(); } @Override public void updateCharacterStream(String columnLabel, Reader reader) { throw new UnsupportedOperationException(); } @Override public void updateBlob(int columnIndex, InputStream inputStream) { throw new UnsupportedOperationException(); } @Override public void updateBlob(String columnLabel, InputStream inputStream) { throw new UnsupportedOperationException(); } @Override public void updateClob(int columnIndex, Reader reader) { throw new UnsupportedOperationException(); } @Override public void updateClob(String columnLabel, Reader reader) { throw new UnsupportedOperationException(); } @Override public void updateNClob(int columnIndex, Reader reader) { throw new UnsupportedOperationException(); } @Override public void updateNClob(String columnLabel, Reader reader) { throw new UnsupportedOperationException(); } @Override public ResultSetMetaData getMetaData() { return new MetaData( columnNames, columnDescriptors ); } private static class MetaData implements ResultSetMetaData { private final List<String> columns; private final List<ColumnDescriptor> descriptors; private final String[] typeNames; public MetaData(List<String> columnNames, List<ColumnDescriptor> columnDescriptors) { columns = columnNames; descriptors = columnDescriptors; typeNames = initTypeNames( columnDescriptors ); } private static String[] initTypeNames(List<ColumnDescriptor> columnDescriptors) { if ( columnDescriptors == null ) { return null; } final String[] typeNames = new String[columnDescriptors.size()]; int i = 0; for ( ColumnDescriptor columnDescriptor : columnDescriptors ) { typeNames[i++] = columnDescriptor.typeName(); } return typeNames; } @Override public int getColumnCount() { return columns.size(); } @Override public int getColumnType(int column) { ColumnDescriptor descriptor = descriptors.get( column - 1 ); return descriptor.isArray() ? Types.ARRAY : descriptor.jdbcType().getVendorTypeNumber(); } @Override public String getColumnLabel(int column) { return columns.get( column - 1 ); } @Override public String getColumnName(int column) { return columns.get( column - 1 ); } @Override public boolean isAutoIncrement(int column) { return false; } @Override public boolean isCaseSensitive(int column) { return false; } @Override public boolean isSearchable(int column) { return false; } @Override public boolean isCurrency(int column) { return false; } @Override public int isNullable(int column) { return columnNullableUnknown; } @Override public boolean isSigned(int column) { return false; } @Override public int getColumnDisplaySize(int column) { return 0; } @Override public String getSchemaName(int column) { return null; } @Override public int getPrecision(int column) { return 0; } @Override public int getScale(int column) { return 0; } @Override public String getTableName(int column) { return null; } @Override public String getCatalogName(int column) { return null; } @Override public String getColumnTypeName(int column) { return typeNames[column - 1]; } @Override public boolean isReadOnly(int column) { return false; } @Override public boolean isWritable(int column) { return false; } @Override public boolean isDefinitelyWritable(int column) { return false; } @Override public String getColumnClassName(int column) { return null; } @Override public <T> T unwrap(Class<T> iface) { return null; } @Override public boolean isWrapperFor(Class<?> iface) { return false; } } }
apache/incubator-kie-kogito-apps
37,539
trusty/trusty-service/trusty-service-common/src/test/java/org/kie/kogito/trusty/service/common/TrustyServiceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.kie.kogito.trusty.service.common; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.kie.kogito.explainability.api.BaseExplainabilityRequest; import org.kie.kogito.explainability.api.CounterfactualDomain; import org.kie.kogito.explainability.api.CounterfactualDomainRange; import org.kie.kogito.explainability.api.CounterfactualExplainabilityRequest; import org.kie.kogito.explainability.api.CounterfactualExplainabilityResult; import org.kie.kogito.explainability.api.CounterfactualSearchDomain; import org.kie.kogito.explainability.api.CounterfactualSearchDomainStructureValue; import org.kie.kogito.explainability.api.CounterfactualSearchDomainUnitValue; import org.kie.kogito.explainability.api.CounterfactualSearchDomainValue; import org.kie.kogito.explainability.api.ExplainabilityStatus; import org.kie.kogito.explainability.api.LIMEExplainabilityResult; import org.kie.kogito.explainability.api.NamedTypedValue; import org.kie.kogito.persistence.api.Storage; import org.kie.kogito.persistence.api.query.Query; import org.kie.kogito.tracing.typedvalue.CollectionValue; import org.kie.kogito.tracing.typedvalue.StructureValue; import org.kie.kogito.tracing.typedvalue.UnitValue; import org.kie.kogito.trusty.service.common.handlers.CounterfactualExplainabilityResultsManagerDuplicates; import org.kie.kogito.trusty.service.common.handlers.CounterfactualExplainabilityResultsManagerSlidingWindow; import org.kie.kogito.trusty.service.common.handlers.CounterfactualExplainerServiceHandler; import org.kie.kogito.trusty.service.common.handlers.ExplainerServiceHandler; import org.kie.kogito.trusty.service.common.handlers.ExplainerServiceHandlerRegistry; import org.kie.kogito.trusty.service.common.handlers.LIMEExplainerServiceHandler; import org.kie.kogito.trusty.service.common.messaging.outgoing.ExplainabilityRequestProducer; import org.kie.kogito.trusty.service.common.mocks.StorageImplMock; import org.kie.kogito.trusty.service.common.models.MatchedExecutionHeaders; import org.kie.kogito.trusty.storage.api.model.decision.DMNModelMetadata; import org.kie.kogito.trusty.storage.api.model.decision.DMNModelWithMetadata; import org.kie.kogito.trusty.storage.api.model.decision.Decision; import org.kie.kogito.trusty.storage.api.model.decision.DecisionInput; import org.kie.kogito.trusty.storage.api.model.decision.DecisionOutcome; import org.kie.kogito.trusty.storage.common.TrustyStorageService; import org.mockito.ArgumentCaptor; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.IntNode; import com.fasterxml.jackson.databind.node.TextNode; import jakarta.enterprise.inject.Instance; 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; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class TrustyServiceTest { private static final String TEST_EXECUTION_ID = UUID.randomUUID().toString(); private static final String TEST_COUNTERFACTUAL_ID = UUID.randomUUID().toString(); private static final String TEST_MODEL = "definition"; private static final String TEST_SOURCE_URL = "http://localhost:8080/model/service"; private static final String TEST_SERVICE_URL = "http://localhost:8080/model"; private static final Long MAX_RUNNING_TIME_SECONDS = 60L; private static final ObjectMapper MAPPER = new ObjectMapper(); private ExplainabilityRequestProducer explainabilityRequestProducerMock; private TrustyStorageService trustyStorageServiceMock; private TrustyServiceImpl trustyService; private LIMEExplainerServiceHandler limeExplainerServiceHandler; private CounterfactualExplainerServiceHandler counterfactualExplainerServiceHandler; private Instance<ExplainerServiceHandler<?>> explanationHandlers; private static JsonNode toJsonNode(String jsonString) throws JsonProcessingException { return MAPPER.reader().readTree(jsonString); } @BeforeEach @SuppressWarnings("unchecked") void setup() { explainabilityRequestProducerMock = mock(ExplainabilityRequestProducer.class); trustyStorageServiceMock = mock(TrustyStorageService.class); limeExplainerServiceHandler = new LIMEExplainerServiceHandler(trustyStorageServiceMock); counterfactualExplainerServiceHandler = new CounterfactualExplainerServiceHandler(trustyStorageServiceMock, mock(CounterfactualExplainabilityResultsManagerSlidingWindow.class), mock(CounterfactualExplainabilityResultsManagerDuplicates.class)); explanationHandlers = mock(Instance.class); when(explanationHandlers.stream()).thenReturn(Stream.of(limeExplainerServiceHandler, counterfactualExplainerServiceHandler)); trustyService = new TrustyServiceImpl(false, explainabilityRequestProducerMock, trustyStorageServiceMock, new ExplainerServiceHandlerRegistry(explanationHandlers), MAX_RUNNING_TIME_SECONDS); } @Test @SuppressWarnings("unchecked") void givenADecisionWhenStoreDecisionIsCalledThenNoExceptionsAreThrown() { Decision decision = new Decision(); Storage storageMock = mock(Storage.class); when(storageMock.put(any(Object.class), any(Object.class))).thenReturn(decision); when(trustyStorageServiceMock.getDecisionsStorage()).thenReturn(storageMock); Assertions.assertDoesNotThrow(() -> trustyService.storeDecision("test", decision)); } @Test @SuppressWarnings("unchecked") void givenADecisionWhenADecisionIsStoredAndRetrievedThenTheOriginalObjectIsReturned() { Decision decision = new Decision(); decision.setExecutionId(TEST_EXECUTION_ID); Query queryMock = mock(Query.class); when(queryMock.filter(any(List.class))).thenReturn(queryMock); when(queryMock.offset(any(Integer.class))).thenReturn(queryMock); when(queryMock.sort(any(List.class))).thenReturn(queryMock); when(queryMock.execute()).thenReturn(List.of(decision)); Storage storageMock = mock(Storage.class); when(storageMock.put(eq(TEST_EXECUTION_ID), any(Object.class))).thenReturn(decision); when(storageMock.containsKey(eq(TEST_EXECUTION_ID))).thenReturn(false); when(storageMock.query()).thenReturn(queryMock); when(trustyStorageServiceMock.getDecisionsStorage()).thenReturn(storageMock); trustyService.storeDecision(TEST_EXECUTION_ID, decision); MatchedExecutionHeaders result = trustyService.getExecutionHeaders(OffsetDateTime.now().minusDays(1), OffsetDateTime.now(), 100, 0, ""); assertEquals(1, result.getExecutions().size()); assertEquals(decision.getExecutionId(), result.getExecutions().get(0).getExecutionId()); } @Test @SuppressWarnings("unchecked") void givenManyExecutionsThenPaginationWorksProperly() { List<Decision> decisions = new ArrayList<>(); IntStream.range(0, 10).forEach(x -> { Decision d = new Decision(); d.setExecutionId(String.valueOf(x)); decisions.add(d); }); Query queryMock = mock(Query.class); when(queryMock.filter(any(List.class))).thenReturn(queryMock); when(queryMock.sort(any(List.class))).thenReturn(queryMock); when(queryMock.execute()).thenReturn(decisions); Storage storageMock = mock(Storage.class); decisions.forEach(x -> { when(storageMock.put(eq(x.getExecutionId()), any(Object.class))).thenReturn(x); when(storageMock.containsKey(eq(x.getExecutionId()))).thenReturn(false); }); when(storageMock.query()).thenReturn(queryMock); when(trustyStorageServiceMock.getDecisionsStorage()).thenReturn(storageMock); decisions.forEach(x -> trustyService.storeDecision(x.getExecutionId(), x)); MatchedExecutionHeaders result = trustyService.getExecutionHeaders(OffsetDateTime.now().minusDays(1), OffsetDateTime.now(), 3, 5, ""); assertEquals(3, result.getExecutions().size()); assertEquals(decisions.size(), result.getAvailableResults()); result = trustyService.getExecutionHeaders(OffsetDateTime.now().minusDays(1), OffsetDateTime.now(), 100, 5, ""); assertEquals(5, result.getExecutions().size()); assertEquals(decisions.size(), result.getAvailableResults()); } @Test @SuppressWarnings("unchecked") void givenNoExecutionsNoExceptionsAreRaised() { Query queryMock = mock(Query.class); when(queryMock.filter(any(List.class))).thenReturn(queryMock); when(queryMock.sort(any(List.class))).thenReturn(queryMock); when(queryMock.execute()).thenReturn(new ArrayList<>()); Storage storageMock = mock(Storage.class); when(storageMock.query()).thenReturn(queryMock); when(trustyStorageServiceMock.getDecisionsStorage()).thenReturn(storageMock); MatchedExecutionHeaders result = trustyService.getExecutionHeaders(OffsetDateTime.now().minusDays(1), OffsetDateTime.now(), 100, 0, ""); assertEquals(0, result.getExecutions().size()); assertEquals(0, result.getAvailableResults()); } @Test @SuppressWarnings("unchecked") void givenADecisionWhenADecisionIsStoredAndRetrievedByIdThenTheOriginalObjectIsReturned() { Decision decision = new Decision(); decision.setExecutionId(TEST_EXECUTION_ID); @SuppressWarnings("unchecked") Storage storageMock = new StorageImplMock(Decision.class); when(trustyStorageServiceMock.getDecisionsStorage()).thenReturn(storageMock); trustyService.storeDecision(TEST_EXECUTION_ID, decision); Decision result = trustyService.getDecisionById(TEST_EXECUTION_ID); assertEquals(TEST_EXECUTION_ID, result.getExecutionId()); } @Test @SuppressWarnings("unchecked") void givenADecisionToProcessWhenExplainabilityIsEnabledThenRequestIsSent() throws JsonProcessingException { trustyService.enableExplainability(); Decision decision = new Decision( TEST_EXECUTION_ID, TEST_SOURCE_URL, TEST_SERVICE_URL, 1591692950000L, true, null, "model", "modelNamespace", List.of( new DecisionInput("1", "Input1", new CollectionValue("string", List.of( new UnitValue("string", "string", toJsonNode("\"ONE\"")), new UnitValue("string", "string", toJsonNode("\"TWO\""))))), new DecisionInput("2", "Input2", new StructureValue("Person", Map.of( "Name", new UnitValue("string", "string", toJsonNode("\"George Orwell\"")), "Age", new UnitValue("number", "number", toJsonNode("45")))))), List.of( new DecisionOutcome( "OUT1", "Result", "SUCCEEDED", new UnitValue("string", "string", toJsonNode("\"YES\"")), Collections.emptyList(), Collections.emptyList()))); Storage<String, Decision> decisionStorageMock = mock(Storage.class); when(decisionStorageMock.containsKey(eq(TEST_EXECUTION_ID))).thenReturn(false); when(trustyStorageServiceMock.getDecisionsStorage()).thenReturn(decisionStorageMock); trustyService.processDecision(TEST_EXECUTION_ID, decision); verify(explainabilityRequestProducerMock).sendEvent(any()); } @Test @SuppressWarnings("unchecked") void givenADecisionToProcessThatAlreadyExistsWhenExplainabilityIsEnabledThenExceptionIsThrown() { trustyService.enableExplainability(); Decision decision = new Decision(); decision.setExecutionId(TEST_EXECUTION_ID); Storage<String, Decision> decisionStorageMock = mock(Storage.class); when(decisionStorageMock.containsKey(eq(TEST_EXECUTION_ID))).thenReturn(true); when(trustyStorageServiceMock.getDecisionsStorage()).thenReturn(decisionStorageMock); assertThrows(IllegalArgumentException.class, () -> trustyService.processDecision(TEST_EXECUTION_ID, decision)); verify(explainabilityRequestProducerMock, never()).sendEvent(any()); } @Test @SuppressWarnings("unchecked") void givenAModelWhenStoreModelIsCalledThenNoExceptionsAreThrown() { String model = TEST_MODEL; Storage storageMock = mock(Storage.class); when(storageMock.put(any(Object.class), any(Object.class))).thenReturn(model); when(trustyStorageServiceMock.getModelStorage(DMNModelWithMetadata.class)).thenReturn(storageMock); Assertions.assertDoesNotThrow(() -> trustyService.storeModel(buildDmnModel(model))); } @Test @SuppressWarnings("unchecked") void givenAModelWhenStoreModelIsCalledMoreThanOnceForSameModelThenExceptionIsThrown() { String model = TEST_MODEL; Storage storageMock = mock(Storage.class); DMNModelWithMetadata dmnModelWithMetadata = buildDmnModel(model); DMNModelMetadata modelIdentifier = dmnModelWithMetadata.getModelMetaData(); when(storageMock.containsKey(modelIdentifier.getIdentifier())).thenReturn(true); when(storageMock.put(any(Object.class), any(Object.class))).thenReturn(model); when(trustyStorageServiceMock.getModelStorage(DMNModelWithMetadata.class)).thenReturn(storageMock); assertThrows(IllegalArgumentException.class, () -> trustyService.storeModel(dmnModelWithMetadata)); } @Test @SuppressWarnings("unchecked") void givenAModelWhenAModelIsStoredAndRetrievedByIdThenTheOriginalObjectIsReturned() { String model = TEST_MODEL; Storage storageMock = new StorageImplMock(String.class); when(trustyStorageServiceMock.getModelStorage(DMNModelWithMetadata.class)).thenReturn(storageMock); DMNModelWithMetadata dmnModelWithMetadata = buildDmnModel(model); DMNModelMetadata modelIdentifier = dmnModelWithMetadata.getModelMetaData(); trustyService.storeModel(buildDmnModel(model)); DMNModelWithMetadata result = trustyService.getModelById(modelIdentifier, DMNModelWithMetadata.class); assertEquals(model, result.getModel()); } @Test @SuppressWarnings("unchecked") void whenAModelIsNotStoredAndRetrievedByIdThenExceptionIsThrown() { DMNModelMetadata modelIdentifier = buildDmnModelIdentifier(); Storage storageMock = mock(Storage.class); when(storageMock.containsKey(modelIdentifier.getIdentifier())).thenReturn(false); when(trustyStorageServiceMock.getModelStorage(DMNModelWithMetadata.class)).thenReturn(storageMock); assertThrows(IllegalArgumentException.class, () -> trustyService.getModelById(modelIdentifier, DMNModelWithMetadata.class)); } @Test @SuppressWarnings("unchecked") void givenAnExplainabilityResultWhenStoreModelIsCalledThenNoExceptionsAreThrown() { LIMEExplainabilityResult result = new LIMEExplainabilityResult(TEST_EXECUTION_ID, ExplainabilityStatus.SUCCEEDED, null, Collections.emptyList()); Storage<String, LIMEExplainabilityResult> storageMock = mock(Storage.class); when(storageMock.put(eq(TEST_EXECUTION_ID), any(LIMEExplainabilityResult.class))).thenReturn(result); when(trustyStorageServiceMock.getLIMEResultStorage()).thenReturn(storageMock); Assertions.assertDoesNotThrow(() -> trustyService.storeExplainabilityResult(TEST_EXECUTION_ID, result)); } @Test @SuppressWarnings("unchecked") void givenAnExplainabilityResultWhenStoreModelIsCalledMoreThanOnceForSameModelThenExceptionIsThrown() { LIMEExplainabilityResult result = new LIMEExplainabilityResult(TEST_EXECUTION_ID, ExplainabilityStatus.SUCCEEDED, null, Collections.emptyList()); Storage<String, LIMEExplainabilityResult> storageMock = mock(Storage.class); when(storageMock.containsKey(eq(TEST_EXECUTION_ID))).thenReturn(true); when(storageMock.put(eq(TEST_EXECUTION_ID), any(LIMEExplainabilityResult.class))).thenReturn(result); when(trustyStorageServiceMock.getLIMEResultStorage()).thenReturn(storageMock); assertThrows(IllegalArgumentException.class, () -> trustyService.storeExplainabilityResult(TEST_EXECUTION_ID, result)); } @Test void givenAnExplainabilityResultWhenAnExplainabilityResultIsStoredAndRetrievedByIdThenTheOriginalObjectIsReturned() { LIMEExplainabilityResult result = new LIMEExplainabilityResult(TEST_EXECUTION_ID, ExplainabilityStatus.SUCCEEDED, null, Collections.emptyList()); Storage<String, LIMEExplainabilityResult> storageMock = new StorageImplMock<>(String.class); when(trustyStorageServiceMock.getLIMEResultStorage()).thenReturn(storageMock); trustyService.storeExplainabilityResult(TEST_EXECUTION_ID, result); //The mocked stream needs to be recreated for subsequent invocations when(explanationHandlers.stream()).thenReturn(Stream.of(limeExplainerServiceHandler, counterfactualExplainerServiceHandler)); assertEquals(result, trustyService.getExplainabilityResultById(TEST_EXECUTION_ID, LIMEExplainabilityResult.class)); } @Test @SuppressWarnings("unchecked") void givenAnExplainabilityResultNotStoredWhenRetrievedByIdThenExceptionIsThrown() { Storage<String, LIMEExplainabilityResult> storageMock = mock(Storage.class); when(storageMock.containsKey(eq(TEST_EXECUTION_ID))).thenReturn(false); when(trustyStorageServiceMock.getLIMEResultStorage()).thenReturn(storageMock); assertThrows(IllegalArgumentException.class, () -> trustyService.getExplainabilityResultById(TEST_EXECUTION_ID, LIMEExplainabilityResult.class)); } @Test @SuppressWarnings("unchecked") void givenNoStoredExecutionWhenCounterfactualRequestIsMadeThenExceptionIsThrown() { Storage<String, Decision> decisionStorage = mock(Storage.class); when(decisionStorage.containsKey(eq(TEST_EXECUTION_ID))).thenReturn(false); when(trustyStorageServiceMock.getDecisionsStorage()).thenReturn(decisionStorage); assertThrows(IllegalArgumentException.class, () -> trustyService.requestCounterfactuals(TEST_EXECUTION_ID, Collections.emptyList(), Collections.emptyList())); } @Test void givenStoredExecutionWhenCounterfactualRequestIsMadeThenRequestIsStored() { doGivenStoredExecutionWhenCounterfactualRequestIsMadeThenRequestIsStoredTest(new CounterfactualDomainRange(new IntNode(10), new IntNode(20))); } @Test void givenStoredExecutionWhenCounterfactualRequestIsMadeThenRequestIsStoredWithNullDomains() { doGivenStoredExecutionWhenCounterfactualRequestIsMadeThenRequestIsStoredTest(null); } @SuppressWarnings("unchecked") void doGivenStoredExecutionWhenCounterfactualRequestIsMadeThenRequestIsStoredTest(CounterfactualDomain domain) { Storage<String, Decision> decisionStorage = mock(Storage.class); Storage<String, CounterfactualExplainabilityRequest> counterfactualStorage = mock(Storage.class); ArgumentCaptor<CounterfactualExplainabilityRequest> counterfactualArgumentCaptor = ArgumentCaptor.forClass(CounterfactualExplainabilityRequest.class); when(decisionStorage.containsKey(eq(TEST_EXECUTION_ID))).thenReturn(true); when(trustyStorageServiceMock.getDecisionsStorage()).thenReturn(decisionStorage); when(trustyStorageServiceMock.getCounterfactualRequestStorage()).thenReturn(counterfactualStorage); when(decisionStorage.get(eq(TEST_EXECUTION_ID))).thenReturn(TrustyServiceTestUtils.buildCorrectDecision(TEST_EXECUTION_ID)); // The Goals structures must be comparable to the original decisions outcomes. // The Search Domain structures must be identical those of the original decision inputs. trustyService.requestCounterfactuals(TEST_EXECUTION_ID, List.of(new NamedTypedValue("Fine", new StructureValue("tFine", Map.of("Amount", new UnitValue("number", "number", new IntNode(0)), "Points", new UnitValue("number", "number", new IntNode(0))))), new NamedTypedValue("Should the driver be suspended?", new UnitValue("string", "string", new TextNode("No")))), List.of(new CounterfactualSearchDomain("Violation", new CounterfactualSearchDomainStructureValue("tViolation", Map.of("Type", new CounterfactualSearchDomainUnitValue("string", "string", true, domain), "Actual Speed", new CounterfactualSearchDomainUnitValue("number", "number", true, domain), "Speed Limit", new CounterfactualSearchDomainUnitValue("number", "number", true, domain)))), new CounterfactualSearchDomain("Driver", new CounterfactualSearchDomainStructureValue("tDriver", Map.of("Age", new CounterfactualSearchDomainUnitValue("number", "number", true, domain), "Points", new CounterfactualSearchDomainUnitValue("number", "number", true, domain)))))); verify(counterfactualStorage).put(anyString(), counterfactualArgumentCaptor.capture()); CounterfactualExplainabilityRequest counterfactual = counterfactualArgumentCaptor.getValue(); assertNotNull(counterfactual); assertEquals(TEST_EXECUTION_ID, counterfactual.getExecutionId()); } @Test void givenStoredExecutionWhenCounterfactualRequestIsMadeThenExplainabilityEventIsEmitted() { doGivenStoredExecutionWhenCounterfactualRequestIsMadeThenExplainabilityEventIsEmittedTest(new CounterfactualDomainRange(new IntNode(10), new IntNode(20))); } @Test void givenStoredExecutionWhenCounterfactualRequestIsMadeThenExplainabilityEventIsEmittedWithNullDomains() { doGivenStoredExecutionWhenCounterfactualRequestIsMadeThenExplainabilityEventIsEmittedTest(null); } @SuppressWarnings("unchecked") void doGivenStoredExecutionWhenCounterfactualRequestIsMadeThenExplainabilityEventIsEmittedTest(CounterfactualDomain domain) { Storage<String, Decision> decisionStorage = mock(Storage.class); Storage<String, CounterfactualExplainabilityRequest> counterfactualStorage = mock(Storage.class); ArgumentCaptor<BaseExplainabilityRequest> explainabilityEventArgumentCaptor = ArgumentCaptor.forClass(BaseExplainabilityRequest.class); when(decisionStorage.containsKey(eq(TEST_EXECUTION_ID))).thenReturn(true); when(trustyStorageServiceMock.getDecisionsStorage()).thenReturn(decisionStorage); when(trustyStorageServiceMock.getCounterfactualRequestStorage()).thenReturn(counterfactualStorage); when(decisionStorage.get(eq(TEST_EXECUTION_ID))).thenReturn(TrustyServiceTestUtils.buildCorrectDecision(TEST_EXECUTION_ID)); // The Goals structures must be comparable to the original decisions outcomes. // The Search Domain structures must be identical those of the original decision inputs. trustyService.requestCounterfactuals(TEST_EXECUTION_ID, List.of(new NamedTypedValue("Fine", new StructureValue("tFine", Map.of("Amount", new UnitValue("number", "number", new IntNode(0)), "Points", new UnitValue("number", "number", new IntNode(0))))), new NamedTypedValue("Should the driver be suspended?", new UnitValue("string", "string", new TextNode("No")))), List.of(new CounterfactualSearchDomain("Violation", new CounterfactualSearchDomainStructureValue("tViolation", Map.of("Type", new CounterfactualSearchDomainUnitValue("string", "string", true, domain), "Actual Speed", new CounterfactualSearchDomainUnitValue("number", "number", true, domain), "Speed Limit", new CounterfactualSearchDomainUnitValue("number", "number", true, domain)))), new CounterfactualSearchDomain("Driver", new CounterfactualSearchDomainStructureValue("tDriver", Map.of("Age", new CounterfactualSearchDomainUnitValue("number", "number", true, domain), "Points", new CounterfactualSearchDomainUnitValue("number", "number", true, domain)))))); verify(explainabilityRequestProducerMock).sendEvent(explainabilityEventArgumentCaptor.capture()); BaseExplainabilityRequest event = explainabilityEventArgumentCaptor.getValue(); assertNotNull(event); assertTrue(event instanceof CounterfactualExplainabilityRequest); CounterfactualExplainabilityRequest request = (CounterfactualExplainabilityRequest) event; assertEquals(TEST_EXECUTION_ID, request.getExecutionId()); } @Test @SuppressWarnings("unchecked") void givenStoredExecutionWhenCounterfactualRequestIsMadeThenExplainabilityEventHasCorrectPayload() { Storage<String, Decision> decisionStorage = mock(Storage.class); Storage<String, CounterfactualExplainabilityRequest> counterfactualStorage = mock(Storage.class); ArgumentCaptor<BaseExplainabilityRequest> explainabilityEventArgumentCaptor = ArgumentCaptor.forClass(BaseExplainabilityRequest.class); Decision decision = new Decision( TEST_EXECUTION_ID, TEST_SOURCE_URL, TEST_SERVICE_URL, 0L, true, null, "model", "modelNamespace", List.of( new DecisionInput("IN1", "yearsOfService", new UnitValue("integer", "integer", new IntNode(10)))), List.of( new DecisionOutcome( "OUT1", "salary", "SUCCEEDED", new UnitValue("integer", "integer", new IntNode(1000)), Collections.emptyList(), Collections.emptyList()))); when(decisionStorage.containsKey(eq(TEST_EXECUTION_ID))).thenReturn(true); when(trustyStorageServiceMock.getDecisionsStorage()).thenReturn(decisionStorage); when(trustyStorageServiceMock.getCounterfactualRequestStorage()).thenReturn(counterfactualStorage); when(decisionStorage.get(eq(TEST_EXECUTION_ID))).thenReturn(decision); trustyService.requestCounterfactuals(TEST_EXECUTION_ID, List.of(new NamedTypedValue("salary", new UnitValue("integer", "integer", new IntNode(2000)))), List.of(new CounterfactualSearchDomain("yearsOfService", new CounterfactualSearchDomainUnitValue("integer", "integer", false, new CounterfactualDomainRange(new IntNode(10), new IntNode(30)))))); verify(explainabilityRequestProducerMock).sendEvent(explainabilityEventArgumentCaptor.capture()); BaseExplainabilityRequest event = explainabilityEventArgumentCaptor.getValue(); CounterfactualExplainabilityRequest request = (CounterfactualExplainabilityRequest) event; assertEquals(TEST_EXECUTION_ID, request.getExecutionId()); assertEquals(TEST_SERVICE_URL, request.getServiceUrl()); //Check original input value has been copied into CF request assertEquals(1, request.getOriginalInputs().size()); assertTrue(request.getOriginalInputs().stream().anyMatch(i -> i.getName().equals("yearsOfService"))); //It is safe to use the iterator unchecked as the collection only contains one item assertEquals(decision.getInputs().iterator().next().getValue().toUnit().getValue().asInt(), request.getOriginalInputs().iterator().next().getValue().toUnit().getValue().asInt()); //Check CF goals have been copied into CF request assertEquals(1, request.getGoals().size()); assertTrue(request.getGoals().stream().anyMatch(g -> g.getName().equals("salary"))); //It is safe to use the iterator unchecked as the collection only contains one item assertEquals(2000, request.getGoals().iterator().next().getValue().toUnit().getValue().asInt()); //Check CF search domains have been copied into CF request assertEquals(1, request.getSearchDomains().size()); assertTrue(request.getSearchDomains().stream().anyMatch(sd -> sd.getName().equals("yearsOfService"))); //It is safe to use the iterator unchecked as the collection only contains one item CounterfactualSearchDomainValue searchDomain = request.getSearchDomains().iterator().next().getValue(); assertTrue(searchDomain instanceof CounterfactualSearchDomainUnitValue); CounterfactualSearchDomainUnitValue unit = (CounterfactualSearchDomainUnitValue) searchDomain; assertFalse(unit.isFixed()); assertNotNull(unit.getDomain()); assertTrue(unit.getDomain() instanceof CounterfactualDomainRange); CounterfactualDomainRange range = (CounterfactualDomainRange) unit.getDomain(); assertEquals(10, range.getLowerBound().asInt()); assertEquals(30, range.getUpperBound().asInt()); //Check Max Running Time Seconds assertEquals(MAX_RUNNING_TIME_SECONDS, request.getMaxRunningTimeSeconds()); } @Test @SuppressWarnings({ "unchecked", "rawtypes" }) void givenStoredCounterfactualRequestsWhenGetCounterfactualRequestsThenRequestsAreReturned() { Storage<String, CounterfactualExplainabilityRequest> counterfactualStorage = mock(Storage.class); CounterfactualExplainabilityRequest request1 = mock(CounterfactualExplainabilityRequest.class); CounterfactualExplainabilityRequest request2 = mock(CounterfactualExplainabilityRequest.class); Query queryMock = mock(Query.class); when(queryMock.filter(any(List.class))).thenReturn(queryMock); when(queryMock.execute()).thenReturn(List.of(request1, request2)); when(counterfactualStorage.query()).thenReturn(queryMock); when(trustyStorageServiceMock.getCounterfactualRequestStorage()).thenReturn(counterfactualStorage); assertTrue(trustyService.getCounterfactualRequests(TEST_EXECUTION_ID).containsAll(List.of(request1, request2))); } @Test @SuppressWarnings({ "unchecked", "rawtypes" }) void givenNoStoredCounterfactualRequestWhenGetCounterfactualRequestThenIllegalArgumentExceptionIsThrown() { Storage<String, CounterfactualExplainabilityRequest> counterfactualStorage = mock(Storage.class); Query queryMock = mock(Query.class); when(queryMock.filter(any(List.class))).thenReturn(queryMock); when(queryMock.execute()).thenReturn(new ArrayList<>()); when(counterfactualStorage.query()).thenReturn(queryMock); when(trustyStorageServiceMock.getCounterfactualRequestStorage()).thenReturn(counterfactualStorage); assertThrows(IllegalArgumentException.class, () -> trustyService.getCounterfactualRequest(TEST_EXECUTION_ID, TEST_COUNTERFACTUAL_ID)); } @Test @SuppressWarnings({ "unchecked", "rawtypes" }) void givenMultipleStoredCounterfactualRequestsWhenGetCounterfactualRequestThenIllegalArgumentExceptionIsThrown() { Storage<String, CounterfactualExplainabilityRequest> counterfactualStorage = mock(Storage.class); CounterfactualExplainabilityRequest request1 = mock(CounterfactualExplainabilityRequest.class); CounterfactualExplainabilityRequest request2 = mock(CounterfactualExplainabilityRequest.class); Query queryMock = mock(Query.class); when(queryMock.filter(any(List.class))).thenReturn(queryMock); when(queryMock.execute()).thenReturn(List.of(request1, request2)); when(counterfactualStorage.query()).thenReturn(queryMock); when(trustyStorageServiceMock.getCounterfactualRequestStorage()).thenReturn(counterfactualStorage); assertThrows(IllegalArgumentException.class, () -> trustyService.getCounterfactualRequest(TEST_EXECUTION_ID, TEST_COUNTERFACTUAL_ID)); } @Test @SuppressWarnings({ "unchecked", "rawtypes" }) void givenSingleStoredCounterfactualRequestWhenGetCounterfactualRequestThenRequestIsReturned() { Storage<String, CounterfactualExplainabilityRequest> counterfactualStorage = mock(Storage.class); CounterfactualExplainabilityRequest request = mock(CounterfactualExplainabilityRequest.class); Query queryMock = mock(Query.class); when(queryMock.filter(any(List.class))).thenReturn(queryMock); when(queryMock.execute()).thenReturn(List.of(request)); when(counterfactualStorage.query()).thenReturn(queryMock); when(trustyStorageServiceMock.getCounterfactualRequestStorage()).thenReturn(counterfactualStorage); assertEquals(request, trustyService.getCounterfactualRequest(TEST_EXECUTION_ID, TEST_COUNTERFACTUAL_ID)); } @Test @SuppressWarnings({ "unchecked", "rawtypes" }) void givenStoredCounterfactualResultsWhenGetCounterfactualResultsThenResultsAreReturned() { Storage<String, CounterfactualExplainabilityResult> counterfactualStorage = mock(Storage.class); CounterfactualExplainabilityResult result1 = mock(CounterfactualExplainabilityResult.class); CounterfactualExplainabilityResult result2 = mock(CounterfactualExplainabilityResult.class); Query queryMock = mock(Query.class); when(queryMock.filter(any(List.class))).thenReturn(queryMock); when(queryMock.execute()).thenReturn(List.of(result1, result2)); when(counterfactualStorage.query()).thenReturn(queryMock); when(trustyStorageServiceMock.getCounterfactualResultStorage()).thenReturn(counterfactualStorage); assertTrue(trustyService.getCounterfactualResults(TEST_EXECUTION_ID, TEST_COUNTERFACTUAL_ID).containsAll(List.of(result1, result2))); } @Test @SuppressWarnings({ "unchecked", "rawtypes" }) void givenNoStoredCounterfactualResultsWhenGetCounterfactualResultsThenEmptyCollectionIsReturned() { Storage<String, CounterfactualExplainabilityResult> counterfactualStorage = mock(Storage.class); Query queryMock = mock(Query.class); when(queryMock.filter(any(List.class))).thenReturn(queryMock); when(queryMock.execute()).thenReturn(new ArrayList()); when(counterfactualStorage.query()).thenReturn(queryMock); when(trustyStorageServiceMock.getCounterfactualResultStorage()).thenReturn(counterfactualStorage); assertTrue(trustyService.getCounterfactualResults(TEST_EXECUTION_ID, TEST_COUNTERFACTUAL_ID).isEmpty()); } private DMNModelWithMetadata buildDmnModel(String model) { return new DMNModelWithMetadata(buildDmnModelIdentifier(), model); } private DMNModelMetadata buildDmnModelIdentifier() { return new DMNModelMetadata("groupId", "artifactId", "version", "dmnVersion", "name", "namespace"); } }
oracle/graal
37,688
substratevm/src/com.oracle.svm.driver/src/com/oracle/svm/driver/APIOptionHandler.java
/* * Copyright (c) 2018, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.svm.driver; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import org.graalvm.collections.EconomicMap; import org.graalvm.nativeimage.ImageSingletons; import org.graalvm.nativeimage.hosted.Feature; import com.oracle.svm.common.option.CommonOptionParser; import com.oracle.svm.common.option.IntentionallyUnsupportedOptions; import com.oracle.svm.common.option.LocatableOption; import com.oracle.svm.common.option.MultiOptionValue; import com.oracle.svm.core.SubstrateOptions; import com.oracle.svm.core.option.APIOption; import com.oracle.svm.core.option.APIOption.APIOptionKind; import com.oracle.svm.core.option.APIOptionGroup; import com.oracle.svm.core.option.BundleMember; import com.oracle.svm.core.option.HostedOptionKey; import com.oracle.svm.core.option.OptionOrigin; import com.oracle.svm.core.option.OptionUtils; import com.oracle.svm.core.option.SubstrateOptionsParser; import com.oracle.svm.core.util.VMError; import com.oracle.svm.driver.APIOptionHandler.HostedOptionInfo; import com.oracle.svm.driver.NativeImage.ArgumentQueue; import com.oracle.svm.hosted.FeatureImpl; import com.oracle.svm.hosted.option.HostedOptionParser; import com.oracle.svm.util.LogUtils; import com.oracle.svm.util.ModuleSupport; import com.oracle.svm.util.ReflectionUtil; import com.oracle.svm.util.ReflectionUtil.ReflectionUtilError; import com.oracle.svm.util.StringUtil; import jdk.graal.compiler.options.OptionDescriptor; import jdk.graal.compiler.options.OptionDescriptors; import jdk.graal.compiler.options.OptionStability; import jdk.graal.compiler.options.OptionsContainer; import jdk.graal.compiler.options.OptionsParser; class APIOptionHandler extends NativeImage.OptionHandler<NativeImage> { private static final String ENTER_UNLOCK_SCOPE = SubstrateOptionsParser.commandArgument(SubstrateOptions.UnlockExperimentalVMOptions, "+"); private static final String LEAVE_UNLOCK_SCOPE = SubstrateOptionsParser.commandArgument(SubstrateOptions.UnlockExperimentalVMOptions, "-"); record OptionInfo(String[] variants, char[] valueSeparator, String builderOption, String defaultValue, String helpText, boolean defaultFinal, String deprecationWarning, List<Function<Object, Object>> valueTransformers, APIOptionGroup group, boolean extra, boolean launcherOption) { boolean isDeprecated() { return deprecationWarning.length() > 0; } } record PathsOptionInfo(String delimiter, BundleMember.Role role) { } private final SortedMap<String, OptionInfo> apiOptions; private final Map<String, GroupInfo> groupInfos; private final Map<String, PathsOptionInfo> pathOptions; record HostedOptionInfo(Boolean isStable, Boolean isBoolean) { } private final HostedOptionInfo injectedKnownHostedRegularOptionInfo = new HostedOptionInfo(false, false); private final HostedOptionInfo injectedKnownHostedBooleanOptionInfo = new HostedOptionInfo(false, true); private final Map<String, HostedOptionInfo> allOptionNames; private int numberOfActiveUnlockExperimentalVMOptions = 0; private Set<String> illegalExperimentalOptions = new HashSet<>(0); APIOptionHandler(NativeImage nativeImage) { super(nativeImage); if (NativeImage.IS_AOT) { APIOptionSupport support = ImageSingletons.lookup(APIOptionSupport.class); groupInfos = support.groupInfos(); pathOptions = support.pathOptions(); allOptionNames = support.allOptionNames(); apiOptions = support.options(); } else { groupInfos = new HashMap<>(); pathOptions = new HashMap<>(); allOptionNames = new HashMap<>(); ClassLoader cl = nativeImage.getClass().getClassLoader(); apiOptions = extractOptions(OptionsContainer.getDiscoverableOptions(cl), groupInfos, pathOptions, allOptionNames); } } static SortedMap<String, OptionInfo> extractOptions(Iterable<OptionDescriptors> optionDescriptors, Map<String, GroupInfo> groupInfos, Map<String, PathsOptionInfo> pathOptions, Map<String, HostedOptionInfo> allOptionNames) { EconomicMap<String, OptionDescriptor> hostedOptions = EconomicMap.create(); EconomicMap<String, OptionDescriptor> runtimeOptions = EconomicMap.create(); HostedOptionParser.collectOptions(optionDescriptors, hostedOptions, runtimeOptions); SortedMap<String, OptionInfo> apiOptions = new TreeMap<>(); Map<Class<? extends APIOptionGroup>, APIOptionGroup> groupInstances = new HashMap<>(); hostedOptions.getValues().forEach(o -> { extractOption(NativeImage.oH, o, apiOptions, groupInfos, groupInstances, allOptionNames); extractPathOption(NativeImage.oH, o, pathOptions); }); runtimeOptions.getValues().forEach(o -> extractOption(NativeImage.oR, o, apiOptions, groupInfos, groupInstances, allOptionNames)); groupInfos.forEach((groupName, groupInfo) -> { if (groupInfo.defaultValues.size() > 1) { VMError.shouldNotReachHere(String.format("APIOptionGroup %s must only have a single default (but has: %s)", groupName, String.join(", ", groupInfo.defaultValues))); } }); return apiOptions; } private static void extractOption(String optionPrefix, OptionDescriptor optionDescriptor, SortedMap<String, OptionInfo> apiOptions, Map<String, GroupInfo> groupInfos, Map<Class<? extends APIOptionGroup>, APIOptionGroup> groupInstances, Map<String, HostedOptionInfo> allOptionNames) { Class<?> optionValueType = optionDescriptor.getOptionValueType(); boolean isBooleanOption = optionValueType.equals(Boolean.class); for (APIOption apiAnnotation : OptionUtils.getAnnotationsByType(optionDescriptor, APIOption.class)) { String builderOption = optionPrefix; if (apiAnnotation.name().length <= 0) { VMError.shouldNotReachHere(String.format("APIOption for %s does not provide a name entry", optionDescriptor.getLocation())); } String apiOptionName = APIOption.Utils.optionName(apiAnnotation.name()[0]); String rawOptionName = optionDescriptor.getName(); APIOptionGroup group = null; String defaultValue = null; if (optionValueType.isArray()) { VMError.guarantee(optionDescriptor.getOptionKey() instanceof HostedOptionKey, "Only HostedOptionKeys are allowed to have array type key values."); optionValueType = optionValueType.getComponentType(); } boolean hasFixedValue = apiAnnotation.fixedValue().length > 0; if (isBooleanOption) { if (!apiAnnotation.group().equals(APIOption.NullGroup.class)) { try { Class<? extends APIOptionGroup> groupClass = apiAnnotation.group(); APIOptionGroup g = group = groupInstances.computeIfAbsent(groupClass, ReflectionUtil::newInstance); String groupName = APIOption.Utils.groupName(group); GroupInfo groupInfo = groupInfos.computeIfAbsent(groupName, _ -> new GroupInfo(g)); if (group.helpText() == null || group.helpText().isEmpty()) { VMError.shouldNotReachHere(String.format("APIOptionGroup %s(%s) needs to provide help text", groupClass.getName(), group.name())); } String groupMember = apiAnnotation.name()[0]; groupInfo.supportedValues.add(groupMember); apiOptionName = groupName + groupMember; Boolean isEnabled = (Boolean) optionDescriptor.getOptionKey().getDefaultValue(); if (isEnabled) { groupInfo.defaultValues.add(groupMember); /* Use OptionInfo.defaultValue to remember group default value */ defaultValue = groupMember; } } catch (ReflectionUtilError ex) { throw VMError.shouldNotReachHere( "Class specified as group for @APIOption " + apiOptionName + " cannot be loaded or instantiated: " + apiAnnotation.group().getTypeName(), ex.getCause()); } } if (apiAnnotation.defaultValue().length > 0) { VMError.shouldNotReachHere(String.format("Boolean APIOption %s(%s) cannot use APIOption.defaultValue", apiOptionName, rawOptionName)); } if (hasFixedValue) { VMError.shouldNotReachHere(String.format("Boolean APIOption %s(%s) cannot use APIOption.fixedValue", apiOptionName, rawOptionName)); } builderOption += apiAnnotation.kind().equals(APIOptionKind.Negated) ? "-" : "+"; builderOption += rawOptionName; } else { if (!apiAnnotation.group().equals(APIOption.NullGroup.class)) { VMError.shouldNotReachHere(String.format("Using @APIOption.group not supported for non-boolean APIOption %s(%s)", apiOptionName, rawOptionName)); } if (apiAnnotation.kind().equals(APIOptionKind.Negated)) { VMError.shouldNotReachHere(String.format("Non-boolean APIOption %s(%s) cannot use APIOptionKind.Negated", apiOptionName, rawOptionName)); } if (apiAnnotation.defaultValue().length > 1) { VMError.shouldNotReachHere(String.format("APIOption %s(%s) cannot have more than one APIOption.defaultValue", apiOptionName, rawOptionName)); } if (apiAnnotation.fixedValue().length > 1) { VMError.shouldNotReachHere(String.format("APIOption %s(%s) cannot have more than one APIOption.fixedValue", apiOptionName, rawOptionName)); } if (hasFixedValue && apiAnnotation.defaultValue().length > 0) { VMError.shouldNotReachHere(String.format("APIOption %s(%s) APIOption.defaultValue and APIOption.fixedValue cannot be combined", apiOptionName, rawOptionName)); } if (apiAnnotation.defaultValue().length > 0) { defaultValue = apiAnnotation.defaultValue()[0]; } if (hasFixedValue) { defaultValue = apiAnnotation.fixedValue()[0]; } builderOption += rawOptionName; builderOption += "="; } String helpText = optionDescriptor.getHelp().getFirst(); if (!apiAnnotation.customHelp().isEmpty()) { helpText = apiAnnotation.customHelp(); } if (helpText == null || helpText.isEmpty()) { VMError.shouldNotReachHere(String.format("APIOption %s(%s) needs to provide help text", apiOptionName, rawOptionName)); } if (group == null) { /* Regular help text needs to start with lower-case letter */ helpText = startLowerCase(helpText); } List<Function<Object, Object>> valueTransformers = new ArrayList<>(apiAnnotation.valueTransformer().length); for (Class<? extends Function<Object, Object>> transformerClass : apiAnnotation.valueTransformer()) { try { valueTransformers.add(ReflectionUtil.newInstance(transformerClass)); } catch (ReflectionUtilError ex) { throw VMError.shouldNotReachHere( "Class specified as valueTransformer for @APIOption " + apiOptionName + " cannot be loaded or instantiated: " + transformerClass.getTypeName(), ex.getCause()); } } if (apiAnnotation.valueSeparator().length == 0) { throw VMError.shouldNotReachHere(String.format("APIOption %s(%s) does not specify any valueSeparator", apiOptionName, rawOptionName)); } for (char valueSeparator : apiAnnotation.valueSeparator()) { if (valueSeparator == APIOption.WHITESPACE_SEPARATOR) { String msgTail = " cannot use APIOption.WHITESPACE_SEPARATOR as value separator"; if (isBooleanOption) { throw VMError.shouldNotReachHere(String.format("Boolean APIOption %s(%s)" + msgTail, apiOptionName, rawOptionName)); } if (hasFixedValue) { VMError.shouldNotReachHere(String.format("APIOption %s(%s) with fixed value" + msgTail, apiOptionName, rawOptionName)); } if (defaultValue != null) { VMError.shouldNotReachHere(String.format("APIOption %s(%s) with default value" + msgTail, apiOptionName, rawOptionName)); } } } boolean defaultFinal = isBooleanOption || hasFixedValue; apiOptions.put(apiOptionName, new APIOptionHandler.OptionInfo(apiAnnotation.name(), apiAnnotation.valueSeparator(), builderOption, defaultValue, helpText, defaultFinal, apiAnnotation.deprecated(), valueTransformers, group, apiAnnotation.extra(), apiAnnotation.launcherOption())); } if (!IntentionallyUnsupportedOptions.contains(optionDescriptor.getOptionKey())) { allOptionNames.put(optionDescriptor.getName(), new HostedOptionInfo(optionDescriptor.getStability() == OptionStability.STABLE, isBooleanOption)); } } private static void extractPathOption(String optionPrefix, OptionDescriptor optionDescriptor, Map<String, PathsOptionInfo> pathOptions) { Object defaultValue = optionDescriptor.getOptionKey().getDefaultValue(); if (defaultValue instanceof MultiOptionValue) { var multiOptionDefaultValue = ((MultiOptionValue<?>) defaultValue); if (Path.class.isAssignableFrom(multiOptionDefaultValue.getValueType())) { String rawOptionName = optionDescriptor.getName(); String builderOption = optionPrefix + rawOptionName; BundleMember.Role role = BundleMember.Role.Ignore; for (BundleMember bundleMember : OptionUtils.getAnnotationsByType(optionDescriptor, BundleMember.class)) { role = bundleMember.role(); } pathOptions.put(builderOption, new PathsOptionInfo(multiOptionDefaultValue.getDelimiter(), role)); } } } private static String startLowerCase(String str) { return str.substring(0, 1).toLowerCase(Locale.ROOT) + str.substring(1); } void injectKnownHostedOption(String optionName) { String baseOptionName; HostedOptionInfo optionInfo; if (optionName.endsWith("=")) { baseOptionName = optionName.substring(0, optionName.length() - 1); optionInfo = injectedKnownHostedRegularOptionInfo; } else { baseOptionName = optionName; optionInfo = injectedKnownHostedBooleanOptionInfo; } allOptionNames.put(baseOptionName, optionInfo); } @Override boolean consume(ArgumentQueue args) { String headArg = args.peek(); String translatedOption = translateOption(args); if (translatedOption != null) { args.poll(); nativeImage.addPlainImageBuilderArg(translatedOption, args.argumentOrigin + OptionOrigin.isAPISuffix); return true; } if (ENTER_UNLOCK_SCOPE.equals(headArg)) { if (args.numberOfFirstObservedActiveUnlockExperimentalVMOptions < 0) { /* * Remember numberOfExperimentalOptionsUnlocks per ArgumentQueue for verification * purposes only. Each queue cannot lock more than it unlocks. */ args.numberOfFirstObservedActiveUnlockExperimentalVMOptions = numberOfActiveUnlockExperimentalVMOptions; } numberOfActiveUnlockExperimentalVMOptions++; } else if (LEAVE_UNLOCK_SCOPE.equals(headArg)) { if (numberOfActiveUnlockExperimentalVMOptions <= 0 || numberOfActiveUnlockExperimentalVMOptions <= args.numberOfFirstObservedActiveUnlockExperimentalVMOptions) { throw VMError.shouldNotReachHere("Unlocking of experimental options in inconsistent state: trying to lock more scopes than exist or allowed."); } numberOfActiveUnlockExperimentalVMOptions--; } else if (!OptionOrigin.isAPI(args.argumentOrigin) && headArg.startsWith(NativeImage.oH)) { validateHostedOption(headArg, args.argumentOrigin); } for (Entry<String, GroupInfo> entry : groupInfos.entrySet()) { String groupNameAndSeparator = entry.getKey(); if (headArg.startsWith(groupNameAndSeparator)) { GroupInfo groupInfo = entry.getValue(); String groupName = APIOption.Utils.optionName(groupInfo.group.name()); NativeImage.showError("In " + args.argumentOrigin + " '" + headArg.substring(groupNameAndSeparator.length()) + "' is not a valid value for the option " + groupName + ". Supported values are " + StringUtil.joinSingleQuoted(groupInfo.supportedValues) + "."); } } return false; } private void validateHostedOption(String hostedOptionArg, String argumentOrigin) { String optionName = hostedOptionArg.substring(NativeImage.oH.length()).split("=", 2)[0].split("@", 2)[0]; char booleanPrefix = 0; if (!optionName.isEmpty()) { char first = optionName.charAt(0); if (first == '+' || first == '-') { optionName = optionName.substring(1); booleanPrefix = first; } } HostedOptionInfo info = allOptionNames.get(optionName); if (info == null) { List<String> matches = new ArrayList<>(); OptionsParser.collectFuzzyMatches(() -> allOptionNames.keySet().iterator(), optionName, matches, Function.identity()); StringBuilder msg = new StringBuilder("Unrecognized option "); msg.append(optionDescription(optionName, booleanPrefix, argumentOrigin)).append('.'); if (!matches.isEmpty()) { msg.append(" Did you mean one of these:"); for (var match : matches) { msg.append(' ').append('\'').append(NativeImage.oH); boolean matchIsBoolean = allOptionNames.get(match).isBoolean; if (matchIsBoolean) { msg.append(CommonOptionParser.PLUS_MINUS_BOOLEAN_OPTION_PREFIX); } msg.append(match); if (!matchIsBoolean) { msg.append("=..."); } msg.append('\''); } msg.append('.'); } msg.append(" Use '--expert-options' (see also '--help-extra') to list all available options."); throw NativeImage.showError(msg.toString()); } if ((booleanPrefix != 0) != info.isBoolean()) { var optionDescription = optionDescription(optionName, booleanPrefix, argumentOrigin); if (info.isBoolean()) { throw NativeImage.showError(CommonOptionParser.MISMATCH_BOOLEAN_OPTION.formatted(optionDescription, optionName)); } else { throw NativeImage.showError(CommonOptionParser.MISMATCH_NON_BOOLEAN_OPTION.formatted(optionDescription, optionName)); } } if (numberOfActiveUnlockExperimentalVMOptions == 0 && !info.isStable()) { illegalExperimentalOptions.add(hostedOptionArg); } } private static String optionDescription(String optionName, char booleanPrefix, String argumentOrigin) { var result = new StringBuilder("'" + NativeImage.oH); if (booleanPrefix != 0) { result.append(booleanPrefix); } result.append(optionName); if (booleanPrefix == 0) { result.append("=..."); } result.append("' from ").append(OptionOrigin.from(argumentOrigin)); return result.toString(); } String translateOption(ArgumentQueue argQueue) { OptionInfo option = null; boolean whitespaceSeparated = false; String[] optionNameAndOptionValue = null; String argumentOriginString = OptionOrigin.from(argQueue.argumentOrigin).toString(); if (nativeImage.useBundle()) { argumentOriginString = nativeImage.bundleSupport.cleanupBuilderOutput(argumentOriginString); } found: for (OptionInfo optionInfo : apiOptions.values()) { for (String variant : optionInfo.variants) { String optionName; if (optionInfo.group == null) { optionName = APIOption.Utils.optionName(variant); } else if (optionInfo.group.multiValueOption() != null) { String headArg = argQueue.peek(); if (!headArg.startsWith(APIOption.Utils.groupName(optionInfo.group))) { continue; } return headArg.replace(APIOption.Utils.optionName(optionInfo.group.name()), "-H:" + optionInfo.group.multiValueOption().getName()); } else { optionName = APIOption.Utils.groupName(optionInfo.group) + variant; } String headArg = argQueue.peek(); if ((optionInfo.defaultFinal || optionInfo.defaultValue != null) && headArg.equals(optionName)) { option = optionInfo; optionNameAndOptionValue = new String[]{optionName}; break found; } for (char valueSeparator : optionInfo.valueSeparator) { if (valueSeparator == APIOption.WHITESPACE_SEPARATOR && headArg.equals(optionName)) { argQueue.poll(); String optionValue = argQueue.peek(); if (optionValue == null) { NativeImage.showError(headArg + " from " + argumentOriginString + " requires option argument"); } option = optionInfo; optionNameAndOptionValue = new String[]{headArg, optionValue}; whitespaceSeparated = true; break found; } else { String optionNameWithSeparator = optionName + APIOption.Utils.valueSeparatorToString(valueSeparator); if (headArg.startsWith(optionNameWithSeparator)) { option = optionInfo; int length = optionNameWithSeparator.length(); optionNameAndOptionValue = new String[]{headArg.substring(0, length), headArg.substring(length)}; break found; } } } } } if (option != null) { if (!option.deprecationWarning.isEmpty()) { LogUtils.warning("Using a deprecated option " + optionNameAndOptionValue[0] + " from " + argumentOriginString + ". " + option.deprecationWarning); } String builderOption = option.builderOption; /* If option is in group, defaultValue has different use */ String optionValue = option.group != null ? null : option.defaultValue; if (optionNameAndOptionValue.length == 2) { if (option.defaultFinal) { NativeImage.showError("Passing values to option " + optionNameAndOptionValue[0] + " from " + argumentOriginString + " is not supported."); } optionValue = optionNameAndOptionValue[1]; } if (optionValue != null) { Object transformed = optionValue; for (Function<Object, Object> transformer : option.valueTransformers) { transformed = transformer.apply(transformed); } builderOption += transformed.toString(); } if (nativeImage.useBundle() && option.launcherOption) { if (whitespaceSeparated) { nativeImage.bundleSupport.bundleLauncherArgs.addAll(List.of(optionNameAndOptionValue)); } else { nativeImage.bundleSupport.bundleLauncherArgs.add(argQueue.peek()); } } return builderOption; } return null; } String transformBuilderArgument(String builderArgument, BiFunction<Path, BundleMember.Role, Path> transformFunction) { BuilderArgumentParts argumentParts = BuilderArgumentParts.from(builderArgument); if (argumentParts.optionValue == null) { /* Option has no value that could need transforming -> early exit */ return builderArgument; } PathsOptionInfo pathsOptionInfo = pathOptions.get(argumentParts.option.name); if (pathsOptionInfo == null || pathsOptionInfo.role == BundleMember.Role.Ignore) { /* Not an option that request value-transforming -> early exit */ return builderArgument; } /* * Option requests value-transformations, first split value aggregate into individual values */ List<String> rawEntries; String delimiter = pathsOptionInfo.delimiter; if (delimiter.isEmpty()) { rawEntries = List.of(argumentParts.optionValue); } else { rawEntries = List.of(StringUtil.split(argumentParts.optionValue, delimiter)); } /* Perform value-transformation on individual values with given transformFunction */ try { String transformedOptionValue = rawEntries.stream() .filter(s -> !s.isEmpty()) .map(this::tryCanonicalize) .map(src -> transformFunction.apply(src, pathsOptionInfo.role)) .map(Path::toString) .collect(Collectors.joining(delimiter)); /* Update argumentParts with transformed aggregate value and return as string */ argumentParts.optionValue = transformedOptionValue; return argumentParts.toString(); } catch (BundleSupport.BundlePathSubstitutionError error) { String originStr = argumentParts.option.origin; Object optionOrigin = OptionOrigin.from(originStr, false); if (optionOrigin == null && originStr != null) { /* If we cannot get an OptionOrigin, fallback to the raw originStr */ optionOrigin = originStr; } String fromPart = optionOrigin != null ? " from '" + optionOrigin + "'" : ""; throw NativeImage.showError("Failed to prepare path entry '" + error.origPath + "' of option " + argumentParts.option.name + fromPart + " for bundle inclusion.", error); } } static final class BuilderArgumentParts { final LocatableOption option; String optionValue; private BuilderArgumentParts(LocatableOption option, String optionValue) { this.option = option; this.optionValue = optionValue; } static BuilderArgumentParts from(String builderArgument) { String[] nameAndValue = StringUtil.split(builderArgument, "=", 2); String optionValue = nameAndValue.length != 2 ? null : nameAndValue[1]; return new BuilderArgumentParts(LocatableOption.from(nameAndValue[0]), optionValue); } @Override public String toString() { String optionName = option.rawName(); return optionValue == null ? optionName : optionName + "=" + optionValue; } } private Path tryCanonicalize(String path) { Path origPath = Paths.get(path); try { return nativeImage.canonicalize(origPath); } catch (NativeImage.NativeImageError e) { /* Allow features to handle the path string. */ return origPath; } } void printOptions(Consumer<String> println, boolean extra) { SortedMap<String, List<OptionInfo>> optionInfo = new TreeMap<>(); apiOptions.forEach((optionName, option) -> { if (option.isDeprecated() || option.extra != extra) { return; } String groupOrOptionName = option.group != null ? APIOption.Utils.groupName(option.group) : optionName; if (optionInfo.containsKey(groupOrOptionName)) { List<OptionInfo> options = optionInfo.get(groupOrOptionName); if (options.size() == 1) { /* Switch from singletonList to ArrayList */ options = new ArrayList<>(options); optionInfo.put(groupOrOptionName, options); } options.add(option); } else { /* Start with space efficient singletonList */ optionInfo.put(groupOrOptionName, List.of(option)); } }); optionInfo.forEach((optionName, options) -> { if (options.size() == 1) { OptionInfo singleOption = options.get(0); if (singleOption.group == null) { SubstrateOptionsParser.printOption(println, optionName, singleOption.helpText, 4, 22, 66); } else { /* * Only print option group with single entry if not enabled by default anyway. */ if (!Arrays.asList(singleOption.variants).contains(singleOption.defaultValue)) { printGroupOption(println, optionName, options); } } } else { printGroupOption(println, optionName, options); } }); } private static void printGroupOption(Consumer<String> println, String groupName, List<OptionInfo> options) { APIOptionGroup group = options.get(0).group; assert group != null; StringBuilder sb = new StringBuilder(); sb.append(startLowerCase(group.helpText())); if (!group.helpText().endsWith(".")) { sb.append("."); } sb.append(" Allowed options for <value>:"); SubstrateOptionsParser.printOption(println, groupName + "<value>", sb.toString(), 4, 22, 66); for (OptionInfo groupEntry : options) { assert groupEntry.group == group; sb.setLength(0); boolean first = true; boolean isDefault = false; for (String variant : groupEntry.variants) { if (variant.equals(groupEntry.defaultValue)) { isDefault = true; } if (first) { first = false; } else { sb.append(" | "); } sb.append("'").append(variant).append("'"); } sb.append(": ").append(groupEntry.helpText); if (isDefault) { sb.append(" (default)"); } SubstrateOptionsParser.printOption(println, "", sb.toString(), 4, 22, 66); } } public void ensureConsistentUnlockScopes(ArgumentQueue queue) { boolean inUnlockScope = false; for (String arg : queue.snapshot()) { if (ENTER_UNLOCK_SCOPE.equals(arg)) { if (inUnlockScope) { LogUtils.warning("'" + ENTER_UNLOCK_SCOPE + "' was used repeatedly. " + "Please check your build arguments, for example with '--verbose', and ensure experimental options are not unlocked more than once. " + "Use '" + LEAVE_UNLOCK_SCOPE + "' to lock access to experimental options again."); } inUnlockScope = true; } else if (LEAVE_UNLOCK_SCOPE.equals(arg)) { if (!inUnlockScope) { throw NativeImage.showError("'" + LEAVE_UNLOCK_SCOPE + "' was used but experimental options are not unlocked via '" + ENTER_UNLOCK_SCOPE + "'. " + "Please check your build arguments, for example with '--verbose', and ensure access to experimental options is only locked after it has been unlocked."); } inUnlockScope = false; } } /* Make sure any unlock scope is closed in the queue. */ if (inUnlockScope) { queue.add(LEAVE_UNLOCK_SCOPE); } } public void validateExperimentalOptions() { if (illegalExperimentalOptions.isEmpty()) { return; } for (var illegalOption : illegalExperimentalOptions) { LogUtils.warning("The option '" + illegalOption + "' is experimental and must be enabled via '" + ENTER_UNLOCK_SCOPE + "' in the future."); } LogUtils.warning("Please re-evaluate whether any experimental option is required, and either remove or unlock it. " + "The build output lists all active experimental options, including where they come from and possible alternatives. " + "If you think an experimental option should be considered as stable, please file an issue."); if ("true".equalsIgnoreCase(System.getenv().get("NATIVE_IMAGE_EXPERIMENTAL_OPTIONS_ARE_FATAL"))) { throw NativeImage.showError("Not all experimental options were unlocked."); } } } class GroupInfo { APIOptionGroup group; ArrayList<String> defaultValues; ArrayList<String> supportedValues; GroupInfo(APIOptionGroup group) { this.group = group; this.defaultValues = new ArrayList<>(); this.supportedValues = new ArrayList<>(); } } record APIOptionSupport(Map<String, GroupInfo> groupInfos, SortedMap<String, APIOptionHandler.OptionInfo> options, Map<String, APIOptionHandler.PathsOptionInfo> pathOptions, Map<String, HostedOptionInfo> allOptionNames) { } final class APIOptionFeature implements Feature { @Override public void afterRegistration(AfterRegistrationAccess access) { ModuleSupport.accessPackagesToClass(ModuleSupport.Access.EXPORT, APIOptionFeature.class, true, "jdk.graal.compiler", "jdk.graal.compiler.options"); } @Override public void duringSetup(DuringSetupAccess access) { FeatureImpl.DuringSetupAccessImpl accessImpl = (FeatureImpl.DuringSetupAccessImpl) access; Map<String, GroupInfo> groupInfos = new HashMap<>(); Map<String, APIOptionHandler.PathsOptionInfo> pathOptions = new HashMap<>(); Map<String, HostedOptionInfo> allOptionNames = new HashMap<>(); Iterable<OptionDescriptors> optionDescriptors = OptionsContainer.getDiscoverableOptions(accessImpl.getImageClassLoader().getClassLoader()); SortedMap<String, APIOptionHandler.OptionInfo> options = APIOptionHandler.extractOptions(optionDescriptors, groupInfos, pathOptions, allOptionNames); ImageSingletons.add(APIOptionSupport.class, new APIOptionSupport(groupInfos, options, pathOptions, allOptionNames)); } }
openjdk/jdk8
37,534
jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java
/* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; import javax.swing.text.View; import sun.swing.*; /** * BasicMenuItem implementation * * @author Georges Saab * @author David Karlton * @author Arnaud Weber * @author Fredrik Lagerblad */ public class BasicMenuItemUI extends MenuItemUI { protected JMenuItem menuItem = null; protected Color selectionBackground; protected Color selectionForeground; protected Color disabledForeground; protected Color acceleratorForeground; protected Color acceleratorSelectionForeground; /** * Accelerator delimiter string, such as {@code '+'} in {@code 'Ctrl+C'}. * @since 1.7 */ protected String acceleratorDelimiter; protected int defaultTextIconGap; protected Font acceleratorFont; protected MouseInputListener mouseInputListener; protected MenuDragMouseListener menuDragMouseListener; protected MenuKeyListener menuKeyListener; /** * <code>PropertyChangeListener</code> returned from * <code>createPropertyChangeListener</code>. You should not * need to access this field, rather if you want to customize the * <code>PropertyChangeListener</code> override * <code>createPropertyChangeListener</code>. * * @since 1.6 * @see #createPropertyChangeListener */ protected PropertyChangeListener propertyChangeListener; // BasicMenuUI also uses this. Handler handler; protected Icon arrowIcon = null; protected Icon checkIcon = null; protected boolean oldBorderPainted; /* diagnostic aids -- should be false for production builds. */ private static final boolean TRACE = false; // trace creates and disposes private static final boolean VERBOSE = false; // show reuse hits/misses private static final boolean DEBUG = false; // show bad params, misc. static void loadActionMap(LazyActionMap map) { // NOTE: BasicMenuUI also calls into this method. map.put(new Actions(Actions.CLICK)); BasicLookAndFeel.installAudioActionMap(map); } public static ComponentUI createUI(JComponent c) { return new BasicMenuItemUI(); } public void installUI(JComponent c) { menuItem = (JMenuItem) c; installDefaults(); installComponents(menuItem); installListeners(); installKeyboardActions(); } protected void installDefaults() { String prefix = getPropertyPrefix(); acceleratorFont = UIManager.getFont("MenuItem.acceleratorFont"); // use default if missing so that BasicMenuItemUI can be used in other // LAFs like Nimbus if (acceleratorFont == null) { acceleratorFont = UIManager.getFont("MenuItem.font"); } Object opaque = UIManager.get(getPropertyPrefix() + ".opaque"); if (opaque != null) { LookAndFeel.installProperty(menuItem, "opaque", opaque); } else { LookAndFeel.installProperty(menuItem, "opaque", Boolean.TRUE); } if(menuItem.getMargin() == null || (menuItem.getMargin() instanceof UIResource)) { menuItem.setMargin(UIManager.getInsets(prefix + ".margin")); } LookAndFeel.installProperty(menuItem, "iconTextGap", Integer.valueOf(4)); defaultTextIconGap = menuItem.getIconTextGap(); LookAndFeel.installBorder(menuItem, prefix + ".border"); oldBorderPainted = menuItem.isBorderPainted(); LookAndFeel.installProperty(menuItem, "borderPainted", UIManager.getBoolean(prefix + ".borderPainted")); LookAndFeel.installColorsAndFont(menuItem, prefix + ".background", prefix + ".foreground", prefix + ".font"); // MenuItem specific defaults if (selectionBackground == null || selectionBackground instanceof UIResource) { selectionBackground = UIManager.getColor(prefix + ".selectionBackground"); } if (selectionForeground == null || selectionForeground instanceof UIResource) { selectionForeground = UIManager.getColor(prefix + ".selectionForeground"); } if (disabledForeground == null || disabledForeground instanceof UIResource) { disabledForeground = UIManager.getColor(prefix + ".disabledForeground"); } if (acceleratorForeground == null || acceleratorForeground instanceof UIResource) { acceleratorForeground = UIManager.getColor(prefix + ".acceleratorForeground"); } if (acceleratorSelectionForeground == null || acceleratorSelectionForeground instanceof UIResource) { acceleratorSelectionForeground = UIManager.getColor(prefix + ".acceleratorSelectionForeground"); } // Get accelerator delimiter acceleratorDelimiter = UIManager.getString("MenuItem.acceleratorDelimiter"); if (acceleratorDelimiter == null) { acceleratorDelimiter = "+"; } // Icons if (arrowIcon == null || arrowIcon instanceof UIResource) { arrowIcon = UIManager.getIcon(prefix + ".arrowIcon"); } if (checkIcon == null || checkIcon instanceof UIResource) { checkIcon = UIManager.getIcon(prefix + ".checkIcon"); //In case of column layout, .checkIconFactory is defined for this UI, //the icon is compatible with it and useCheckAndArrow() is true, //then the icon is handled by the checkIcon. boolean isColumnLayout = MenuItemLayoutHelper.isColumnLayout( BasicGraphicsUtils.isLeftToRight(menuItem), menuItem); if (isColumnLayout) { MenuItemCheckIconFactory iconFactory = (MenuItemCheckIconFactory) UIManager.get(prefix + ".checkIconFactory"); if (iconFactory != null && MenuItemLayoutHelper.useCheckAndArrow(menuItem) && iconFactory.isCompatible(checkIcon, prefix)) { checkIcon = iconFactory.getIcon(menuItem); } } } } /** * @since 1.3 */ protected void installComponents(JMenuItem menuItem){ BasicHTML.updateRenderer(menuItem, menuItem.getText()); } protected String getPropertyPrefix() { return "MenuItem"; } protected void installListeners() { if ((mouseInputListener = createMouseInputListener(menuItem)) != null) { menuItem.addMouseListener(mouseInputListener); menuItem.addMouseMotionListener(mouseInputListener); } if ((menuDragMouseListener = createMenuDragMouseListener(menuItem)) != null) { menuItem.addMenuDragMouseListener(menuDragMouseListener); } if ((menuKeyListener = createMenuKeyListener(menuItem)) != null) { menuItem.addMenuKeyListener(menuKeyListener); } if ((propertyChangeListener = createPropertyChangeListener(menuItem)) != null) { menuItem.addPropertyChangeListener(propertyChangeListener); } } protected void installKeyboardActions() { installLazyActionMap(); updateAcceleratorBinding(); } void installLazyActionMap() { LazyActionMap.installLazyActionMap(menuItem, BasicMenuItemUI.class, getPropertyPrefix() + ".actionMap"); } public void uninstallUI(JComponent c) { menuItem = (JMenuItem)c; uninstallDefaults(); uninstallComponents(menuItem); uninstallListeners(); uninstallKeyboardActions(); MenuItemLayoutHelper.clearUsedParentClientProperties(menuItem); menuItem = null; } protected void uninstallDefaults() { LookAndFeel.uninstallBorder(menuItem); LookAndFeel.installProperty(menuItem, "borderPainted", oldBorderPainted); if (menuItem.getMargin() instanceof UIResource) menuItem.setMargin(null); if (arrowIcon instanceof UIResource) arrowIcon = null; if (checkIcon instanceof UIResource) checkIcon = null; } /** * @since 1.3 */ protected void uninstallComponents(JMenuItem menuItem){ BasicHTML.updateRenderer(menuItem, ""); } protected void uninstallListeners() { if (mouseInputListener != null) { menuItem.removeMouseListener(mouseInputListener); menuItem.removeMouseMotionListener(mouseInputListener); } if (menuDragMouseListener != null) { menuItem.removeMenuDragMouseListener(menuDragMouseListener); } if (menuKeyListener != null) { menuItem.removeMenuKeyListener(menuKeyListener); } if (propertyChangeListener != null) { menuItem.removePropertyChangeListener(propertyChangeListener); } mouseInputListener = null; menuDragMouseListener = null; menuKeyListener = null; propertyChangeListener = null; handler = null; } protected void uninstallKeyboardActions() { SwingUtilities.replaceUIActionMap(menuItem, null); SwingUtilities.replaceUIInputMap(menuItem, JComponent. WHEN_IN_FOCUSED_WINDOW, null); } protected MouseInputListener createMouseInputListener(JComponent c) { return getHandler(); } protected MenuDragMouseListener createMenuDragMouseListener(JComponent c) { return getHandler(); } protected MenuKeyListener createMenuKeyListener(JComponent c) { return null; } /** * Creates a <code>PropertyChangeListener</code> which will be added to * the menu item. * If this method returns null then it will not be added to the menu item. * * @return an instance of a <code>PropertyChangeListener</code> or null * @since 1.6 */ protected PropertyChangeListener createPropertyChangeListener(JComponent c) { return getHandler(); } Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } InputMap createInputMap(int condition) { if (condition == JComponent.WHEN_IN_FOCUSED_WINDOW) { return new ComponentInputMapUIResource(menuItem); } return null; } void updateAcceleratorBinding() { KeyStroke accelerator = menuItem.getAccelerator(); InputMap windowInputMap = SwingUtilities.getUIInputMap( menuItem, JComponent.WHEN_IN_FOCUSED_WINDOW); if (windowInputMap != null) { windowInputMap.clear(); } if (accelerator != null) { if (windowInputMap == null) { windowInputMap = createInputMap(JComponent. WHEN_IN_FOCUSED_WINDOW); SwingUtilities.replaceUIInputMap(menuItem, JComponent.WHEN_IN_FOCUSED_WINDOW, windowInputMap); } windowInputMap.put(accelerator, "doClick"); } } public Dimension getMinimumSize(JComponent c) { Dimension d = null; View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { d = getPreferredSize(c); d.width -= v.getPreferredSpan(View.X_AXIS) - v.getMinimumSpan(View.X_AXIS); } return d; } public Dimension getPreferredSize(JComponent c) { return getPreferredMenuItemSize(c, checkIcon, arrowIcon, defaultTextIconGap); } public Dimension getMaximumSize(JComponent c) { Dimension d = null; View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { d = getPreferredSize(c); d.width += v.getMaximumSpan(View.X_AXIS) - v.getPreferredSpan(View.X_AXIS); } return d; } protected Dimension getPreferredMenuItemSize(JComponent c, Icon checkIcon, Icon arrowIcon, int defaultTextIconGap) { // The method also determines the preferred width of the // parent popup menu (through DefaultMenuLayout class). // The menu width equals to the maximal width // among child menu items. // Menu item width will be a sum of the widest check icon, label, // arrow icon and accelerator text among neighbor menu items. // For the latest menu item we will know the maximal widths exactly. // It will be the widest menu item and it will determine // the width of the parent popup menu. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // There is a conceptual problem: if user sets preferred size manually // for a menu item, this method won't be called for it // (see JComponent.getPreferredSize()), // maximal widths won't be calculated, other menu items won't be able // to take them into account and will be layouted in such a way, // as there is no the item with manual preferred size. // But after the first paint() method call, all maximal widths // will be correctly calculated and layout of some menu items // can be changed. For example, it can cause a shift of // the icon and text when user points a menu item by mouse. JMenuItem mi = (JMenuItem) c; MenuItemLayoutHelper lh = new MenuItemLayoutHelper(mi, checkIcon, arrowIcon, MenuItemLayoutHelper.createMaxRect(), defaultTextIconGap, acceleratorDelimiter, BasicGraphicsUtils.isLeftToRight(mi), mi.getFont(), acceleratorFont, MenuItemLayoutHelper.useCheckAndArrow(menuItem), getPropertyPrefix()); Dimension result = new Dimension(); // Calculate the result width result.width = lh.getLeadingGap(); MenuItemLayoutHelper.addMaxWidth(lh.getCheckSize(), lh.getAfterCheckIconGap(), result); // Take into account mimimal text offset. if ((!lh.isTopLevelMenu()) && (lh.getMinTextOffset() > 0) && (result.width < lh.getMinTextOffset())) { result.width = lh.getMinTextOffset(); } MenuItemLayoutHelper.addMaxWidth(lh.getLabelSize(), lh.getGap(), result); MenuItemLayoutHelper.addMaxWidth(lh.getAccSize(), lh.getGap(), result); MenuItemLayoutHelper.addMaxWidth(lh.getArrowSize(), lh.getGap(), result); // Calculate the result height result.height = MenuItemLayoutHelper.max(lh.getCheckSize().getHeight(), lh.getLabelSize().getHeight(), lh.getAccSize().getHeight(), lh.getArrowSize().getHeight()); // Take into account menu item insets Insets insets = lh.getMenuItem().getInsets(); if(insets != null) { result.width += insets.left + insets.right; result.height += insets.top + insets.bottom; } // if the width is even, bump it up one. This is critical // for the focus dash line to draw properly if(result.width%2 == 0) { result.width++; } // if the height is even, bump it up one. This is critical // for the text to center properly if(result.height%2 == 0 && Boolean.TRUE != UIManager.get(getPropertyPrefix() + ".evenHeight")) { result.height++; } return result; } /** * We draw the background in paintMenuItem() * so override update (which fills the background of opaque * components by default) to just call paint(). * */ public void update(Graphics g, JComponent c) { paint(g, c); } public void paint(Graphics g, JComponent c) { paintMenuItem(g, c, checkIcon, arrowIcon, selectionBackground, selectionForeground, defaultTextIconGap); } protected void paintMenuItem(Graphics g, JComponent c, Icon checkIcon, Icon arrowIcon, Color background, Color foreground, int defaultTextIconGap) { // Save original graphics font and color Font holdf = g.getFont(); Color holdc = g.getColor(); JMenuItem mi = (JMenuItem) c; g.setFont(mi.getFont()); Rectangle viewRect = new Rectangle(0, 0, mi.getWidth(), mi.getHeight()); applyInsets(viewRect, mi.getInsets()); MenuItemLayoutHelper lh = new MenuItemLayoutHelper(mi, checkIcon, arrowIcon, viewRect, defaultTextIconGap, acceleratorDelimiter, BasicGraphicsUtils.isLeftToRight(mi), mi.getFont(), acceleratorFont, MenuItemLayoutHelper.useCheckAndArrow(menuItem), getPropertyPrefix()); MenuItemLayoutHelper.LayoutResult lr = lh.layoutMenuItem(); paintBackground(g, mi, background); paintCheckIcon(g, lh, lr, holdc, foreground); paintIcon(g, lh, lr, holdc); paintText(g, lh, lr); paintAccText(g, lh, lr); paintArrowIcon(g, lh, lr, foreground); // Restore original graphics font and color g.setColor(holdc); g.setFont(holdf); } private void paintIcon(Graphics g, MenuItemLayoutHelper lh, MenuItemLayoutHelper.LayoutResult lr, Color holdc) { if (lh.getIcon() != null) { Icon icon; ButtonModel model = lh.getMenuItem().getModel(); if (!model.isEnabled()) { icon = lh.getMenuItem().getDisabledIcon(); } else if (model.isPressed() && model.isArmed()) { icon = lh.getMenuItem().getPressedIcon(); if (icon == null) { // Use default icon icon = lh.getMenuItem().getIcon(); } } else { icon = lh.getMenuItem().getIcon(); } if (icon != null) { icon.paintIcon(lh.getMenuItem(), g, lr.getIconRect().x, lr.getIconRect().y); g.setColor(holdc); } } } private void paintCheckIcon(Graphics g, MenuItemLayoutHelper lh, MenuItemLayoutHelper.LayoutResult lr, Color holdc, Color foreground) { if (lh.getCheckIcon() != null) { ButtonModel model = lh.getMenuItem().getModel(); if (model.isArmed() || (lh.getMenuItem() instanceof JMenu && model.isSelected())) { g.setColor(foreground); } else { g.setColor(holdc); } if (lh.useCheckAndArrow()) { lh.getCheckIcon().paintIcon(lh.getMenuItem(), g, lr.getCheckRect().x, lr.getCheckRect().y); } g.setColor(holdc); } } private void paintAccText(Graphics g, MenuItemLayoutHelper lh, MenuItemLayoutHelper.LayoutResult lr) { if (!lh.getAccText().equals("")) { ButtonModel model = lh.getMenuItem().getModel(); g.setFont(lh.getAccFontMetrics().getFont()); if (!model.isEnabled()) { // *** paint the accText disabled if (disabledForeground != null) { g.setColor(disabledForeground); SwingUtilities2.drawString(lh.getMenuItem(), g, lh.getAccText(), lr.getAccRect().x, lr.getAccRect().y + lh.getAccFontMetrics().getAscent()); } else { g.setColor(lh.getMenuItem().getBackground().brighter()); SwingUtilities2.drawString(lh.getMenuItem(), g, lh.getAccText(), lr.getAccRect().x, lr.getAccRect().y + lh.getAccFontMetrics().getAscent()); g.setColor(lh.getMenuItem().getBackground().darker()); SwingUtilities2.drawString(lh.getMenuItem(), g, lh.getAccText(), lr.getAccRect().x - 1, lr.getAccRect().y + lh.getFontMetrics().getAscent() - 1); } } else { // *** paint the accText normally if (model.isArmed() || (lh.getMenuItem() instanceof JMenu && model.isSelected())) { g.setColor(acceleratorSelectionForeground); } else { g.setColor(acceleratorForeground); } SwingUtilities2.drawString(lh.getMenuItem(), g, lh.getAccText(), lr.getAccRect().x, lr.getAccRect().y + lh.getAccFontMetrics().getAscent()); } } } private void paintText(Graphics g, MenuItemLayoutHelper lh, MenuItemLayoutHelper.LayoutResult lr) { if (!lh.getText().equals("")) { if (lh.getHtmlView() != null) { // Text is HTML lh.getHtmlView().paint(g, lr.getTextRect()); } else { // Text isn't HTML paintText(g, lh.getMenuItem(), lr.getTextRect(), lh.getText()); } } } private void paintArrowIcon(Graphics g, MenuItemLayoutHelper lh, MenuItemLayoutHelper.LayoutResult lr, Color foreground) { if (lh.getArrowIcon() != null) { ButtonModel model = lh.getMenuItem().getModel(); if (model.isArmed() || (lh.getMenuItem() instanceof JMenu && model.isSelected())) { g.setColor(foreground); } if (lh.useCheckAndArrow()) { lh.getArrowIcon().paintIcon(lh.getMenuItem(), g, lr.getArrowRect().x, lr.getArrowRect().y); } } } private void applyInsets(Rectangle rect, Insets insets) { if(insets != null) { rect.x += insets.left; rect.y += insets.top; rect.width -= (insets.right + rect.x); rect.height -= (insets.bottom + rect.y); } } /** * Draws the background of the menu item. * * @param g the paint graphics * @param menuItem menu item to be painted * @param bgColor selection background color * @since 1.4 */ protected void paintBackground(Graphics g, JMenuItem menuItem, Color bgColor) { ButtonModel model = menuItem.getModel(); Color oldColor = g.getColor(); int menuWidth = menuItem.getWidth(); int menuHeight = menuItem.getHeight(); if(menuItem.isOpaque()) { if (model.isArmed()|| (menuItem instanceof JMenu && model.isSelected())) { g.setColor(bgColor); g.fillRect(0,0, menuWidth, menuHeight); } else { g.setColor(menuItem.getBackground()); g.fillRect(0,0, menuWidth, menuHeight); } g.setColor(oldColor); } else if (model.isArmed() || (menuItem instanceof JMenu && model.isSelected())) { g.setColor(bgColor); g.fillRect(0,0, menuWidth, menuHeight); g.setColor(oldColor); } } /** * Renders the text of the current menu item. * <p> * @param g graphics context * @param menuItem menu item to render * @param textRect bounding rectangle for rendering the text * @param text string to render * @since 1.4 */ protected void paintText(Graphics g, JMenuItem menuItem, Rectangle textRect, String text) { ButtonModel model = menuItem.getModel(); FontMetrics fm = SwingUtilities2.getFontMetrics(menuItem, g); int mnemIndex = menuItem.getDisplayedMnemonicIndex(); if(!model.isEnabled()) { // *** paint the text disabled if ( UIManager.get("MenuItem.disabledForeground") instanceof Color ) { g.setColor( UIManager.getColor("MenuItem.disabledForeground") ); SwingUtilities2.drawStringUnderlineCharAt(menuItem, g,text, mnemIndex, textRect.x, textRect.y + fm.getAscent()); } else { g.setColor(menuItem.getBackground().brighter()); SwingUtilities2.drawStringUnderlineCharAt(menuItem, g, text, mnemIndex, textRect.x, textRect.y + fm.getAscent()); g.setColor(menuItem.getBackground().darker()); SwingUtilities2.drawStringUnderlineCharAt(menuItem, g,text, mnemIndex, textRect.x - 1, textRect.y + fm.getAscent() - 1); } } else { // *** paint the text normally if (model.isArmed()|| (menuItem instanceof JMenu && model.isSelected())) { g.setColor(selectionForeground); // Uses protected field. } SwingUtilities2.drawStringUnderlineCharAt(menuItem, g,text, mnemIndex, textRect.x, textRect.y + fm.getAscent()); } } public MenuElement[] getPath() { MenuSelectionManager m = MenuSelectionManager.defaultManager(); MenuElement oldPath[] = m.getSelectedPath(); MenuElement newPath[]; int i = oldPath.length; if (i == 0) return new MenuElement[0]; Component parent = menuItem.getParent(); if (oldPath[i-1].getComponent() == parent) { // The parent popup menu is the last so far newPath = new MenuElement[i+1]; System.arraycopy(oldPath, 0, newPath, 0, i); newPath[i] = menuItem; } else { // A sibling menuitem is the current selection // // This probably needs to handle 'exit submenu into // a menu item. Search backwards along the current // selection until you find the parent popup menu, // then copy up to that and add yourself... int j; for (j = oldPath.length-1; j >= 0; j--) { if (oldPath[j].getComponent() == parent) break; } newPath = new MenuElement[j+2]; System.arraycopy(oldPath, 0, newPath, 0, j+1); newPath[j+1] = menuItem; /* System.out.println("Sibling condition -- "); System.out.println("Old array : "); printMenuElementArray(oldPath, false); System.out.println("New array : "); printMenuElementArray(newPath, false); */ } return newPath; } void printMenuElementArray(MenuElement path[], boolean dumpStack) { System.out.println("Path is("); int i, j; for(i=0,j=path.length; i<j ;i++){ for (int k=0; k<=i; k++) System.out.print(" "); MenuElement me = path[i]; if(me instanceof JMenuItem) System.out.println(((JMenuItem)me).getText() + ", "); else if (me == null) System.out.println("NULL , "); else System.out.println("" + me + ", "); } System.out.println(")"); if (dumpStack == true) Thread.dumpStack(); } protected class MouseInputHandler implements MouseInputListener { // NOTE: This class exists only for backward compatibility. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void mouseClicked(MouseEvent e) { getHandler().mouseClicked(e); } public void mousePressed(MouseEvent e) { getHandler().mousePressed(e); } public void mouseReleased(MouseEvent e) { getHandler().mouseReleased(e); } public void mouseEntered(MouseEvent e) { getHandler().mouseEntered(e); } public void mouseExited(MouseEvent e) { getHandler().mouseExited(e); } public void mouseDragged(MouseEvent e) { getHandler().mouseDragged(e); } public void mouseMoved(MouseEvent e) { getHandler().mouseMoved(e); } } private static class Actions extends UIAction { private static final String CLICK = "doClick"; Actions(String key) { super(key); } public void actionPerformed(ActionEvent e) { JMenuItem mi = (JMenuItem)e.getSource(); MenuSelectionManager.defaultManager().clearSelectedPath(); mi.doClick(); } } /** * Call this method when a menu item is to be activated. * This method handles some of the details of menu item activation * such as clearing the selected path and messaging the * JMenuItem's doClick() method. * * @param msm A MenuSelectionManager. The visual feedback and * internal bookkeeping tasks are delegated to * this MenuSelectionManager. If <code>null</code> is * passed as this argument, the * <code>MenuSelectionManager.defaultManager</code> is * used. * @see MenuSelectionManager * @see JMenuItem#doClick(int) * @since 1.4 */ protected void doClick(MenuSelectionManager msm) { // Auditory cue if (! isInternalFrameSystemMenu()) { BasicLookAndFeel.playSound(menuItem, getPropertyPrefix() + ".commandSound"); } // Visual feedback if (msm == null) { msm = MenuSelectionManager.defaultManager(); } msm.clearSelectedPath(); menuItem.doClick(0); } /** * This is to see if the menu item in question is part of the * system menu on an internal frame. * The Strings that are being checked can be found in * MetalInternalFrameTitlePaneUI.java, * WindowsInternalFrameTitlePaneUI.java, and * MotifInternalFrameTitlePaneUI.java. * * @since 1.4 */ private boolean isInternalFrameSystemMenu() { String actionCommand = menuItem.getActionCommand(); if ((actionCommand == "Close") || (actionCommand == "Minimize") || (actionCommand == "Restore") || (actionCommand == "Maximize")) { return true; } else { return false; } } // BasicMenuUI subclasses this. class Handler implements MenuDragMouseListener, MouseInputListener, PropertyChangeListener { // // MouseInputListener // public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { if (!menuItem.isEnabled()) { return; } MenuSelectionManager manager = MenuSelectionManager.defaultManager(); Point p = e.getPoint(); if(p.x >= 0 && p.x < menuItem.getWidth() && p.y >= 0 && p.y < menuItem.getHeight()) { doClick(manager); } else { manager.processMouseEvent(e); } } public void mouseEntered(MouseEvent e) { MenuSelectionManager manager = MenuSelectionManager.defaultManager(); int modifiers = e.getModifiers(); // 4188027: drag enter/exit added in JDK 1.1.7A, JDK1.2 if ((modifiers & (InputEvent.BUTTON1_MASK | InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK)) !=0 ) { MenuSelectionManager.defaultManager().processMouseEvent(e); } else { manager.setSelectedPath(getPath()); } } public void mouseExited(MouseEvent e) { MenuSelectionManager manager = MenuSelectionManager.defaultManager(); int modifiers = e.getModifiers(); // 4188027: drag enter/exit added in JDK 1.1.7A, JDK1.2 if ((modifiers & (InputEvent.BUTTON1_MASK | InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK)) !=0 ) { MenuSelectionManager.defaultManager().processMouseEvent(e); } else { MenuElement path[] = manager.getSelectedPath(); if (path.length > 1 && path[path.length-1] == menuItem) { MenuElement newPath[] = new MenuElement[path.length-1]; int i,c; for(i=0,c=path.length-1;i<c;i++) newPath[i] = path[i]; manager.setSelectedPath(newPath); } } } public void mouseDragged(MouseEvent e) { MenuSelectionManager.defaultManager().processMouseEvent(e); } public void mouseMoved(MouseEvent e) { } // // MenuDragListener // public void menuDragMouseEntered(MenuDragMouseEvent e) { MenuSelectionManager manager = e.getMenuSelectionManager(); MenuElement path[] = e.getPath(); manager.setSelectedPath(path); } public void menuDragMouseDragged(MenuDragMouseEvent e) { MenuSelectionManager manager = e.getMenuSelectionManager(); MenuElement path[] = e.getPath(); manager.setSelectedPath(path); } public void menuDragMouseExited(MenuDragMouseEvent e) {} public void menuDragMouseReleased(MenuDragMouseEvent e) { if (!menuItem.isEnabled()) { return; } MenuSelectionManager manager = e.getMenuSelectionManager(); MenuElement path[] = e.getPath(); Point p = e.getPoint(); if (p.x >= 0 && p.x < menuItem.getWidth() && p.y >= 0 && p.y < menuItem.getHeight()) { doClick(manager); } else { manager.clearSelectedPath(); } } // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent e) { String name = e.getPropertyName(); if (name == "labelFor" || name == "displayedMnemonic" || name == "accelerator") { updateAcceleratorBinding(); } else if (name == "text" || "font" == name || "foreground" == name) { // remove the old html view client property if one // existed, and install a new one if the text installed // into the JLabel is html source. JMenuItem lbl = ((JMenuItem) e.getSource()); String text = lbl.getText(); BasicHTML.updateRenderer(lbl, text); } else if (name == "iconTextGap") { defaultTextIconGap = ((Number)e.getNewValue()).intValue(); } } } }
apache/pig
36,892
test/org/apache/pig/test/TestUnionOnSchema.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.pig.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.junit.Assert; import org.apache.pig.EvalFunc; import org.apache.pig.PigException; import org.apache.pig.PigServer; import org.apache.pig.builtin.mock.Storage; import org.apache.pig.builtin.mock.Storage.Data; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.impl.io.FileLocalizer; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema; import org.apache.pig.impl.util.LogUtils; import org.apache.pig.impl.util.Utils; import org.apache.pig.parser.ParserException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class TestUnionOnSchema { private static final String INP_FILE_2NUMS = "TestUnionOnSchemaInput1"; private static final String INP_FILE_2NUM_1CHAR_1BAG = "TestUnionOnSchemaInput2"; private static final String INP_FILE_EMPTY= "TestUnionOnSchemaInput3"; private static final String INP_FILE_3NUMS = "TestUnionOnSchemaInput4"; @Before public void setUp() throws Exception { FileLocalizer.setInitialized(false); } @After public void tearDown() throws Exception { } @BeforeClass public static void oneTimeSetup() throws IOException, Exception { // first input file String[] input1 = {"1\t2","5\t3"}; Util.createLocalInputFile(INP_FILE_2NUMS, input1); // 2nd input file String[] input2 = { "1\tabc\t2\t{(1,a),(1,b)}\t(1,c)", "5\tdef\t3\t{(2,a),(2,b)}\t(2,c)" }; Util.createLocalInputFile(INP_FILE_2NUM_1CHAR_1BAG, input2); //3rd input - empty file Util.createLocalInputFile(INP_FILE_EMPTY, new String[0]); // 4th input String[] input4 = {"1\t2\t3","4\t5\t6",}; Util.createLocalInputFile(INP_FILE_3NUMS, input4); } @AfterClass public static void oneTimeTearDown() throws Exception { new File(INP_FILE_2NUMS).delete(); new File(INP_FILE_2NUM_1CHAR_1BAG).delete(); new File(INP_FILE_EMPTY).delete(); } /** * Test UNION ONSCHEMA on two inputs with same schema */ @Test public void testUnionOnSchemaSameSchema() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUMS + "' as (i : int, j : int);" + "l2 = load '" + INP_FILE_2NUMS + "' as (i : int, j : int);" + "u = union onschema l1, l2;" ; Util.registerMultiLineQuery(pig, query); Schema expectedSch = Utils.getSchemaFromString("i: int, j: int"); Schema sch = pig.dumpSchema("u"); assertEquals("Checking expected schema",sch, expectedSch); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1,2)", "(5,3)", "(1,2)", "(5,3)" }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test UNION ONSCHEMA with operations after the union */ @Test public void testUnionOnSchemaFilter() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUMS + "' as (i : int, x : int);" + "l2 = load '" + INP_FILE_2NUMS + "' as (i : int, j : int);" + "u = union onschema l1, l2;" + "fil = filter u by i == 5 and (x is null or x != 1);" ; Util.registerMultiLineQuery(pig, query); Schema sch = pig.dumpSchema("fil"); Schema expectedSch = Utils.getSchemaFromString("i: int, x: int, j: int"); assertEquals("Checking expected schema",sch, expectedSch); Iterator<Tuple> it = pig.openIterator("fil"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(5,null,3)", "(5,3,null)" }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test UNION ONSCHEMA with operations after the union */ @Test public void testUnionOnSchemaSuccOps() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUMS + "' as (i : int);" + "l2 = load '" + INP_FILE_2NUMS + "' as (x : int, y : int);" + "u = union onschema l1, l2;" + "o = order u by i desc;" + "lim = limit o 2;" + "fil = filter lim by i == 5 and y is null;" ; Util.registerMultiLineQuery(pig, query); Schema sch = pig.dumpSchema("fil"); Schema expectedSch = Utils.getSchemaFromString("i: int, x: int, y: int"); assertEquals("Checking expected schema",sch, expectedSch); Iterator<Tuple> it = pig.openIterator("fil"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(5,null,null)", }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test UNION ONSCHEMA with cast from bytearray to another type */ @Test public void testUnionOnSchemaCastOnByteArray() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUMS + "' as (i, j);" + " f1 = foreach l1 generate (int)i, (int)j;" + "u = union onschema f1, l1;" ; Util.registerMultiLineQuery(pig, query); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1,2)", "(5,3)", "(1,2)", "(5,3)" }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test UNION ONSCHEMA where a common column has additional 'namespace' part * in the column name in one of the inputs */ @Test public void testUnionOnSchemaScopedColumnName() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query_prefix = " l1 = load '" + INP_FILE_2NUMS + "' as (i : int, j : int); " + "g = group l1 by i; " + "f = foreach g generate flatten(l1); " + "l2 = load '" + INP_FILE_2NUMS + "' as (i : int, j : int); "; String query = query_prefix + "u = union onschema f, l2; " ; Util.registerMultiLineQuery(pig, query); Schema sch = pig.dumpSchema("u"); Schema expectedSch = Utils.getSchemaFromString("i: int, j: int"); assertEquals("Checking expected schema",sch, expectedSch); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1,2)", "(5,3)", "(1,2)", "(5,3)" }); Util.checkQueryOutputsAfterSort(it, expectedRes); // now try reversing the order of relation query = query_prefix + "u = union onschema l2, f; " ; Util.registerMultiLineQuery(pig, query); sch = pig.dumpSchema("u"); expectedSch = Utils.getSchemaFromString("i: int, j: int"); assertEquals("Checking expected schema",sch, expectedSch); it = pig.openIterator("u"); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test UNION ONSCHEMA where a common column has additional 'namespace' part * in the column name in both the inputs */ @Test public void testUnionOnSchemaScopedColumnNameBothInp1() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUMS + "' as (i : int, j : int); " + "g1 = group l1 by i; " + "f1 = foreach g1 generate group as gkey, flatten(l1); " + "l2 = load '" + INP_FILE_2NUMS + "' as (i : int, x : chararray); " + "g2 = group l2 by i; " + "f2 = foreach g2 generate group as gkey, flatten(l2); " + "u = union onschema f1, f2; " ; Util.registerMultiLineQuery(pig, query); Schema sch = pig.dumpSchema("u"); Schema expectedSch = Utils.getSchemaFromString("gkey: int, l1::i: int, l1::j: int, l2::i: int, l2::x: chararray"); assertEquals("Checking expected schema",sch, expectedSch); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1,1,2,null,null)", "(5,5,3,null,null)", "(1,null,null,1,'2')", "(5,null,null,5,'3')" }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test UNION ONSCHEMA where a common column has additional 'namespace' part * in the column name in both the inputs */ @Test public void testUnionOnSchemaScopedColumnNameBothInp2() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUMS + "' as (i : int, j : int); " + " l2 = load '" + INP_FILE_2NUMS + "' as (i : int, x : chararray); " + " cg1 = cogroup l1 by i, l2 by i; " + " f1 = foreach cg1 generate group as gkey, flatten(l1), flatten(l2); " + " cg2 = cogroup l2 by i, l1 by i; " + " f2 = foreach cg1 generate group as gkey, flatten(l2), flatten(l1); " + "u = union onschema f1, f2; " ; Util.registerMultiLineQuery(pig, query); Schema sch = pig.dumpSchema("u"); Schema expectedSch = Utils.getSchemaFromString("gkey: int, l1::i: int, l1::j: int, l2::i: int, l2::x: chararray"); assertEquals("Checking expected schema",sch, expectedSch); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1,1,2,1,'2')", "(5,5,3,5,'3')", "(1,1,2,1,'2')", "(5,5,3,5,'3')", }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test UNION ONSCHEMA where a common column has additional 'namespace' part * in the column name in one of the inputs. * Negative test case */ @Test public void testUnionOnSchemaScopedColumnNameNeg() throws Exception { String expectedErr = "Found more than one match: l1::i, l2::i"; String query_prefix = " l1 = load '/tmp/fn' as (i : int, j : long); " + "l2 = load '/tmp/fn' as (i : int, j : long); " + "cg = cogroup l1 by i, l2 by i;" + "f = foreach cg generate flatten(l1), flatten(l2); " + "l3 = load '/tmp/fn2' as (i : int, j : long); " ; String query = query_prefix + "u = union onschema f, l3; "; checkSchemaEx(query, expectedErr); // now try reversing the order of relation query = query_prefix + "u = union onschema l3, f; "; checkSchemaEx(query, expectedErr); } /** * Test UNION ONSCHEMA on two inputs with same column names, but different * numeric types - test type promotion */ @Test public void testUnionOnSchemaDiffNumType() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUMS + "' as (i : int, j : double);" + "l2 = load '" + INP_FILE_2NUMS + "' as (i : long, j : float);" + "u = union onschema l1, l2;" ; Util.registerMultiLineQuery(pig, query); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1L,2.0)", "(5L,3.0)", "(1L,2.0)", "(5L,3.0)" }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test UNION ONSCHEMA on two inputs with no common columns */ @Test public void testUnionOnSchemaNoCommonCols() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUMS + "' as (i : int, j : int);" + "l2 = load '" + INP_FILE_2NUMS + "' as (x : long, y : float);" + "u = union onschema l1, l2;" ; Util.registerMultiLineQuery(pig, query); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1,2,null,null)", "(5,3,null,null)", "(null,null,1L,2.0F)", "(null,null,5L,3.0F)" }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test UNION ONSCHEMA on two inputs , one input with additional columns */ @Test public void testUnionOnSchemaAdditionalColumn() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUMS + "' as (i : int, j : int);" + "l2 = load '" + INP_FILE_2NUM_1CHAR_1BAG + "' as " + " (i : long, c : chararray, j : int " + ", b : bag { t : tuple (c1 : int, c2 : chararray)}" + ", t : tuple (tc1 : int, tc2 : chararray) );" + "l3 = load '" + INP_FILE_EMPTY + "' as (i : int, x : long);" + "u = union onschema l1, l2, l3;" ; Util.registerMultiLineQuery(pig, query); pig.explain("u", System.out); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1L,2,null,null,null,null)", "(5L,3,null,null,null,null)", "(1L,2,'abc',{(1,'a'),(1,'b')},(1,'c'),null)", "(5L,3,'def',{(2,'a'),(2,'b')},(2,'c'),null)", }); Util.checkQueryOutputsAfterSort(it, expectedRes); } @Test public void testUnionOnSchemaAdditionalColumnsWithImplicitSplit() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); Data data = Storage.resetData(pig); // Use batch to force multiple outputs from relation l3. This causes // ImplicitSplitInsertVisitor to call SchemaResetter. pig.setBatchOn(); String query = " l1 = load '" + INP_FILE_2NUMS + "' as (i : int, j: int);" + "l2 = load '" + INP_FILE_3NUMS + "' as (i : int, j : int, k : int);" + "l3 = load '" + INP_FILE_EMPTY + "' as (i : int, j : int, k : int, l :int);" + "u = union onschema l1, l2, l3;" + "store u into 'out1' using mock.Storage;" + "store l3 into 'out2' using mock.Storage;" ; Util.registerMultiLineQuery(pig, query); pig.executeBatch(); List<Tuple> list1 = data.get("out1"); List<Tuple> list2 = data.get("out2"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1,2,null,null)", "(5,3,null,null)", "(1,2,3,null)", "(4,5,6,null)", }); Util.checkQueryOutputsAfterSort(list1, expectedRes); assertEquals(0, list2.size()); } /** * Test UNION ONSCHEMA on 3 inputs */ @Test public void testUnionOnSchemaInnerSchema() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUM_1CHAR_1BAG + "' as " + " (i : long, c : chararray, j : int " + ", b : bag { t : tuple (c1 : int, c2 : chararray)} ); " + "l2 = load '" + INP_FILE_2NUM_1CHAR_1BAG + "' as " + " (i : long, c : chararray, j : int " + ", b : bag { t : tuple (c1 : int, c2 : chararray)} ); " + "u = union onschema l1, l2; " // The addition in the inner foreach will fail if the inner schema's uids // are all set to -1, since the code that finds the inner load's schema will // match the last item in b's schema, which is a chararray + "p = foreach u { x = foreach b GENERATE c1 + 5 as c3; GENERATE i, c, x; }"; Util.registerMultiLineQuery(pig, query); pig.explain("p", System.out); Iterator<Tuple> it = pig.openIterator("p"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1L,'abc',{(6),(6)})", "(5L,'def',{(7),(7)})", "(1L,'abc',{(6),(6)})", "(5L,'def',{(7),(7)})" }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test UNION ONSCHEMA on 3 inputs * @throws IOException * @throws ParserException */ @Test public void testUnionOnSchema3Inputs() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUMS + "' as (i : int, j : int); " + "l2 = load '" + INP_FILE_2NUMS + "' as (i : double, x : int); " + "l3 = load '" + INP_FILE_2NUM_1CHAR_1BAG + "' as " + " (i : long, c : chararray, j : int " + ", b : bag { t : tuple (c1 : int, c2 : chararray)} ); " + "u = union onschema l1, l2, l3;" ; Util.registerMultiLineQuery(pig, query); pig.explain("u", System.out); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1.0,2,null,null,null)", "(5.0,3,null,null,null)", "(1.0,null,2,null,null)", "(5.0,null,3,null,null)", "(1.0,2,null,'abc',{(1,'a'),(1,'b')})", "(5.0,3,null,'def',{(2,'a'),(2,'b')})", }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test UNION ONSCHEMA with bytearray type */ @Test public void testUnionOnSchemaByteArrayConversions() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUM_1CHAR_1BAG + "' as " + " (i : bytearray, x : bytearray, j : bytearray " + ", b : bytearray); " + "l2 = load '" + INP_FILE_2NUM_1CHAR_1BAG + "' as " + " (i : long, c : chararray, j : int " + ", b : bag { t : tuple (c1 : int, c2 : chararray)} ); " + "u = union onSchema l1, l2;" ; Util.registerMultiLineQuery(pig, query); pig.explain("u", System.out); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1L,null,2,{(1,'a'),(1,'b')},'abc')", "(1L,'abc',2,{(1,'a'),(1,'b')},null)", "(5L,null,3,{(2,'a'),(2,'b')},'def')", "(5L,'def',3,{(2,'a'),(2,'b')},null)", }); //update expectedRes to use bytearray instead of chararray in 2nd field for(Tuple t : expectedRes){ if(t.get(1) != null){ t.set(1, new DataByteArray(t.get(1).toString())); } } Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * negative test - test error on no schema */ @Test public void testUnionOnSchemaNoSchema() throws Exception { String expectedErr = "UNION ONSCHEMA cannot be used with " + "relations that have null schema"; String query = " l1 = load '" + INP_FILE_2NUMS + "' ;" + "l2 = load '" + INP_FILE_2NUMS + "' as (x : long, y : float);" + "u = union onschema l1, l2;" ; checkSchemaEx(query, expectedErr); query = " l1 = load '" + INP_FILE_2NUMS + "' ;" + "l2 = load '" + INP_FILE_2NUMS + "' ;" + "u = union onschema l1, l2;" ; checkSchemaEx(query, expectedErr); } /** * negative test - test error on null alias in one of the FieldSchema */ @Test public void testUnionOnSchemaNullAliasInFieldSchema() throws Exception { String expectedErr = "Schema of relation f has a null fieldschema for " + "column(s). Schema ::long,y:float"; String query = " l = load '" + INP_FILE_2NUMS + "' as (x : long, y : float);" + "f = foreach l generate x+1, y;" + "u = union onschema l, f;" ; checkSchemaEx(query, expectedErr); } private void checkSchemaEx(String query, String expectedErr) throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); boolean foundEx = false; try{ Util.registerMultiLineQuery(pig, query); pig.dumpSchema("u"); }catch(FrontendException e){ PigException pigEx = LogUtils.getPigException(e); foundEx = true; if(!pigEx.getMessage().contains(expectedErr)){ String msg = "Expected exception message matching '" + expectedErr + "' but got '" + pigEx.getMessage() + "'" ; fail(msg); } } if(!foundEx) fail("No exception thrown. Exception is expected."); } /** * test union with incompatible types in schema */ @Test public void testUnionOnSchemaIncompatibleTypes() throws Exception { String query = " l1 = load '" + INP_FILE_2NUMS + "' as (x : long, y : chararray);" + "l2 = load '" + INP_FILE_2NUMS + "' as (x : long, y : float);" + "u = union onschema l1, l2;"; checkSchemaEx(query, "Cannot cast from chararray to bytearray"); //without "onschema" query = " l1 = load '" + INP_FILE_2NUMS + "' as (x : long, y : chararray);" + "l2 = load '" + INP_FILE_2NUMS + "' as (x : long, y : float);" + "u = union l1, l2;"; checkSchemaEx(query, "Cannot cast from chararray to bytearray"); query = " l1 = load '" + INP_FILE_2NUMS + "' as (x : long, y : chararray);" + "l2 = load '" + INP_FILE_2NUMS + "' as (x : map[ ], y : chararray);" + "u = union onschema l1, l2;" ; checkSchemaEx(query, "Cannot cast from long to bytearray"); query = " l1 = load '" + INP_FILE_2NUMS + "' as (x : long, y : chararray);" + "l2 = load '" + INP_FILE_2NUMS + "' as (x : map[ ], y : chararray);" + "u = union l1, l2;" ; checkSchemaEx(query, "Cannot cast from long to bytearray"); // bag column with different internal column types query = " l1 = load '" + INP_FILE_2NUMS + "' as (x : long, b : bag { t : tuple (c1 : int, c2 : chararray)} );" + "l2 = load '" + INP_FILE_2NUMS + "' as (x : long, b : bag { t : tuple (c1 : long, c2 : chararray)} );" + "u = union onschema l1, l2;" ; Schema sch = new Schema(); sch.add(new FieldSchema("x", DataType.LONG)); Schema bagInnerSchema = new Schema(); bagInnerSchema.add(new FieldSchema(null, new Schema(), DataType.TUPLE)); sch.add(new FieldSchema("b", bagInnerSchema, DataType.BAG)); checkSchemaEquals(query, sch); // tuple column with different internal column types query = " l1 = load '" + INP_FILE_2NUMS + "' as (t : tuple (c1 : int, c2 : chararray) );" + "l2 = load '" + INP_FILE_2NUMS + "' as (t : tuple (c1 : long, c2 : chararray) );" + "u = union onschema l1, l2;" ; sch = new Schema(); sch.add(new FieldSchema("t", new Schema(), DataType.TUPLE)); checkSchemaEquals(query, sch); } private void checkSchemaEquals(String query, Schema expectedSch) throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); Util.registerMultiLineQuery(pig, query); Schema sch = pig.dumpSchema("u"); assertEquals("Checking expected schema", expectedSch, sch); } private void checkSchemaEquals(String query, String schemaStr) throws Exception { Schema expectedSch = Utils.getSchemaFromString(schemaStr); checkSchemaEquals(query, expectedSch); } /** * Test UNION ONSCHEMA with input relation having udfs */ @Test public void testUnionOnSchemaInputUdfs() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUMS + "' as (i : int, j : chararray);" + "l2 = load '" + INP_FILE_2NUMS + "' as (i : int, j : chararray);" + "f1 = foreach l1 generate i, CONCAT(j,j) as cj, " + "org.apache.pig.test.TestUnionOnSchema\\$UDFTupleNullSchema(i,j) as uo;" + "u = union onschema f1, l2;" ; Util.registerMultiLineQuery(pig, query); Schema sch = pig.dumpSchema("u"); String expectedSch = "{i: int,cj: chararray,uo: (),j: chararray}"; Assert.assertTrue( expectedSch.equals( sch.toString() ) ); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1,null,null,'2')", "(5,null,null,'3')", "(1,'22',(1,'2'),null)", "(5,'33',(5,'3'),null)" }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test UNION ONSCHEMA with udf whose default type is different from * final type */ @Test public void testUnionOnSchemaUdfTypeEvolution() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query_prefix = " l1 = load '" + INP_FILE_2NUM_1CHAR_1BAG + "' as " + " (i : int, c : chararray, j : int " + ", b : bag { t : tuple (c1 : int, c2 : chararray)}" + ", t : tuple (tc1 : int, tc2 : chararray) );" + " l2 = load '" + INP_FILE_2NUM_1CHAR_1BAG + "' as " + " (i : int, c : chararray, j : int " + ", b : bag { t : tuple (c1 : int, c2 : chararray)}" + ", t : tuple (tc1 : int, tc2 : chararray) );" + "f1 = foreach l1 generate i, MAX(b.c1) as mx;" + "f2 = foreach l2 generate i, COUNT(b.c1) as mx;" ; String query = query_prefix + "u = union onschema f1, f2;"; Util.registerMultiLineQuery(pig, query); Schema sch = pig.dumpSchema("u"); Schema expectedSch = Utils.getSchemaFromString("i: int, mx: long"); assertEquals("Checking expected schema",sch, expectedSch); // verify schema for reverse order of relations as well query = query_prefix + "u = union onschema f2, f1;"; Util.registerMultiLineQuery(pig, query); sch = pig.dumpSchema("u"); expectedSch = Utils.getSchemaFromString("i: int, mx: long"); assertEquals("Checking expected schema",sch, expectedSch); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1,1L)", "(5,2L)", "(1,2L)", "(5,2L)" }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test UNION ONSCHEMA with udf whose default type is different from * final type - where udf is not in immediate input of union */ @Test public void testUnionOnSchemaUdfTypeEvolution2() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query_prefix = " l1 = load '" + INP_FILE_2NUM_1CHAR_1BAG + "' as " + " (i : int, c : chararray, j : int " + ", b : bag { t : tuple (c1 : int, c2 : chararray)}" + ", t : tuple (tc1 : int, tc2 : chararray) );" + " l2 = load '" + INP_FILE_2NUM_1CHAR_1BAG + "' as " + " (i : int, c : chararray, j : int " + ", b : bag { t : tuple (c1 : int, c2 : chararray)}" + ", t : tuple (tc1 : int, tc2 : chararray) );" + "f1 = foreach l1 generate i, MAX(b.c1) as mx;" + "f11 = foreach f1 generate i, mx;" + "f2 = foreach l2 generate i, COUNT(b.c1) as mx;" + "f22 = foreach f2 generate i, mx;" ; String query = query_prefix + "u = union onschema f11, f22;"; Util.registerMultiLineQuery(pig, query); Schema sch = pig.dumpSchema("u"); Schema expectedSch = Utils.getSchemaFromString("i: int, mx: long"); assertEquals("Checking expected schema",sch, expectedSch); // verify schema for reverse order of relations as well query = query_prefix + "u = union onschema f22, f11;"; Util.registerMultiLineQuery(pig, query); sch = pig.dumpSchema("u"); expectedSch = Utils.getSchemaFromString("i: int, mx: long"); assertEquals("Checking expected schema",sch, expectedSch); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1,1L)", "(5,2L)", "(1,2L)", "(5,2L)" }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Udf that has schema of tuple column with no inner schema */ public static class UDFTupleNullSchema extends EvalFunc <Tuple> { @Override public Tuple exec(Tuple input) { return input; } @Override public Schema outputSchema(Schema input) { FieldSchema fs = new Schema.FieldSchema(getSchemaName("UDFTupleNullSchema", input), DataType.TUPLE); return new Schema(fs); } } /** * Test UNION ONSCHEMA with input relation having column names with multiple * level of namespace in their names */ @Test public void testUnionOnSchemaScopeMulti() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query_prefix = " a = load '" + INP_FILE_2NUMS+ "' as (i:int, j:int); " + "b = group a by i; " + "c = foreach b generate group as gp, flatten(a); " + "d = group c by $0; " + "e = foreach d generate group as gp, flatten(c); " + "f = load '" + INP_FILE_2NUMS + "' as (i, j); " ; String query = query_prefix + "u = union onschema e,f;"; Util.registerMultiLineQuery(pig, query); Schema sch = pig.dumpSchema("u"); Schema expectedSch = Utils.getSchemaFromString("gp: int,c::gp: int,i: int,j: int"); assertEquals("Checking expected schema",sch, expectedSch); query = query_prefix + "u = union onschema f,e;"; Util.registerMultiLineQuery(pig, query); sch = pig.dumpSchema("u"); expectedSch = Utils.getSchemaFromString("i: int,j: int, gp: int,c::gp: int"); assertEquals("Checking expected schema",sch, expectedSch); Iterator<Tuple> it = pig.openIterator("u"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1,2,null,null)", "(5,3,null,null)", "(1,2,1,1)", "(5,3,5,5)", }); Util.checkQueryOutputsAfterSort(it, expectedRes); } /** * Test query with a union-onschema having another as input */ @Test public void testTwoUnions() throws Exception { PigServer pig = new PigServer(Util.getLocalTestMode()); String query = " l1 = load '" + INP_FILE_2NUMS + "' as (i : int, j : int);" + "l2 = load '" + INP_FILE_2NUMS + "' as (i : long, j : int);" + "u1 = union onschema l1, l2;" + "l3 = load '" + INP_FILE_2NUMS + "' as (i : long, j : double);" + "u2 = union onschema u1, l3;" ; Util.registerMultiLineQuery(pig, query); Iterator<Tuple> it = pig.openIterator("u2"); List<Tuple> expectedRes = Util.getTuplesFromConstantTupleStrings( new String[] { "(1L,2.0)", "(5L,3.0)", "(1L,2.0)", "(5L,3.0)", "(1L,2.0)", "(5L,3.0)" }); Util.checkQueryOutputsAfterSort(it, expectedRes); } }
apache/seatunnel
37,497
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLTransformTest.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.seatunnel.transform.sql; import org.apache.seatunnel.api.configuration.ReadonlyConfig; import org.apache.seatunnel.api.table.catalog.CatalogTable; import org.apache.seatunnel.api.table.catalog.CatalogTableUtil; import org.apache.seatunnel.api.table.catalog.PhysicalColumn; import org.apache.seatunnel.api.table.catalog.TableIdentifier; import org.apache.seatunnel.api.table.catalog.TableSchema; import org.apache.seatunnel.api.table.type.BasicType; import org.apache.seatunnel.api.table.type.LocalTimeType; import org.apache.seatunnel.api.table.type.MapType; import org.apache.seatunnel.api.table.type.SeaTunnelDataType; import org.apache.seatunnel.api.table.type.SeaTunnelRow; import org.apache.seatunnel.api.table.type.SeaTunnelRowType; import org.apache.seatunnel.transform.exception.TransformException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Objects; public class SQLTransformTest { private static final String TEST_NAME = "test"; private static final String TIMESTAMP_FIELDNAME = "create_time"; private static final String[] FIELD_NAMES = new String[] {"id", "name", "age", TIMESTAMP_FIELDNAME}; private static final String GENERATE_PARTITION_KEY = "dt"; private static final ReadonlyConfig READONLY_CONFIG = ReadonlyConfig.fromMap( new HashMap<String, Object>() { { put( "query", "select *,FORMATDATETIME(create_time,'yyyy-MM-dd HH:mm') as dt from dual"); } }); @Test public void testScaleSupport() { SQLTransform sqlTransform = new SQLTransform(READONLY_CONFIG, getCatalogTable()); TableSchema tableSchema = sqlTransform.transformTableSchema(); tableSchema .getColumns() .forEach( column -> { if (column.getName().equals(TIMESTAMP_FIELDNAME)) { Assertions.assertEquals(9, column.getScale()); } else if (column.getName().equals(GENERATE_PARTITION_KEY)) { Assertions.assertTrue(Objects.isNull(column.getScale())); } else { Assertions.assertEquals(3, column.getColumnLength()); } }); } @Test public void testQueryWithAnyTable() { SQLTransform sqlTransform = new SQLTransform( ReadonlyConfig.fromMap( new HashMap<String, Object>() { { put("query", "select * from dual"); } }), getCatalogTable()); TableSchema tableSchema = sqlTransform.transformTableSchema(); Assertions.assertEquals(4, tableSchema.getColumns().size()); } @Test public void testNotLoseSourceTypeAndOptions() { SQLTransform sqlTransform = new SQLTransform(READONLY_CONFIG, getCatalogTable()); TableSchema tableSchema = sqlTransform.transformTableSchema(); tableSchema .getColumns() .forEach( column -> { if (!column.getName().equals(GENERATE_PARTITION_KEY)) { Assertions.assertEquals( "source_" + column.getDataType(), column.getSourceType()); Assertions.assertEquals( "testInSQL", column.getOptions().get("context")); } }); } private CatalogTable getCatalogTable() { SeaTunnelRowType rowType = new SeaTunnelRowType( FIELD_NAMES, new SeaTunnelDataType[] { BasicType.INT_TYPE, BasicType.STRING_TYPE, BasicType.INT_TYPE, LocalTimeType.LOCAL_DATE_TIME_TYPE }); TableSchema.Builder schemaBuilder = TableSchema.builder(); for (int i = 0; i < rowType.getTotalFields(); i++) { Integer scale = null; Long columnLength = null; if (rowType.getFieldName(i).equals(TIMESTAMP_FIELDNAME)) { scale = 9; } else { columnLength = 3L; } PhysicalColumn column = new PhysicalColumn( rowType.getFieldName(i), rowType.getFieldType(i), columnLength, scale, true, null, null, "source_" + rowType.getFieldType(i), new HashMap<String, Object>() { { put("context", "testInSQL"); } }); schemaBuilder.column(column); } return CatalogTable.of( TableIdentifier.of(TEST_NAME, TEST_NAME, null, TEST_NAME), schemaBuilder.build(), new HashMap<>(), new ArrayList<>(), "It has column information."); } @Test public void testEscapeIdentifier() { String tableName = "test"; String[] fields = new String[] {"id", "apply"}; CatalogTable table = CatalogTableUtil.getCatalogTable( tableName, new SeaTunnelRowType( fields, new SeaTunnelDataType[] { BasicType.INT_TYPE, BasicType.STRING_TYPE })); ReadonlyConfig config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select `id`, trim(`apply`) as `apply` from dual where `apply` = 'a'")); SQLTransform sqlTransform = new SQLTransform(config, table); TableSchema tableSchema = sqlTransform.transformTableSchema(); List<SeaTunnelRow> result = sqlTransform.transformRow( new SeaTunnelRow(new Object[] {Integer.valueOf(1), String.valueOf("a")})); Assertions.assertEquals("id", tableSchema.getFieldNames()[0]); Assertions.assertEquals("apply", tableSchema.getFieldNames()[1]); Assertions.assertEquals("a", result.get(0).getField(1)); result = sqlTransform.transformRow( new SeaTunnelRow(new Object[] {Integer.valueOf(1), String.valueOf("b")})); Assertions.assertNull(result); config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select id, IFNULL(`apply`, '1') as `apply` from dual where `apply` = 'a'")); sqlTransform = new SQLTransform(config, table); tableSchema = sqlTransform.transformTableSchema(); result = sqlTransform.transformRow( new SeaTunnelRow(new Object[] {Integer.valueOf(1), String.valueOf("a")})); Assertions.assertEquals("apply", tableSchema.getFieldNames()[1]); Assertions.assertEquals( BasicType.STRING_TYPE, tableSchema.getColumns().get(1).getDataType()); Assertions.assertEquals("a", result.get(0).getField(1)); table = CatalogTableUtil.getCatalogTable( tableName, new SeaTunnelRowType( fields, new SeaTunnelDataType[] {BasicType.INT_TYPE, BasicType.LONG_TYPE})); config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select id, `apply` + 1 as `apply` from dual where `apply` > 0")); sqlTransform = new SQLTransform(config, table); tableSchema = sqlTransform.transformTableSchema(); result = sqlTransform.transformRow( new SeaTunnelRow(new Object[] {Integer.valueOf(1), Long.valueOf(1)})); Assertions.assertEquals("apply", tableSchema.getFieldNames()[1]); Assertions.assertEquals(BasicType.LONG_TYPE, tableSchema.getColumns().get(1).getDataType()); Assertions.assertEquals(Long.valueOf(2), result.get(0).getField(1)); result = sqlTransform.transformRow( new SeaTunnelRow(new Object[] {Integer.valueOf(1), Long.valueOf(0)})); Assertions.assertNull(result); table = CatalogTableUtil.getCatalogTable( tableName, new SeaTunnelRowType( fields, new SeaTunnelDataType[] { BasicType.INT_TYPE, new MapType<String, String>( BasicType.STRING_TYPE, BasicType.STRING_TYPE) })); config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select id, `apply`.k1 as `apply` from dual where `apply`.k1 = 'a'")); sqlTransform = new SQLTransform(config, table); tableSchema = sqlTransform.transformTableSchema(); result = sqlTransform.transformRow( new SeaTunnelRow( new Object[] { Integer.valueOf(1), Collections.singletonMap("k1", "a") })); Assertions.assertEquals("apply", tableSchema.getFieldNames()[1]); Assertions.assertEquals( BasicType.STRING_TYPE, tableSchema.getColumns().get(1).getDataType()); Assertions.assertEquals("a", result.get(0).getField(1)); result = sqlTransform.transformRow( new SeaTunnelRow( new Object[] { Integer.valueOf(1), Collections.singletonMap("k1", "b") })); Assertions.assertNull(result); table = CatalogTableUtil.getCatalogTable( tableName, new SeaTunnelRowType( new String[] {"id", "map"}, new SeaTunnelDataType[] { BasicType.INT_TYPE, new MapType<String, String>( BasicType.STRING_TYPE, BasicType.STRING_TYPE) })); config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select id, map.`apply` as `apply` from dual where map.`apply` = 'a'")); sqlTransform = new SQLTransform(config, table); tableSchema = sqlTransform.transformTableSchema(); result = sqlTransform.transformRow( new SeaTunnelRow( new Object[] { Integer.valueOf(1), Collections.singletonMap("apply", "a") })); Assertions.assertEquals("apply", tableSchema.getFieldNames()[1]); Assertions.assertEquals( BasicType.STRING_TYPE, tableSchema.getColumns().get(1).getDataType()); Assertions.assertEquals("a", result.get(0).getField(1)); } @Test public void tesCaseWhenClausesWithBooleanField() { String tableName = "test"; String[] fields = new String[] {"id", "bool"}; CatalogTable table = CatalogTableUtil.getCatalogTable( tableName, new SeaTunnelRowType( fields, new SeaTunnelDataType[] { BasicType.INT_TYPE, BasicType.BOOLEAN_TYPE })); ReadonlyConfig config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select `id`, `bool`, case when bool then 1 else 2 end as bool_1 from dual")); SQLTransform sqlTransform = new SQLTransform(config, table); List<SeaTunnelRow> result = sqlTransform.transformRow( new SeaTunnelRow(new Object[] {Integer.valueOf(1), true})); Assertions.assertEquals(1, result.get(0).getField(0)); Assertions.assertEquals(true, result.get(0).getField(1)); Assertions.assertEquals(1, result.get(0).getField(2)); result = sqlTransform.transformRow( new SeaTunnelRow(new Object[] {Integer.valueOf(1), false})); Assertions.assertEquals(1, result.get(0).getField(0)); Assertions.assertEquals(false, result.get(0).getField(1)); Assertions.assertEquals(2, result.get(0).getField(2)); } @Test public void tesCaseWhenBooleanClausesWithField() { String tableName = "test"; String[] fields = new String[] {"id", "int", "string"}; CatalogTable table = CatalogTableUtil.getCatalogTable( tableName, new SeaTunnelRowType( fields, new SeaTunnelDataType[] { BasicType.INT_TYPE, BasicType.INT_TYPE, BasicType.STRING_TYPE })); ReadonlyConfig config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select `id`, `int`, (case when `int` = 1 then true else false end) as bool_1 , `string`, (case when `string` = 'true' then true else false end) as bool_2 from dual")); SQLTransform sqlTransform = new SQLTransform(config, table); List<SeaTunnelRow> result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, 1, "true"})); Assertions.assertEquals(1, result.get(0).getField(0)); Assertions.assertEquals(1, result.get(0).getField(1)); Assertions.assertEquals(true, result.get(0).getField(2)); Assertions.assertEquals("true", result.get(0).getField(3)); Assertions.assertEquals(true, result.get(0).getField(4)); result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, 0, "false"})); Assertions.assertEquals(1, result.get(0).getField(0)); Assertions.assertEquals(0, result.get(0).getField(1)); Assertions.assertEquals(false, result.get(0).getField(2)); Assertions.assertEquals("false", result.get(0).getField(3)); Assertions.assertEquals(false, result.get(0).getField(4)); } @Test public void tesCastBooleanClausesWithField() { String tableName = "test"; String[] fields = new String[] {"id", "int", "string"}; CatalogTable table = CatalogTableUtil.getCatalogTable( tableName, new SeaTunnelRowType( fields, new SeaTunnelDataType[] { BasicType.INT_TYPE, BasicType.INT_TYPE, BasicType.STRING_TYPE })); ReadonlyConfig config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select `id`, `int`, cast(`int` as boolean) as bool_1 , `string`, cast(`string` as boolean) as bool_2 from dual")); SQLTransform sqlTransform = new SQLTransform(config, table); List<SeaTunnelRow> result = sqlTransform.transformRow( new SeaTunnelRow(new Object[] {Integer.valueOf(1), 1, "true"})); Assertions.assertEquals(1, result.get(0).getField(0)); Assertions.assertEquals(1, result.get(0).getField(1)); Assertions.assertEquals(true, result.get(0).getField(2)); Assertions.assertEquals("true", result.get(0).getField(3)); Assertions.assertEquals(true, result.get(0).getField(4)); result = sqlTransform.transformRow( new SeaTunnelRow(new Object[] {Integer.valueOf(1), 0, "false"})); Assertions.assertEquals(1, result.get(0).getField(0)); Assertions.assertEquals(0, result.get(0).getField(1)); Assertions.assertEquals(false, result.get(0).getField(2)); Assertions.assertEquals("false", result.get(0).getField(3)); Assertions.assertEquals(false, result.get(0).getField(4)); Assertions.assertThrows( TransformException.class, () -> { try { sqlTransform.transformRow( new SeaTunnelRow(new Object[] {Integer.valueOf(1), 3, "false"})); } catch (Exception e) { Assertions.assertEquals( "ErrorCode:[TRANSFORM_COMMON-06], ErrorDescription:[The expression 'cast(`int` AS boolean)' of SQL transform execute failed]", e.getMessage()); Assertions.assertEquals( "ErrorCode:[COMMON-05], ErrorDescription:[Unsupported operation] - Unsupported CAST AS Boolean: 3", e.getCause().getMessage()); throw e; } }); Assertions.assertThrows( TransformException.class, () -> { try { sqlTransform.transformRow( new SeaTunnelRow(new Object[] {Integer.valueOf(1), 0, "false333"})); } catch (Exception e) { Assertions.assertEquals( "ErrorCode:[TRANSFORM_COMMON-06], ErrorDescription:[The expression 'cast(`string` AS boolean)' of SQL transform execute failed]", e.getMessage()); Assertions.assertEquals( "ErrorCode:[COMMON-05], ErrorDescription:[Unsupported operation] - Unsupported CAST AS Boolean: false333", e.getCause().getMessage()); throw e; } }); } @Test public void tesBooleanField() { String tableName = "test"; String[] fields = new String[] {"id", "int", "string"}; CatalogTable table = CatalogTableUtil.getCatalogTable( tableName, new SeaTunnelRowType( fields, new SeaTunnelDataType[] { BasicType.INT_TYPE, BasicType.INT_TYPE, BasicType.STRING_TYPE })); ReadonlyConfig config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select `id`, true as bool_1, false as bool_2 from dual")); SQLTransform sqlTransform = new SQLTransform(config, table); List<SeaTunnelRow> result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, 1, "true"})); Assertions.assertEquals(1, result.get(0).getField(0)); Assertions.assertEquals(true, result.get(0).getField(1)); Assertions.assertEquals(false, result.get(0).getField(2)); } @Test public void testExpressionErrorField() { String tableName = "test"; String[] fields = new String[] {"FIELD1", "FIELD2", "FIELD3"}; SeaTunnelDataType[] fieldTypes = new SeaTunnelDataType[] { BasicType.INT_TYPE, BasicType.DOUBLE_TYPE, BasicType.STRING_TYPE }; CatalogTable table = CatalogTableUtil.getCatalogTable( tableName, new SeaTunnelRowType(fields, fieldTypes)); String sqlQuery = "select " + "CAST(`FIELD1` AS STRING) AS FIELD1, " + "CAST(`FIELD1` AS decimal(22,4)) AS FIELD2, " + "CAST(`FIELD3` AS decimal(22,0)) AS FIELD3 " + "from dual"; ReadonlyConfig config = ReadonlyConfig.fromMap(Collections.singletonMap("query", sqlQuery)); SQLTransform sqlTransform = new SQLTransform(config, table); Assertions.assertThrows( TransformException.class, () -> { try { sqlTransform.transformRow( new SeaTunnelRow(new Object[] {1, 123.123, "true"})); } catch (Exception e) { Assertions.assertEquals( "ErrorCode:[TRANSFORM_COMMON-06], ErrorDescription:[The expression 'CAST(`FIELD3` AS decimal (22, 0))' of SQL transform execute failed]", e.getMessage()); throw e; } }); sqlQuery = "select * from dual where FIELD1/0 > 10"; config = ReadonlyConfig.fromMap(Collections.singletonMap("query", sqlQuery)); SQLTransform sqlTransform2 = new SQLTransform(config, table); Assertions.assertThrows( TransformException.class, () -> { try { sqlTransform2.transformRow( new SeaTunnelRow(new Object[] {1, 123.123, "true"})); } catch (Exception e) { Assertions.assertEquals( "ErrorCode:[TRANSFORM_COMMON-07], ErrorDescription:[The where statement 'FIELD1 / 0 > 10' of SQL transform execute failed]", e.getMessage()); throw e; } }); } @Test public void testCoalesceTypeConversion() { String tableName = "test"; String[] fields = new String[] {"id", "stringField", "intField", "doubleField"}; CatalogTable table = CatalogTableUtil.getCatalogTable( tableName, new SeaTunnelRowType( fields, new SeaTunnelDataType[] { BasicType.INT_TYPE, BasicType.STRING_TYPE, BasicType.INT_TYPE, BasicType.DOUBLE_TYPE })); // The first parameter to test COALESCE is the string type, followed by the integer type ReadonlyConfig config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select id, COALESCE(stringField, intField) as result from dual")); SQLTransform sqlTransform = new SQLTransform(config, table); TableSchema tableSchema = sqlTransform.transformTableSchema(); // Verify that the field type is STRING Assertions.assertEquals("result", tableSchema.getFieldNames()[1]); Assertions.assertEquals( BasicType.STRING_TYPE, tableSchema.getColumns().get(1).getDataType()); // The first field is not null, and the value of the first field should be directly returned List<SeaTunnelRow> result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, "test", 123, 123.45})); Assertions.assertEquals("test", result.get(0).getField(1)); // The first field is null, and the value converted to the string should be returned. result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, null, 123, 123.45})); Assertions.assertEquals("123", result.get(0).getField(1)); // Make sure the return value is a string type rather than an integer type Assertions.assertTrue( result.get(0).getField(1) instanceof String, "The result should be a string type, but is actually " + result.get(0).getField(1).getClass().getName()); // The first parameter to test COALESCE is the integer type, followed by the floating point // type config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select id, COALESCE(intField, doubleField) as result from dual")); sqlTransform = new SQLTransform(config, table); tableSchema = sqlTransform.transformTableSchema(); // Verify that the field type is INT Assertions.assertEquals("result", tableSchema.getFieldNames()[1]); Assertions.assertEquals(BasicType.INT_TYPE, tableSchema.getColumns().get(1).getDataType()); // The first field is not null, and the value of the first field should be directly // returned result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, "test", 123, 123.45})); Assertions.assertEquals(123, result.get(0).getField(1)); Assertions.assertTrue( result.get(0).getField(1) instanceof Integer, "The result should be an integer type, but is actually " + result.get(0).getField(1).getClass().getName()); // The first field is null, and the value converted to an integer should be returned. result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, "test", null, 456.78})); Assertions.assertEquals(456, result.get(0).getField(1)); Assertions.assertTrue( result.get(0).getField(1) instanceof Integer, "The result should be an integer type, but is actually " + result.get(0).getField(1).getClass().getName()); // Test COALESCE with null as first argument config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select id, COALESCE(null, stringField, intField) as result from dual")); sqlTransform = new SQLTransform(config, table); tableSchema = sqlTransform.transformTableSchema(); // Verify that the result field type is STRING (since stringField is the first non-null // parameter) Assertions.assertEquals("result", tableSchema.getFieldNames()[1]); Assertions.assertEquals( BasicType.STRING_TYPE, tableSchema.getColumns().get(1).getDataType()); // Test with both stringField and intField having values result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, "test", 123, 123.45})); Assertions.assertEquals("test", result.get(0).getField(1)); Assertions.assertTrue( result.get(0).getField(1) instanceof String, "The result should be a string type, but is actually " + result.get(0).getField(1).getClass().getName()); // Test with stringField being null, should return intField as string result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, null, 123, 123.45})); Assertions.assertEquals("123", result.get(0).getField(1)); Assertions.assertTrue( result.get(0).getField(1) instanceof String, "The result should be a string type, but is actually " + result.get(0).getField(1).getClass().getName()); } @Test public void testIfNullTypeConversion() { String tableName = "test"; String[] fields = new String[] {"id", "stringField", "intField", "doubleField"}; CatalogTable table = CatalogTableUtil.getCatalogTable( tableName, new SeaTunnelRowType( fields, new SeaTunnelDataType[] { BasicType.INT_TYPE, BasicType.STRING_TYPE, BasicType.INT_TYPE, BasicType.DOUBLE_TYPE })); // Test IFNULL with string field as first parameter and integer as second ReadonlyConfig config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select id, IFNULL(stringField, intField) as result from dual")); SQLTransform sqlTransform = new SQLTransform(config, table); TableSchema tableSchema = sqlTransform.transformTableSchema(); // Verify that the field type is STRING Assertions.assertEquals("result", tableSchema.getFieldNames()[1]); Assertions.assertEquals( BasicType.STRING_TYPE, tableSchema.getColumns().get(1).getDataType()); // The first field is not null, and the value of the first field should be directly returned List<SeaTunnelRow> result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, "test", 123, 123.45})); Assertions.assertEquals("test", result.get(0).getField(1)); // The first field is null, and the value converted to the string should be returned. result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, null, 123, 123.45})); Assertions.assertEquals("123", result.get(0).getField(1)); // Make sure the return value is a string type rather than an integer type Assertions.assertTrue( result.get(0).getField(1) instanceof String, "The result should be a string type, but is actually " + result.get(0).getField(1).getClass().getName()); // Test IFNULL with integer field as first parameter and double as second config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select id, IFNULL(intField, doubleField) as result from dual")); sqlTransform = new SQLTransform(config, table); tableSchema = sqlTransform.transformTableSchema(); // Verify that the field type is INT Assertions.assertEquals("result", tableSchema.getFieldNames()[1]); Assertions.assertEquals(BasicType.INT_TYPE, tableSchema.getColumns().get(1).getDataType()); // The first field is not null, and the value of the first field should be directly // returned result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, "test", 123, 123.45})); Assertions.assertEquals(123, result.get(0).getField(1)); Assertions.assertTrue( result.get(0).getField(1) instanceof Integer, "The result should be an integer type, but is actually " + result.get(0).getField(1).getClass().getName()); // The first field is null, and the value converted to an integer should be returned. result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, "test", null, 456.78})); Assertions.assertEquals(456, result.get(0).getField(1)); Assertions.assertTrue( result.get(0).getField(1) instanceof Integer, "The result should be an integer type, but is actually " + result.get(0).getField(1).getClass().getName()); // Test IFNULL with null literal as first argument config = ReadonlyConfig.fromMap( Collections.singletonMap( "query", "select id, IFNULL(null, stringField) as result from dual")); sqlTransform = new SQLTransform(config, table); tableSchema = sqlTransform.transformTableSchema(); // Verify that the result field type is STRING Assertions.assertEquals("result", tableSchema.getFieldNames()[1]); Assertions.assertEquals( BasicType.STRING_TYPE, tableSchema.getColumns().get(1).getDataType()); // Test with stringField having a value result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, "test", 123, 123.45})); Assertions.assertEquals("test", result.get(0).getField(1)); Assertions.assertTrue( result.get(0).getField(1) instanceof String, "The result should be a string type, but is actually " + result.get(0).getField(1).getClass().getName()); // Test with stringField being null, should return null result = sqlTransform.transformRow(new SeaTunnelRow(new Object[] {1, null, 123, 123.45})); Assertions.assertNull(result.get(0).getField(1)); } public void testCastTimestampValidate() { String querySql = "select CAST(`id` AS TIMESTAMP) AS idStr, name AS name from dual"; SQLTransform sqlTransform = new SQLTransform( ReadonlyConfig.fromMap( new HashMap<String, Object>() { { put("query", querySql); } }), getCatalogTable()); Assertions.assertThrows( TransformException.class, () -> { try { sqlTransform.transformTableSchema(); } catch (Exception e) { Assertions.assertEquals( "ErrorCode:[COMMON-05], ErrorDescription:[Unsupported operation] - Unsupported CAST FROM INT AS type: TIMESTAMP", e.getMessage()); throw e; } }); } @Test public void testCastIntValidate() { String querySql = "select id AS id, name AS name, CAST(create_time AS INT) AS timeInt from dual"; SQLTransform sqlTransform = new SQLTransform( ReadonlyConfig.fromMap( new HashMap<String, Object>() { { put("query", querySql); } }), getCatalogTable()); Assertions.assertThrows( TransformException.class, () -> { try { sqlTransform.transformTableSchema(); } catch (Exception e) { Assertions.assertEquals( "ErrorCode:[COMMON-05], ErrorDescription:[Unsupported operation] - Unsupported CAST FROM TIMESTAMP AS type: INT", e.getMessage()); throw e; } }); } }
googleapis/google-cloud-java
37,318
java-asset/proto-google-cloud-asset-v1/src/main/java/com/google/cloud/asset/v1/GcsDestination.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/asset/v1/asset_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.asset.v1; /** * * * <pre> * A Cloud Storage location. * </pre> * * Protobuf type {@code google.cloud.asset.v1.GcsDestination} */ public final class GcsDestination extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.asset.v1.GcsDestination) GcsDestinationOrBuilder { private static final long serialVersionUID = 0L; // Use GcsDestination.newBuilder() to construct. private GcsDestination(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GcsDestination() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new GcsDestination(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.asset.v1.AssetServiceProto .internal_static_google_cloud_asset_v1_GcsDestination_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.asset.v1.AssetServiceProto .internal_static_google_cloud_asset_v1_GcsDestination_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.asset.v1.GcsDestination.class, com.google.cloud.asset.v1.GcsDestination.Builder.class); } private int objectUriCase_ = 0; @SuppressWarnings("serial") private java.lang.Object objectUri_; public enum ObjectUriCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { URI(1), URI_PREFIX(2), OBJECTURI_NOT_SET(0); private final int value; private ObjectUriCase(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 ObjectUriCase valueOf(int value) { return forNumber(value); } public static ObjectUriCase forNumber(int value) { switch (value) { case 1: return URI; case 2: return URI_PREFIX; case 0: return OBJECTURI_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public ObjectUriCase getObjectUriCase() { return ObjectUriCase.forNumber(objectUriCase_); } public static final int URI_FIELD_NUMBER = 1; /** * * * <pre> * The URI of the Cloud Storage object. It's the same URI that is used by * gsutil. Example: "gs://bucket_name/object_name". See [Viewing and * Editing Object * Metadata](https://cloud.google.com/storage/docs/viewing-editing-metadata) * for more information. * * If the specified Cloud Storage object already exists and there is no * [hold](https://cloud.google.com/storage/docs/object-holds), it will be * overwritten with the exported result. * </pre> * * <code>string uri = 1;</code> * * @return Whether the uri field is set. */ public boolean hasUri() { return objectUriCase_ == 1; } /** * * * <pre> * The URI of the Cloud Storage object. It's the same URI that is used by * gsutil. Example: "gs://bucket_name/object_name". See [Viewing and * Editing Object * Metadata](https://cloud.google.com/storage/docs/viewing-editing-metadata) * for more information. * * If the specified Cloud Storage object already exists and there is no * [hold](https://cloud.google.com/storage/docs/object-holds), it will be * overwritten with the exported result. * </pre> * * <code>string uri = 1;</code> * * @return The uri. */ public java.lang.String getUri() { java.lang.Object ref = ""; if (objectUriCase_ == 1) { ref = objectUri_; } if (ref instanceof java.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 (objectUriCase_ == 1) { objectUri_ = s; } return s; } } /** * * * <pre> * The URI of the Cloud Storage object. It's the same URI that is used by * gsutil. Example: "gs://bucket_name/object_name". See [Viewing and * Editing Object * Metadata](https://cloud.google.com/storage/docs/viewing-editing-metadata) * for more information. * * If the specified Cloud Storage object already exists and there is no * [hold](https://cloud.google.com/storage/docs/object-holds), it will be * overwritten with the exported result. * </pre> * * <code>string uri = 1;</code> * * @return The bytes for uri. */ public com.google.protobuf.ByteString getUriBytes() { java.lang.Object ref = ""; if (objectUriCase_ == 1) { ref = objectUri_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (objectUriCase_ == 1) { objectUri_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int URI_PREFIX_FIELD_NUMBER = 2; /** * * * <pre> * The URI prefix of all generated Cloud Storage objects. Example: * "gs://bucket_name/object_name_prefix". Each object URI is in format: * "gs://bucket_name/object_name_prefix/&lt;asset type&gt;/&lt;shard number&gt; and only * contains assets for that type. &lt;shard number&gt; starts from 0. Example: * "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" is * the first shard of output objects containing all * compute.googleapis.com/Disk assets. An INVALID_ARGUMENT error will be * returned if file with the same name "gs://bucket_name/object_name_prefix" * already exists. * </pre> * * <code>string uri_prefix = 2;</code> * * @return Whether the uriPrefix field is set. */ public boolean hasUriPrefix() { return objectUriCase_ == 2; } /** * * * <pre> * The URI prefix of all generated Cloud Storage objects. Example: * "gs://bucket_name/object_name_prefix". Each object URI is in format: * "gs://bucket_name/object_name_prefix/&lt;asset type&gt;/&lt;shard number&gt; and only * contains assets for that type. &lt;shard number&gt; starts from 0. Example: * "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" is * the first shard of output objects containing all * compute.googleapis.com/Disk assets. An INVALID_ARGUMENT error will be * returned if file with the same name "gs://bucket_name/object_name_prefix" * already exists. * </pre> * * <code>string uri_prefix = 2;</code> * * @return The uriPrefix. */ public java.lang.String getUriPrefix() { java.lang.Object ref = ""; if (objectUriCase_ == 2) { ref = objectUri_; } if (ref instanceof java.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 (objectUriCase_ == 2) { objectUri_ = s; } return s; } } /** * * * <pre> * The URI prefix of all generated Cloud Storage objects. Example: * "gs://bucket_name/object_name_prefix". Each object URI is in format: * "gs://bucket_name/object_name_prefix/&lt;asset type&gt;/&lt;shard number&gt; and only * contains assets for that type. &lt;shard number&gt; starts from 0. Example: * "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" is * the first shard of output objects containing all * compute.googleapis.com/Disk assets. An INVALID_ARGUMENT error will be * returned if file with the same name "gs://bucket_name/object_name_prefix" * already exists. * </pre> * * <code>string uri_prefix = 2;</code> * * @return The bytes for uriPrefix. */ public com.google.protobuf.ByteString getUriPrefixBytes() { java.lang.Object ref = ""; if (objectUriCase_ == 2) { ref = objectUri_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (objectUriCase_ == 2) { objectUri_ = 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 (objectUriCase_ == 1) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, objectUri_); } if (objectUriCase_ == 2) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, objectUri_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (objectUriCase_ == 1) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, objectUri_); } if (objectUriCase_ == 2) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, objectUri_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.asset.v1.GcsDestination)) { return super.equals(obj); } com.google.cloud.asset.v1.GcsDestination other = (com.google.cloud.asset.v1.GcsDestination) obj; if (!getObjectUriCase().equals(other.getObjectUriCase())) return false; switch (objectUriCase_) { case 1: if (!getUri().equals(other.getUri())) return false; break; case 2: if (!getUriPrefix().equals(other.getUriPrefix())) 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 (objectUriCase_) { case 1: hash = (37 * hash) + URI_FIELD_NUMBER; hash = (53 * hash) + getUri().hashCode(); break; case 2: hash = (37 * hash) + URI_PREFIX_FIELD_NUMBER; hash = (53 * hash) + getUriPrefix().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.asset.v1.GcsDestination parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.asset.v1.GcsDestination parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.asset.v1.GcsDestination parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.asset.v1.GcsDestination parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.asset.v1.GcsDestination parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.asset.v1.GcsDestination parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.asset.v1.GcsDestination parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.asset.v1.GcsDestination parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.asset.v1.GcsDestination parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.asset.v1.GcsDestination parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.asset.v1.GcsDestination parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.asset.v1.GcsDestination parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.asset.v1.GcsDestination 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 Cloud Storage location. * </pre> * * Protobuf type {@code google.cloud.asset.v1.GcsDestination} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.asset.v1.GcsDestination) com.google.cloud.asset.v1.GcsDestinationOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.asset.v1.AssetServiceProto .internal_static_google_cloud_asset_v1_GcsDestination_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.asset.v1.AssetServiceProto .internal_static_google_cloud_asset_v1_GcsDestination_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.asset.v1.GcsDestination.class, com.google.cloud.asset.v1.GcsDestination.Builder.class); } // Construct using com.google.cloud.asset.v1.GcsDestination.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; objectUriCase_ = 0; objectUri_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.asset.v1.AssetServiceProto .internal_static_google_cloud_asset_v1_GcsDestination_descriptor; } @java.lang.Override public com.google.cloud.asset.v1.GcsDestination getDefaultInstanceForType() { return com.google.cloud.asset.v1.GcsDestination.getDefaultInstance(); } @java.lang.Override public com.google.cloud.asset.v1.GcsDestination build() { com.google.cloud.asset.v1.GcsDestination result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.asset.v1.GcsDestination buildPartial() { com.google.cloud.asset.v1.GcsDestination result = new com.google.cloud.asset.v1.GcsDestination(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.cloud.asset.v1.GcsDestination result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs(com.google.cloud.asset.v1.GcsDestination result) { result.objectUriCase_ = objectUriCase_; result.objectUri_ = this.objectUri_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.asset.v1.GcsDestination) { return mergeFrom((com.google.cloud.asset.v1.GcsDestination) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.asset.v1.GcsDestination other) { if (other == com.google.cloud.asset.v1.GcsDestination.getDefaultInstance()) return this; switch (other.getObjectUriCase()) { case URI: { objectUriCase_ = 1; objectUri_ = other.objectUri_; onChanged(); break; } case URI_PREFIX: { objectUriCase_ = 2; objectUri_ = other.objectUri_; onChanged(); break; } case OBJECTURI_NOT_SET: { break; } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); objectUriCase_ = 1; objectUri_ = s; break; } // case 10 case 18: { java.lang.String s = input.readStringRequireUtf8(); objectUriCase_ = 2; objectUri_ = 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 objectUriCase_ = 0; private java.lang.Object objectUri_; public ObjectUriCase getObjectUriCase() { return ObjectUriCase.forNumber(objectUriCase_); } public Builder clearObjectUri() { objectUriCase_ = 0; objectUri_ = null; onChanged(); return this; } private int bitField0_; /** * * * <pre> * The URI of the Cloud Storage object. It's the same URI that is used by * gsutil. Example: "gs://bucket_name/object_name". See [Viewing and * Editing Object * Metadata](https://cloud.google.com/storage/docs/viewing-editing-metadata) * for more information. * * If the specified Cloud Storage object already exists and there is no * [hold](https://cloud.google.com/storage/docs/object-holds), it will be * overwritten with the exported result. * </pre> * * <code>string uri = 1;</code> * * @return Whether the uri field is set. */ @java.lang.Override public boolean hasUri() { return objectUriCase_ == 1; } /** * * * <pre> * The URI of the Cloud Storage object. It's the same URI that is used by * gsutil. Example: "gs://bucket_name/object_name". See [Viewing and * Editing Object * Metadata](https://cloud.google.com/storage/docs/viewing-editing-metadata) * for more information. * * If the specified Cloud Storage object already exists and there is no * [hold](https://cloud.google.com/storage/docs/object-holds), it will be * overwritten with the exported result. * </pre> * * <code>string uri = 1;</code> * * @return The uri. */ @java.lang.Override public java.lang.String getUri() { java.lang.Object ref = ""; if (objectUriCase_ == 1) { ref = objectUri_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (objectUriCase_ == 1) { objectUri_ = s; } return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The URI of the Cloud Storage object. It's the same URI that is used by * gsutil. Example: "gs://bucket_name/object_name". See [Viewing and * Editing Object * Metadata](https://cloud.google.com/storage/docs/viewing-editing-metadata) * for more information. * * If the specified Cloud Storage object already exists and there is no * [hold](https://cloud.google.com/storage/docs/object-holds), it will be * overwritten with the exported result. * </pre> * * <code>string uri = 1;</code> * * @return The bytes for uri. */ @java.lang.Override public com.google.protobuf.ByteString getUriBytes() { java.lang.Object ref = ""; if (objectUriCase_ == 1) { ref = objectUri_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (objectUriCase_ == 1) { objectUri_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The URI of the Cloud Storage object. It's the same URI that is used by * gsutil. Example: "gs://bucket_name/object_name". See [Viewing and * Editing Object * Metadata](https://cloud.google.com/storage/docs/viewing-editing-metadata) * for more information. * * If the specified Cloud Storage object already exists and there is no * [hold](https://cloud.google.com/storage/docs/object-holds), it will be * overwritten with the exported result. * </pre> * * <code>string uri = 1;</code> * * @param value The uri to set. * @return This builder for chaining. */ public Builder setUri(java.lang.String value) { if (value == null) { throw new NullPointerException(); } objectUriCase_ = 1; objectUri_ = value; onChanged(); return this; } /** * * * <pre> * The URI of the Cloud Storage object. It's the same URI that is used by * gsutil. Example: "gs://bucket_name/object_name". See [Viewing and * Editing Object * Metadata](https://cloud.google.com/storage/docs/viewing-editing-metadata) * for more information. * * If the specified Cloud Storage object already exists and there is no * [hold](https://cloud.google.com/storage/docs/object-holds), it will be * overwritten with the exported result. * </pre> * * <code>string uri = 1;</code> * * @return This builder for chaining. */ public Builder clearUri() { if (objectUriCase_ == 1) { objectUriCase_ = 0; objectUri_ = null; onChanged(); } return this; } /** * * * <pre> * The URI of the Cloud Storage object. It's the same URI that is used by * gsutil. Example: "gs://bucket_name/object_name". See [Viewing and * Editing Object * Metadata](https://cloud.google.com/storage/docs/viewing-editing-metadata) * for more information. * * If the specified Cloud Storage object already exists and there is no * [hold](https://cloud.google.com/storage/docs/object-holds), it will be * overwritten with the exported result. * </pre> * * <code>string uri = 1;</code> * * @param value The bytes for uri to set. * @return This builder for chaining. */ public Builder setUriBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); objectUriCase_ = 1; objectUri_ = value; onChanged(); return this; } /** * * * <pre> * The URI prefix of all generated Cloud Storage objects. Example: * "gs://bucket_name/object_name_prefix". Each object URI is in format: * "gs://bucket_name/object_name_prefix/&lt;asset type&gt;/&lt;shard number&gt; and only * contains assets for that type. &lt;shard number&gt; starts from 0. Example: * "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" is * the first shard of output objects containing all * compute.googleapis.com/Disk assets. An INVALID_ARGUMENT error will be * returned if file with the same name "gs://bucket_name/object_name_prefix" * already exists. * </pre> * * <code>string uri_prefix = 2;</code> * * @return Whether the uriPrefix field is set. */ @java.lang.Override public boolean hasUriPrefix() { return objectUriCase_ == 2; } /** * * * <pre> * The URI prefix of all generated Cloud Storage objects. Example: * "gs://bucket_name/object_name_prefix". Each object URI is in format: * "gs://bucket_name/object_name_prefix/&lt;asset type&gt;/&lt;shard number&gt; and only * contains assets for that type. &lt;shard number&gt; starts from 0. Example: * "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" is * the first shard of output objects containing all * compute.googleapis.com/Disk assets. An INVALID_ARGUMENT error will be * returned if file with the same name "gs://bucket_name/object_name_prefix" * already exists. * </pre> * * <code>string uri_prefix = 2;</code> * * @return The uriPrefix. */ @java.lang.Override public java.lang.String getUriPrefix() { java.lang.Object ref = ""; if (objectUriCase_ == 2) { ref = objectUri_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (objectUriCase_ == 2) { objectUri_ = s; } return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The URI prefix of all generated Cloud Storage objects. Example: * "gs://bucket_name/object_name_prefix". Each object URI is in format: * "gs://bucket_name/object_name_prefix/&lt;asset type&gt;/&lt;shard number&gt; and only * contains assets for that type. &lt;shard number&gt; starts from 0. Example: * "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" is * the first shard of output objects containing all * compute.googleapis.com/Disk assets. An INVALID_ARGUMENT error will be * returned if file with the same name "gs://bucket_name/object_name_prefix" * already exists. * </pre> * * <code>string uri_prefix = 2;</code> * * @return The bytes for uriPrefix. */ @java.lang.Override public com.google.protobuf.ByteString getUriPrefixBytes() { java.lang.Object ref = ""; if (objectUriCase_ == 2) { ref = objectUri_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (objectUriCase_ == 2) { objectUri_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The URI prefix of all generated Cloud Storage objects. Example: * "gs://bucket_name/object_name_prefix". Each object URI is in format: * "gs://bucket_name/object_name_prefix/&lt;asset type&gt;/&lt;shard number&gt; and only * contains assets for that type. &lt;shard number&gt; starts from 0. Example: * "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" is * the first shard of output objects containing all * compute.googleapis.com/Disk assets. An INVALID_ARGUMENT error will be * returned if file with the same name "gs://bucket_name/object_name_prefix" * already exists. * </pre> * * <code>string uri_prefix = 2;</code> * * @param value The uriPrefix to set. * @return This builder for chaining. */ public Builder setUriPrefix(java.lang.String value) { if (value == null) { throw new NullPointerException(); } objectUriCase_ = 2; objectUri_ = value; onChanged(); return this; } /** * * * <pre> * The URI prefix of all generated Cloud Storage objects. Example: * "gs://bucket_name/object_name_prefix". Each object URI is in format: * "gs://bucket_name/object_name_prefix/&lt;asset type&gt;/&lt;shard number&gt; and only * contains assets for that type. &lt;shard number&gt; starts from 0. Example: * "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" is * the first shard of output objects containing all * compute.googleapis.com/Disk assets. An INVALID_ARGUMENT error will be * returned if file with the same name "gs://bucket_name/object_name_prefix" * already exists. * </pre> * * <code>string uri_prefix = 2;</code> * * @return This builder for chaining. */ public Builder clearUriPrefix() { if (objectUriCase_ == 2) { objectUriCase_ = 0; objectUri_ = null; onChanged(); } return this; } /** * * * <pre> * The URI prefix of all generated Cloud Storage objects. Example: * "gs://bucket_name/object_name_prefix". Each object URI is in format: * "gs://bucket_name/object_name_prefix/&lt;asset type&gt;/&lt;shard number&gt; and only * contains assets for that type. &lt;shard number&gt; starts from 0. Example: * "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" is * the first shard of output objects containing all * compute.googleapis.com/Disk assets. An INVALID_ARGUMENT error will be * returned if file with the same name "gs://bucket_name/object_name_prefix" * already exists. * </pre> * * <code>string uri_prefix = 2;</code> * * @param value The bytes for uriPrefix to set. * @return This builder for chaining. */ public Builder setUriPrefixBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); objectUriCase_ = 2; objectUri_ = 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.cloud.asset.v1.GcsDestination) } // @@protoc_insertion_point(class_scope:google.cloud.asset.v1.GcsDestination) private static final com.google.cloud.asset.v1.GcsDestination DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.asset.v1.GcsDestination(); } public static com.google.cloud.asset.v1.GcsDestination getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GcsDestination> PARSER = new com.google.protobuf.AbstractParser<GcsDestination>() { @java.lang.Override public GcsDestination 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<GcsDestination> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GcsDestination> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.asset.v1.GcsDestination getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,420
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/schema/predict/params/VideoClassificationPredictionParams.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/schema/predict/params/video_classification.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1beta1.schema.predict.params; /** * * * <pre> * Prediction model parameters for Video Classification. * </pre> * * Protobuf type {@code * google.cloud.aiplatform.v1beta1.schema.predict.params.VideoClassificationPredictionParams} */ public final class VideoClassificationPredictionParams extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.schema.predict.params.VideoClassificationPredictionParams) VideoClassificationPredictionParamsOrBuilder { private static final long serialVersionUID = 0L; // Use VideoClassificationPredictionParams.newBuilder() to construct. private VideoClassificationPredictionParams( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private VideoClassificationPredictionParams() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new VideoClassificationPredictionParams(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParamsProto .internal_static_google_cloud_aiplatform_v1beta1_schema_predict_params_VideoClassificationPredictionParams_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParamsProto .internal_static_google_cloud_aiplatform_v1beta1_schema_predict_params_VideoClassificationPredictionParams_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams.class, com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams.Builder.class); } public static final int CONFIDENCE_THRESHOLD_FIELD_NUMBER = 1; private float confidenceThreshold_ = 0F; /** * * * <pre> * The Model only returns predictions with at least this confidence score. * Default value is 0.0 * </pre> * * <code>float confidence_threshold = 1;</code> * * @return The confidenceThreshold. */ @java.lang.Override public float getConfidenceThreshold() { return confidenceThreshold_; } public static final int MAX_PREDICTIONS_FIELD_NUMBER = 2; private int maxPredictions_ = 0; /** * * * <pre> * The Model only returns up to that many top, by confidence score, * predictions per instance. If this number is very high, the Model may return * fewer predictions. Default value is 10,000. * </pre> * * <code>int32 max_predictions = 2;</code> * * @return The maxPredictions. */ @java.lang.Override public int getMaxPredictions() { return maxPredictions_; } public static final int SEGMENT_CLASSIFICATION_FIELD_NUMBER = 3; private boolean segmentClassification_ = false; /** * * * <pre> * Set to true to request segment-level classification. Vertex AI returns * labels and their confidence scores for the entire time segment of the * video that user specified in the input instance. * Default value is true * </pre> * * <code>bool segment_classification = 3;</code> * * @return The segmentClassification. */ @java.lang.Override public boolean getSegmentClassification() { return segmentClassification_; } public static final int SHOT_CLASSIFICATION_FIELD_NUMBER = 4; private boolean shotClassification_ = false; /** * * * <pre> * Set to true to request shot-level classification. Vertex AI determines * the boundaries for each camera shot in the entire time segment of the * video that user specified in the input instance. Vertex AI then * returns labels and their confidence scores for each detected shot, along * with the start and end time of the shot. * WARNING: Model evaluation is not done for this classification type, * the quality of it depends on the training data, but there are no metrics * provided to describe that quality. * Default value is false * </pre> * * <code>bool shot_classification = 4;</code> * * @return The shotClassification. */ @java.lang.Override public boolean getShotClassification() { return shotClassification_; } public static final int ONE_SEC_INTERVAL_CLASSIFICATION_FIELD_NUMBER = 5; private boolean oneSecIntervalClassification_ = false; /** * * * <pre> * Set to true to request classification for a video at one-second intervals. * Vertex AI returns labels and their confidence scores for each second of * the entire time segment of the video that user specified in the input * WARNING: Model evaluation is not done for this classification type, the * quality of it depends on the training data, but there are no metrics * provided to describe that quality. Default value is false * </pre> * * <code>bool one_sec_interval_classification = 5;</code> * * @return The oneSecIntervalClassification. */ @java.lang.Override public boolean getOneSecIntervalClassification() { return oneSecIntervalClassification_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (java.lang.Float.floatToRawIntBits(confidenceThreshold_) != 0) { output.writeFloat(1, confidenceThreshold_); } if (maxPredictions_ != 0) { output.writeInt32(2, maxPredictions_); } if (segmentClassification_ != false) { output.writeBool(3, segmentClassification_); } if (shotClassification_ != false) { output.writeBool(4, shotClassification_); } if (oneSecIntervalClassification_ != false) { output.writeBool(5, oneSecIntervalClassification_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (java.lang.Float.floatToRawIntBits(confidenceThreshold_) != 0) { size += com.google.protobuf.CodedOutputStream.computeFloatSize(1, confidenceThreshold_); } if (maxPredictions_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, maxPredictions_); } if (segmentClassification_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, segmentClassification_); } if (shotClassification_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(4, shotClassification_); } if (oneSecIntervalClassification_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(5, oneSecIntervalClassification_); } 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.schema.predict.params .VideoClassificationPredictionParams)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.schema.predict.params.VideoClassificationPredictionParams other = (com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams) obj; if (java.lang.Float.floatToIntBits(getConfidenceThreshold()) != java.lang.Float.floatToIntBits(other.getConfidenceThreshold())) return false; if (getMaxPredictions() != other.getMaxPredictions()) return false; if (getSegmentClassification() != other.getSegmentClassification()) return false; if (getShotClassification() != other.getShotClassification()) return false; if (getOneSecIntervalClassification() != other.getOneSecIntervalClassification()) 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) + CONFIDENCE_THRESHOLD_FIELD_NUMBER; hash = (53 * hash) + java.lang.Float.floatToIntBits(getConfidenceThreshold()); hash = (37 * hash) + MAX_PREDICTIONS_FIELD_NUMBER; hash = (53 * hash) + getMaxPredictions(); hash = (37 * hash) + SEGMENT_CLASSIFICATION_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getSegmentClassification()); hash = (37 * hash) + SHOT_CLASSIFICATION_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getShotClassification()); hash = (37 * hash) + ONE_SEC_INTERVAL_CLASSIFICATION_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getOneSecIntervalClassification()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams 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.schema.predict.params .VideoClassificationPredictionParams parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams 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.schema.predict.params .VideoClassificationPredictionParams parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams 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.schema.predict.params .VideoClassificationPredictionParams parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams 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.schema.predict.params .VideoClassificationPredictionParams parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams 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.schema.predict.params .VideoClassificationPredictionParams 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.schema.predict.params .VideoClassificationPredictionParams 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.schema.predict.params.VideoClassificationPredictionParams 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> * Prediction model parameters for Video Classification. * </pre> * * Protobuf type {@code * google.cloud.aiplatform.v1beta1.schema.predict.params.VideoClassificationPredictionParams} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.schema.predict.params.VideoClassificationPredictionParams) com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParamsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParamsProto .internal_static_google_cloud_aiplatform_v1beta1_schema_predict_params_VideoClassificationPredictionParams_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParamsProto .internal_static_google_cloud_aiplatform_v1beta1_schema_predict_params_VideoClassificationPredictionParams_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams.class, com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams.Builder.class); } // Construct using // com.google.cloud.aiplatform.v1beta1.schema.predict.params.VideoClassificationPredictionParams.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; confidenceThreshold_ = 0F; maxPredictions_ = 0; segmentClassification_ = false; shotClassification_ = false; oneSecIntervalClassification_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParamsProto .internal_static_google_cloud_aiplatform_v1beta1_schema_predict_params_VideoClassificationPredictionParams_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams build() { com.google.cloud.aiplatform.v1beta1.schema.predict.params.VideoClassificationPredictionParams result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams buildPartial() { com.google.cloud.aiplatform.v1beta1.schema.predict.params.VideoClassificationPredictionParams result = new com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.confidenceThreshold_ = confidenceThreshold_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.maxPredictions_ = maxPredictions_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.segmentClassification_ = segmentClassification_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.shotClassification_ = shotClassification_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.oneSecIntervalClassification_ = oneSecIntervalClassification_; } } @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.schema.predict.params .VideoClassificationPredictionParams) { return mergeFrom( (com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams other) { if (other == com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams.getDefaultInstance()) return this; if (other.getConfidenceThreshold() != 0F) { setConfidenceThreshold(other.getConfidenceThreshold()); } if (other.getMaxPredictions() != 0) { setMaxPredictions(other.getMaxPredictions()); } if (other.getSegmentClassification() != false) { setSegmentClassification(other.getSegmentClassification()); } if (other.getShotClassification() != false) { setShotClassification(other.getShotClassification()); } if (other.getOneSecIntervalClassification() != false) { setOneSecIntervalClassification(other.getOneSecIntervalClassification()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 13: { confidenceThreshold_ = input.readFloat(); bitField0_ |= 0x00000001; break; } // case 13 case 16: { maxPredictions_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 24: { segmentClassification_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 24 case 32: { shotClassification_ = input.readBool(); bitField0_ |= 0x00000008; break; } // case 32 case 40: { oneSecIntervalClassification_ = input.readBool(); bitField0_ |= 0x00000010; break; } // case 40 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private float confidenceThreshold_; /** * * * <pre> * The Model only returns predictions with at least this confidence score. * Default value is 0.0 * </pre> * * <code>float confidence_threshold = 1;</code> * * @return The confidenceThreshold. */ @java.lang.Override public float getConfidenceThreshold() { return confidenceThreshold_; } /** * * * <pre> * The Model only returns predictions with at least this confidence score. * Default value is 0.0 * </pre> * * <code>float confidence_threshold = 1;</code> * * @param value The confidenceThreshold to set. * @return This builder for chaining. */ public Builder setConfidenceThreshold(float value) { confidenceThreshold_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The Model only returns predictions with at least this confidence score. * Default value is 0.0 * </pre> * * <code>float confidence_threshold = 1;</code> * * @return This builder for chaining. */ public Builder clearConfidenceThreshold() { bitField0_ = (bitField0_ & ~0x00000001); confidenceThreshold_ = 0F; onChanged(); return this; } private int maxPredictions_; /** * * * <pre> * The Model only returns up to that many top, by confidence score, * predictions per instance. If this number is very high, the Model may return * fewer predictions. Default value is 10,000. * </pre> * * <code>int32 max_predictions = 2;</code> * * @return The maxPredictions. */ @java.lang.Override public int getMaxPredictions() { return maxPredictions_; } /** * * * <pre> * The Model only returns up to that many top, by confidence score, * predictions per instance. If this number is very high, the Model may return * fewer predictions. Default value is 10,000. * </pre> * * <code>int32 max_predictions = 2;</code> * * @param value The maxPredictions to set. * @return This builder for chaining. */ public Builder setMaxPredictions(int value) { maxPredictions_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The Model only returns up to that many top, by confidence score, * predictions per instance. If this number is very high, the Model may return * fewer predictions. Default value is 10,000. * </pre> * * <code>int32 max_predictions = 2;</code> * * @return This builder for chaining. */ public Builder clearMaxPredictions() { bitField0_ = (bitField0_ & ~0x00000002); maxPredictions_ = 0; onChanged(); return this; } private boolean segmentClassification_; /** * * * <pre> * Set to true to request segment-level classification. Vertex AI returns * labels and their confidence scores for the entire time segment of the * video that user specified in the input instance. * Default value is true * </pre> * * <code>bool segment_classification = 3;</code> * * @return The segmentClassification. */ @java.lang.Override public boolean getSegmentClassification() { return segmentClassification_; } /** * * * <pre> * Set to true to request segment-level classification. Vertex AI returns * labels and their confidence scores for the entire time segment of the * video that user specified in the input instance. * Default value is true * </pre> * * <code>bool segment_classification = 3;</code> * * @param value The segmentClassification to set. * @return This builder for chaining. */ public Builder setSegmentClassification(boolean value) { segmentClassification_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Set to true to request segment-level classification. Vertex AI returns * labels and their confidence scores for the entire time segment of the * video that user specified in the input instance. * Default value is true * </pre> * * <code>bool segment_classification = 3;</code> * * @return This builder for chaining. */ public Builder clearSegmentClassification() { bitField0_ = (bitField0_ & ~0x00000004); segmentClassification_ = false; onChanged(); return this; } private boolean shotClassification_; /** * * * <pre> * Set to true to request shot-level classification. Vertex AI determines * the boundaries for each camera shot in the entire time segment of the * video that user specified in the input instance. Vertex AI then * returns labels and their confidence scores for each detected shot, along * with the start and end time of the shot. * WARNING: Model evaluation is not done for this classification type, * the quality of it depends on the training data, but there are no metrics * provided to describe that quality. * Default value is false * </pre> * * <code>bool shot_classification = 4;</code> * * @return The shotClassification. */ @java.lang.Override public boolean getShotClassification() { return shotClassification_; } /** * * * <pre> * Set to true to request shot-level classification. Vertex AI determines * the boundaries for each camera shot in the entire time segment of the * video that user specified in the input instance. Vertex AI then * returns labels and their confidence scores for each detected shot, along * with the start and end time of the shot. * WARNING: Model evaluation is not done for this classification type, * the quality of it depends on the training data, but there are no metrics * provided to describe that quality. * Default value is false * </pre> * * <code>bool shot_classification = 4;</code> * * @param value The shotClassification to set. * @return This builder for chaining. */ public Builder setShotClassification(boolean value) { shotClassification_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Set to true to request shot-level classification. Vertex AI determines * the boundaries for each camera shot in the entire time segment of the * video that user specified in the input instance. Vertex AI then * returns labels and their confidence scores for each detected shot, along * with the start and end time of the shot. * WARNING: Model evaluation is not done for this classification type, * the quality of it depends on the training data, but there are no metrics * provided to describe that quality. * Default value is false * </pre> * * <code>bool shot_classification = 4;</code> * * @return This builder for chaining. */ public Builder clearShotClassification() { bitField0_ = (bitField0_ & ~0x00000008); shotClassification_ = false; onChanged(); return this; } private boolean oneSecIntervalClassification_; /** * * * <pre> * Set to true to request classification for a video at one-second intervals. * Vertex AI returns labels and their confidence scores for each second of * the entire time segment of the video that user specified in the input * WARNING: Model evaluation is not done for this classification type, the * quality of it depends on the training data, but there are no metrics * provided to describe that quality. Default value is false * </pre> * * <code>bool one_sec_interval_classification = 5;</code> * * @return The oneSecIntervalClassification. */ @java.lang.Override public boolean getOneSecIntervalClassification() { return oneSecIntervalClassification_; } /** * * * <pre> * Set to true to request classification for a video at one-second intervals. * Vertex AI returns labels and their confidence scores for each second of * the entire time segment of the video that user specified in the input * WARNING: Model evaluation is not done for this classification type, the * quality of it depends on the training data, but there are no metrics * provided to describe that quality. Default value is false * </pre> * * <code>bool one_sec_interval_classification = 5;</code> * * @param value The oneSecIntervalClassification to set. * @return This builder for chaining. */ public Builder setOneSecIntervalClassification(boolean value) { oneSecIntervalClassification_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** * * * <pre> * Set to true to request classification for a video at one-second intervals. * Vertex AI returns labels and their confidence scores for each second of * the entire time segment of the video that user specified in the input * WARNING: Model evaluation is not done for this classification type, the * quality of it depends on the training data, but there are no metrics * provided to describe that quality. Default value is false * </pre> * * <code>bool one_sec_interval_classification = 5;</code> * * @return This builder for chaining. */ public Builder clearOneSecIntervalClassification() { bitField0_ = (bitField0_ & ~0x00000010); oneSecIntervalClassification_ = 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.aiplatform.v1beta1.schema.predict.params.VideoClassificationPredictionParams) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.schema.predict.params.VideoClassificationPredictionParams) private static final com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams(); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<VideoClassificationPredictionParams> PARSER = new com.google.protobuf.AbstractParser<VideoClassificationPredictionParams>() { @java.lang.Override public VideoClassificationPredictionParams 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<VideoClassificationPredictionParams> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<VideoClassificationPredictionParams> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.schema.predict.params .VideoClassificationPredictionParams getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/juneau
35,748
juneau-core/juneau-marshall/src/main/java/org/apache/juneau/serializer/SerializerSession.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.juneau.serializer; import static org.apache.juneau.collections.JsonMap.*; import static org.apache.juneau.common.utils.StringUtils.*; import static org.apache.juneau.common.utils.Utils.*; import java.io.*; import java.lang.reflect.*; import java.text.*; import java.util.*; import java.util.function.*; import java.util.stream.*; import org.apache.juneau.*; import org.apache.juneau.collections.*; import org.apache.juneau.cp.*; import org.apache.juneau.httppart.*; import org.apache.juneau.internal.*; import org.apache.juneau.parser.*; import org.apache.juneau.reflect.*; import org.apache.juneau.soap.*; import org.apache.juneau.svl.*; import org.apache.juneau.swap.*; /** * Serializer session that lives for the duration of a single use of {@link Serializer}. * * <p> * Used by serializers for the following purposes: * <ul class='spaced-list'> * <li> * Keeping track of how deep it is in a model for indentation purposes. * <li> * Ensuring infinite loops don't occur by setting a limit on how deep to traverse a model. * <li> * Ensuring infinite loops don't occur from loops in the model (when detectRecursions is enabled. * <li> * Allowing serializer properties to be overridden on method calls. * </ul> * * <h5 class='section'>Notes:</h5><ul> * <li class='warn'>This class is not thread safe and is typically discarded after one use. * </ul> * * <h5 class='section'>See Also:</h5><ul> * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/SerializersAndParsers">Serializers and Parsers</a> * </ul> */ public class SerializerSession extends BeanTraverseSession { //------------------------------------------------------------------------------------------------------------------- // Static //------------------------------------------------------------------------------------------------------------------- /** * Creates a new builder for this object. * * @param ctx The context creating this session. * @return A new builder. */ public static Builder create(Serializer ctx) { return new Builder(ctx); } //----------------------------------------------------------------------------------------------------------------- // Builder //----------------------------------------------------------------------------------------------------------------- /** * Builder class. */ @FluentSetters public static class Builder extends BeanTraverseSession.Builder { Serializer ctx; Method javaMethod; VarResolverSession resolver; UriContext uriContext; HttpPartSchema schema; /** * Constructor * * @param ctx The context creating this session. */ protected Builder(Serializer ctx) { super(ctx); this.ctx = ctx; uriContext = ctx.uriContext; mediaTypeDefault(ctx.getResponseContentType()); } @Override public SerializerSession build() { return new SerializerSession(this); } /** * The java method that called this serializer, usually the method in a REST servlet. * * @param value * The new property value. * <br>Can be <jk>null</jk>. * @return This object. */ @FluentSetter public Builder javaMethod(Method value) { if (value != null) javaMethod = value; return this; } /** * String variable resolver. * * <p> * If not specified, defaults to session created by {@link VarResolver#DEFAULT}. * * @param value * The new property value. * <br>Can be <jk>null</jk>. * @return This object. */ @FluentSetter public Builder resolver(VarResolverSession value) { if (value != null) resolver = value; return this; } /** * URI context bean. * * <p> * Bean used for resolution of URIs to absolute or root-relative form. * * <p> * If not specified, defaults to {@link Serializer.Builder#uriContext(UriContext)}. * * @param value * The new property value. * <br>Can be <jk>null</jk>. * @return This object. */ @FluentSetter public Builder uriContext(UriContext value) { if (value != null) uriContext = value; return this; } /** * HTTP-part schema. * * <p> * Used for schema-based serializers and parsers to define additional formatting. * * @param value * The new value for this property. * <br>Can be <jk>null</jk>. * @return This object. */ @FluentSetter public Builder schema(HttpPartSchema value) { if (value != null) this.schema = value; return this; } /** * Same as {@link #schema(HttpPartSchema)} but doesn't overwrite the value if it is already set. * * @param value * The new value for this property. * <br>If <jk>null</jk>, then the locale defined on the context is used. * @return This object. */ @FluentSetter public Builder schemaDefault(HttpPartSchema value) { if (value != null && schema == null) this.schema = value; return this; } // <FluentSetters> @Override /* GENERATED - org.apache.juneau.ContextSession.Builder */ public <T> Builder apply(Class<T> type, Consumer<T> apply) { super.apply(type, apply); return this; } @Override /* GENERATED - org.apache.juneau.ContextSession.Builder */ public Builder debug(Boolean value) { super.debug(value); return this; } @Override /* GENERATED - org.apache.juneau.ContextSession.Builder */ public Builder properties(Map<String,Object> value) { super.properties(value); return this; } @Override /* GENERATED - org.apache.juneau.ContextSession.Builder */ public Builder property(String key, Object value) { super.property(key, value); return this; } @Override /* GENERATED - org.apache.juneau.ContextSession.Builder */ public Builder unmodifiable() { super.unmodifiable(); return this; } @Override /* GENERATED - org.apache.juneau.BeanSession.Builder */ public Builder locale(Locale value) { super.locale(value); return this; } @Override /* GENERATED - org.apache.juneau.BeanSession.Builder */ public Builder localeDefault(Locale value) { super.localeDefault(value); return this; } @Override /* GENERATED - org.apache.juneau.BeanSession.Builder */ public Builder mediaType(MediaType value) { super.mediaType(value); return this; } @Override /* GENERATED - org.apache.juneau.BeanSession.Builder */ public Builder mediaTypeDefault(MediaType value) { super.mediaTypeDefault(value); return this; } @Override /* GENERATED - org.apache.juneau.BeanSession.Builder */ public Builder timeZone(TimeZone value) { super.timeZone(value); return this; } @Override /* GENERATED - org.apache.juneau.BeanSession.Builder */ public Builder timeZoneDefault(TimeZone value) { super.timeZoneDefault(value); return this; } // </FluentSetters> } //----------------------------------------------------------------------------------------------------------------- // Instance //----------------------------------------------------------------------------------------------------------------- private final Serializer ctx; private final UriResolver uriResolver; private final HttpPartSchema schema; private VarResolverSession vrs; private final Method javaMethod; // Java method that invoked this serializer. // Writable properties private final SerializerListener listener; /** * Constructor. * * @param builder The builder for this object. */ protected SerializerSession(Builder builder) { super(builder); ctx = builder.ctx; javaMethod = builder.javaMethod; UriContext uriContext = builder.uriContext; uriResolver = UriResolver.of(ctx.getUriResolution(), ctx.getUriRelativity(), uriContext); listener = BeanCreator.of(SerializerListener.class).type(ctx.getListener()).orElse(null); vrs = builder.resolver; schema = builder.schema; } /** * Adds a session object to the {@link VarResolverSession} in this session. * * @param <T> The bean type. * @param c The bean type being added. * @param value The bean being added. * @return This object. */ public <T> SerializerSession addVarBean(Class<T> c, T value) { getVarResolver().bean(c, value); return this; } /** * Adds a session object to the {@link VarResolverSession} in this session. * * @return This object. */ protected VarResolverSession createDefaultVarResolverSession() { return VarResolver.DEFAULT.createSession(); } /** * Returns the variable resolver session. * * @return The variable resolver session. */ public VarResolverSession getVarResolver() { if (vrs == null) vrs = createDefaultVarResolverSession(); return vrs; } /** * HTTP part schema of object being serialized. * * @return HTTP part schema of object being serialized, or <jk>null</jk> if not specified. */ public final HttpPartSchema getSchema() { return schema; } //----------------------------------------------------------------------------------------------------------------- // Abstract methods //----------------------------------------------------------------------------------------------------------------- /** * Serializes a POJO to the specified pipe. * * <p> * This method should NOT close the context object. * * <p> * The default implementation of this method simply calls {@link Serializer#doSerialize(SerializerSession,SerializerPipe,Object)}. * * @param pipe Where to send the output from the serializer. * @param o The object to serialize. * @throws IOException Thrown by underlying stream. * @throws SerializeException Problem occurred trying to serialize object. */ protected void doSerialize(SerializerPipe pipe, Object o) throws IOException, SerializeException { ctx.doSerialize(this, pipe, o); } /** * Shortcut method for serializing objects directly to either a <c>String</c> or <code><jk>byte</jk>[]</code> * depending on the serializer type. * * @param o The object to serialize. * @return * The serialized object. * <br>Character-based serializers will return a <c>String</c>. * <br>Stream-based serializers will return a <code><jk>byte</jk>[]</code>. * @throws SerializeException If a problem occurred trying to convert the output. */ public Object serialize(Object o) throws SerializeException { throw new UnsupportedOperationException(); } /** * Shortcut method for serializing an object to a String. * * @param o The object to serialize. * @return * The serialized object. * <br>Character-based serializers will return a <c>String</c> * <br>Stream-based serializers will return a <code><jk>byte</jk>[]</code> converted to a string based on the {@link OutputStreamSerializer.Builder#binaryFormat(BinaryFormat)} setting. * @throws SerializeException If a problem occurred trying to convert the output. */ public String serializeToString(Object o) throws SerializeException { throw new UnsupportedOperationException(); } /** * Returns <jk>true</jk> if this serializer subclasses from {@link WriterSerializer}. * * @return <jk>true</jk> if this serializer subclasses from {@link WriterSerializer}. */ public boolean isWriterSerializer() { return false; } /** * Wraps the specified input object into a {@link ParserPipe} object so that it can be easily converted into * a stream or reader. * * @param output * The output location. * <br>For character-based serializers, this can be any of the following types: * <ul> * <li>{@link Writer} * <li>{@link OutputStream} - Output will be written as UTF-8 encoded stream. * <li>{@link File} - Output will be written as system-default encoded stream. * <li>{@link StringBuilder} * </ul> * <br>For byte-based serializers, this can be any of the following types: * <ul> * <li>{@link OutputStream} * <li>{@link File} * </ul> * @return * A new {@link ParserPipe} wrapper around the specified input object. */ protected SerializerPipe createPipe(Object output) { return new SerializerPipe(output); } //----------------------------------------------------------------------------------------------------------------- // Other methods //----------------------------------------------------------------------------------------------------------------- /** * Serialize the specified object using the specified session. * * @param out Where to send the output from the serializer. * @param o The object to serialize. * @throws SerializeException If a problem occurred trying to convert the output. * @throws IOException Thrown by the underlying stream. */ public final void serialize(Object o, Object out) throws SerializeException, IOException { try (SerializerPipe pipe = createPipe(out)) { doSerialize(pipe, o); } catch (SerializeException | IOException e) { throw e; } catch (StackOverflowError e) { throw new SerializeException(this, "Stack overflow occurred. This can occur when trying to serialize models containing loops. It's recommended you use the BeanTraverseContext.BEANTRAVERSE_detectRecursions setting to help locate the loop."); } catch (Exception e) { throw new SerializeException(this, e); } finally { checkForWarnings(); } } /** * Returns the Java method that invoked this serializer. * * <p> * When using the REST API, this is the Java method invoked by the REST call. * Can be used to access annotations defined on the method or class. * * @return The Java method that invoked this serializer. */ protected final Method getJavaMethod() { return javaMethod; } /** * Returns the URI resolver. * * @return The URI resolver. */ protected final UriResolver getUriResolver() { return uriResolver; } /** * Specialized warning when an exception is thrown while executing a bean getter. * * @param p The bean map entry representing the bean property. * @param t The throwable that the bean getter threw. * @throws SerializeException Thrown if ignoreInvocationExceptionOnGetters is false. */ protected final void onBeanGetterException(BeanPropertyMeta p, Throwable t) throws SerializeException { if (listener != null) listener.onBeanGetterException(this, t, p); String prefix = (isDebug() ? getStack(false) + ": " : ""); addWarning("{0}Could not call getValue() on property ''{1}'' of class ''{2}'', exception = {3}", prefix, p.getName(), p.getBeanMeta().getClassMeta(), t.getLocalizedMessage()); if (! isIgnoreInvocationExceptionsOnGetters()) throw new SerializeException(this, "{0}Could not call getValue() on property ''{1}'' of class ''{2}'', exception = {3}", prefix, p.getName(), p.getBeanMeta().getClassMeta(), t.getLocalizedMessage()).initCause(t); } /** * Logs a warning message. * * @param t The throwable that was thrown (if there was one). * @param msg The warning message. * @param args Optional {@link MessageFormat}-style arguments. */ @Override protected void onError(Throwable t, String msg, Object... args) { if (listener != null) listener.onError(this, t, format(msg, args)); super.onError(t, msg, args); } /** * Trims the specified string if {@link SerializerSession#isTrimStrings()} returns <jk>true</jk>. * * @param o The input string to trim. * @return The trimmed string, or <jk>null</jk> if the input was <jk>null</jk>. */ public final String trim(Object o) { if (o == null) return null; String s = o.toString(); if (isTrimStrings()) s = s.trim(); return s; } /** * Generalize the specified object if a POJO swap is associated with it. * * @param o The object to generalize. * @param type The type of object. * @return The generalized object, or <jk>null</jk> if the object is <jk>null</jk>. * @throws SerializeException If a problem occurred trying to convert the output. */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected final Object generalize(Object o, ClassMeta<?> type) throws SerializeException { try { if (o == null) return null; ObjectSwap f = (type == null || type.isObject() || type.isString() ? getClassMeta(o.getClass()).getSwap(this) : type.getSwap(this)); if (f == null) return o; return f.swap(this, o); } catch (SerializeException e) { throw e; } catch (Exception e) { throw new SerializeException(e); } } /** * Returns <jk>true</jk> if the specified value should not be serialized. * * @param cm The class type of the object being serialized. * @param attrName The bean attribute name, or <jk>null</jk> if this isn't a bean attribute. * @param value The object being serialized. * @return <jk>true</jk> if the specified value should not be serialized. * @throws SerializeException If recursion occurred. */ public final boolean canIgnoreValue(ClassMeta<?> cm, String attrName, Object value) throws SerializeException { if (value == null && ! isKeepNullProperties()) return true; if (value == null) return false; if (cm == null) cm = object(); if (isTrimEmptyCollections()) { if (cm.isArray() || (cm.isObject() && isArray(value))) { if (((Object[])value).length == 0) return true; } if (cm.isCollection() || (cm.isObject() && ClassInfo.of(value).isChildOf(Collection.class))) { if (((Collection<?>)value).isEmpty()) return true; } } if (isTrimEmptyMaps()) { if (cm.isMap() || (cm.isObject() && ClassInfo.of(value).isChildOf(Map.class))) { if (((Map<?,?>)value).isEmpty()) return true; } } try { if ((! isKeepNullProperties()) && (willRecurse(attrName, value, cm) || willExceedDepth())) return true; } catch (BeanRecursionException e) { throw new SerializeException(e); } return false; } /** * Sorts the specified map if {@link SerializerSession#isSortMaps()} returns <jk>true</jk>. * * @param <K> The key type. * @param <V> The value type. * @param m The map being sorted. * @return A new sorted {@link TreeMap}. */ public final <K,V> Map<K,V> sort(Map<K,V> m) { if (m == null || m.isEmpty() || SortedMap.class.isInstance(m)) return m; if (isSortMaps() && isSortable(m.keySet())) return new TreeMap<>(m); return m; } /** * Consumes each map entry in the map. * * @param <K> The key type. * @param <V> The value type. * @param m The map being consumed. * @param consumer The map entry consumer. */ @SuppressWarnings({ "unchecked", "rawtypes", "cast" }) public final <K,V> void forEachEntry(Map<K,V> m, Consumer<Map.Entry<K,V>> consumer) { if (m == null || m.isEmpty()) return; if (isSortMaps() && ! SortedMap.class.isInstance(m) && isSortable(m.keySet())) ((Map)m).entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(x -> consumer.accept((Map.Entry<K,V>) x)); else m.entrySet().forEach(consumer); } /** * Sorts the specified collection if {@link SerializerSession#isSortCollections()} returns <jk>true</jk>. * * @param <E> The element type. * @param c The collection being sorted. * @return A new sorted {@link TreeSet}. */ public final <E> Collection<E> sort(Collection<E> c) { if (c == null || c.isEmpty() || SortedSet.class.isInstance(c)) return c; if (isSortCollections() && isSortable(c)) return c.stream().sorted().collect(Collectors.toList()); return c; } /** * Consumes each entry in the list. * * @param <E> The element type. * @param c The collection being sorted. * @param consumer The entry consumer. */ public final <E> void forEachEntry(Collection<E> c, Consumer<E> consumer) { if (c == null || c.isEmpty()) return; if (isSortCollections() && ! SortedSet.class.isInstance(c) && isSortable(c)) c.stream().sorted().forEach(consumer); else c.forEach(consumer); } /** * Sorts the specified collection if {@link SerializerSession#isSortCollections()} returns <jk>true</jk>. * * @param <E> The element type. * @param c The collection being sorted. * @return A new sorted {@link TreeSet}. */ public final <E> List<E> sort(List<E> c) { if (c == null || c.isEmpty()) return c; if (isSortCollections() && isSortable(c)) return c.stream().sorted().collect(Collectors.toList()); return c; } private boolean isSortable(Collection<?> c) { if (c == null) return false; for (Object o : c) if (! (o instanceof Comparable)) return false; return true; } /** * Converts the contents of the specified object array to a list. * * <p> * Works on both object and primitive arrays. * * <p> * In the case of multi-dimensional arrays, the outgoing list will contain elements of type n-1 dimension. * i.e. if {@code type} is <code><jk>int</jk>[][]</code> then {@code list} will have entries of type * <code><jk>int</jk>[]</code>. * * @param type The type of array. * @param array The array being converted. * @return The array as a list. */ protected static final List<Object> toList(Class<?> type, Object array) { Class<?> componentType = type.getComponentType(); if (componentType.isPrimitive()) { int l = Array.getLength(array); List<Object> list = new ArrayList<>(l); for (int i = 0; i < l; i++) list.add(Array.get(array, i)); return list; } return alist((Object[])array); } /** * Converts a String to an absolute URI based on the {@link UriContext} on this session. * * @param uri * The input URI. * Can be any of the following: * <ul> * <li>{@link java.net.URI} * <li>{@link java.net.URL} * <li>{@link CharSequence} * </ul> * URI can be any of the following forms: * <ul> * <li><js>"foo://foo"</js> - Absolute URI. * <li><js>"/foo"</js> - Root-relative URI. * <li><js>"/"</js> - Root URI. * <li><js>"context:/foo"</js> - Context-root-relative URI. * <li><js>"context:/"</js> - Context-root URI. * <li><js>"servlet:/foo"</js> - Servlet-path-relative URI. * <li><js>"servlet:/"</js> - Servlet-path URI. * <li><js>"request:/foo"</js> - Request-path-relative URI. * <li><js>"request:/"</js> - Request-path URI. * <li><js>"foo"</js> - Path-info-relative URI. * <li><js>""</js> - Path-info URI. * </ul> * @return The resolved URI. */ public final String resolveUri(Object uri) { return uriResolver.resolve(uri); } /** * Opposite of {@link #resolveUri(Object)}. * * <p> * Converts the URI to a value relative to the specified <c>relativeTo</c> parameter. * * <p> * Both parameters can be any of the following: * <ul> * <li>{@link java.net.URI} * <li>{@link java.net.URL} * <li>{@link CharSequence} * </ul> * * <p> * Both URIs can be any of the following forms: * <ul> * <li><js>"foo://foo"</js> - Absolute URI. * <li><js>"/foo"</js> - Root-relative URI. * <li><js>"/"</js> - Root URI. * <li><js>"context:/foo"</js> - Context-root-relative URI. * <li><js>"context:/"</js> - Context-root URI. * <li><js>"servlet:/foo"</js> - Servlet-path-relative URI. * <li><js>"servlet:/"</js> - Servlet-path URI. * <li><js>"request:/foo"</js> - Request-path-relative URI. * <li><js>"request:/"</js> - Request-path URI. * <li><js>"foo"</js> - Path-info-relative URI. * <li><js>""</js> - Path-info URI. * </ul> * * @param relativeTo The URI to relativize against. * @param uri The URI to relativize. * @return The relativized URI. */ protected final String relativizeUri(Object relativeTo, Object uri) { return uriResolver.relativize(relativeTo, uri); } /** * Converts the specified object to a <c>String</c>. * * <p> * Also has the following effects: * <ul> * <li><c>Class</c> object is converted to a readable name. See {@link ClassInfo#getFullName()}. * <li>Whitespace is trimmed if the trim-strings setting is enabled. * </ul> * * @param o The object to convert to a <c>String</c>. * @return The object converted to a String, or <jk>null</jk> if the input was <jk>null</jk>. */ public final String toString(Object o) { if (o == null) return null; if (o.getClass() == Class.class) return ClassInfo.of((Class<?>)o).getFullName(); if (o.getClass() == ClassInfo.class) return ((ClassInfo)o).getFullName(); if (o.getClass().isEnum()) return getClassMetaForObject(o).toString(o); String s = o.toString(); if (isTrimStrings()) s = s.trim(); return s; } /** * Create a "_type" property that contains the dictionary name of the bean. * * @param m The bean map to create a class property on. * @param typeName The type name of the bean. * @return A new bean property value. */ protected static final BeanPropertyValue createBeanTypeNameProperty(BeanMap<?> m, String typeName) { BeanMeta<?> bm = m.getMeta(); return new BeanPropertyValue(bm.getTypeProperty(), bm.getTypeProperty().getName(), typeName, null); } /** * Resolves the dictionary name for the actual type. * * @param session The current serializer session. * @param eType The expected type of the bean property. * @param aType The actual type of the bean property. * @param pMeta The current bean property being serialized. * @return The bean dictionary name, or <jk>null</jk> if a name could not be found. */ protected final String getBeanTypeName(SerializerSession session, ClassMeta<?> eType, ClassMeta<?> aType, BeanPropertyMeta pMeta) { if (eType == aType || ! (isAddBeanTypes() || (session.isRoot() && isAddRootType()))) return null; String eTypeTn = eType.getDictionaryName(); // First see if it's defined on the actual type. String tn = aType.getDictionaryName(); if (tn != null && ! tn.equals(eTypeTn)) { return tn; } // Then see if it's defined on the expected type. // The expected type might be an interface with mappings for implementation classes. BeanRegistry br = eType.getBeanRegistry(); if (br != null) { tn = br.getTypeName(aType); if (tn != null && ! tn.equals(eTypeTn)) return tn; } // Then look on the bean property. br = pMeta == null ? null : pMeta.getBeanRegistry(); if (br != null) { tn = br.getTypeName(aType); if (tn != null && ! tn.equals(eTypeTn)) return tn; } // Finally look in the session. br = getBeanRegistry(); if (br != null) { tn = br.getTypeName(aType); if (tn != null && ! tn.equals(eTypeTn)) return tn; } return null; } /** * Returns the parser-side expected type for the object. * * <p> * The return value depends on the {@link Serializer.Builder#addRootType()} setting. * When disabled, the parser already knows the Java POJO type being parsed, so there is * no reason to add <js>"_type"</js> attributes to the root-level object. * * @param o The object to get the expected type on. * @return The expected type. */ protected final ClassMeta<?> getExpectedRootType(Object o) { if (isAddRootType()) return object(); ClassMeta<?> cm = getClassMetaForObject(o); if (cm != null && cm.isOptional()) return cm.getElementType(); return cm; } /** * Optional method that specifies HTTP request headers for this serializer. * * <p> * For example, {@link SoapXmlSerializer} needs to set a <c>SOAPAction</c> header. * * <p> * This method is typically meaningless if the serializer is being used stand-alone (i.e. outside of a REST server * or client). * * <p> * The default implementation of this method simply calls {@link Serializer#getResponseHeaders(SerializerSession)}. * * @return * The HTTP headers to set on HTTP requests. * Never <jk>null</jk>. */ public Map<String,String> getResponseHeaders() { return ctx.getResponseHeaders(this); } /** * Returns the listener associated with this session. * * @param <T> The listener type. * @param c The listener class to cast to. * @return The listener associated with this session, or <jk>null</jk> if there is no listener. */ @SuppressWarnings("unchecked") public <T extends SerializerListener> T getListener(Class<T> c) { return (T)listener; } /** * Resolves any variables in the specified string. * * @param string The string to resolve values in. * @return The string with variables resolved. */ public String resolve(String string) { return getVarResolver().resolve(string); } /** * Same as {@link #push(String, Object, ClassMeta)} but wraps {@link BeanRecursionException} inside {@link SerializeException}. * * @param attrName The attribute name. * @param o The current object being traversed. * @param eType The expected class type. * @return * The {@link ClassMeta} of the object so that <c>instanceof</c> operations only need to be performed * once (since they can be expensive). * @throws SerializeException If recursion occurred. */ protected final ClassMeta<?> push2(String attrName, Object o, ClassMeta<?> eType) throws SerializeException { try { return super.push(attrName, o, eType); } catch (BeanRecursionException e) { throw new SerializeException(e); } } /** * Invokes the specified swap on the specified object if the swap is not null. * * @param swap The swap to invoke. Can be <jk>null</jk>. * @param o The input object. * @return The swapped object. * @throws SerializeException If swap method threw an exception. */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected Object swap(ObjectSwap swap, Object o) throws SerializeException { try { if (swap == null) return o; return swap.swap(this, o); } catch (Exception e) { throw new SerializeException(e); } } //----------------------------------------------------------------------------------------------------------------- // Properties //----------------------------------------------------------------------------------------------------------------- /** * Add <js>"_type"</js> properties when needed. * * @see Serializer.Builder#addBeanTypes() * @return * <jk>true</jk> if <js>"_type"</js> properties added to beans if their type cannot be inferred * through reflection. */ protected boolean isAddBeanTypes() { return ctx.isAddBeanTypes(); } /** * Add type attribute to root nodes. * * @see Serializer.Builder#addRootType() * @return * <jk>true</jk> if type property should be added to root node. */ protected final boolean isAddRootType() { return ctx.isAddRootType(); } /** * Returns the listener associated with this session. * * @return The listener associated with this session, or <jk>null</jk> if there is no listener. */ public SerializerListener getListener() { return listener; } /** * Sort arrays and collections alphabetically. * * @see Serializer.Builder#sortCollections() * @return * <jk>true</jk> if arrays and collections are copied and sorted before serialization. */ protected final boolean isSortCollections() { return ctx.isSortCollections(); } /** * Sort maps alphabetically. * * @see Serializer.Builder#sortMaps() * @return * <jk>true</jk> if maps are copied and sorted before serialization. */ protected final boolean isSortMaps() { return ctx.isSortMaps(); } /** * Trim empty lists and arrays. * * @see Serializer.Builder#trimEmptyCollections() * @return * <jk>true</jk> if empty lists and arrays are not serialized to the output. */ protected final boolean isTrimEmptyCollections() { return ctx.isTrimEmptyCollections(); } /** * Trim empty maps. * * @see Serializer.Builder#trimEmptyMaps() * @return * <jk>true</jk> if empty map values are not serialized to the output. */ protected final boolean isTrimEmptyMaps() { return ctx.isTrimEmptyMaps(); } /** * Don't trim null bean property values. * * @see Serializer.Builder#keepNullProperties() * @return * <jk>true</jk> if null bean values are serialized to the output. */ protected final boolean isKeepNullProperties() { return ctx.isKeepNullProperties(); } /** * Trim strings. * * @see Serializer.Builder#trimStrings() * @return * <jk>true</jk> if string values will be trimmed of whitespace using {@link String#trim()} before being serialized. */ protected boolean isTrimStrings() { return ctx.isTrimStrings(); } /** * URI context bean. * * @see Serializer.Builder#uriContext(UriContext) * @return * Bean used for resolution of URIs to absolute or root-relative form. */ protected final UriContext getUriContext() { return ctx.getUriContext(); } /** * URI relativity. * * @see Serializer.Builder#uriRelativity(UriRelativity) * @return * Defines what relative URIs are relative to when serializing any of the following: */ protected final UriRelativity getUriRelativity() { return ctx.getUriRelativity(); } /** * URI resolution. * * @see Serializer.Builder#uriResolution(UriResolution) * @return * Defines the resolution level for URIs when serializing URIs. */ protected final UriResolution getUriResolution() { return ctx.getUriResolution(); } /** * Converts the specified throwable to either a {@link RuntimeException} or {@link SerializeException}. * * @param <T> The throwable type. * @param causedBy The exception to cast or wrap. */ protected static <T extends Throwable> void handleThrown(T causedBy) { if (causedBy instanceof Error) throw (Error)causedBy; if (causedBy instanceof RuntimeException) throw (RuntimeException)causedBy; if (causedBy instanceof StackOverflowError) throw new SerializeException("Stack overflow occurred. This can occur when trying to serialize models containing loops. It's recommended you use the BeanTraverseContext.BEANTRAVERSE_detectRecursions setting to help locate the loop."); if (causedBy instanceof SerializeException) throw (SerializeException)causedBy; throw new SerializeException(causedBy); } //----------------------------------------------------------------------------------------------------------------- // Other methods //----------------------------------------------------------------------------------------------------------------- @Override /* ContextSession */ protected JsonMap properties() { return filteredMap("uriResolver", uriResolver); } }
google/j2objc
37,504
jre_emul/android/platform/libcore/ojluni/src/main/java/java/nio/charset/CharsetEncoder.java
/* * Copyright (C) 2014 The Android Open Source Project * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ // -- This file was mechanically generated: Do not edit! -- // package java.nio.charset; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.lang.ref.WeakReference; import java.nio.charset.CoderMalfunctionError; // javadoc import java.util.Arrays; /** * An engine that can transform a sequence of sixteen-bit Unicode characters into a sequence of * bytes in a specific charset. * * <a name="steps"></a> * * <p> The input character sequence is provided in a character buffer or a series * of such buffers. The output byte sequence is written to a byte buffer * or a series of such buffers. An encoder should always be used by making * the following sequence of method invocations, hereinafter referred to as an * <i>encoding operation</i>: * * <ol> * * <li><p> Reset the encoder via the {@link #reset reset} method, unless it * has not been used before; </p></li> * * <li><p> Invoke the {@link #encode encode} method zero or more times, as * long as additional input may be available, passing <tt>false</tt> for the * <tt>endOfInput</tt> argument and filling the input buffer and flushing the * output buffer between invocations; </p></li> * * <li><p> Invoke the {@link #encode encode} method one final time, passing * <tt>true</tt> for the <tt>endOfInput</tt> argument; and then </p></li> * * <li><p> Invoke the {@link #flush flush} method so that the encoder can * flush any internal state to the output buffer. </p></li> * * </ol> * * Each invocation of the {@link #encode encode} method will encode as many * characters as possible from the input buffer, writing the resulting bytes * to the output buffer. The {@link #encode encode} method returns when more * input is required, when there is not enough room in the output buffer, or * when an encoding error has occurred. In each case a {@link CoderResult} * object is returned to describe the reason for termination. An invoker can * examine this object and fill the input buffer, flush the output buffer, or * attempt to recover from an encoding error, as appropriate, and try again. * * <a name="ce"></a> * * <p> There are two general types of encoding errors. If the input character * sequence is not a legal sixteen-bit Unicode sequence then the input is considered <i>malformed</i>. If * the input character sequence is legal but cannot be mapped to a valid * byte sequence in the given charset then an <i>unmappable character</i> has been encountered. * * <a name="cae"></a> * * <p> How an encoding error is handled depends upon the action requested for * that type of error, which is described by an instance of the {@link * CodingErrorAction} class. The possible error actions are to {@linkplain * CodingErrorAction#IGNORE ignore} the erroneous input, {@linkplain * CodingErrorAction#REPORT report} the error to the invoker via * the returned {@link CoderResult} object, or {@linkplain CodingErrorAction#REPLACE * replace} the erroneous input with the current value of the * replacement byte array. The replacement * * is initially set to the encoder's default replacement, which often * (but not always) has the initial value&nbsp;<tt>{</tt>&nbsp;<tt>(byte)'?'</tt>&nbsp;<tt>}</tt>; * * its value may be changed via the {@link #replaceWith(byte[]) * replaceWith} method. * * <p> The default action for malformed-input and unmappable-character errors * is to {@linkplain CodingErrorAction#REPORT report} them. The * malformed-input error action may be changed via the {@link * #onMalformedInput(CodingErrorAction) onMalformedInput} method; the * unmappable-character action may be changed via the {@link * #onUnmappableCharacter(CodingErrorAction) onUnmappableCharacter} method. * * <p> This class is designed to handle many of the details of the encoding * process, including the implementation of error actions. An encoder for a * specific charset, which is a concrete subclass of this class, need only * implement the abstract {@link #encodeLoop encodeLoop} method, which * encapsulates the basic encoding loop. A subclass that maintains internal * state should, additionally, override the {@link #implFlush implFlush} and * {@link #implReset implReset} methods. * * <p> Instances of this class are not safe for use by multiple concurrent * threads. </p> * * * @author Mark Reinhold * @author JSR-51 Expert Group * @since 1.4 * * @see ByteBuffer * @see CharBuffer * @see Charset * @see CharsetDecoder */ public abstract class CharsetEncoder { private final Charset charset; private final float averageBytesPerChar; private final float maxBytesPerChar; private byte[] replacement; private CodingErrorAction malformedInputAction = CodingErrorAction.REPORT; private CodingErrorAction unmappableCharacterAction = CodingErrorAction.REPORT; // Internal states // private static final int ST_RESET = 0; private static final int ST_CODING = 1; private static final int ST_END = 2; private static final int ST_FLUSHED = 3; private int state = ST_RESET; private static String stateNames[] = { "RESET", "CODING", "CODING_END", "FLUSHED" }; /** * Initializes a new encoder. The new encoder will have the given * bytes-per-char and replacement values. * * @param cs * The charset that created this encoder * * @param averageBytesPerChar * A positive float value indicating the expected number of * bytes that will be produced for each input character * * @param maxBytesPerChar * A positive float value indicating the maximum number of * bytes that will be produced for each input character * * @param replacement * The initial replacement; must not be <tt>null</tt>, must have * non-zero length, must not be longer than maxBytesPerChar, * and must be {@linkplain #isLegalReplacement legal} * * @throws IllegalArgumentException * If the preconditions on the parameters do not hold */ protected CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar, byte[] replacement) { // BEGIN Android-added: A hidden constructor for the CharsetEncoderICU subclass. this(cs, averageBytesPerChar, maxBytesPerChar, replacement, false); } /** * This constructor is for subclasses to specify whether {@code replacement} can be used as it * is ("trusted"). If it is trusted, {@link #replaceWith(byte[])} and * {@link #implReplaceWith(byte[])} will not be called. * @hide */ protected CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar, byte[] replacement, boolean trusted) { // END Android-added: A hidden constructor for the CharsetEncoderICU subclass. this.charset = cs; if (averageBytesPerChar <= 0.0f) throw new IllegalArgumentException("Non-positive " + "averageBytesPerChar"); if (maxBytesPerChar <= 0.0f) throw new IllegalArgumentException("Non-positive " + "maxBytesPerChar"); /* J2ObjC removed. if (!Charset.atBugLevel("1.4")) {*/ if (averageBytesPerChar > maxBytesPerChar) throw new IllegalArgumentException("averageBytesPerChar" + " exceeds " + "maxBytesPerChar"); //} this.replacement = replacement; this.averageBytesPerChar = averageBytesPerChar; this.maxBytesPerChar = maxBytesPerChar; // BEGIN Android-changed: Avoid calling replaceWith() for trusted subclasses. // replaceWith(replacement); if (!trusted) { replaceWith(replacement); } // END Android-changed: Avoid calling replaceWith() for trusted subclasses. } /** * Initializes a new encoder. The new encoder will have the given * bytes-per-char values and its replacement will be the * byte array <tt>{</tt>&nbsp;<tt>(byte)'?'</tt>&nbsp;<tt>}</tt>. * * @param cs * The charset that created this encoder * * @param averageBytesPerChar * A positive float value indicating the expected number of * bytes that will be produced for each input character * * @param maxBytesPerChar * A positive float value indicating the maximum number of * bytes that will be produced for each input character * * @throws IllegalArgumentException * If the preconditions on the parameters do not hold */ protected CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar) { this(cs, averageBytesPerChar, maxBytesPerChar, new byte[] { (byte)'?' }); } /** * Returns the charset that created this encoder. * * @return This encoder's charset */ public final Charset charset() { return charset; } /** * Returns this encoder's replacement value. * * @return This encoder's current replacement, * which is never <tt>null</tt> and is never empty */ public final byte[] replacement() { return Arrays.copyOf(replacement, replacement.length); } /** * Changes this encoder's replacement value. * * <p> This method invokes the {@link #implReplaceWith implReplaceWith} * method, passing the new replacement, after checking that the new * replacement is acceptable. </p> * * @param newReplacement The replacement value * * The new replacement; must not be <tt>null</tt>, must have * non-zero length, must not be longer than the value returned by * the {@link #maxBytesPerChar() maxBytesPerChar} method, and * must be {@link #isLegalReplacement legal} * * @return This encoder * * @throws IllegalArgumentException * If the preconditions on the parameter do not hold */ public final CharsetEncoder replaceWith(byte[] newReplacement) { if (newReplacement == null) throw new IllegalArgumentException("Null replacement"); int len = newReplacement.length; if (len == 0) throw new IllegalArgumentException("Empty replacement"); if (len > maxBytesPerChar) throw new IllegalArgumentException("Replacement too long"); if (!isLegalReplacement(newReplacement)) throw new IllegalArgumentException("Illegal replacement"); this.replacement = Arrays.copyOf(newReplacement, newReplacement.length); implReplaceWith(this.replacement); return this; } /** * Reports a change to this encoder's replacement value. * * <p> The default implementation of this method does nothing. This method * should be overridden by encoders that require notification of changes to * the replacement. </p> * * @param newReplacement The replacement value */ protected void implReplaceWith(byte[] newReplacement) { } // J2ObjC: Removed use of WeakReference. private CharsetDecoder cachedDecoder = null; /** * Tells whether or not the given byte array is a legal replacement value * for this encoder. * * <p> A replacement is legal if, and only if, it is a legal sequence of * bytes in this encoder's charset; that is, it must be possible to decode * the replacement into one or more sixteen-bit Unicode characters. * * <p> The default implementation of this method is not very efficient; it * should generally be overridden to improve performance. </p> * * @param repl The byte array to be tested * * @return <tt>true</tt> if, and only if, the given byte array * is a legal replacement value for this encoder */ public boolean isLegalReplacement(byte[] repl) { /* J2ObjC: Removed use of WeakReference. WeakReference<CharsetDecoder> wr = cachedDecoder; CharsetDecoder dec = null; if ((wr == null) || ((dec = wr.get()) == null)) {*/ CharsetDecoder dec = cachedDecoder; if (dec == null) { dec = charset().newDecoder(); dec.onMalformedInput(CodingErrorAction.REPORT); dec.onUnmappableCharacter(CodingErrorAction.REPORT); //cachedDecoder = new WeakReference<CharsetDecoder>(dec); cachedDecoder = dec; } else { dec.reset(); } ByteBuffer bb = ByteBuffer.wrap(repl); CharBuffer cb = CharBuffer.allocate((int)(bb.remaining() * dec.maxCharsPerByte())); CoderResult cr = dec.decode(bb, cb, true); return !cr.isError(); } /** * Returns this encoder's current action for malformed-input errors. * * @return The current malformed-input action, which is never <tt>null</tt> */ public CodingErrorAction malformedInputAction() { return malformedInputAction; } /** * Changes this encoder's action for malformed-input errors. * * <p> This method invokes the {@link #implOnMalformedInput * implOnMalformedInput} method, passing the new action. </p> * * @param newAction The new action; must not be <tt>null</tt> * * @return This encoder * * @throws IllegalArgumentException * If the precondition on the parameter does not hold */ public final CharsetEncoder onMalformedInput(CodingErrorAction newAction) { if (newAction == null) throw new IllegalArgumentException("Null action"); malformedInputAction = newAction; implOnMalformedInput(newAction); return this; } /** * Reports a change to this encoder's malformed-input action. * * <p> The default implementation of this method does nothing. This method * should be overridden by encoders that require notification of changes to * the malformed-input action. </p> * * @param newAction The new action */ protected void implOnMalformedInput(CodingErrorAction newAction) { } /** * Returns this encoder's current action for unmappable-character errors. * * @return The current unmappable-character action, which is never * <tt>null</tt> */ public CodingErrorAction unmappableCharacterAction() { return unmappableCharacterAction; } /** * Changes this encoder's action for unmappable-character errors. * * <p> This method invokes the {@link #implOnUnmappableCharacter * implOnUnmappableCharacter} method, passing the new action. </p> * * @param newAction The new action; must not be <tt>null</tt> * * @return This encoder * * @throws IllegalArgumentException * If the precondition on the parameter does not hold */ public final CharsetEncoder onUnmappableCharacter(CodingErrorAction newAction) { if (newAction == null) throw new IllegalArgumentException("Null action"); unmappableCharacterAction = newAction; implOnUnmappableCharacter(newAction); return this; } /** * Reports a change to this encoder's unmappable-character action. * * <p> The default implementation of this method does nothing. This method * should be overridden by encoders that require notification of changes to * the unmappable-character action. </p> * * @param newAction The new action */ protected void implOnUnmappableCharacter(CodingErrorAction newAction) { } /** * Returns the average number of bytes that will be produced for each * character of input. This heuristic value may be used to estimate the size * of the output buffer required for a given input sequence. * * @return The average number of bytes produced * per character of input */ public final float averageBytesPerChar() { return averageBytesPerChar; } /** * Returns the maximum number of bytes that will be produced for each * character of input. This value may be used to compute the worst-case size * of the output buffer required for a given input sequence. * * @return The maximum number of bytes that will be produced per * character of input */ public final float maxBytesPerChar() { return maxBytesPerChar; } /** * Encodes as many characters as possible from the given input buffer, * writing the results to the given output buffer. * * <p> The buffers are read from, and written to, starting at their current * positions. At most {@link Buffer#remaining in.remaining()} characters * will be read and at most {@link Buffer#remaining out.remaining()} * bytes will be written. The buffers' positions will be advanced to * reflect the characters read and the bytes written, but their marks and * limits will not be modified. * * <p> In addition to reading characters from the input buffer and writing * bytes to the output buffer, this method returns a {@link CoderResult} * object to describe its reason for termination: * * <ul> * * <li><p> {@link CoderResult#UNDERFLOW} indicates that as much of the * input buffer as possible has been encoded. If there is no further * input then the invoker can proceed to the next step of the * <a href="#steps">encoding operation</a>. Otherwise this method * should be invoked again with further input. </p></li> * * <li><p> {@link CoderResult#OVERFLOW} indicates that there is * insufficient space in the output buffer to encode any more characters. * This method should be invoked again with an output buffer that has * more {@linkplain Buffer#remaining remaining} bytes. This is * typically done by draining any encoded bytes from the output * buffer. </p></li> * * <li><p> A {@linkplain CoderResult#malformedForLength * malformed-input} result indicates that a malformed-input * error has been detected. The malformed characters begin at the input * buffer's (possibly incremented) position; the number of malformed * characters may be determined by invoking the result object's {@link * CoderResult#length() length} method. This case applies only if the * {@linkplain #onMalformedInput malformed action} of this encoder * is {@link CodingErrorAction#REPORT}; otherwise the malformed input * will be ignored or replaced, as requested. </p></li> * * <li><p> An {@linkplain CoderResult#unmappableForLength * unmappable-character} result indicates that an * unmappable-character error has been detected. The characters that * encode the unmappable character begin at the input buffer's (possibly * incremented) position; the number of such characters may be determined * by invoking the result object's {@link CoderResult#length() length} * method. This case applies only if the {@linkplain #onUnmappableCharacter * unmappable action} of this encoder is {@link * CodingErrorAction#REPORT}; otherwise the unmappable character will be * ignored or replaced, as requested. </p></li> * * </ul> * * In any case, if this method is to be reinvoked in the same encoding * operation then care should be taken to preserve any characters remaining * in the input buffer so that they are available to the next invocation. * * <p> The <tt>endOfInput</tt> parameter advises this method as to whether * the invoker can provide further input beyond that contained in the given * input buffer. If there is a possibility of providing additional input * then the invoker should pass <tt>false</tt> for this parameter; if there * is no possibility of providing further input then the invoker should * pass <tt>true</tt>. It is not erroneous, and in fact it is quite * common, to pass <tt>false</tt> in one invocation and later discover that * no further input was actually available. It is critical, however, that * the final invocation of this method in a sequence of invocations always * pass <tt>true</tt> so that any remaining unencoded input will be treated * as being malformed. * * <p> This method works by invoking the {@link #encodeLoop encodeLoop} * method, interpreting its results, handling error conditions, and * reinvoking it as necessary. </p> * * * @param in * The input character buffer * * @param out * The output byte buffer * * @param endOfInput * <tt>true</tt> if, and only if, the invoker can provide no * additional input characters beyond those in the given buffer * * @return A coder-result object describing the reason for termination * * @throws IllegalStateException * If an encoding operation is already in progress and the previous * step was an invocation neither of the {@link #reset reset} * method, nor of this method with a value of <tt>false</tt> for * the <tt>endOfInput</tt> parameter, nor of this method with a * value of <tt>true</tt> for the <tt>endOfInput</tt> parameter * but a return value indicating an incomplete encoding operation * * @throws CoderMalfunctionError * If an invocation of the encodeLoop method threw * an unexpected exception */ public final CoderResult encode(CharBuffer in, ByteBuffer out, boolean endOfInput) { int newState = endOfInput ? ST_END : ST_CODING; if ((state != ST_RESET) && (state != ST_CODING) && !(endOfInput && (state == ST_END))) throwIllegalStateException(state, newState); state = newState; for (;;) { CoderResult cr; try { cr = encodeLoop(in, out); } catch (BufferUnderflowException x) { throw new CoderMalfunctionError(x); } catch (BufferOverflowException x) { throw new CoderMalfunctionError(x); } if (cr.isOverflow()) return cr; if (cr.isUnderflow()) { if (endOfInput && in.hasRemaining()) { cr = CoderResult.malformedForLength(in.remaining()); // Fall through to malformed-input case } else { return cr; } } CodingErrorAction action = null; if (cr.isMalformed()) action = malformedInputAction; else if (cr.isUnmappable()) action = unmappableCharacterAction; else assert false : cr.toString(); if (action == CodingErrorAction.REPORT) return cr; if (action == CodingErrorAction.REPLACE) { if (out.remaining() < replacement.length) return CoderResult.OVERFLOW; out.put(replacement); } if ((action == CodingErrorAction.IGNORE) || (action == CodingErrorAction.REPLACE)) { // Skip erroneous input either way in.position(in.position() + cr.length()); continue; } assert false; } } /** * Flushes this encoder. * * <p> Some encoders maintain internal state and may need to write some * final bytes to the output buffer once the overall input sequence has * been read. * * <p> Any additional output is written to the output buffer beginning at * its current position. At most {@link Buffer#remaining out.remaining()} * bytes will be written. The buffer's position will be advanced * appropriately, but its mark and limit will not be modified. * * <p> If this method completes successfully then it returns {@link * CoderResult#UNDERFLOW}. If there is insufficient room in the output * buffer then it returns {@link CoderResult#OVERFLOW}. If this happens * then this method must be invoked again, with an output buffer that has * more room, in order to complete the current <a href="#steps">encoding * operation</a>. * * <p> If this encoder has already been flushed then invoking this method * has no effect. * * <p> This method invokes the {@link #implFlush implFlush} method to * perform the actual flushing operation. </p> * * @param out * The output byte buffer * * @return A coder-result object, either {@link CoderResult#UNDERFLOW} or * {@link CoderResult#OVERFLOW} * * @throws IllegalStateException * If the previous step of the current encoding operation was an * invocation neither of the {@link #flush flush} method nor of * the three-argument {@link * #encode(CharBuffer,ByteBuffer,boolean) encode} method * with a value of <tt>true</tt> for the <tt>endOfInput</tt> * parameter */ public final CoderResult flush(ByteBuffer out) { if (state == ST_END) { CoderResult cr = implFlush(out); if (cr.isUnderflow()) state = ST_FLUSHED; return cr; } if (state != ST_FLUSHED) throwIllegalStateException(state, ST_FLUSHED); return CoderResult.UNDERFLOW; // Already flushed } /** * Flushes this encoder. * * <p> The default implementation of this method does nothing, and always * returns {@link CoderResult#UNDERFLOW}. This method should be overridden * by encoders that may need to write final bytes to the output buffer * once the entire input sequence has been read. </p> * * @param out * The output byte buffer * * @return A coder-result object, either {@link CoderResult#UNDERFLOW} or * {@link CoderResult#OVERFLOW} */ protected CoderResult implFlush(ByteBuffer out) { return CoderResult.UNDERFLOW; } /** * Resets this encoder, clearing any internal state. * * <p> This method resets charset-independent state and also invokes the * {@link #implReset() implReset} method in order to perform any * charset-specific reset actions. </p> * * @return This encoder * */ public final CharsetEncoder reset() { implReset(); state = ST_RESET; return this; } /** * Resets this encoder, clearing any charset-specific internal state. * * <p> The default implementation of this method does nothing. This method * should be overridden by encoders that maintain internal state. </p> */ protected void implReset() { } /** * Encodes one or more characters into one or more bytes. * * <p> This method encapsulates the basic encoding loop, encoding as many * characters as possible until it either runs out of input, runs out of room * in the output buffer, or encounters an encoding error. This method is * invoked by the {@link #encode encode} method, which handles result * interpretation and error recovery. * * <p> The buffers are read from, and written to, starting at their current * positions. At most {@link Buffer#remaining in.remaining()} characters * will be read, and at most {@link Buffer#remaining out.remaining()} * bytes will be written. The buffers' positions will be advanced to * reflect the characters read and the bytes written, but their marks and * limits will not be modified. * * <p> This method returns a {@link CoderResult} object to describe its * reason for termination, in the same manner as the {@link #encode encode} * method. Most implementations of this method will handle encoding errors * by returning an appropriate result object for interpretation by the * {@link #encode encode} method. An optimized implementation may instead * examine the relevant error action and implement that action itself. * * <p> An implementation of this method may perform arbitrary lookahead by * returning {@link CoderResult#UNDERFLOW} until it receives sufficient * input. </p> * * @param in * The input character buffer * * @param out * The output byte buffer * * @return A coder-result object describing the reason for termination */ protected abstract CoderResult encodeLoop(CharBuffer in, ByteBuffer out); /** * Convenience method that encodes the remaining content of a single input * character buffer into a newly-allocated byte buffer. * * <p> This method implements an entire <a href="#steps">encoding * operation</a>; that is, it resets this encoder, then it encodes the * characters in the given character buffer, and finally it flushes this * encoder. This method should therefore not be invoked if an encoding * operation is already in progress. </p> * * @param in * The input character buffer * * @return A newly-allocated byte buffer containing the result of the * encoding operation. The buffer's position will be zero and its * limit will follow the last byte written. * * @throws IllegalStateException * If an encoding operation is already in progress * * @throws MalformedInputException * If the character sequence starting at the input buffer's current * position is not a legal sixteen-bit Unicode sequence and the current malformed-input action * is {@link CodingErrorAction#REPORT} * * @throws UnmappableCharacterException * If the character sequence starting at the input buffer's current * position cannot be mapped to an equivalent byte sequence and * the current unmappable-character action is {@link * CodingErrorAction#REPORT} */ public final ByteBuffer encode(CharBuffer in) throws CharacterCodingException { int n = (int)(in.remaining() * averageBytesPerChar()); ByteBuffer out = ByteBuffer.allocate(n); if ((n == 0) && (in.remaining() == 0)) return out; reset(); for (;;) { CoderResult cr = in.hasRemaining() ? encode(in, out, true) : CoderResult.UNDERFLOW; if (cr.isUnderflow()) cr = flush(out); if (cr.isUnderflow()) break; if (cr.isOverflow()) { n = 2*n + 1; // Ensure progress; n might be 0! ByteBuffer o = ByteBuffer.allocate(n); out.flip(); o.put(out); out = o; continue; } cr.throwException(); } out.flip(); return out; } private boolean canEncode(CharBuffer cb) { if (state == ST_FLUSHED) reset(); else if (state != ST_RESET) throwIllegalStateException(state, ST_CODING); // BEGIN Android-added: Fast path handling for empty buffers. // Empty buffers can always be "encoded". if (!cb.hasRemaining()) { return true; } // END Android-added: Fast path handling for empty buffers. CodingErrorAction ma = malformedInputAction(); CodingErrorAction ua = unmappableCharacterAction(); try { onMalformedInput(CodingErrorAction.REPORT); onUnmappableCharacter(CodingErrorAction.REPORT); encode(cb); } catch (CharacterCodingException x) { return false; } finally { onMalformedInput(ma); onUnmappableCharacter(ua); reset(); } return true; } /** * Tells whether or not this encoder can encode the given character. * * <p> This method returns <tt>false</tt> if the given character is a * surrogate character; such characters can be interpreted only when they * are members of a pair consisting of a high surrogate followed by a low * surrogate. The {@link #canEncode(java.lang.CharSequence) * canEncode(CharSequence)} method may be used to test whether or not a * character sequence can be encoded. * * <p> This method may modify this encoder's state; it should therefore not * be invoked if an <a href="#steps">encoding operation</a> is already in * progress. * * <p> The default implementation of this method is not very efficient; it * should generally be overridden to improve performance. </p> * * @param c * The given character * * @return <tt>true</tt> if, and only if, this encoder can encode * the given character * * @throws IllegalStateException * If an encoding operation is already in progress */ public boolean canEncode(char c) { CharBuffer cb = CharBuffer.allocate(1); cb.put(c); cb.flip(); return canEncode(cb); } /** * Tells whether or not this encoder can encode the given character * sequence. * * <p> If this method returns <tt>false</tt> for a particular character * sequence then more information about why the sequence cannot be encoded * may be obtained by performing a full <a href="#steps">encoding * operation</a>. * * <p> This method may modify this encoder's state; it should therefore not * be invoked if an encoding operation is already in progress. * * <p> The default implementation of this method is not very efficient; it * should generally be overridden to improve performance. </p> * * @param cs * The given character sequence * * @return <tt>true</tt> if, and only if, this encoder can encode * the given character without throwing any exceptions and without * performing any replacements * * @throws IllegalStateException * If an encoding operation is already in progress */ public boolean canEncode(CharSequence cs) { CharBuffer cb; if (cs instanceof CharBuffer) cb = ((CharBuffer)cs).duplicate(); else // Android-removed: An unnecessary call to toString(). // cb = CharBuffer.wrap(cs.toString()); cb = CharBuffer.wrap(cs); return canEncode(cb); } private void throwIllegalStateException(int from, int to) { throw new IllegalStateException("Current state = " + stateNames[from] + ", new state = " + stateNames[to]); } }
apache/ofbiz
37,554
framework/minilang/src/main/java/org/apache/ofbiz/minilang/SimpleMethod.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.minilang; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.ofbiz.base.location.FlexibleLocation; import org.apache.ofbiz.base.util.Assert; import org.apache.ofbiz.base.util.Debug; import org.apache.ofbiz.base.util.UtilGenerics; import org.apache.ofbiz.base.util.UtilMisc; import org.apache.ofbiz.base.util.UtilProperties; import org.apache.ofbiz.base.util.UtilValidate; import org.apache.ofbiz.base.util.UtilXml; import org.apache.ofbiz.base.util.cache.UtilCache; import org.apache.ofbiz.entity.GenericEntity; import org.apache.ofbiz.entity.GenericValue; import org.apache.ofbiz.entity.transaction.GenericTransactionException; import org.apache.ofbiz.entity.transaction.TransactionUtil; import org.apache.ofbiz.minilang.artifact.ArtifactInfoContext; import org.apache.ofbiz.minilang.method.MethodContext; import org.apache.ofbiz.minilang.method.MethodOperation; import org.apache.ofbiz.minilang.method.MethodOperation.DeprecatedOperation; import org.apache.ofbiz.service.DispatchContext; import org.apache.ofbiz.service.ModelService; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Implements the &lt;simple-method&gt; element. * <p> * The Mini-language script engine follows the * <a href="http://en.wikipedia.org/wiki/Flyweight_pattern">flyweight</a> * design pattern. Mini-language XML files are parsed twice - first into a W3C DOM * tree, then the DOM tree is parsed into element model objects. Each XML element * has a model class, and each model class has its own factory. * </p> * <p> * Mini-language can be extended by:</p> * <ul> * <li>Creating model classes that extend {@link org.apache.ofbiz.minilang.method.MethodOperation}</li> * <li>Creating factories for the model classes that implement {@link org.apache.ofbiz.minilang.method.MethodOperation.Factory}</li> * <li>Create a service provider information file for the factory classes * (see <a href="http://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html" target="_blank">ServiceLoader</a>) * </li> * </ul> * * @see <a href="https://cwiki.apache.org/confluence/display/OFBADMIN/Mini+Language+-+minilang+-+simple-method+-+Reference">Mini-language Reference</a> */ public final class SimpleMethod extends MiniLangElement { public static final String module = SimpleMethod.class.getName(); private static final String err_resource = "MiniLangErrorUiLabels"; private static final String[] DEPRECATED_ATTRIBUTES = {"parameter-map-name", "locale-name", "delegator-name", "security-name", "dispatcher-name", "user-login-name"}; private static final Map<String, MethodOperation.Factory<MethodOperation>> methodOperationFactories; private static final UtilCache<String, Map<String, SimpleMethod>> simpleMethodsDirectCache = UtilCache.createUtilCache("minilang.SimpleMethodsDirect", 0, 0); private static final UtilCache<String, SimpleMethod> simpleMethodsResourceCache = UtilCache.createUtilCache("minilang.SimpleMethodsResource", 0, 0); static { Map<String, MethodOperation.Factory<MethodOperation>> mapFactories = new HashMap<String, MethodOperation.Factory<MethodOperation>>(); Iterator<MethodOperation.Factory<MethodOperation>> it = UtilGenerics.cast(ServiceLoader.load(MethodOperation.Factory.class, SimpleMethod.class.getClassLoader()).iterator()); while (it.hasNext()) { MethodOperation.Factory<MethodOperation> factory = it.next(); mapFactories.put(factory.getName(), factory); } methodOperationFactories = Collections.unmodifiableMap(mapFactories); } // This method is needed only during the v1 to v2 transition private static boolean autoCorrect(Element element) { boolean elementModified = false; for (int i = 0; i < DEPRECATED_ATTRIBUTES.length; i++) { if (!element.getAttribute(DEPRECATED_ATTRIBUTES[i]).isEmpty()) { element.removeAttribute(DEPRECATED_ATTRIBUTES[i]); elementModified = true; } } return elementModified; } private static void compileAllSimpleMethods(Element rootElement, Map<String, SimpleMethod> simpleMethods, String location) throws MiniLangException { for (Element simpleMethodElement : UtilXml.childElementList(rootElement, "simple-method")) { SimpleMethod simpleMethod = new SimpleMethod(simpleMethodElement, location); if (simpleMethods.containsKey(simpleMethod.getMethodName())) { MiniLangValidate.handleError("Duplicate method name found", simpleMethod, simpleMethodElement); } simpleMethods.put(simpleMethod.getMethodName(), simpleMethod); } } private static Map<String, SimpleMethod> getAllDirectSimpleMethods(String name, String content, String fromLocation) throws MiniLangException { if (UtilValidate.isEmpty(fromLocation)) { fromLocation = "<location not known>"; } Map<String, SimpleMethod> simpleMethods = new HashMap<String, SimpleMethod>(); Document document = null; try { document = UtilXml.readXmlDocument(content, true, true); } catch (Exception e) { throw new MiniLangException("Could not read SimpleMethod XML document [" + name + "]: ", e); } compileAllSimpleMethods(document.getDocumentElement(), simpleMethods, fromLocation); return simpleMethods; } private static Map<String, SimpleMethod> getAllSimpleMethods(URL xmlURL) throws MiniLangException { Map<String, SimpleMethod> simpleMethods = new LinkedHashMap<String, SimpleMethod>(); Document document = null; try { document = UtilXml.readXmlDocument(xmlURL, true, true); } catch (Exception e) { throw new MiniLangException("Could not read SimpleMethod XML document [" + xmlURL + "]: ", e); } Element rootElement = document.getDocumentElement(); if (!"simple-methods".equalsIgnoreCase(rootElement.getTagName())) { rootElement = UtilXml.firstChildElement(rootElement, "simple-methods"); } compileAllSimpleMethods(rootElement, simpleMethods, xmlURL.toString()); if (MiniLangUtil.isDocumentAutoCorrected(document)) { MiniLangUtil.writeMiniLangDocument(xmlURL, document); } return simpleMethods; } public static Map<String, SimpleMethod> getDirectSimpleMethods(String name, String content, String fromLocation) throws MiniLangException { Assert.notNull("name", name, "content", content); Map<String, SimpleMethod> simpleMethods = simpleMethodsDirectCache.get(name); if (simpleMethods == null) { simpleMethods = getAllDirectSimpleMethods(name, content, fromLocation); simpleMethods = simpleMethodsDirectCache.putIfAbsentAndGet(name, simpleMethods); } return simpleMethods; } public static SimpleMethod getSimpleMethod(String xmlResource, String methodName, ClassLoader loader) throws MiniLangException { Assert.notNull("methodName", methodName); String key = xmlResource.concat("#").concat(methodName); SimpleMethod method = simpleMethodsResourceCache.get(key); if (method == null) { Map<String, SimpleMethod> simpleMethods = getSimpleMethods(xmlResource, loader); for (Map.Entry<String, SimpleMethod> entry : simpleMethods.entrySet()) { String putKey = xmlResource.concat("#").concat(entry.getKey()); simpleMethodsResourceCache.putIfAbsent(putKey, entry.getValue()); } } return simpleMethodsResourceCache.get(key); } public static SimpleMethod getSimpleMethod(URL xmlUrl, String methodName) throws MiniLangException { Assert.notNull("methodName", methodName); String xmlResource = xmlUrl.toString(); String key = xmlResource.concat("#").concat(methodName); SimpleMethod method = simpleMethodsResourceCache.get(key); if (method == null) { Map<String, SimpleMethod> simpleMethods = getAllSimpleMethods(xmlUrl); for (Map.Entry<String, SimpleMethod> entry : simpleMethods.entrySet()) { String putKey = xmlResource.concat("#").concat(entry.getKey()); simpleMethodsResourceCache.putIfAbsent(putKey, entry.getValue()); } } return simpleMethodsResourceCache.get(key); } private static Map<String, SimpleMethod> getSimpleMethods(String xmlResource, ClassLoader loader) throws MiniLangException { Assert.notNull("xmlResource", xmlResource); URL xmlURL = null; try { xmlURL = FlexibleLocation.resolveLocation(xmlResource, loader); } catch (MalformedURLException e) { throw new MiniLangException("Could not find SimpleMethod XML document in resource: " + xmlResource + "; error was: " + e.toString(), e); } if (xmlURL == null) { throw new MiniLangException("Could not find SimpleMethod XML document in resource: " + xmlResource); } return getAllSimpleMethods(xmlURL); } /** * Returns a List of <code>SimpleMethod</code> objects compiled from <code>xmlResource</code>. * The ordering in the List is the same as the XML file. * <p>This method is used by unit test framework to run tests in the order they appear in the XML file. * Method caching is bypassed since the methods are executed only once.</p> * * @param xmlResource * @param loader * @return * @throws MiniLangException */ public static List<SimpleMethod> getSimpleMethodsList(String xmlResource, ClassLoader loader) throws MiniLangException { Map<String, SimpleMethod> simpleMethodMap = getSimpleMethods(xmlResource, loader); return new ArrayList<SimpleMethod>(simpleMethodMap.values()); } public static List<MethodOperation> readOperations(Element simpleMethodElement, SimpleMethod simpleMethod) throws MiniLangException { Assert.notNull("simpleMethodElement", simpleMethodElement, "simpleMethod", simpleMethod); List<? extends Element> operationElements = UtilXml.childElementList(simpleMethodElement); ArrayList<MethodOperation> methodOperations = new ArrayList<MethodOperation>(operationElements.size()); if (UtilValidate.isNotEmpty(operationElements)) { for (Element curOperElem : operationElements) { String nodeName = UtilXml.getNodeNameIgnorePrefix(curOperElem); MethodOperation methodOp = null; MethodOperation.Factory<MethodOperation> factory = methodOperationFactories.get(nodeName); if (factory != null) { methodOp = factory.createMethodOperation(curOperElem, simpleMethod); } else if ("else".equals(nodeName)) { // don't add anything, but don't complain either, this one is handled in the individual operations } else { MiniLangValidate.handleError("Invalid element found", simpleMethod, curOperElem); } if (methodOp == null) { continue; } methodOperations.add(methodOp); DeprecatedOperation depOp = methodOp.getClass().getAnnotation(DeprecatedOperation.class); if (depOp != null) { MiniLangValidate.handleError("The " + nodeName + " operation has been deprecated in favor of the " + depOp.value() + " operation", simpleMethod, curOperElem); } } } methodOperations.trimToSize(); return methodOperations; } public static String runSimpleEvent(String xmlResource, String methodName, HttpServletRequest request, HttpServletResponse response) throws MiniLangException { return runSimpleMethod(xmlResource, methodName, new MethodContext(request, response, null)); } public static String runSimpleEvent(String xmlResource, String methodName, HttpServletRequest request, HttpServletResponse response, ClassLoader loader) throws MiniLangException { return runSimpleMethod(xmlResource, methodName, new MethodContext(request, response, loader)); } public static String runSimpleEvent(URL xmlURL, String methodName, HttpServletRequest request, HttpServletResponse response, ClassLoader loader) throws MiniLangException { return runSimpleMethod(xmlURL, methodName, new MethodContext(request, response, loader)); } public static String runSimpleMethod(String xmlResource, String methodName, MethodContext methodContext) throws MiniLangException { Assert.notNull("methodContext", methodContext); SimpleMethod simpleMethod = getSimpleMethod(xmlResource, methodName, methodContext.getLoader()); if (simpleMethod == null) { throw new MiniLangException("Could not find SimpleMethod " + methodName + " in XML document in resource: " + xmlResource); } return simpleMethod.exec(methodContext); } public static String runSimpleMethod(URL xmlURL, String methodName, MethodContext methodContext) throws MiniLangException { SimpleMethod simpleMethod = getSimpleMethod(xmlURL, methodName); if (simpleMethod == null) { throw new MiniLangException("Could not find SimpleMethod " + methodName + " in XML document from URL: " + xmlURL.toString()); } return simpleMethod.exec(methodContext); } public static Map<String, Object> runSimpleService(String xmlResource, String methodName, DispatchContext ctx, Map<String, ? extends Object> context) throws MiniLangException { MethodContext methodContext = new MethodContext(ctx, context, null); runSimpleMethod(xmlResource, methodName, methodContext); return methodContext.getResults(); } public static Map<String, Object> runSimpleService(String xmlResource, String methodName, DispatchContext ctx, Map<String, ? extends Object> context, ClassLoader loader) throws MiniLangException { MethodContext methodContext = new MethodContext(ctx, context, loader); runSimpleMethod(xmlResource, methodName, methodContext); return methodContext.getResults(); } public static Map<String, Object> runSimpleService(URL xmlURL, String methodName, DispatchContext ctx, Map<String, ? extends Object> context, ClassLoader loader) throws MiniLangException { MethodContext methodContext = new MethodContext(ctx, context, loader); runSimpleMethod(xmlURL, methodName, methodContext); return methodContext.getResults(); } /** * Execs the given operations returning true if all return true, or returning false and stopping if any return false. * @throws MiniLangException */ public static boolean runSubOps(List<MethodOperation> methodOperations, MethodContext methodContext) throws MiniLangException { Assert.notNull("methodOperations", methodOperations, "methodContext", methodContext); for (MethodOperation methodOperation : methodOperations) { if (!methodOperation.exec(methodContext)) { return false; } } return true; } private final String defaultErrorCode; private final String defaultSuccessCode; private final String eventErrorMessageListName; private final String eventErrorMessageName; private final String eventEventMessageListName; private final String eventEventMessageName; private final String eventRequestName; private final String eventResponseCodeName; private final String eventResponseName; private final String eventSessionName; private final String fromLocation; private final boolean loginRequired; private final String methodName; private final List<MethodOperation> methodOperations; private final String serviceErrorMessageListName; private final String serviceErrorMessageMapName; private final String serviceErrorMessageName; private final String serviceResponseMessageName; private final String serviceSuccessMessageListName; private final String serviceSuccessMessageName; private final String shortDescription; private final boolean useTransaction; public SimpleMethod(Element simpleMethodElement, String fromLocation) throws MiniLangException { super(simpleMethodElement, null); if (MiniLangValidate.validationOn()) { String locationMsg = " File = ".concat(fromLocation); if (simpleMethodElement.getAttribute("method-name").isEmpty()) { MiniLangValidate.handleError("Element must include the \"method-name\" attribute.".concat(locationMsg), null, simpleMethodElement); } for (int i = 0; i < DEPRECATED_ATTRIBUTES.length; i++) { if (!simpleMethodElement.getAttribute(DEPRECATED_ATTRIBUTES[i]).isEmpty()) { MiniLangValidate.handleError("Attribute \"" + DEPRECATED_ATTRIBUTES[i] + "\" is deprecated (no replacement)." + locationMsg, null, simpleMethodElement); } } } boolean elementModified = autoCorrect(simpleMethodElement); if (elementModified && MiniLangUtil.autoCorrectOn()) { MiniLangUtil.flagDocumentAsCorrected(simpleMethodElement); } this.fromLocation = fromLocation; methodName = simpleMethodElement.getAttribute("method-name"); shortDescription = simpleMethodElement.getAttribute("short-description"); defaultErrorCode = UtilXml.elementAttribute(simpleMethodElement, "default-error-code", "error"); defaultSuccessCode = UtilXml.elementAttribute(simpleMethodElement, "default-success-code", "success"); eventRequestName = UtilXml.elementAttribute(simpleMethodElement, "event-request-object-name", "request"); eventSessionName = UtilXml.elementAttribute(simpleMethodElement, "event-session-object-name", "session"); eventResponseName = UtilXml.elementAttribute(simpleMethodElement, "event-response-object-name", "response"); eventResponseCodeName = UtilXml.elementAttribute(simpleMethodElement, "event-response-code-name", "_response_code_"); eventErrorMessageName = UtilXml.elementAttribute(simpleMethodElement, "event-error-message-name", "_error_message_"); eventErrorMessageListName = UtilXml.elementAttribute(simpleMethodElement, "event-error-message-list-name", "_error_message_list_"); eventEventMessageName = UtilXml.elementAttribute(simpleMethodElement, "event-event-message-name", "_event_message_"); eventEventMessageListName = UtilXml.elementAttribute(simpleMethodElement, "event-event-message-list-name", "_event_message_list_"); serviceResponseMessageName = UtilXml.elementAttribute(simpleMethodElement, "service-response-message-name", "responseMessage"); serviceErrorMessageName = UtilXml.elementAttribute(simpleMethodElement, "service-error-message-name", "errorMessage"); serviceErrorMessageListName = UtilXml.elementAttribute(simpleMethodElement, "service-error-message-list-name", "errorMessageList"); serviceErrorMessageMapName = UtilXml.elementAttribute(simpleMethodElement, "service-error-message-map-name", "errorMessageMap"); serviceSuccessMessageName = UtilXml.elementAttribute(simpleMethodElement, "service-success-message-name", "successMessage"); serviceSuccessMessageListName = UtilXml.elementAttribute(simpleMethodElement, "service-success-message-list-name", "successMessageList"); loginRequired = !"false".equals(simpleMethodElement.getAttribute("login-required")); useTransaction = !"false".equals(simpleMethodElement.getAttribute("use-transaction")); methodOperations = Collections.unmodifiableList(readOperations(simpleMethodElement, this)); } public void addErrorMessage(MethodContext methodContext, String message) { String messageListName = methodContext.getMethodType() == MethodContext.EVENT ? getEventErrorMessageListName() : getServiceErrorMessageListName(); addMessage(methodContext, messageListName, message); } public void addMessage(MethodContext methodContext, String message) { String messageListName = methodContext.getMethodType() == MethodContext.EVENT ? getEventEventMessageListName() : getServiceSuccessMessageListName(); addMessage(methodContext, messageListName, message); } private void addMessage(MethodContext methodContext, String messageListName, String message) { List<String> messages = methodContext.getEnv(messageListName); if (messages == null) { messages = new LinkedList<String>(); methodContext.putEnv(messageListName, messages); } messages.add(message); } /** Execute the Simple Method operations */ public String exec(MethodContext methodContext) throws MiniLangException { if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "Begin simple-method. Script is running as " + (methodContext.getMethodType() == MethodContext.EVENT ? "an event." : "a service.")); } Locale locale = methodContext.getLocale(); GenericValue userLogin = methodContext.getUserLogin(); if (loginRequired) { if (userLogin == null) { Map<String, Object> messageMap = UtilMisc.<String, Object> toMap("shortDescription", shortDescription); String errMsg = UtilProperties.getMessage(SimpleMethod.err_resource, "simpleMethod.must_logged_process", messageMap, locale) + "."; if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "login-required attribute set to \"true\" but UserLogin GenericValue was not found, returning error message:", errMsg); } return returnError(methodContext, errMsg); } } if (userLogin != null) { methodContext.putEnv(getUserLoginEnvName(), userLogin); } methodContext.putEnv("nullField", GenericEntity.NULL_FIELD); methodContext.putEnv(getDelegatorEnvName(), methodContext.getDelegator()); methodContext.putEnv(getSecurityEnvName(), methodContext.getSecurity()); methodContext.putEnv(getDispatcherEnvName(), methodContext.getDispatcher()); methodContext.putEnv("locale", locale); methodContext.putEnv(getParameterMapName(), methodContext.getParameters()); if (methodContext.getMethodType() == MethodContext.EVENT) { methodContext.putEnv(eventRequestName, methodContext.getRequest()); methodContext.putEnv(eventSessionName, methodContext.getRequest().getSession()); methodContext.putEnv(eventResponseName, methodContext.getResponse()); } methodContext.putEnv("simpleMethod", this); methodContext.putEnv("methodName", this.getMethodName()); methodContext.putEnv("methodShortDescription", this.getShortDescription()); // if using transaction, try to start here boolean beganTransaction = false; if (useTransaction) { if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "use-transaction attribute set to \"true\", beginning transaction."); } try { beganTransaction = TransactionUtil.begin(); } catch (GenericTransactionException e) { String errMsg = UtilProperties.getMessage(SimpleMethod.err_resource, "simpleMethod.error_begin_transaction", locale) + ": " + e.getMessage(); if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "An exception was thrown while beginning a transaction, returning error message:", errMsg); } return returnError(methodContext, errMsg); } } // declare errorMsg here just in case transaction ops fail String errorMsg = ""; boolean finished = false; try { if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "Begin running sub-elements."); } finished = runSubOps(methodOperations, methodContext); } catch (Throwable t) { // make SURE nothing gets thrown through String errMsg = UtilProperties.getMessage(SimpleMethod.err_resource, "simpleMethod.error_running", locale) + ": " + t.getMessage(); if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "An exception was thrown while running sub-elements, error message was:", errMsg); } finished = false; errorMsg += errMsg; } if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "End running sub-elements."); } String returnValue = null; String response = null; StringBuilder summaryErrorStringBuffer = new StringBuilder(); if (methodContext.getMethodType() == MethodContext.EVENT) { boolean forceError = false; String tempErrorMsg = (String) methodContext.getEnv(eventErrorMessageName); if (errorMsg.length() > 0 || UtilValidate.isNotEmpty(tempErrorMsg)) { errorMsg += tempErrorMsg; methodContext.getRequest().setAttribute("_ERROR_MESSAGE_", errorMsg); forceError = true; summaryErrorStringBuffer.append(errorMsg); } List<Object> tempErrorMsgList = UtilGenerics.checkList(methodContext.getEnv(eventErrorMessageListName)); if (UtilValidate.isNotEmpty(tempErrorMsgList)) { methodContext.getRequest().setAttribute("_ERROR_MESSAGE_LIST_", tempErrorMsgList); forceError = true; summaryErrorStringBuffer.append("; "); summaryErrorStringBuffer.append(tempErrorMsgList.toString()); } String eventMsg = (String) methodContext.getEnv(eventEventMessageName); if (UtilValidate.isNotEmpty(eventMsg)) { methodContext.getRequest().setAttribute("_EVENT_MESSAGE_", eventMsg); } List<String> eventMsgList = UtilGenerics.checkList(methodContext.getEnv(eventEventMessageListName)); if (UtilValidate.isNotEmpty(eventMsgList)) { methodContext.getRequest().setAttribute("_EVENT_MESSAGE_LIST_", eventMsgList); } response = (String) methodContext.getEnv(eventResponseCodeName); if (UtilValidate.isEmpty(response)) { if (forceError) { // override response code, always use error code Debug.logInfo("No response code string found, but error messages found so assuming error; returning code [" + defaultErrorCode + "]", module); response = defaultErrorCode; } else { Debug.logInfo("No response code string or errors found, assuming success; returning code [" + defaultSuccessCode + "]", module); response = defaultSuccessCode; } } else if ("null".equalsIgnoreCase(response)) { response = null; } returnValue = response; } else { boolean forceError = false; String tempErrorMsg = (String) methodContext.getEnv(serviceErrorMessageName); if (errorMsg.length() > 0 || UtilValidate.isNotEmpty(tempErrorMsg)) { errorMsg += tempErrorMsg; methodContext.putResult(ModelService.ERROR_MESSAGE, errorMsg); forceError = true; summaryErrorStringBuffer.append(errorMsg); } List<Object> errorMsgList = UtilGenerics.checkList(methodContext.getEnv(serviceErrorMessageListName)); if (UtilValidate.isNotEmpty(errorMsgList)) { methodContext.putResult(ModelService.ERROR_MESSAGE_LIST, errorMsgList); forceError = true; summaryErrorStringBuffer.append("; "); summaryErrorStringBuffer.append(errorMsgList.toString()); } Map<String, Object> errorMsgMap = UtilGenerics.checkMap(methodContext.getEnv(serviceErrorMessageMapName)); if (UtilValidate.isNotEmpty(errorMsgMap)) { methodContext.putResult(ModelService.ERROR_MESSAGE_MAP, errorMsgMap); forceError = true; summaryErrorStringBuffer.append("; "); summaryErrorStringBuffer.append(errorMsgMap.toString()); } String successMsg = (String) methodContext.getEnv(serviceSuccessMessageName); if (UtilValidate.isNotEmpty(successMsg)) { methodContext.putResult(ModelService.SUCCESS_MESSAGE, successMsg); } List<Object> successMsgList = UtilGenerics.checkList(methodContext.getEnv(serviceSuccessMessageListName)); if (UtilValidate.isNotEmpty(successMsgList)) { methodContext.putResult(ModelService.SUCCESS_MESSAGE_LIST, successMsgList); } response = (String) methodContext.getEnv(serviceResponseMessageName); if (UtilValidate.isEmpty(response)) { if (forceError) { // override response code, always use error code Debug.logVerbose("No response code string found, but error messages found so assuming error; returning code [" + defaultErrorCode + "]", module); response = defaultErrorCode; } else { Debug.logVerbose("No response code string or errors found, assuming success; returning code [" + defaultSuccessCode + "]", module); response = defaultSuccessCode; } } methodContext.putResult(ModelService.RESPONSE_MESSAGE, response); returnValue = response; } // decide whether or not to commit based on the response message, ie only rollback if error is returned and not finished boolean doCommit = true; if (!finished && defaultErrorCode.equals(response)) { doCommit = false; } if (doCommit) { if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "Begin commit transaction."); } // commit here passing beganTransaction to perform it properly try { TransactionUtil.commit(beganTransaction); } catch (GenericTransactionException e) { String errMsg = "Error trying to commit transaction, could not process method: " + e.getMessage(); if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "An exception was thrown while committing a transaction, returning error message:", errMsg); } errorMsg += errMsg; } } else { if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "Begin roll back transaction."); } // rollback here passing beganTransaction to either rollback, or set rollback only try { TransactionUtil.rollback(beganTransaction, "Error in simple-method [" + this.getShortDescription() + "]: " + summaryErrorStringBuffer, null); } catch (GenericTransactionException e) { String errMsg = "Error trying to rollback transaction, could not process method: " + e.getMessage(); if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "An exception was thrown while rolling back a transaction, returning error message:", errMsg); } errorMsg += errMsg; } } if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "End simple-method."); } return returnValue; } @Override public void gatherArtifactInfo(ArtifactInfoContext aic) { for (MethodOperation methodOp : this.methodOperations) { methodOp.gatherArtifactInfo(aic); } } @Deprecated public Set<String> getAllEntityNamesUsed() throws MiniLangException { ArtifactInfoContext aic = new ArtifactInfoContext(); gatherArtifactInfo(aic); return aic.getEntityNames(); } @Deprecated public Set<String> getAllServiceNamesCalled() throws MiniLangException { ArtifactInfoContext aic = new ArtifactInfoContext(); gatherArtifactInfo(aic); return aic.getServiceNames(); } public String getDefaultErrorCode() { return this.defaultErrorCode; } public String getDefaultSuccessCode() { return this.defaultSuccessCode; } public String getDelegatorEnvName() { return "delegator"; } public String getDispatcherEnvName() { return "dispatcher"; } public String getEventErrorMessageListName() { return this.eventErrorMessageListName; } public String getEventErrorMessageName() { return this.eventErrorMessageName; } public String getEventEventMessageListName() { return this.eventEventMessageListName; } public String getEventEventMessageName() { return this.eventEventMessageName; } // event fields public String getEventRequestName() { return this.eventRequestName; } public String getEventResponseCodeName() { return this.eventResponseCodeName; } public String getEventSessionName() { return this.eventSessionName; } public String getFileName() { return this.fromLocation.substring(this.fromLocation.lastIndexOf("/") + 1); } public String getFromLocation() { return this.fromLocation; } public String getLocationAndName() { return this.fromLocation + "#" + this.methodName; } public boolean getLoginRequired() { return this.loginRequired; } public String getMethodName() { return this.methodName; } public List<MethodOperation> getMethodOperations() { return this.methodOperations; } public String getParameterMapName() { return "parameters"; } public String getSecurityEnvName() { return "security"; } public String getServiceErrorMessageListName() { return this.serviceErrorMessageListName; } public String getServiceErrorMessageMapName() { return this.serviceErrorMessageMapName; } public String getServiceErrorMessageName() { return this.serviceErrorMessageName; } public String getServiceResponseMessageName() { return this.serviceResponseMessageName; } public String getServiceSuccessMessageListName() { return this.serviceSuccessMessageListName; } public String getServiceSuccessMessageName() { return this.serviceSuccessMessageName; } public String getShortDescription() { return this.shortDescription + " [" + this.fromLocation + "#" + this.methodName + "]"; } @Override public SimpleMethod getSimpleMethod() { return this; } public String getUserLoginEnvName() { return "userLogin"; } public boolean getUseTransaction() { return this.useTransaction; } private String returnError(MethodContext methodContext, String errorMsg) { if (methodContext.getMethodType() == MethodContext.EVENT) { methodContext.getRequest().setAttribute("_ERROR_MESSAGE_", errorMsg); } else { methodContext.putResult(ModelService.ERROR_MESSAGE, errorMsg); methodContext.putResult(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR); } return defaultErrorCode; } }
googleapis/google-cloud-java
37,364
java-speech/proto-google-cloud-speech-v1p1beta1/src/main/java/com/google/cloud/speech/v1p1beta1/ListCustomClassesResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/speech/v1p1beta1/cloud_speech_adaptation.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.speech.v1p1beta1; /** * * * <pre> * Message returned to the client by the `ListCustomClasses` method. * </pre> * * Protobuf type {@code google.cloud.speech.v1p1beta1.ListCustomClassesResponse} */ public final class ListCustomClassesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.speech.v1p1beta1.ListCustomClassesResponse) ListCustomClassesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListCustomClassesResponse.newBuilder() to construct. private ListCustomClassesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListCustomClassesResponse() { customClasses_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListCustomClassesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto .internal_static_google_cloud_speech_v1p1beta1_ListCustomClassesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto .internal_static_google_cloud_speech_v1p1beta1_ListCustomClassesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.class, com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.Builder.class); } public static final int CUSTOM_CLASSES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.speech.v1p1beta1.CustomClass> customClasses_; /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.speech.v1p1beta1.CustomClass> getCustomClassesList() { return customClasses_; } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder> getCustomClassesOrBuilderList() { return customClasses_; } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ @java.lang.Override public int getCustomClassesCount() { return customClasses_.size(); } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ @java.lang.Override public com.google.cloud.speech.v1p1beta1.CustomClass getCustomClasses(int index) { return customClasses_.get(index); } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ @java.lang.Override public com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder getCustomClassesOrBuilder( int index) { return customClasses_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < customClasses_.size(); i++) { output.writeMessage(1, customClasses_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < customClasses_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, customClasses_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse)) { return super.equals(obj); } com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse other = (com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse) obj; if (!getCustomClassesList().equals(other.getCustomClassesList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getCustomClassesCount() > 0) { hash = (37 * hash) + CUSTOM_CLASSES_FIELD_NUMBER; hash = (53 * hash) + getCustomClassesList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Message returned to the client by the `ListCustomClasses` method. * </pre> * * Protobuf type {@code google.cloud.speech.v1p1beta1.ListCustomClassesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.speech.v1p1beta1.ListCustomClassesResponse) com.google.cloud.speech.v1p1beta1.ListCustomClassesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto .internal_static_google_cloud_speech_v1p1beta1_ListCustomClassesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto .internal_static_google_cloud_speech_v1p1beta1_ListCustomClassesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.class, com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.Builder.class); } // Construct using com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (customClassesBuilder_ == null) { customClasses_ = java.util.Collections.emptyList(); } else { customClasses_ = null; customClassesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto .internal_static_google_cloud_speech_v1p1beta1_ListCustomClassesResponse_descriptor; } @java.lang.Override public com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse getDefaultInstanceForType() { return com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse build() { com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse buildPartial() { com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse result = new com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse result) { if (customClassesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { customClasses_ = java.util.Collections.unmodifiableList(customClasses_); bitField0_ = (bitField0_ & ~0x00000001); } result.customClasses_ = customClasses_; } else { result.customClasses_ = customClassesBuilder_.build(); } } private void buildPartial0(com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse) { return mergeFrom((com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse other) { if (other == com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse.getDefaultInstance()) return this; if (customClassesBuilder_ == null) { if (!other.customClasses_.isEmpty()) { if (customClasses_.isEmpty()) { customClasses_ = other.customClasses_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureCustomClassesIsMutable(); customClasses_.addAll(other.customClasses_); } onChanged(); } } else { if (!other.customClasses_.isEmpty()) { if (customClassesBuilder_.isEmpty()) { customClassesBuilder_.dispose(); customClassesBuilder_ = null; customClasses_ = other.customClasses_; bitField0_ = (bitField0_ & ~0x00000001); customClassesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getCustomClassesFieldBuilder() : null; } else { customClassesBuilder_.addAllMessages(other.customClasses_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.speech.v1p1beta1.CustomClass m = input.readMessage( com.google.cloud.speech.v1p1beta1.CustomClass.parser(), extensionRegistry); if (customClassesBuilder_ == null) { ensureCustomClassesIsMutable(); customClasses_.add(m); } else { customClassesBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.speech.v1p1beta1.CustomClass> customClasses_ = java.util.Collections.emptyList(); private void ensureCustomClassesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { customClasses_ = new java.util.ArrayList<com.google.cloud.speech.v1p1beta1.CustomClass>(customClasses_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.speech.v1p1beta1.CustomClass, com.google.cloud.speech.v1p1beta1.CustomClass.Builder, com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder> customClassesBuilder_; /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public java.util.List<com.google.cloud.speech.v1p1beta1.CustomClass> getCustomClassesList() { if (customClassesBuilder_ == null) { return java.util.Collections.unmodifiableList(customClasses_); } else { return customClassesBuilder_.getMessageList(); } } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public int getCustomClassesCount() { if (customClassesBuilder_ == null) { return customClasses_.size(); } else { return customClassesBuilder_.getCount(); } } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public com.google.cloud.speech.v1p1beta1.CustomClass getCustomClasses(int index) { if (customClassesBuilder_ == null) { return customClasses_.get(index); } else { return customClassesBuilder_.getMessage(index); } } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public Builder setCustomClasses( int index, com.google.cloud.speech.v1p1beta1.CustomClass value) { if (customClassesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCustomClassesIsMutable(); customClasses_.set(index, value); onChanged(); } else { customClassesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public Builder setCustomClasses( int index, com.google.cloud.speech.v1p1beta1.CustomClass.Builder builderForValue) { if (customClassesBuilder_ == null) { ensureCustomClassesIsMutable(); customClasses_.set(index, builderForValue.build()); onChanged(); } else { customClassesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public Builder addCustomClasses(com.google.cloud.speech.v1p1beta1.CustomClass value) { if (customClassesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCustomClassesIsMutable(); customClasses_.add(value); onChanged(); } else { customClassesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public Builder addCustomClasses( int index, com.google.cloud.speech.v1p1beta1.CustomClass value) { if (customClassesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCustomClassesIsMutable(); customClasses_.add(index, value); onChanged(); } else { customClassesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public Builder addCustomClasses( com.google.cloud.speech.v1p1beta1.CustomClass.Builder builderForValue) { if (customClassesBuilder_ == null) { ensureCustomClassesIsMutable(); customClasses_.add(builderForValue.build()); onChanged(); } else { customClassesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public Builder addCustomClasses( int index, com.google.cloud.speech.v1p1beta1.CustomClass.Builder builderForValue) { if (customClassesBuilder_ == null) { ensureCustomClassesIsMutable(); customClasses_.add(index, builderForValue.build()); onChanged(); } else { customClassesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public Builder addAllCustomClasses( java.lang.Iterable<? extends com.google.cloud.speech.v1p1beta1.CustomClass> values) { if (customClassesBuilder_ == null) { ensureCustomClassesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, customClasses_); onChanged(); } else { customClassesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public Builder clearCustomClasses() { if (customClassesBuilder_ == null) { customClasses_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { customClassesBuilder_.clear(); } return this; } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public Builder removeCustomClasses(int index) { if (customClassesBuilder_ == null) { ensureCustomClassesIsMutable(); customClasses_.remove(index); onChanged(); } else { customClassesBuilder_.remove(index); } return this; } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public com.google.cloud.speech.v1p1beta1.CustomClass.Builder getCustomClassesBuilder( int index) { return getCustomClassesFieldBuilder().getBuilder(index); } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder getCustomClassesOrBuilder( int index) { if (customClassesBuilder_ == null) { return customClasses_.get(index); } else { return customClassesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public java.util.List<? extends com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder> getCustomClassesOrBuilderList() { if (customClassesBuilder_ != null) { return customClassesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(customClasses_); } } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public com.google.cloud.speech.v1p1beta1.CustomClass.Builder addCustomClassesBuilder() { return getCustomClassesFieldBuilder() .addBuilder(com.google.cloud.speech.v1p1beta1.CustomClass.getDefaultInstance()); } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public com.google.cloud.speech.v1p1beta1.CustomClass.Builder addCustomClassesBuilder( int index) { return getCustomClassesFieldBuilder() .addBuilder(index, com.google.cloud.speech.v1p1beta1.CustomClass.getDefaultInstance()); } /** * * * <pre> * The custom classes. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.CustomClass custom_classes = 1;</code> */ public java.util.List<com.google.cloud.speech.v1p1beta1.CustomClass.Builder> getCustomClassesBuilderList() { return getCustomClassesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.speech.v1p1beta1.CustomClass, com.google.cloud.speech.v1p1beta1.CustomClass.Builder, com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder> getCustomClassesFieldBuilder() { if (customClassesBuilder_ == null) { customClassesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.speech.v1p1beta1.CustomClass, com.google.cloud.speech.v1p1beta1.CustomClass.Builder, com.google.cloud.speech.v1p1beta1.CustomClassOrBuilder>( customClasses_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); customClasses_ = null; } return customClassesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.speech.v1p1beta1.ListCustomClassesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.speech.v1p1beta1.ListCustomClassesResponse) private static final com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse(); } public static com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListCustomClassesResponse> PARSER = new com.google.protobuf.AbstractParser<ListCustomClassesResponse>() { @java.lang.Override public ListCustomClassesResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListCustomClassesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListCustomClassesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/jackrabbit-oak
37,479
oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/BaseDocumentDiscoveryLiteServiceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.plugins.document; import static org.apache.jackrabbit.oak.plugins.document.ClusterNodeInfo.LEASE_END_KEY; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import javax.jcr.PropertyType; import javax.jcr.Value; import javax.jcr.ValueFormatException; import org.apache.jackrabbit.oak.api.CommitFailedException; import org.apache.jackrabbit.oak.api.Descriptors; import org.apache.jackrabbit.oak.commons.json.JsonObject; import org.apache.jackrabbit.oak.commons.json.JsopTokenizer; import org.apache.jackrabbit.oak.commons.junit.LogDumper; import org.apache.jackrabbit.oak.commons.junit.LogLevelModifier; import org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore; import org.apache.jackrabbit.oak.plugins.document.util.MongoConnection; import org.apache.jackrabbit.oak.spi.blob.BlobStore; import org.apache.jackrabbit.oak.spi.blob.MemoryBlobStore; import org.apache.jackrabbit.oak.spi.commit.CommitInfo; import org.apache.jackrabbit.oak.spi.commit.EmptyHook; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TestRule; import org.mockito.stubbing.Answer; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.client.MongoDatabase; import junitx.util.PrivateAccessor; /** * Abstract base class for the DocumentDiscoveryLiteService tests */ public abstract class BaseDocumentDiscoveryLiteServiceTest { @Rule public MongoConnectionFactory connectionFactory = new MongoConnectionFactory(); /** * container for what should represent an instance, but is not a complete * one, hence 'simplified'. it contains most importantly the * DocuemntNodeStore and the discoveryLite service */ class SimplifiedInstance { DocumentDiscoveryLiteService service; DocumentNodeStore ns; private final Descriptors descriptors; private Map<Object, Object> registeredServices; private final long lastRevInterval; private volatile boolean lastRevStopped = false; private volatile boolean writeSimulationStopped = false; private Thread lastRevThread; private Thread writeSimulationThread; public String workingDir; SimplifiedInstance(DocumentDiscoveryLiteService service, DocumentNodeStore ns, Descriptors descriptors, Map<Object, Object> registeredServices, long lastRevInterval, String workingDir) { this.service = service; this.ns = ns; this.workingDir = workingDir; this.descriptors = descriptors; this.registeredServices = registeredServices; this.lastRevInterval = lastRevInterval; if (lastRevInterval > 0) { startLastRevThread(); } } @Override public String toString() { return "SimplifiedInstance[cid=" + ns.getClusterId() + "]"; } void startLastRevThread() { lastRevStopped = false; lastRevThread = new Thread(new Runnable() { @Override public void run() { while (!lastRevStopped) { SimplifiedInstance.this.ns.getLastRevRecoveryAgent().performRecoveryIfNeeded(); try { Thread.sleep(SimplifiedInstance.this.lastRevInterval); } catch (InterruptedException e) { e.printStackTrace(); } } } }); lastRevThread.setDaemon(true); lastRevThread.setName("lastRevThread[cid=" + ns.getClusterId() + "]"); lastRevThread.start(); } void stopLastRevThread() throws InterruptedException { lastRevStopped = true; lastRevThread.join(); } boolean isFinal() throws Exception { final JsonObject clusterViewObj = getClusterViewObj(); if (clusterViewObj == null) { throw new IllegalStateException("should always have that final flag set"); } String finalStr = clusterViewObj.getProperties().get("final"); return Boolean.valueOf(finalStr); } boolean isInvisible() { return ns.getClusterInfo().isInvisible(); } boolean hasActiveIds(String clusterViewStr, int... expected) throws Exception { return hasIds(clusterViewStr, "active", expected); } boolean hasDeactivatingIds(String clusterViewStr, int... expected) throws Exception { return hasIds(clusterViewStr, "deactivating", expected); } boolean hasInactiveIds(String clusterViewStr, int... expected) throws Exception { return hasIds(clusterViewStr, "inactive", expected); } private boolean hasIds(final String clusterViewStr, final String key, int... expectedIds) throws Exception { final JsonObject clusterViewObj = asJsonObject(clusterViewStr); String actualIdsStr = clusterViewObj == null ? null : clusterViewObj.getProperties().get(key); boolean actualEmpty = actualIdsStr == null || actualIdsStr.length() == 0 || actualIdsStr.equals("[]"); boolean expectedEmpty = expectedIds == null || expectedIds.length == 0; if (actualEmpty && expectedEmpty) { return true; } if (actualEmpty != expectedEmpty) { return false; } final List<Integer> actualList = Arrays .asList(ClusterViewDocument.csvToIntegerArray(actualIdsStr.substring(1, actualIdsStr.length() - 1))); if (expectedIds.length != actualList.size()) { return false; } for (int i = 0; i < expectedIds.length; i++) { int anExpectedId = expectedIds[i]; if (!actualList.contains(anExpectedId)) { return false; } } return true; } JsonObject getClusterViewObj() throws Exception { final String json = getClusterViewStr(); return asJsonObject(json); } private JsonObject asJsonObject(final String json) { if (json == null) { return null; } JsopTokenizer t = new JsopTokenizer(json); t.read('{'); JsonObject o = JsonObject.create(t); return o; } String getClusterViewStr() throws Exception { return getDescriptor(DocumentDiscoveryLiteService.OAK_DISCOVERYLITE_CLUSTERVIEW); } String getDescriptor(String key) throws Exception { final Value value = descriptors.getValue(key); if (value == null) { return null; } if (value.getType() != PropertyType.STRING) { return null; } try { return value.getString(); } catch (ValueFormatException vfe) { return null; } } public void dispose() { logger.info("Disposing " + this); try { stopSimulatingWrites(); } catch (InterruptedException e) { fail("interrupted"); } if (lastRevThread != null) { try { stopLastRevThread(); } catch (InterruptedException ok) { fail("interrupted"); } lastRevThread = null; } if (service != null) { service.deactivate(); service = null; } if (ns != null) { ns.dispose(); ns = null; } if (registeredServices != null) { registeredServices.clear(); registeredServices = null; } } /** * shutdown simulates the normal, graceful, shutdown * * @throws InterruptedException */ public void shutdown() throws InterruptedException { stopSimulatingWrites(); stopLastRevThread(); ns.dispose(); service.deactivate(); } /** * crash simulates a kill -9, sort of * * @throws Throwable */ public void crash() throws Throwable { logger.info("crash: stopping simulating writes..."); stopSimulatingWrites(); logger.info("crash: stopping lastrev thread..."); stopLastRevThread(); logger.info("crash: stopped lastrev thread, now setting lease to end within 1 sec"); boolean renewed = setLeaseTime(1000 /* 1 sec */, 10 /*10ms*/); logger.info("renewed : {}", renewed); // OAK-11477: lease could have been updated by lease update thread while we wanted to do that // in which case testing for !renewed is not very useful here //if (!renewed) { // logger.info("halt"); // fail("did not renew clusterid lease"); //} logger.info("crash: now stopping background read/update"); stopAllBackgroundThreads(); // but don't do the following from DocumentNodeStore.dispose(): // * don't do the last internalRunBackgroundUpdateOperations - as // we're trying to simulate a crash here // * don't dispose clusterNodeInfo to leave the node in active state // the DocumentDiscoveryLiteService currently can simply be // deactivated, doesn't differ much from crashing service.deactivate(); logger.info("crash: crash simulation done."); } /** * very hacky way of doing the following: make sure this instance's * clusterNodes entry is marked with a very short (1 sec off) lease end * time so that the crash detection doesn't take a minute (as it would * by default) */ private boolean setLeaseTime(final int leaseTime, final int leaseUpdateInterval) throws NoSuchFieldException { ns.getClusterInfo().setLeaseTime(leaseTime); ns.getClusterInfo().setLeaseUpdateInterval(leaseUpdateInterval); long newLeaseTime = System.currentTimeMillis() + (leaseTime / 3) - 10 /* 10ms safety margin */; PrivateAccessor.setField(ns.getClusterInfo(), "leaseEndTime", newLeaseTime); // OAK-9564: Apply the update low level to the nodeStore, as the max operation wouldn't let to apply the // new lease time if it is lower than the current one. UpdateOp op = new UpdateOp(String.valueOf(ns.getClusterId()), false); op.set(LEASE_END_KEY, newLeaseTime); ns.getDocumentStore().findAndUpdate(Collection.CLUSTER_NODES, op); boolean renewed = ns.renewClusterIdLease(); return renewed; } private AtomicBoolean getIsDisposed() throws NoSuchFieldException { AtomicBoolean isDisposed = (AtomicBoolean) PrivateAccessor.getField(ns, "isDisposed"); return isDisposed; } private AtomicBoolean getStopLeaseUpdateThread() throws NoSuchFieldException { AtomicBoolean stopLeaseUpdateThread = (AtomicBoolean) PrivateAccessor.getField(ns, "stopLeaseUpdateThread"); return stopLeaseUpdateThread; } private void stopAllBackgroundThreads() throws NoSuchFieldException { // get all those background threads... Thread backgroundReadThread = (Thread) PrivateAccessor.getField(ns, "backgroundReadThread"); assertNotNull(backgroundReadThread); Thread backgroundUpdateThread = (Thread) PrivateAccessor.getField(ns, "backgroundUpdateThread"); assertNotNull(backgroundUpdateThread); Thread leaseUpdateThread = (Thread) PrivateAccessor.getField(ns, "leaseUpdateThread"); assertNotNull(leaseUpdateThread); // start doing what DocumentNodeStore.dispose() would do - except do // it very fine controlled, basically: // make sure to stop backgroundReadThread, backgroundUpdateThread // and leaseUpdateThread // but then nothing else. final AtomicBoolean isDisposed = getIsDisposed(); assertFalse(isDisposed.getAndSet(true)); // notify background threads waiting on isDisposed synchronized (isDisposed) { isDisposed.notifyAll(); } try { backgroundReadThread.join(5000); assertTrue(!backgroundReadThread.isAlive()); } catch (InterruptedException e) { // ignore } try { backgroundUpdateThread.join(5000); assertTrue(!backgroundUpdateThread.isAlive()); } catch (InterruptedException e) { // ignore } final AtomicBoolean stopLeaseUpdateThread = getStopLeaseUpdateThread(); assertFalse(stopLeaseUpdateThread.getAndSet(true)); // notify background threads waiting on stopLeaseUpdateThread synchronized (stopLeaseUpdateThread) { stopLeaseUpdateThread.notifyAll(); } try { leaseUpdateThread.join(5000); assertTrue(!leaseUpdateThread.isAlive()); } catch (InterruptedException e) { // ignore } } public void stopBgReadThread() throws NoSuchFieldException { final Thread backgroundReadThread = (Thread) PrivateAccessor.getField(ns, "backgroundReadThread"); assertNotNull(backgroundReadThread); final Runnable bgReadRunnable = (Runnable) PrivateAccessor.getField(backgroundReadThread, "target"); assertNotNull(bgReadRunnable); final AtomicBoolean bgReadIsDisposed = new AtomicBoolean(false); PrivateAccessor.setField(bgReadRunnable, "isDisposed", bgReadIsDisposed); assertFalse(bgReadIsDisposed.getAndSet(true)); try { backgroundReadThread.join(5000); assertTrue(!backgroundReadThread.isAlive()); } catch (InterruptedException e) { // ignore } // big of heavy work, but now the backgroundReadThread is stopped // and all the others are still running } public void addNode(String path) throws CommitFailedException { NodeBuilder root = ns.getRoot().builder(); NodeBuilder child = root; String[] split = path.split("/"); for (int i = 1; i < split.length; i++) { child = child.child(split[i]); } logger.info("addNode: " + ns.getClusterId() + " is merging path " + path); ns.merge(root, EmptyHook.INSTANCE, CommitInfo.EMPTY); } public void setProperty(String path, String key, String value) throws CommitFailedException { NodeBuilder root = ns.getRoot().builder(); NodeBuilder child = root; String[] split = path.split("/"); for (int i = 1; i < split.length; i++) { child = child.child(split[i]); } child.setProperty(key, value); logger.info("setProperty: " + ns.getClusterId() + " is merging path/property " + path + ", key=" + key + ", value=" + value); ns.merge(root, EmptyHook.INSTANCE, CommitInfo.EMPTY); } public void setLeastTimeout(long timeoutInMs, long updateIntervalInMs) throws NoSuchFieldException { ns.getClusterInfo().setLeaseTime(timeoutInMs); ns.getClusterInfo().setLeaseUpdateInterval(updateIntervalInMs); PrivateAccessor.setField(ns.getClusterInfo(), "leaseEndTime", System.currentTimeMillis() - 1000); } void startSimulatingWrites(final long writeInterval) { writeSimulationStopped = false; writeSimulationThread = new Thread(new Runnable() { final Random random = new Random(); @Override public void run() { while (!writeSimulationStopped) { try { writeSomething(); Thread.sleep(SimplifiedInstance.this.lastRevInterval); } catch (Exception e) { e.printStackTrace(); } } } private void writeSomething() throws CommitFailedException { final String path = "/" + ns.getClusterId() + "/" + random.nextInt(100) + "/" + random.nextInt(100) + "/" + random.nextInt(100); logger.info("Writing [" + ns.getClusterId() + "]" + path); addNode(path); } }); writeSimulationThread.setDaemon(true); writeSimulationThread.start(); } void stopSimulatingWrites() throws InterruptedException { writeSimulationStopped = true; if (writeSimulationThread != null) { writeSimulationThread.join(); } } } interface Expectation { /** * check if the expectation is fulfilled, return true if it is, return a * descriptive error msg if not **/ String fulfilled() throws Exception; } class ViewExpectation implements Expectation { private int[] activeIds = new int[0]; private int[] deactivatingIds = new int[0]; private int[] inactiveIds = new int[0]; private final SimplifiedInstance discoveryLiteCombo; private boolean isFinal = true; ViewExpectation(SimplifiedInstance discoveryLiteCombo) { this.discoveryLiteCombo = discoveryLiteCombo; } private int[] asIntArray(Integer[] arr) { int[] result = new int[arr.length]; for (int i = 0; i < arr.length; i++) { result[i] = arr[i]; } return result; } void setActiveIds(Integer[] activeIds) { this.activeIds = asIntArray(activeIds); } void setActiveIds(int... activeIds) { this.activeIds = activeIds; } void setDeactivatingIds(int... deactivatingIds) { this.deactivatingIds = deactivatingIds; } void setInactiveIds(Integer[] inactiveIds) { this.inactiveIds = asIntArray(inactiveIds); } void setInactiveIds(int... inaactiveIds) { this.inactiveIds = inaactiveIds; } @Override public String fulfilled() throws Exception { final String clusterViewStr = discoveryLiteCombo.getClusterViewStr(); if (clusterViewStr == null) { if (activeIds.length != 0) { return "no clusterView, but expected activeIds: " + beautify(activeIds); } if (deactivatingIds.length != 0) { return "no clusterView, but expected deactivatingIds: " + beautify(deactivatingIds); } if (inactiveIds.length != 0) { return "no clusterView, but expected inactiveIds: " + beautify(inactiveIds); } } if (!discoveryLiteCombo.hasActiveIds(clusterViewStr, activeIds)) { return "activeIds dont match, expected: " + beautify(activeIds) + ", got clusterView: " + clusterViewStr; } if (!discoveryLiteCombo.hasDeactivatingIds(clusterViewStr, deactivatingIds)) { return "deactivatingIds dont match, expected: " + beautify(deactivatingIds) + ", got clusterView: " + clusterViewStr; } if (!discoveryLiteCombo.hasInactiveIds(clusterViewStr, inactiveIds)) { return "inactiveIds dont match, expected: " + beautify(inactiveIds) + ", got clusterView: " + clusterViewStr; } if (!discoveryLiteCombo.isInvisible() && discoveryLiteCombo.isFinal() != isFinal) { return "final flag does not match. expected: " + isFinal + ", but is: " + discoveryLiteCombo.isFinal(); } return null; } private String beautify(int[] ids) { if (ids == null) { return ""; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < ids.length; i++) { if (i != 0) { sb.append(","); } sb.append(ids[i]); } return sb.toString(); } public void setFinal(boolean isFinal) { this.isFinal = isFinal; } } // private static final boolean MONGO_DB = true; private static final boolean MONGO_DB = false; static final int SEED = Integer.getInteger(BaseDocumentDiscoveryLiteServiceTest.class.getSimpleName() + "-seed", new Random().nextInt()); private List<DocumentMK> mks = new ArrayList<>(); private MemoryDocumentStore ds; private MemoryBlobStore bs; final Logger logger = LoggerFactory.getLogger(this.getClass()); private List<SimplifiedInstance> allInstances = new LinkedList<SimplifiedInstance>(); @Rule public TestRule logDumper = new LogDumper(50000); @Rule public TestRule logLevelModifier = new LogLevelModifier() .newConsoleAppender("console") .addAppenderFilter("console", "info") .addAppenderFilter("file", "info") .setLoggerLevel("org.apache.jackrabbit.oak", "debug"); // subsequent tests should get a DocumentDiscoveryLiteService setup from the // start DocumentNodeStore createNodeStore(String workingDir) throws SecurityException, Exception { return createNodeStore(workingDir, false); } // subsequent tests should get a DocumentDiscoveryLiteService setup from the // start DocumentNodeStore createNodeStore(String workingDir, boolean invisible) throws SecurityException, Exception { String prevWorkingDir = ClusterNodeInfo.WORKING_DIR; try { // ensure that we always get a fresh cluster[node]id ClusterNodeInfo.WORKING_DIR = workingDir; // then create the DocumentNodeStore DocumentMK mk1 = createMK( 0 /* to make sure the clusterNodes collection is used **/, 500, /* asyncDelay: background interval */ invisible /* cluster node invisibility */); logger.info("createNodeStore: created DocumentNodeStore with cid=" + mk1.nodeStore.getClusterId() + ", workingDir=" + workingDir); return mk1.nodeStore; } finally { ClusterNodeInfo.WORKING_DIR = prevWorkingDir; } } SimplifiedInstance createInstance() throws Exception { return createInstance(false); } SimplifiedInstance createInstance(boolean invisible) throws Exception { final String workingDir = UUID.randomUUID().toString(); return createInstance(workingDir, invisible); } SimplifiedInstance createInstance(String workingDir) throws SecurityException, Exception { return createInstance(workingDir, false); } SimplifiedInstance createInstance(String workingDir, boolean invisible) throws SecurityException, Exception { DocumentNodeStore ns = createNodeStore(workingDir, invisible); return createInstance(ns, workingDir); } SimplifiedInstance createInstance(DocumentNodeStore ns, String workingDir) throws NoSuchFieldException { DocumentDiscoveryLiteService discoveryLite = new DocumentDiscoveryLiteService(); PrivateAccessor.setField(discoveryLite, "nodeStore", ns); BundleContext bc = mock(BundleContext.class); ComponentContext c = mock(ComponentContext.class); when(c.getBundleContext()).thenReturn(bc); final Map<Object, Object> registeredServices = new HashMap(); when(bc.registerService(any(Class.class), any(Object.class), any())).then((Answer<ServiceRegistration>) invocation -> { registeredServices.put(invocation.getArguments()[0], invocation.getArguments()[1]); return null; }); discoveryLite.activate(c); Descriptors d = (Descriptors) registeredServices.get(Descriptors.class); final SimplifiedInstance result = new SimplifiedInstance(discoveryLite, ns, d, registeredServices, 500, workingDir); allInstances.add(result); logger.info("Created " + result); return result; } void waitFor(Expectation expectation, int timeout, String msg) throws Exception { final long tooLate = System.currentTimeMillis() + timeout; while (true) { final String fulfillmentResult = expectation.fulfilled(); if (fulfillmentResult == null) { // everything's fine return; } if (System.currentTimeMillis() > tooLate) { fail("expectation not fulfilled within " + timeout + "ms: " + msg + ", fulfillment result: " + fulfillmentResult); } Thread.sleep(100); } } void dumpChildren(DocumentNodeState root) { logger.info("testEmptyParentRecovery: root: " + root); Iterator<String> it = root.getChildNodeNames().iterator(); while (it.hasNext()) { String n = it.next(); logger.info("testEmptyParentRecovery: a child: '" + n + "'"); } } void checkFiestaState(final List<SimplifiedInstance> instances, Set<Integer> inactiveIds) throws Exception { final List<Integer> activeIds = new LinkedList<Integer>(); for (Iterator<SimplifiedInstance> it = instances.iterator(); it.hasNext();) { SimplifiedInstance anInstance = it.next(); if (!anInstance.isInvisible()) { activeIds.add(anInstance.ns.getClusterId()); } } logger.info("checkFiestaState: checking state. expected active: "+activeIds+", inactive: "+inactiveIds); for (Iterator<SimplifiedInstance> it = instances.iterator(); it.hasNext();) { SimplifiedInstance anInstance = it.next(); if (!anInstance.isInvisible()) { final ViewExpectation e = new ViewExpectation(anInstance); e.setActiveIds(activeIds.toArray(new Integer[activeIds.size()])); e.setInactiveIds(inactiveIds.toArray(new Integer[inactiveIds.size()])); waitFor(e, 60000, "checkFiestaState failed for " + anInstance + ", with instances: " + instances + "," + " and inactiveIds: " + inactiveIds); } } } @Before @After public void clear() { logger.info("clear: seed="+SEED); for (SimplifiedInstance i : allInstances) { i.dispose(); } for (DocumentMK mk : mks) { mk.dispose(); } mks.clear(); if (MONGO_DB) { MongoConnection connection = connectionFactory.getConnection(); if (connection != null) { MongoDatabase db = connection.getDatabase(); if (db != null) { MongoUtils.dropCollections(db); } } } } DocumentMK createMK(int clusterId, int asyncDelay) { return createMK(clusterId, asyncDelay, false); } DocumentMK createMK(int clusterId, int asyncDelay, boolean invisible) { if (MONGO_DB) { MongoConnection connection = connectionFactory.getConnection(); return register(new DocumentMK.Builder() .setMongoDB(connection.getMongoClient(), connection.getDBName()) .setLeaseCheckMode(LeaseCheckMode.DISABLED).setClusterId(clusterId) .setAsyncDelay(asyncDelay).open()); } else { if (ds == null) { ds = new MemoryDocumentStore(); } if (bs == null) { bs = new MemoryBlobStore(); } return createMK(clusterId, asyncDelay, ds, bs, invisible); } } DocumentMK createMK(int clusterId, int asyncDelay, DocumentStore ds, BlobStore bs, boolean invisible) { return register(new DocumentMK.Builder().setDocumentStore(ds).setBlobStore(bs).setClusterId(clusterId).setClusterInvisible(invisible) .setLeaseCheckMode(LeaseCheckMode.DISABLED) .setAsyncDelay(asyncDelay).open()); } DocumentMK register(DocumentMK mk) { mks.add(mk); return mk; } /** * Probability of invisible instance at 20% * @param random * @return */ boolean isInvisibleInstance(Random random) { boolean invisible = false; double invisibleProb = random.nextDouble(); if (invisibleProb <= 0.2) { invisible = true; } return invisible; } /** * This test creates a large number of documentnodestores which it starts, * runs, stops in a random fashion, always testing to make sure the * clusterView is correct */ void doStartStopFiesta(int loopCnt) throws Throwable { logger.info("testLargeStartStopFiesta: start, seed="+SEED); final List<SimplifiedInstance> instances = new LinkedList<SimplifiedInstance>(); final Map<Integer, String> inactiveIds = new HashMap<Integer, String>(); final Random random = new Random(SEED); final int CHECK_EVERY = 3; final int MAX_NUM_INSTANCES = 8; for (int i = 0; i < loopCnt; i++) { if (i % CHECK_EVERY == 0) { checkFiestaState(instances, inactiveIds.keySet()); } final int nextInt = random.nextInt(5); // logger.info("testLargeStartStopFiesta: iteration "+i+" with case // "+nextInt); String workingDir = UUID.randomUUID().toString(); switch (nextInt) { case 0: { // increase likelihood of creating instances.. // but reuse an inactive one if possible if (inactiveIds.size() > 0) { logger.info("Case 0 - reactivating an instance..."); final int n = random.nextInt(inactiveIds.size()); final Integer cid = new LinkedList<Integer>(inactiveIds.keySet()).get(n); final String reactivatedWorkingDir = inactiveIds.remove(cid); if (reactivatedWorkingDir == null) { fail("reactivatedWorkingDir null for n=" + n + ", cid=" + cid + ", other inactives: " + inactiveIds); } assertNotNull(reactivatedWorkingDir); logger.info("Case 0 - reactivated instance " + cid + ", workingDir=" + reactivatedWorkingDir); workingDir = reactivatedWorkingDir; logger.info("Case 0: creating instance"); final SimplifiedInstance newInstance = createInstance(workingDir, isInvisibleInstance(random)); newInstance.setLeastTimeout(5000, 1000); newInstance.startSimulatingWrites(500); logger.info("Case 0: created instance: " + newInstance.ns.getClusterId()); if (newInstance.ns.getClusterId() != cid) { logger.info( "Case 0: reactivated instance did not take over cid - probably a testing artifact. expected cid: {}, actual cid: {}", cid, newInstance.ns.getClusterId()); inactiveIds.put(cid, reactivatedWorkingDir); // remove the newly reactivated from the inactives - // although it shouldn't be there, it might! inactiveIds.remove(newInstance.ns.getClusterId()); } instances.add(newInstance); } break; } case 1: { // creates a new instance if (instances.size() < MAX_NUM_INSTANCES) { logger.info("Case 1: creating instance"); final SimplifiedInstance newInstance = createInstance(workingDir, isInvisibleInstance(random)); newInstance.setLeastTimeout(5000, 1000); newInstance.startSimulatingWrites(500); logger.info("Case 1: created instance: " + newInstance.ns.getClusterId()); instances.add(newInstance); // OAK-3292 : in case a previously crashed or shut-down instance is created again here // make sure to remove it from inactive (if it in the inactive list at all) inactiveIds.remove(newInstance.ns.getClusterId()); } break; } case 2: { // do nothing break; } case 3: { // shutdown instance if (instances.size() > 1) { // before shutting down: make sure we have a stable view // (we could otherwise not correctly startup too) checkFiestaState(instances, inactiveIds.keySet()); final SimplifiedInstance instance = instances.remove(random.nextInt(instances.size())); assertNotNull(instance.workingDir); logger.info("Case 3: Shutdown instance: " + instance.ns.getClusterId()); inactiveIds.put(instance.ns.getClusterId(), instance.workingDir); instance.shutdown(); } break; } case 4: { // crash instance if (instances.size() > 1) { // before crashing make sure we have a stable view (we // could otherwise not correctly startup too) checkFiestaState(instances, inactiveIds.keySet()); final SimplifiedInstance instance = instances.remove(random.nextInt(instances.size())); assertNotNull(instance.workingDir); logger.info("Case 4: Crashing instance: " + instance.ns.getClusterId()); if (!instance.isInvisible()) { inactiveIds.put(instance.ns.getClusterId(), instance.workingDir); } instance.addNode("/" + instance.ns.getClusterId() + "/stuffForRecovery/" + random.nextInt(10000)); instance.crash(); } break; } } } } }
googleapis/google-cloud-java
37,432
java-admanager/proto-ad-manager-v1/src/main/java/com/google/ads/admanager/v1/UpdateEntitySignalsMappingRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/admanager/v1/entity_signals_mapping_service.proto // Protobuf Java Version: 3.25.8 package com.google.ads.admanager.v1; /** * * * <pre> * Request object for 'UpdateEntitySignalsMapping' method. * </pre> * * Protobuf type {@code google.ads.admanager.v1.UpdateEntitySignalsMappingRequest} */ public final class UpdateEntitySignalsMappingRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.admanager.v1.UpdateEntitySignalsMappingRequest) UpdateEntitySignalsMappingRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateEntitySignalsMappingRequest.newBuilder() to construct. private UpdateEntitySignalsMappingRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateEntitySignalsMappingRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateEntitySignalsMappingRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.admanager.v1.EntitySignalsMappingServiceProto .internal_static_google_ads_admanager_v1_UpdateEntitySignalsMappingRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.admanager.v1.EntitySignalsMappingServiceProto .internal_static_google_ads_admanager_v1_UpdateEntitySignalsMappingRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest.class, com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest.Builder.class); } private int bitField0_; public static final int ENTITY_SIGNALS_MAPPING_FIELD_NUMBER = 1; private com.google.ads.admanager.v1.EntitySignalsMapping entitySignalsMapping_; /** * * * <pre> * Required. The `EntitySignalsMapping` to update. * * The EntitySignalsMapping's name is used to identify the * EntitySignalsMapping to update. * Format: * `networks/{network_code}/entitySignalsMappings/{entity_signals_mapping}` * </pre> * * <code> * .google.ads.admanager.v1.EntitySignalsMapping entity_signals_mapping = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the entitySignalsMapping field is set. */ @java.lang.Override public boolean hasEntitySignalsMapping() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The `EntitySignalsMapping` to update. * * The EntitySignalsMapping's name is used to identify the * EntitySignalsMapping to update. * Format: * `networks/{network_code}/entitySignalsMappings/{entity_signals_mapping}` * </pre> * * <code> * .google.ads.admanager.v1.EntitySignalsMapping entity_signals_mapping = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The entitySignalsMapping. */ @java.lang.Override public com.google.ads.admanager.v1.EntitySignalsMapping getEntitySignalsMapping() { return entitySignalsMapping_ == null ? com.google.ads.admanager.v1.EntitySignalsMapping.getDefaultInstance() : entitySignalsMapping_; } /** * * * <pre> * Required. The `EntitySignalsMapping` to update. * * The EntitySignalsMapping's name is used to identify the * EntitySignalsMapping to update. * Format: * `networks/{network_code}/entitySignalsMappings/{entity_signals_mapping}` * </pre> * * <code> * .google.ads.admanager.v1.EntitySignalsMapping entity_signals_mapping = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.ads.admanager.v1.EntitySignalsMappingOrBuilder getEntitySignalsMappingOrBuilder() { return entitySignalsMapping_ == null ? com.google.ads.admanager.v1.EntitySignalsMapping.getDefaultInstance() : entitySignalsMapping_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. The list 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. The list 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. The list 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_; } 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, getEntitySignalsMapping()); } 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, getEntitySignalsMapping()); } 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.ads.admanager.v1.UpdateEntitySignalsMappingRequest)) { return super.equals(obj); } com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest other = (com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest) obj; if (hasEntitySignalsMapping() != other.hasEntitySignalsMapping()) return false; if (hasEntitySignalsMapping()) { if (!getEntitySignalsMapping().equals(other.getEntitySignalsMapping())) 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 (hasEntitySignalsMapping()) { hash = (37 * hash) + ENTITY_SIGNALS_MAPPING_FIELD_NUMBER; hash = (53 * hash) + getEntitySignalsMapping().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.ads.admanager.v1.UpdateEntitySignalsMappingRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest 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 object for 'UpdateEntitySignalsMapping' method. * </pre> * * Protobuf type {@code google.ads.admanager.v1.UpdateEntitySignalsMappingRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.admanager.v1.UpdateEntitySignalsMappingRequest) com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.admanager.v1.EntitySignalsMappingServiceProto .internal_static_google_ads_admanager_v1_UpdateEntitySignalsMappingRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.admanager.v1.EntitySignalsMappingServiceProto .internal_static_google_ads_admanager_v1_UpdateEntitySignalsMappingRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest.class, com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest.Builder.class); } // Construct using com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getEntitySignalsMappingFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; entitySignalsMapping_ = null; if (entitySignalsMappingBuilder_ != null) { entitySignalsMappingBuilder_.dispose(); entitySignalsMappingBuilder_ = 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.ads.admanager.v1.EntitySignalsMappingServiceProto .internal_static_google_ads_admanager_v1_UpdateEntitySignalsMappingRequest_descriptor; } @java.lang.Override public com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest getDefaultInstanceForType() { return com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest.getDefaultInstance(); } @java.lang.Override public com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest build() { com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest buildPartial() { com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest result = new com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.entitySignalsMapping_ = entitySignalsMappingBuilder_ == null ? entitySignalsMapping_ : entitySignalsMappingBuilder_.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.ads.admanager.v1.UpdateEntitySignalsMappingRequest) { return mergeFrom((com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest other) { if (other == com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest.getDefaultInstance()) return this; if (other.hasEntitySignalsMapping()) { mergeEntitySignalsMapping(other.getEntitySignalsMapping()); } 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( getEntitySignalsMappingFieldBuilder().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.ads.admanager.v1.EntitySignalsMapping entitySignalsMapping_; private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.admanager.v1.EntitySignalsMapping, com.google.ads.admanager.v1.EntitySignalsMapping.Builder, com.google.ads.admanager.v1.EntitySignalsMappingOrBuilder> entitySignalsMappingBuilder_; /** * * * <pre> * Required. The `EntitySignalsMapping` to update. * * The EntitySignalsMapping's name is used to identify the * EntitySignalsMapping to update. * Format: * `networks/{network_code}/entitySignalsMappings/{entity_signals_mapping}` * </pre> * * <code> * .google.ads.admanager.v1.EntitySignalsMapping entity_signals_mapping = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the entitySignalsMapping field is set. */ public boolean hasEntitySignalsMapping() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The `EntitySignalsMapping` to update. * * The EntitySignalsMapping's name is used to identify the * EntitySignalsMapping to update. * Format: * `networks/{network_code}/entitySignalsMappings/{entity_signals_mapping}` * </pre> * * <code> * .google.ads.admanager.v1.EntitySignalsMapping entity_signals_mapping = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The entitySignalsMapping. */ public com.google.ads.admanager.v1.EntitySignalsMapping getEntitySignalsMapping() { if (entitySignalsMappingBuilder_ == null) { return entitySignalsMapping_ == null ? com.google.ads.admanager.v1.EntitySignalsMapping.getDefaultInstance() : entitySignalsMapping_; } else { return entitySignalsMappingBuilder_.getMessage(); } } /** * * * <pre> * Required. The `EntitySignalsMapping` to update. * * The EntitySignalsMapping's name is used to identify the * EntitySignalsMapping to update. * Format: * `networks/{network_code}/entitySignalsMappings/{entity_signals_mapping}` * </pre> * * <code> * .google.ads.admanager.v1.EntitySignalsMapping entity_signals_mapping = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setEntitySignalsMapping(com.google.ads.admanager.v1.EntitySignalsMapping value) { if (entitySignalsMappingBuilder_ == null) { if (value == null) { throw new NullPointerException(); } entitySignalsMapping_ = value; } else { entitySignalsMappingBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The `EntitySignalsMapping` to update. * * The EntitySignalsMapping's name is used to identify the * EntitySignalsMapping to update. * Format: * `networks/{network_code}/entitySignalsMappings/{entity_signals_mapping}` * </pre> * * <code> * .google.ads.admanager.v1.EntitySignalsMapping entity_signals_mapping = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setEntitySignalsMapping( com.google.ads.admanager.v1.EntitySignalsMapping.Builder builderForValue) { if (entitySignalsMappingBuilder_ == null) { entitySignalsMapping_ = builderForValue.build(); } else { entitySignalsMappingBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The `EntitySignalsMapping` to update. * * The EntitySignalsMapping's name is used to identify the * EntitySignalsMapping to update. * Format: * `networks/{network_code}/entitySignalsMappings/{entity_signals_mapping}` * </pre> * * <code> * .google.ads.admanager.v1.EntitySignalsMapping entity_signals_mapping = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeEntitySignalsMapping( com.google.ads.admanager.v1.EntitySignalsMapping value) { if (entitySignalsMappingBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && entitySignalsMapping_ != null && entitySignalsMapping_ != com.google.ads.admanager.v1.EntitySignalsMapping.getDefaultInstance()) { getEntitySignalsMappingBuilder().mergeFrom(value); } else { entitySignalsMapping_ = value; } } else { entitySignalsMappingBuilder_.mergeFrom(value); } if (entitySignalsMapping_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The `EntitySignalsMapping` to update. * * The EntitySignalsMapping's name is used to identify the * EntitySignalsMapping to update. * Format: * `networks/{network_code}/entitySignalsMappings/{entity_signals_mapping}` * </pre> * * <code> * .google.ads.admanager.v1.EntitySignalsMapping entity_signals_mapping = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearEntitySignalsMapping() { bitField0_ = (bitField0_ & ~0x00000001); entitySignalsMapping_ = null; if (entitySignalsMappingBuilder_ != null) { entitySignalsMappingBuilder_.dispose(); entitySignalsMappingBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The `EntitySignalsMapping` to update. * * The EntitySignalsMapping's name is used to identify the * EntitySignalsMapping to update. * Format: * `networks/{network_code}/entitySignalsMappings/{entity_signals_mapping}` * </pre> * * <code> * .google.ads.admanager.v1.EntitySignalsMapping entity_signals_mapping = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.ads.admanager.v1.EntitySignalsMapping.Builder getEntitySignalsMappingBuilder() { bitField0_ |= 0x00000001; onChanged(); return getEntitySignalsMappingFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The `EntitySignalsMapping` to update. * * The EntitySignalsMapping's name is used to identify the * EntitySignalsMapping to update. * Format: * `networks/{network_code}/entitySignalsMappings/{entity_signals_mapping}` * </pre> * * <code> * .google.ads.admanager.v1.EntitySignalsMapping entity_signals_mapping = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.ads.admanager.v1.EntitySignalsMappingOrBuilder getEntitySignalsMappingOrBuilder() { if (entitySignalsMappingBuilder_ != null) { return entitySignalsMappingBuilder_.getMessageOrBuilder(); } else { return entitySignalsMapping_ == null ? com.google.ads.admanager.v1.EntitySignalsMapping.getDefaultInstance() : entitySignalsMapping_; } } /** * * * <pre> * Required. The `EntitySignalsMapping` to update. * * The EntitySignalsMapping's name is used to identify the * EntitySignalsMapping to update. * Format: * `networks/{network_code}/entitySignalsMappings/{entity_signals_mapping}` * </pre> * * <code> * .google.ads.admanager.v1.EntitySignalsMapping entity_signals_mapping = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.admanager.v1.EntitySignalsMapping, com.google.ads.admanager.v1.EntitySignalsMapping.Builder, com.google.ads.admanager.v1.EntitySignalsMappingOrBuilder> getEntitySignalsMappingFieldBuilder() { if (entitySignalsMappingBuilder_ == null) { entitySignalsMappingBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.ads.admanager.v1.EntitySignalsMapping, com.google.ads.admanager.v1.EntitySignalsMapping.Builder, com.google.ads.admanager.v1.EntitySignalsMappingOrBuilder>( getEntitySignalsMapping(), getParentForChildren(), isClean()); entitySignalsMapping_ = null; } return entitySignalsMappingBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Required. The list of fields to 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 list 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. The list 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. The list 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. The list 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. The list 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. The list 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. The list 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. The list 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_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.admanager.v1.UpdateEntitySignalsMappingRequest) } // @@protoc_insertion_point(class_scope:google.ads.admanager.v1.UpdateEntitySignalsMappingRequest) private static final com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest(); } public static com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateEntitySignalsMappingRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateEntitySignalsMappingRequest>() { @java.lang.Override public UpdateEntitySignalsMappingRequest 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<UpdateEntitySignalsMappingRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateEntitySignalsMappingRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.admanager.v1.UpdateEntitySignalsMappingRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/phoenix
37,558
phoenix-core-server/src/main/java/org/apache/phoenix/mapreduce/util/PhoenixConfigurationUtil.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.mapreduce.util; import static org.apache.commons.lang3.StringUtils.isNotEmpty; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.Base64; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.db.DBInputFormat.NullDBWritable; import org.apache.hadoop.mapreduce.lib.db.DBWritable; import org.apache.hadoop.util.ReflectionUtils; import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.mapreduce.FormatToBytesWritableMapper; import org.apache.phoenix.mapreduce.ImportPreUpsertKeyValueProcessor; import org.apache.phoenix.mapreduce.index.IndexScrutinyTool; import org.apache.phoenix.mapreduce.index.IndexScrutinyTool.OutputFormat; import org.apache.phoenix.mapreduce.index.IndexScrutinyTool.SourceTable; import org.apache.phoenix.mapreduce.index.IndexTool; import org.apache.phoenix.query.QueryServices; import org.apache.phoenix.util.ColumnInfo; import org.apache.phoenix.util.PhoenixRuntime; import org.apache.phoenix.util.QueryUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.phoenix.thirdparty.com.google.common.base.Joiner; import org.apache.phoenix.thirdparty.com.google.common.base.Preconditions; import org.apache.phoenix.thirdparty.com.google.common.collect.Lists; /** * A utility class to set properties on the {#link Configuration} instance. Used as part of Map * Reduce job configuration. */ public final class PhoenixConfigurationUtil { private static final Logger LOGGER = LoggerFactory.getLogger(PhoenixConfigurationUtil.class); public static final String SESSION_ID = "phoenix.sessionid"; public static final String UPSERT_STATEMENT = "phoenix.upsert.stmt"; public static final String SELECT_STATEMENT = "phoenix.select.stmt"; public static final String UPSERT_BATCH_SIZE = "phoenix.upsert.batch.size"; public static final String SCHEMA_TYPE = "phoenix.select.schema.type"; public static final String MAPREDUCE_SELECT_COLUMN_VALUE_PREFIX = "phoenix.mr.select.column.value"; public static final String MAPREDUCE_SELECT_COLUMN_COUNT = "phoenix.mr.select.column.count"; public static final String MAPREDUCE_UPSERT_COLUMN_VALUE_PREFIX = "phoenix.mr.upsert.column.value"; public static final String MAPREDUCE_UPSERT_COLUMN_COUNT = "phoenix.mr.upsert.column.count"; public static final String INPUT_TABLE_NAME = "phoenix.input.table.name"; public static final String OUTPUT_TABLE_NAME = "phoenix.colinfo.table.name"; public static final String INPUT_TABLE_CONDITIONS = "phoenix.input.table.conditions"; /** For local indexes which are stored in a single separate physical table */ public static final String PHYSICAL_TABLE_NAME = "phoenix.output.table.name"; public static final String TRANSFORM_RETRY_COUNT_VALUE = "phoenix.transform.retry.count"; public static final int DEFAULT_TRANSFORM_RETRY_COUNT = 50; public static final long DEFAULT_UPSERT_BATCH_SIZE = 1000; public static final String INPUT_CLASS = "phoenix.input.class"; public static final String CURRENT_SCN_VALUE = "phoenix.mr.currentscn.value"; public static final String TX_SCN_VALUE = "phoenix.mr.txscn.value"; public static final String TX_PROVIDER = "phoenix.mr.txprovider"; /** Configuration key for the class name of an ImportPreUpsertKeyValueProcessor */ public static final String UPSERT_HOOK_CLASS_CONFKEY = "phoenix.mapreduce.import.kvprocessor"; public static final String INDEX_DISABLED_TIMESTAMP_VALUE = "phoenix.mr.index.disableTimestamp"; public static final String INDEX_MAINTAINERS = "phoenix.mr.index.maintainers"; public static final String SCRUTINY_DATA_TABLE_NAME = "phoenix.mr.scrutiny.data.table.name"; public static final String SCRUTINY_INDEX_TABLE_NAME = "phoenix.mr.scrutiny.index.table.name"; public static final String INDEX_TOOL_DATA_TABLE_NAME = "phoenix.mr.index_tool.data.table.name"; public static final String INDEX_TOOL_INDEX_TABLE_NAME = "phoenix.mr.index_tool.index.table.name"; public static final String INDEX_TOOL_SOURCE_TABLE = "phoenix.mr.index_tool.source.table"; public static final String SCRUTINY_SOURCE_TABLE = "phoenix.mr.scrutiny.source.table"; public static final String SCRUTINY_BATCH_SIZE = "phoenix.mr.scrutiny.batch.size"; public static final String SCRUTINY_OUTPUT_INVALID_ROWS = "phoenix.mr.scrutiny.output.invalid.rows"; public static final boolean DEFAULT_SCRUTINY_OUTPUT_INVALID_ROWS = false; public static final String SHOULD_FIX_UNVERIFIED_TRANSFORM = "phoenix.mr.fix.unverified.transform"; public static final boolean DEFAULT_SHOULD_FIX_UNVERIFIED_TRANSFORM = false; public static final String SCRUTINY_OUTPUT_FORMAT = "phoenix.mr.scrutiny.output.format"; public static final String SCRUTINY_EXECUTE_TIMESTAMP = "phoenix.mr.scrutiny.execute.timestamp"; // max output rows per mapper public static final String SCRUTINY_OUTPUT_MAX = "phoenix.mr.scrutiny.output.max"; public static final long DEFAULT_SCRUTINY_BATCH_SIZE = 1000; public static final String DISABLED_INDEXES = "phoenix.mr.index.disabledIndexes"; public static final String VERIFY_INDEX = "phoenix.mr.index.verifyIndex"; public static final String ONLY_VERIFY_INDEX = "phoenix.mr.index.onlyVerifyIndex"; public static final String INDEX_VERIFY_TYPE = "phoenix.mr.index.IndexVerifyType"; public static final String DISABLE_LOGGING_TYPE = "phoenix.mr.index" + ".IndexDisableLoggingType"; // Generate splits based on scans from stats, or just from region splits public static final String MAPREDUCE_SPLIT_BY_STATS = "phoenix.mapreduce.split.by.stats"; public static final boolean DEFAULT_SPLIT_BY_STATS = true; public static final String SNAPSHOT_NAME_KEY = "phoenix.mapreduce.snapshot.name"; public static final String RESTORE_DIR_KEY = "phoenix.tableSnapshot.restore.dir"; public static final String MAPREDUCE_TENANT_ID = "phoenix.mapreduce.tenantid"; private static final String INDEX_TOOL_END_TIME = "phoenix.mr.index.endtime"; private static final String INDEX_TOOL_START_TIME = "phoenix.mr.index.starttime"; private static final String INDEX_TOOL_LAST_VERIFY_TIME = "phoenix.mr.index.last.verify.time"; public static final String MAPREDUCE_JOB_TYPE = "phoenix.mapreduce.jobtype"; // provide control to whether or not handle mapreduce snapshot restore and cleanup operations // which // is used by scanners on phoenix side internally or handled by caller externally public static final String MAPREDUCE_EXTERNAL_SNAPSHOT_RESTORE = "phoenix.mapreduce.external.snapshot.restore"; // by default MR snapshot restore is handled internally by phoenix public static final boolean DEFAULT_MAPREDUCE_EXTERNAL_SNAPSHOT_RESTORE = false; // Is the mapreduce used for table/index transform public static final String IS_TRANSFORMING_VALUE = "phoenix.mr.istransforming"; // Is force transform cutover public static final String FORCE_CUTOVER_VALUE = "phoenix.mr.force.cutover"; // Is the mapreduce used for table/index transform public static final String TRANSFORMING_TABLE_TYPE = "phoenix.mr.transform.tabletype"; public static final String IS_PARTIAL_TRANSFORM = "phoenix.mr.transform.ispartial"; // Randomize mapper execution order public static final String MAPREDUCE_RANDOMIZE_MAPPER_EXECUTION_ORDER = "phoenix.mapreduce.randomize.mapper.execution.order"; // non-index jobs benefit less from this public static final boolean DEFAULT_MAPREDUCE_RANDOMIZE_MAPPER_EXECUTION_ORDER = false; /** * Determines type of Phoenix Map Reduce job. 1. QUERY allows running arbitrary queries without * aggregates 2. UPDATE_STATS collects statistics for the table */ public enum MRJobType { QUERY, UPDATE_STATS } public enum SchemaType { TABLE, QUERY } private PhoenixConfigurationUtil() { } /** * */ public static void setInputTableName(final Configuration configuration, final String tableName) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(tableName); configuration.set(INPUT_TABLE_NAME, tableName); } public static void setInputTableConditions(final Configuration configuration, final String conditions) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(conditions); configuration.set(INPUT_TABLE_CONDITIONS, conditions); } private static void setValues(final Configuration configuration, final String[] columns, final String VALUE_COUNT, final String VALUE_NAME) { Preconditions.checkNotNull(configuration); configuration.setInt(VALUE_COUNT, columns.length); for (int i = 0; i < columns.length; ++i) { configuration.set(String.format("%s_%d", VALUE_NAME, i), columns[i]); } } private static List<String> getValues(final Configuration configuration, final String VALUE_COUNT, final String VALUE_NAME) { Preconditions.checkNotNull(configuration); int numCols = configuration.getInt(VALUE_COUNT, 0); List<String> cols = Lists.newArrayListWithExpectedSize(numCols); for (int i = 0; i < numCols; ++i) { cols.add(configuration.get(String.format("%s_%d", VALUE_NAME, i))); } return cols; } public static void setSelectColumnNames(final Configuration configuration, final String[] columns) { setValues(configuration, columns, MAPREDUCE_SELECT_COLUMN_COUNT, MAPREDUCE_SELECT_COLUMN_VALUE_PREFIX); } public static List<String> getSelectColumnNames(final Configuration configuration) { return getValues(configuration, MAPREDUCE_SELECT_COLUMN_COUNT, MAPREDUCE_SELECT_COLUMN_VALUE_PREFIX); } public static void setInputClass(final Configuration configuration, Class<? extends DBWritable> inputClass) { Preconditions.checkNotNull(configuration); configuration.setClass(INPUT_CLASS, inputClass, DBWritable.class); } public static void setInputQuery(final Configuration configuration, final String inputQuery) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(inputQuery); configuration.set(SELECT_STATEMENT, inputQuery); } public static void setPropertyPolicyProviderDisabled(final Configuration configuration) { Preconditions.checkNotNull(configuration); configuration.set(QueryServices.PROPERTY_POLICY_PROVIDER_ENABLED, "false"); } public static void setSchemaType(Configuration configuration, final SchemaType schemaType) { Preconditions.checkNotNull(configuration); configuration.set(SCHEMA_TYPE, schemaType.name()); } public static void setMRJobType(Configuration configuration, final MRJobType mrJobType) { Preconditions.checkNotNull(configuration); configuration.set(MAPREDUCE_JOB_TYPE, mrJobType.name()); } public static void setPhysicalTableName(final Configuration configuration, final String tableName) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(tableName); configuration.set(PHYSICAL_TABLE_NAME, tableName); } public static void setOutputTableName(final Configuration configuration, final String tableName) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(tableName); configuration.set(OUTPUT_TABLE_NAME, tableName); } public static void setUpsertColumnNames(final Configuration configuration, final String[] columns) { setValues(configuration, columns, MAPREDUCE_UPSERT_COLUMN_COUNT, MAPREDUCE_UPSERT_COLUMN_VALUE_PREFIX); } public static void setSnapshotNameKey(final Configuration configuration, final String snapshotName) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(snapshotName); configuration.set(SNAPSHOT_NAME_KEY, snapshotName); } public static void setRestoreDirKey(final Configuration configuration, final String restoreDir) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(restoreDir); configuration.set(RESTORE_DIR_KEY, restoreDir); } public static void setIndexToolStartTime(Configuration configuration, Long startTime) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(startTime); configuration.set(INDEX_TOOL_START_TIME, Long.toString(startTime)); } public static void setIndexToolLastVerifyTime(Configuration configuration, Long lastVerifyTime) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(lastVerifyTime); configuration.set(INDEX_TOOL_LAST_VERIFY_TIME, Long.toString(lastVerifyTime)); } public static void setCurrentScnValue(Configuration configuration, Long scn) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(scn); configuration.set(CURRENT_SCN_VALUE, Long.toString(scn)); } public static String getIndexToolStartTime(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.get(INDEX_TOOL_START_TIME); } public static String getCurrentScnValue(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.get(CURRENT_SCN_VALUE); } public static String getIndexToolLastVerifyTime(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.get(INDEX_TOOL_LAST_VERIFY_TIME); } public static List<String> getUpsertColumnNames(final Configuration configuration) { return getValues(configuration, MAPREDUCE_UPSERT_COLUMN_COUNT, MAPREDUCE_UPSERT_COLUMN_VALUE_PREFIX); } public static void setBatchSize(final Configuration configuration, final Long batchSize) { Preconditions.checkNotNull(configuration); configuration.setLong(UPSERT_BATCH_SIZE, batchSize); } /** * Sets which HBase cluster a Phoenix MapReduce job should read from * @param quorum ZooKeeper quorum string for HBase cluster the MapReduce job will read from */ @Deprecated public static void setInputCluster(final Configuration configuration, final String quorum) { Preconditions.checkNotNull(configuration); configuration.set(PhoenixConfigurationUtilHelper.MAPREDUCE_INPUT_CLUSTER_QUORUM, quorum); } /** * Sets which HBase cluster a Phoenix MapReduce job should write to * @param quorum ZooKeeper quorum string for HBase cluster the MapReduce job will write to */ @Deprecated public static void setOutputCluster(final Configuration configuration, final String quorum) { Preconditions.checkNotNull(configuration); configuration.set(PhoenixConfigurationUtilHelper.MAPREDUCE_OUTPUT_CLUSTER_QUORUM, quorum); } /** * Sets which HBase cluster a Phoenix MapReduce job should read from * @param url Phoenix JDBC URL */ public static void setInputClusterUrl(final Configuration configuration, final String url) { Preconditions.checkNotNull(configuration); configuration.set(PhoenixConfigurationUtilHelper.MAPREDUCE_INPUT_CLUSTER_URL, url); } /** * Sets which HBase cluster a Phoenix MapReduce job should write to * @param url Phoenix JDBC URL string for HBase cluster the MapReduce job will write to */ public static void setOutputClusterUrl(final Configuration configuration, final String url) { Preconditions.checkNotNull(configuration); configuration.set(PhoenixConfigurationUtilHelper.MAPREDUCE_OUTPUT_CLUSTER_URL, url); } public static Class<?> getInputClass(final Configuration configuration) { return configuration.getClass(INPUT_CLASS, NullDBWritable.class); } public static SchemaType getSchemaType(final Configuration configuration) { final String schemaTp = configuration.get(SCHEMA_TYPE); Preconditions.checkNotNull(schemaTp); return SchemaType.valueOf(schemaTp); } public static MRJobType getMRJobType(final Configuration configuration, String defaultMRJobType) { final String mrJobType = configuration.get(MAPREDUCE_JOB_TYPE, defaultMRJobType); Preconditions.checkNotNull(mrJobType); return MRJobType.valueOf(mrJobType); } public static List<ColumnInfo> getUpsertColumnMetadataList(final Configuration configuration) throws SQLException { Preconditions.checkNotNull(configuration); List<ColumnInfo> columnMetadataList = null; columnMetadataList = ColumnInfoToStringEncoderDecoder.decode(configuration); if (columnMetadataList != null && !columnMetadataList.isEmpty()) { return columnMetadataList; } final String tableName = getOutputTableName(configuration); Preconditions.checkNotNull(tableName); try (PhoenixConnection connection = ConnectionUtil.getOutputConnection(configuration).unwrap(PhoenixConnection.class)) { List<String> upsertColumnList = PhoenixConfigurationUtil.getUpsertColumnNames(configuration); if (!upsertColumnList.isEmpty()) { LOGGER.info(String.format( "UseUpsertColumns=%s, upsertColumnList.size()=%s," + " upsertColumnList=%s ", !upsertColumnList.isEmpty(), upsertColumnList.size(), Joiner.on(",").join(upsertColumnList))); } columnMetadataList = PhoenixRuntime.generateColumnInfo(connection, tableName, upsertColumnList); // we put the encoded column infos in the Configuration for re usability. ColumnInfoToStringEncoderDecoder.encode(configuration, columnMetadataList); } return columnMetadataList; } public static String getUpsertStatement(final Configuration configuration) throws SQLException { Preconditions.checkNotNull(configuration); String upsertStmt = configuration.get(UPSERT_STATEMENT); if (isNotEmpty(upsertStmt)) { return upsertStmt; } final String tableName = getOutputTableName(configuration); Preconditions.checkNotNull(tableName); List<String> upsertColumnNames = PhoenixConfigurationUtil.getUpsertColumnNames(configuration); final List<ColumnInfo> columnMetadataList = getUpsertColumnMetadataList(configuration); if (!upsertColumnNames.isEmpty()) { // Generating UPSERT statement without column name information. upsertStmt = QueryUtil.constructUpsertStatement(tableName, columnMetadataList); LOGGER.info("Phoenix Custom Upsert Statement: " + upsertStmt); } else { // Generating UPSERT statement without column name information. upsertStmt = QueryUtil.constructGenericUpsertStatement(tableName, columnMetadataList.size()); LOGGER.info("Phoenix Generic Upsert Statement: " + upsertStmt); } configuration.set(UPSERT_STATEMENT, upsertStmt); return upsertStmt; } public static void setUpsertStatement(final Configuration configuration, String upsertStmt) throws SQLException { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(upsertStmt); configuration.set(UPSERT_STATEMENT, upsertStmt); } public static List<ColumnInfo> getSelectColumnMetadataList(final Configuration configuration) throws SQLException { Preconditions.checkNotNull(configuration); List<ColumnInfo> columnMetadataList = null; columnMetadataList = ColumnInfoToStringEncoderDecoder.decode(configuration); if (columnMetadataList != null && !columnMetadataList.isEmpty()) { return columnMetadataList; } final String tableName = getInputTableName(configuration); Preconditions.checkNotNull(tableName); Properties props = new Properties(); String tenantId = configuration.get(PhoenixConfigurationUtil.MAPREDUCE_TENANT_ID); if (tenantId != null) { props.setProperty(PhoenixRuntime.TENANT_ID_ATTRIB, tenantId); } try (PhoenixConnection connection = ConnectionUtil.getInputConnection(configuration, props).unwrap(PhoenixConnection.class)) { final List<String> selectColumnList = getSelectColumnList(configuration); columnMetadataList = PhoenixRuntime.generateColumnInfo(connection, tableName, selectColumnList); // we put the encoded column infos in the Configuration for re usability. ColumnInfoToStringEncoderDecoder.encode(configuration, columnMetadataList); } return columnMetadataList; } private static List<String> getSelectColumnList(final Configuration configuration) { List<String> selectColumnList = PhoenixConfigurationUtil.getSelectColumnNames(configuration); if (!selectColumnList.isEmpty()) { LOGGER.info( String.format("UseSelectColumns=%s, selectColumnList.size()=%s, " + "selectColumnList=%s ", !selectColumnList.isEmpty(), selectColumnList.size(), Joiner.on(",").join(selectColumnList))); } return selectColumnList; } public static String getSelectStatement(final Configuration configuration) throws SQLException { Preconditions.checkNotNull(configuration); String selectStmt = configuration.get(SELECT_STATEMENT); if (isNotEmpty(selectStmt)) { LOGGER.info("Select Statement: " + selectStmt); return selectStmt; } final String tableName = getInputTableName(configuration); Preconditions.checkNotNull(tableName); final List<ColumnInfo> columnMetadataList = getSelectColumnMetadataList(configuration); final String conditions = configuration.get(INPUT_TABLE_CONDITIONS); LOGGER.info("Building select statement from input conditions: " + conditions); selectStmt = QueryUtil.constructSelectStatement(tableName, columnMetadataList, conditions); LOGGER.info("Select Statement: " + selectStmt); configuration.set(SELECT_STATEMENT, selectStmt); return selectStmt; } public static long getBatchSize(final Configuration configuration) throws SQLException { Preconditions.checkNotNull(configuration); long batchSize = configuration.getLong(UPSERT_BATCH_SIZE, DEFAULT_UPSERT_BATCH_SIZE); if (batchSize <= 0) { try (Connection conn = ConnectionUtil.getOutputConnection(configuration)) { batchSize = ((PhoenixConnection) conn).getMutateBatchSize(); } } configuration.setLong(UPSERT_BATCH_SIZE, batchSize); return batchSize; } public static int getSelectColumnsCount(Configuration configuration, String tableName) throws SQLException { Preconditions.checkNotNull(configuration); final String schemaTp = configuration.get(SCHEMA_TYPE); final SchemaType schemaType = SchemaType.valueOf(schemaTp); int count = 0; if (SchemaType.QUERY.equals(schemaType)) { List<String> selectedColumnList = getSelectColumnList(configuration); count = selectedColumnList == null ? 0 : selectedColumnList.size(); } else { List<ColumnInfo> columnInfos = getSelectColumnMetadataList(configuration); count = columnInfos == null ? 0 : columnInfos.size(); } return count; } public static String getInputTableName(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.get(INPUT_TABLE_NAME); } public static String getPhysicalTableName(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.get(PHYSICAL_TABLE_NAME); } public static String getOutputTableName(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.get(OUTPUT_TABLE_NAME); } public static void setIsTransforming(Configuration configuration, Boolean isTransforming) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(isTransforming); configuration.set(IS_TRANSFORMING_VALUE, Boolean.toString(isTransforming)); } public static Boolean getIsTransforming(Configuration configuration) { Preconditions.checkNotNull(configuration); return Boolean.valueOf(configuration.get(IS_TRANSFORMING_VALUE, "false")); } public static void setForceCutover(Configuration configuration, Boolean forceCutover) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(forceCutover); configuration.set(FORCE_CUTOVER_VALUE, Boolean.toString(forceCutover)); } public static Boolean getForceCutover(Configuration configuration) { Preconditions.checkNotNull(configuration); return Boolean.valueOf(configuration.get(FORCE_CUTOVER_VALUE, "false")); } public static void setTransformingTableType(Configuration configuration, SourceTable sourceTable) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(sourceTable); configuration.set(TRANSFORMING_TABLE_TYPE, sourceTable.name()); } public static SourceTable getTransformingTableType(Configuration configuration) { Preconditions.checkNotNull(configuration); return SourceTable.valueOf(configuration.get(TRANSFORMING_TABLE_TYPE)); } public static void setIsPartialTransform(final Configuration configuration, Boolean partialTransform) throws SQLException { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(partialTransform); configuration.set(IS_PARTIAL_TRANSFORM, String.valueOf(partialTransform)); } public static boolean getIsPartialTransform(final Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.getBoolean(IS_PARTIAL_TRANSFORM, false); } public static void loadHBaseConfiguration(Job job) throws IOException { // load hbase-site.xml Configuration hbaseConf = HBaseConfiguration.create(); for (Map.Entry<String, String> entry : hbaseConf) { if (job.getConfiguration().get(entry.getKey()) == null) { job.getConfiguration().set(entry.getKey(), entry.getValue()); } } // In order to have phoenix working on a secured cluster TableMapReduceUtil.initCredentials(job); } public static ImportPreUpsertKeyValueProcessor loadPreUpsertProcessor(Configuration conf) { Class<? extends ImportPreUpsertKeyValueProcessor> processorClass = null; try { processorClass = conf.getClass(UPSERT_HOOK_CLASS_CONFKEY, FormatToBytesWritableMapper.DefaultImportPreUpsertKeyValueProcessor.class, ImportPreUpsertKeyValueProcessor.class); } catch (Exception e) { throw new IllegalStateException("Couldn't load upsert hook class", e); } return ReflectionUtils.newInstance(processorClass, conf); } public static byte[] getIndexMaintainers(final Configuration configuration) { Preconditions.checkNotNull(configuration); return Base64.getDecoder().decode(configuration.get(INDEX_MAINTAINERS)); } public static void setIndexMaintainers(final Configuration configuration, final ImmutableBytesWritable indexMetaDataPtr) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(indexMetaDataPtr); configuration.set(INDEX_MAINTAINERS, Bytes.toString(Base64.getEncoder().encode(indexMetaDataPtr.get()))); } public static void setDisableIndexes(Configuration configuration, String indexName) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(indexName); configuration.set(DISABLED_INDEXES, indexName); } public static void setVerifyIndex(Configuration configuration, boolean verify) { Preconditions.checkNotNull(configuration); configuration.setBoolean(VERIFY_INDEX, verify); } public static void setOnlyVerifyIndex(Configuration configuration, boolean verify) { Preconditions.checkNotNull(configuration); configuration.setBoolean(ONLY_VERIFY_INDEX, verify); } public static void setIndexVerifyType(Configuration configuration, IndexTool.IndexVerifyType verifyType) { Preconditions.checkNotNull(configuration); configuration.set(INDEX_VERIFY_TYPE, verifyType.getValue()); } public static void setDisableLoggingVerifyType(Configuration configuration, IndexTool.IndexDisableLoggingType disableLoggingType) { Preconditions.checkNotNull(configuration); configuration.set(DISABLE_LOGGING_TYPE, disableLoggingType.getValue()); } public static String getScrutinyDataTableName(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.get(SCRUTINY_DATA_TABLE_NAME); } public static void setScrutinyDataTable(Configuration configuration, String qDataTableName) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(qDataTableName); configuration.set(SCRUTINY_DATA_TABLE_NAME, qDataTableName); } public static String getScrutinyIndexTableName(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.get(SCRUTINY_INDEX_TABLE_NAME); } public static void setIndexToolDataTableName(Configuration configuration, String qDataTableName) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(qDataTableName); configuration.set(INDEX_TOOL_DATA_TABLE_NAME, qDataTableName); } public static String getIndexToolDataTableName(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.get(INDEX_TOOL_DATA_TABLE_NAME); } public static void setScrutinyIndexTable(Configuration configuration, String qIndexTableName) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(qIndexTableName); configuration.set(SCRUTINY_INDEX_TABLE_NAME, qIndexTableName); } public static SourceTable getScrutinySourceTable(Configuration configuration) { Preconditions.checkNotNull(configuration); return SourceTable.valueOf(configuration.get(SCRUTINY_SOURCE_TABLE)); } public static void setIndexToolIndexTableName(Configuration configuration, String qIndexTableName) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(qIndexTableName); configuration.set(INDEX_TOOL_INDEX_TABLE_NAME, qIndexTableName); } public static String getIndexToolIndexTableName(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.get(INDEX_TOOL_INDEX_TABLE_NAME); } public static void setIndexToolSourceTable(Configuration configuration, IndexScrutinyTool.SourceTable sourceTable) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(sourceTable); configuration.set(INDEX_TOOL_SOURCE_TABLE, sourceTable.name()); } public static IndexScrutinyTool.SourceTable getIndexToolSourceTable(Configuration configuration) { Preconditions.checkNotNull(configuration); return IndexScrutinyTool.SourceTable.valueOf(configuration.get(INDEX_TOOL_SOURCE_TABLE, IndexScrutinyTool.SourceTable.DATA_TABLE_SOURCE.name())); } public static void setScrutinySourceTable(Configuration configuration, SourceTable sourceTable) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(sourceTable); configuration.set(SCRUTINY_SOURCE_TABLE, sourceTable.name()); } public static boolean getScrutinyOutputInvalidRows(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.getBoolean(SCRUTINY_OUTPUT_INVALID_ROWS, DEFAULT_SCRUTINY_OUTPUT_INVALID_ROWS); } public static void setScrutinyOutputInvalidRows(Configuration configuration, boolean outputInvalidRows) { Preconditions.checkNotNull(configuration); configuration.setBoolean(SCRUTINY_OUTPUT_INVALID_ROWS, outputInvalidRows); } public static long getScrutinyBatchSize(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.getLong(SCRUTINY_BATCH_SIZE, DEFAULT_SCRUTINY_BATCH_SIZE); } public static void setScrutinyBatchSize(Configuration configuration, long batchSize) { Preconditions.checkNotNull(configuration); configuration.setLong(SCRUTINY_BATCH_SIZE, batchSize); } public static OutputFormat getScrutinyOutputFormat(Configuration configuration) { Preconditions.checkNotNull(configuration); return OutputFormat .valueOf(configuration.get(SCRUTINY_OUTPUT_FORMAT, OutputFormat.FILE.name())); } public static void setScrutinyOutputFormat(Configuration configuration, OutputFormat outputFormat) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(outputFormat); configuration.set(SCRUTINY_OUTPUT_FORMAT, outputFormat.name()); } public static long getScrutinyExecuteTimestamp(Configuration configuration) { Preconditions.checkNotNull(configuration); long ts = configuration.getLong(SCRUTINY_EXECUTE_TIMESTAMP, -1); Preconditions.checkArgument(ts != -1); return ts; } public static void setScrutinyOutputMax(Configuration configuration, long outputMaxRows) { Preconditions.checkNotNull(configuration); configuration.setLong(SCRUTINY_OUTPUT_MAX, outputMaxRows); } public static long getScrutinyOutputMax(Configuration configuration) { Preconditions.checkNotNull(configuration); long maxRows = configuration.getLong(SCRUTINY_OUTPUT_MAX, -1); Preconditions.checkArgument(maxRows != -1); return maxRows; } public static void setScrutinyExecuteTimestamp(Configuration configuration, long ts) { Preconditions.checkNotNull(configuration); configuration.setLong(SCRUTINY_EXECUTE_TIMESTAMP, ts); } public static void setSplitByStats(final Configuration configuration, boolean value) { Preconditions.checkNotNull(configuration); configuration.setBoolean(MAPREDUCE_SPLIT_BY_STATS, value); } public static String getDisableIndexes(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.get(DISABLED_INDEXES); } public static boolean getVerifyIndex(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.getBoolean(VERIFY_INDEX, false); } public static boolean getOnlyVerifyIndex(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.getBoolean(ONLY_VERIFY_INDEX, false); } public static IndexTool.IndexVerifyType getIndexVerifyType(Configuration configuration) { Preconditions.checkNotNull(configuration); String value = configuration.get(INDEX_VERIFY_TYPE, IndexTool.IndexVerifyType.NONE.getValue()); return IndexTool.IndexVerifyType.fromValue(value); } public static boolean getShouldFixUnverifiedTransform(Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.getBoolean(SHOULD_FIX_UNVERIFIED_TRANSFORM, DEFAULT_SHOULD_FIX_UNVERIFIED_TRANSFORM); } public static void setShouldFixUnverifiedTransform(Configuration configuration, boolean shouldFixUnverified) { Preconditions.checkNotNull(configuration); configuration.setBoolean(SHOULD_FIX_UNVERIFIED_TRANSFORM, shouldFixUnverified); } public static IndexTool.IndexVerifyType getDisableLoggingVerifyType(Configuration configuration) { Preconditions.checkNotNull(configuration); String value = configuration.get(DISABLE_LOGGING_TYPE, IndexTool.IndexVerifyType.NONE.getValue()); return IndexTool.IndexVerifyType.fromValue(value); } public static boolean getSplitByStats(final Configuration configuration) { Preconditions.checkNotNull(configuration); boolean split = configuration.getBoolean(MAPREDUCE_SPLIT_BY_STATS, DEFAULT_SPLIT_BY_STATS); return split; } public static void setTenantId(Configuration configuration, String tenantId) { Preconditions.checkNotNull(configuration); configuration.set(MAPREDUCE_TENANT_ID, tenantId); } public static void setMRSnapshotManagedExternally(Configuration configuration, Boolean isSnapshotRestoreManagedExternally) { Preconditions.checkNotNull(configuration); Preconditions.checkNotNull(isSnapshotRestoreManagedExternally); configuration.setBoolean(MAPREDUCE_EXTERNAL_SNAPSHOT_RESTORE, isSnapshotRestoreManagedExternally); } public static boolean isMRSnapshotManagedExternally(final Configuration configuration) { Preconditions.checkNotNull(configuration); boolean isSnapshotRestoreManagedExternally = configuration .getBoolean(MAPREDUCE_EXTERNAL_SNAPSHOT_RESTORE, DEFAULT_MAPREDUCE_EXTERNAL_SNAPSHOT_RESTORE); return isSnapshotRestoreManagedExternally; } public static boolean isMRRandomizeMapperExecutionOrder(final Configuration configuration) { Preconditions.checkNotNull(configuration); return configuration.getBoolean(MAPREDUCE_RANDOMIZE_MAPPER_EXECUTION_ORDER, DEFAULT_MAPREDUCE_RANDOMIZE_MAPPER_EXECUTION_ORDER); } }
googleapis/google-cloud-java
37,279
java-saasservicemgmt/proto-google-cloud-saasservicemgmt-v1beta1/src/main/java/com/google/cloud/saasplatform/saasservicemgmt/v1beta1/UnitVariable.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/saasplatform/saasservicemgmt/v1beta1/common.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.saasplatform.saasservicemgmt.v1beta1; /** * * * <pre> * UnitVariable describes a parameter for a Unit. * </pre> * * Protobuf type {@code google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable} */ public final class UnitVariable extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable) UnitVariableOrBuilder { private static final long serialVersionUID = 0L; // Use UnitVariable.newBuilder() to construct. private UnitVariable(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UnitVariable() { variable_ = ""; type_ = 0; value_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UnitVariable(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.saasplatform.saasservicemgmt.v1beta1.CommonProto .internal_static_google_cloud_saasplatform_saasservicemgmt_v1beta1_UnitVariable_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.saasplatform.saasservicemgmt.v1beta1.CommonProto .internal_static_google_cloud_saasplatform_saasservicemgmt_v1beta1_UnitVariable_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.class, com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Builder.class); } /** * * * <pre> * Enumeration of variable types. * </pre> * * Protobuf enum {@code google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type} */ public enum Type implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Variable type is unspecified. * </pre> * * <code>TYPE_UNSPECIFIED = 0;</code> */ TYPE_UNSPECIFIED(0), /** * * * <pre> * Variable type is string. * </pre> * * <code>STRING = 1;</code> */ STRING(1), /** * * * <pre> * Variable type is int. * </pre> * * <code>INT = 2;</code> */ INT(2), /** * * * <pre> * Variable type is bool. * </pre> * * <code>BOOL = 3;</code> */ BOOL(3), UNRECOGNIZED(-1), ; /** * * * <pre> * Variable type is unspecified. * </pre> * * <code>TYPE_UNSPECIFIED = 0;</code> */ public static final int TYPE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Variable type is string. * </pre> * * <code>STRING = 1;</code> */ public static final int STRING_VALUE = 1; /** * * * <pre> * Variable type is int. * </pre> * * <code>INT = 2;</code> */ public static final int INT_VALUE = 2; /** * * * <pre> * Variable type is bool. * </pre> * * <code>BOOL = 3;</code> */ public static final int BOOL_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 STRING; case 2: return INT; case 3: return BOOL; 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.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.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.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type) } public static final int VARIABLE_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object variable_ = ""; /** * * * <pre> * Required. Immutable. Name of the variable from actuation configs. * </pre> * * <code> * string variable = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @return The variable. */ @java.lang.Override public java.lang.String getVariable() { java.lang.Object ref = variable_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); variable_ = s; return s; } } /** * * * <pre> * Required. Immutable. Name of the variable from actuation configs. * </pre> * * <code> * string variable = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @return The bytes for variable. */ @java.lang.Override public com.google.protobuf.ByteString getVariableBytes() { java.lang.Object ref = variable_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); variable_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TYPE_FIELD_NUMBER = 2; private int type_ = 0; /** * * * <pre> * Optional. Immutable. Name of a supported variable type. Supported types are * string, int, bool. * </pre> * * <code> * .google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type type = 2 [(.google.api.field_behavior) = OPTIONAL, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** * * * <pre> * Optional. Immutable. Name of a supported variable type. Supported types are * string, int, bool. * </pre> * * <code> * .google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type type = 2 [(.google.api.field_behavior) = OPTIONAL, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @return The type. */ @java.lang.Override public com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type getType() { com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type result = com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type.forNumber(type_); return result == null ? com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type.UNRECOGNIZED : result; } public static final int VALUE_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object value_ = ""; /** * * * <pre> * Optional. String encoded value for the variable. * </pre> * * <code>string value = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The value. */ @java.lang.Override public java.lang.String getValue() { java.lang.Object ref = value_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); value_ = s; return s; } } /** * * * <pre> * Optional. String encoded value for the variable. * </pre> * * <code>string value = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for value. */ @java.lang.Override public com.google.protobuf.ByteString getValueBytes() { java.lang.Object ref = value_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); value_ = 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(variable_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, variable_); } if (type_ != com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type.TYPE_UNSPECIFIED .getNumber()) { output.writeEnum(2, type_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(value_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, value_); } 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(variable_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, variable_); } if (type_ != com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type.TYPE_UNSPECIFIED .getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, type_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(value_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, value_); } 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.saasplatform.saasservicemgmt.v1beta1.UnitVariable)) { return super.equals(obj); } com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable other = (com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable) obj; if (!getVariable().equals(other.getVariable())) return false; if (type_ != other.type_) return false; if (!getValue().equals(other.getValue())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + VARIABLE_FIELD_NUMBER; hash = (53 * hash) + getVariable().hashCode(); hash = (37 * hash) + TYPE_FIELD_NUMBER; hash = (53 * hash) + type_; hash = (37 * hash) + VALUE_FIELD_NUMBER; hash = (53 * hash) + getValue().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable 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.saasplatform.saasservicemgmt.v1beta1.UnitVariable parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable 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.saasplatform.saasservicemgmt.v1beta1.UnitVariable parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable 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.saasplatform.saasservicemgmt.v1beta1.UnitVariable parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable 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.saasplatform.saasservicemgmt.v1beta1.UnitVariable parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable 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.saasplatform.saasservicemgmt.v1beta1.UnitVariable 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> * UnitVariable describes a parameter for a Unit. * </pre> * * Protobuf type {@code google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable) com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariableOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.saasplatform.saasservicemgmt.v1beta1.CommonProto .internal_static_google_cloud_saasplatform_saasservicemgmt_v1beta1_UnitVariable_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.saasplatform.saasservicemgmt.v1beta1.CommonProto .internal_static_google_cloud_saasplatform_saasservicemgmt_v1beta1_UnitVariable_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.class, com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Builder.class); } // Construct using // com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; variable_ = ""; type_ = 0; value_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.saasplatform.saasservicemgmt.v1beta1.CommonProto .internal_static_google_cloud_saasplatform_saasservicemgmt_v1beta1_UnitVariable_descriptor; } @java.lang.Override public com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable getDefaultInstanceForType() { return com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable .getDefaultInstance(); } @java.lang.Override public com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable build() { com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable buildPartial() { com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable result = new com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.variable_ = variable_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.type_ = type_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.value_ = value_; } } @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.saasplatform.saasservicemgmt.v1beta1.UnitVariable) { return mergeFrom( (com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable other) { if (other == com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable .getDefaultInstance()) return this; if (!other.getVariable().isEmpty()) { variable_ = other.variable_; bitField0_ |= 0x00000001; onChanged(); } if (other.type_ != 0) { setTypeValue(other.getTypeValue()); } if (!other.getValue().isEmpty()) { value_ = other.value_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { variable_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { type_ = input.readEnum(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { value_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object variable_ = ""; /** * * * <pre> * Required. Immutable. Name of the variable from actuation configs. * </pre> * * <code> * string variable = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @return The variable. */ public java.lang.String getVariable() { java.lang.Object ref = variable_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); variable_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Immutable. Name of the variable from actuation configs. * </pre> * * <code> * string variable = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @return The bytes for variable. */ public com.google.protobuf.ByteString getVariableBytes() { java.lang.Object ref = variable_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); variable_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Immutable. Name of the variable from actuation configs. * </pre> * * <code> * string variable = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @param value The variable to set. * @return This builder for chaining. */ public Builder setVariable(java.lang.String value) { if (value == null) { throw new NullPointerException(); } variable_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Immutable. Name of the variable from actuation configs. * </pre> * * <code> * string variable = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @return This builder for chaining. */ public Builder clearVariable() { variable_ = getDefaultInstance().getVariable(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. Immutable. Name of the variable from actuation configs. * </pre> * * <code> * string variable = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @param value The bytes for variable to set. * @return This builder for chaining. */ public Builder setVariableBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); variable_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int type_ = 0; /** * * * <pre> * Optional. Immutable. Name of a supported variable type. Supported types are * string, int, bool. * </pre> * * <code> * .google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type type = 2 [(.google.api.field_behavior) = OPTIONAL, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** * * * <pre> * Optional. Immutable. Name of a supported variable type. Supported types are * string, int, bool. * </pre> * * <code> * .google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type type = 2 [(.google.api.field_behavior) = OPTIONAL, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @param value The enum numeric value on the wire for type to set. * @return This builder for chaining. */ public Builder setTypeValue(int value) { type_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Immutable. Name of a supported variable type. Supported types are * string, int, bool. * </pre> * * <code> * .google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type type = 2 [(.google.api.field_behavior) = OPTIONAL, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @return The type. */ @java.lang.Override public com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type getType() { com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type result = com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type.forNumber(type_); return result == null ? com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type.UNRECOGNIZED : result; } /** * * * <pre> * Optional. Immutable. Name of a supported variable type. Supported types are * string, int, bool. * </pre> * * <code> * .google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type type = 2 [(.google.api.field_behavior) = OPTIONAL, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @param value The type to set. * @return This builder for chaining. */ public Builder setType( com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; type_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Optional. Immutable. Name of a supported variable type. Supported types are * string, int, bool. * </pre> * * <code> * .google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable.Type type = 2 [(.google.api.field_behavior) = OPTIONAL, (.google.api.field_behavior) = IMMUTABLE]; * </code> * * @return This builder for chaining. */ public Builder clearType() { bitField0_ = (bitField0_ & ~0x00000002); type_ = 0; onChanged(); return this; } private java.lang.Object value_ = ""; /** * * * <pre> * Optional. String encoded value for the variable. * </pre> * * <code>string value = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The value. */ public java.lang.String getValue() { java.lang.Object ref = value_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); value_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. String encoded value for the variable. * </pre> * * <code>string value = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for value. */ public com.google.protobuf.ByteString getValueBytes() { java.lang.Object ref = value_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); value_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. String encoded value for the variable. * </pre> * * <code>string value = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The value to set. * @return This builder for chaining. */ public Builder setValue(java.lang.String value) { if (value == null) { throw new NullPointerException(); } value_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. String encoded value for the variable. * </pre> * * <code>string value = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearValue() { value_ = getDefaultInstance().getValue(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Optional. String encoded value for the variable. * </pre> * * <code>string value = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for value to set. * @return This builder for chaining. */ public Builder setValueBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); value_ = 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.saasplatform.saasservicemgmt.v1beta1.UnitVariable) } // @@protoc_insertion_point(class_scope:google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable) private static final com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable(); } public static com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UnitVariable> PARSER = new com.google.protobuf.AbstractParser<UnitVariable>() { @java.lang.Override public UnitVariable 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<UnitVariable> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UnitVariable> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UnitVariable getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/incubator-kie-drools
37,620
drools-scenario-simulation/drools-scenario-simulation-backend/src/test/java/org/drools/scenariosimulation/backend/runner/DMNScenarioRunnerHelperTest.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.drools.scenariosimulation.backend.runner; import java.math.BigDecimal; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.IntStream; import org.drools.scenariosimulation.api.model.AuditLogLine; import org.drools.scenariosimulation.api.model.ExpressionIdentifier; import org.drools.scenariosimulation.api.model.FactIdentifier; import org.drools.scenariosimulation.api.model.FactMapping; import org.drools.scenariosimulation.api.model.FactMappingType; import org.drools.scenariosimulation.api.model.FactMappingValue; import org.drools.scenariosimulation.api.model.FactMappingValueStatus; import org.drools.scenariosimulation.api.model.Scenario; import org.drools.scenariosimulation.api.model.ScenarioSimulationModel; import org.drools.scenariosimulation.api.model.ScenarioWithIndex; import org.drools.scenariosimulation.api.model.Settings; import org.drools.scenariosimulation.api.model.Simulation; import org.drools.scenariosimulation.backend.expression.DMNFeelExpressionEvaluator; import org.drools.scenariosimulation.backend.expression.ExpressionEvaluator; import org.drools.scenariosimulation.backend.expression.ExpressionEvaluatorFactory; import org.drools.scenariosimulation.backend.fluent.DMNScenarioExecutableBuilder; import org.drools.scenariosimulation.backend.runner.model.InstanceGiven; import org.drools.scenariosimulation.backend.runner.model.ScenarioExpect; import org.drools.scenariosimulation.backend.runner.model.ScenarioResultMetadata; import org.drools.scenariosimulation.backend.runner.model.ScenarioRunnerData; import org.drools.scenariosimulation.backend.runner.model.ValueWrapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.RequestContext; import org.kie.dmn.api.core.DMNDecisionResult; import org.kie.dmn.api.core.DMNDecisionResult.DecisionEvaluationStatus; import org.kie.dmn.api.core.DMNMessage; import org.kie.dmn.api.core.DMNMessageType; import org.kie.dmn.api.core.DMNModel; import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.ast.DecisionNode; import org.kie.dmn.core.impl.DMNMessageImpl; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.drools.scenariosimulation.api.utils.ConstantsHolder.IMPORTED_PREFIX; import static org.drools.scenariosimulation.backend.TestUtils.commonCheckAuditLogLine; import static org.drools.scenariosimulation.backend.TestUtils.getRandomlyGeneratedDMNMessageList; import static org.kie.dmn.api.core.DMNMessage.Severity.ERROR; import static org.kie.dmn.api.core.DMNMessage.Severity.WARN; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class DMNScenarioRunnerHelperTest { private static final String NAME = "NAME"; private static final String FEEL_EXPRESSION_NAME = "\"" + NAME + "\""; private static final BigDecimal AMOUNT = BigDecimal.valueOf(10); private static final String DMN_FILE_PATH = "dmnFilePath"; private static final String DMN_NAMESPACE = "dmnNamespace"; private static final String TEST_DESCRIPTION = "Test description"; private static final ClassLoader classLoader = RuleScenarioRunnerHelperTest.class.getClassLoader(); private static final ExpressionEvaluatorFactory expressionEvaluatorFactory = ExpressionEvaluatorFactory.create(classLoader, ScenarioSimulationModel.Type.DMN); private static final ExpressionEvaluator expressionEvaluator = new DMNFeelExpressionEvaluator(classLoader); private final DMNScenarioRunnerHelper runnerHelper = new DMNScenarioRunnerHelper() { @Override protected DMNScenarioExecutableBuilder createBuilderWrapper() { return dmnScenarioExecutableBuilderMock; } }; @Mock protected Map<String, Object> requestContextMock; @Mock protected DMNResult dmnResultMock; @Mock protected DMNDecisionResult dmnDecisionResultMock; @Mock protected DMNModel dmnModelMock; @Mock protected DMNScenarioExecutableBuilder dmnScenarioExecutableBuilderMock; @Mock protected KieContainer kieContainerMock; @Captor private ArgumentCaptor<Object> valueCaptor; @Captor private ArgumentCaptor<String> keyCaptor; private Simulation simulation; private Settings settings; private FactIdentifier personFactIdentifier; private ExpressionIdentifier firstNameGivenExpressionIdentifier; private FactMapping firstNameGivenFactMapping; private Scenario scenario1; private Scenario scenario2; private ExpressionIdentifier firstNameExpectedExpressionIdentifier; private FactMapping firstNameExpectedFactMapping; private FactIdentifier disputeFactIdentifier; private ExpressionIdentifier amountGivenExpressionIdentifier; private FactMapping amountNameGivenFactMapping; private ExpressionIdentifier amountExpectedExpressionIdentifier; private FactMapping amountNameExpectedFactMapping; private FactMappingValue amountNameExpectedFactMappingValue; private FactMappingValue firstNameExpectedValue; @BeforeEach void init() { simulation = new Simulation(); settings = new Settings(); settings.setType(ScenarioSimulationModel.Type.DMN); settings.setDmnFilePath(DMN_FILE_PATH); settings.setDmnName(NAME); settings.setDmnNamespace(DMN_NAMESPACE); personFactIdentifier = FactIdentifier.create("Fact 1", "Fact 1"); firstNameGivenExpressionIdentifier = ExpressionIdentifier.create("First Name Given", FactMappingType.GIVEN); firstNameGivenFactMapping = simulation.getScesimModelDescriptor().addFactMapping(personFactIdentifier, firstNameGivenExpressionIdentifier); firstNameGivenFactMapping.addExpressionElement("Fact 1", String.class.getCanonicalName()); firstNameGivenFactMapping.addExpressionElement("firstName", String.class.getCanonicalName()); disputeFactIdentifier = FactIdentifier.create("Fact 2", "Fact 2"); amountGivenExpressionIdentifier = ExpressionIdentifier.create("Amount Given", FactMappingType.GIVEN); amountNameGivenFactMapping = simulation.getScesimModelDescriptor().addFactMapping(disputeFactIdentifier, amountGivenExpressionIdentifier); amountNameGivenFactMapping.addExpressionElement("Fact 2", BigDecimal.class.getCanonicalName()); amountNameGivenFactMapping.addExpressionElement("amount", BigDecimal.class.getCanonicalName()); firstNameExpectedExpressionIdentifier = ExpressionIdentifier.create("First Name Expected", FactMappingType.EXPECT); firstNameExpectedFactMapping = simulation.getScesimModelDescriptor().addFactMapping(personFactIdentifier, firstNameExpectedExpressionIdentifier); firstNameExpectedFactMapping.addExpressionElement("Fact 1", String.class.getCanonicalName()); firstNameExpectedFactMapping.addExpressionElement("firstName", String.class.getCanonicalName()); amountExpectedExpressionIdentifier = ExpressionIdentifier.create("Amount Expected", FactMappingType.EXPECT); amountNameExpectedFactMapping = simulation.getScesimModelDescriptor().addFactMapping(disputeFactIdentifier, amountExpectedExpressionIdentifier); amountNameExpectedFactMapping.addExpressionElement("Fact 2", Double.class.getCanonicalName()); amountNameExpectedFactMapping.addExpressionElement("amount", Double.class.getCanonicalName()); scenario1 = simulation.addData(); scenario1.setDescription(TEST_DESCRIPTION); scenario1.addMappingValue(personFactIdentifier, firstNameGivenExpressionIdentifier, FEEL_EXPRESSION_NAME); firstNameExpectedValue = scenario1.addMappingValue(personFactIdentifier, firstNameExpectedExpressionIdentifier, FEEL_EXPRESSION_NAME); scenario2 = simulation.addData(); scenario2.setDescription(TEST_DESCRIPTION); scenario2.addMappingValue(personFactIdentifier, firstNameGivenExpressionIdentifier, FEEL_EXPRESSION_NAME); scenario2.addMappingValue(personFactIdentifier, firstNameExpectedExpressionIdentifier, FEEL_EXPRESSION_NAME); scenario2.addMappingValue(disputeFactIdentifier, amountGivenExpressionIdentifier, AMOUNT); amountNameExpectedFactMappingValue = scenario2.addMappingValue(disputeFactIdentifier, amountExpectedExpressionIdentifier, AMOUNT); } @Test void verifyConditions_noDecisionGeneratedForSpecificName() { // test 1 - no decision generated for specific decisionName ScenarioRunnerData scenarioRunnerData = new ScenarioRunnerData(); scenarioRunnerData.addExpect(new ScenarioExpect(personFactIdentifier, List.of(firstNameExpectedValue))); when(requestContextMock.get(DMNScenarioExecutableBuilder.DMN_RESULT)).thenReturn(dmnResultMock); assertThatThrownBy(() -> runnerHelper.verifyConditions(simulation.getScesimModelDescriptor(), scenarioRunnerData, expressionEvaluatorFactory, requestContextMock)) .isInstanceOf(ScenarioException.class) .hasMessage("DMN execution has not generated a decision result with name Fact 1"); } @Test void verifyConditions_decisionResultContainsANull() { // test 2 - when decisionResult contains a null value skip the steps and just do the comparison (that should be false in this case) ScenarioRunnerData scenarioRunnerData = new ScenarioRunnerData(); scenarioRunnerData.addExpect(new ScenarioExpect(personFactIdentifier, List.of(firstNameExpectedValue))); when(dmnResultMock.getDecisionResultByName(anyString())).thenReturn(dmnDecisionResultMock); when(dmnDecisionResultMock.getEvaluationStatus()).thenReturn(DecisionEvaluationStatus.SUCCEEDED); when(requestContextMock.get(DMNScenarioExecutableBuilder.DMN_RESULT)).thenReturn(dmnResultMock); runnerHelper.verifyConditions(simulation.getScesimModelDescriptor(), scenarioRunnerData, expressionEvaluatorFactory, requestContextMock); assertThat(scenarioRunnerData.getResults()).hasSize(1); assertThat(scenarioRunnerData.getResults().get(0).getResult()).isFalse(); } @Test void verifyConditions_decisionResultIsNotNullButMalformed() { // test 3 - now result is not null but data structure is wrong (expected steps but data is a simple string) ScenarioRunnerData scenarioRunnerData = new ScenarioRunnerData(); scenarioRunnerData.addExpect(new ScenarioExpect(personFactIdentifier, List.of(firstNameExpectedValue))); when(dmnResultMock.getDecisionResultByName(anyString())).thenReturn(dmnDecisionResultMock); when(dmnDecisionResultMock.getEvaluationStatus()).thenReturn(DecisionEvaluationStatus.SUCCEEDED); when(dmnDecisionResultMock.getResult()).thenReturn(""); when(requestContextMock.get(DMNScenarioExecutableBuilder.DMN_RESULT)).thenReturn(dmnResultMock); assertThatThrownBy(() -> runnerHelper.verifyConditions(simulation.getScesimModelDescriptor(), scenarioRunnerData, expressionEvaluatorFactory, requestContextMock)) .isInstanceOf(ScenarioException.class) .hasMessage("Wrong resultRaw structure because it is not a complex type as expected"); } @Test void verifyConditions_checksArePerformed_fail() { // test 4 - check are performed (but fail) ScenarioRunnerData scenarioRunnerData = new ScenarioRunnerData(); scenarioRunnerData.addExpect(new ScenarioExpect(personFactIdentifier, List.of(firstNameExpectedValue))); when(dmnResultMock.getDecisionResultByName(anyString())).thenReturn(dmnDecisionResultMock); when(dmnDecisionResultMock.getEvaluationStatus()).thenReturn(DecisionEvaluationStatus.SUCCEEDED); Map<String, Object> resultMap = new HashMap<>(); resultMap.put("firstName", "WrongValue"); when(dmnDecisionResultMock.getResult()).thenReturn(resultMap); when(requestContextMock.get(DMNScenarioExecutableBuilder.DMN_RESULT)).thenReturn(dmnResultMock); runnerHelper.verifyConditions(simulation.getScesimModelDescriptor(), scenarioRunnerData, expressionEvaluatorFactory, requestContextMock); assertThat(scenarioRunnerData.getResults()).hasSize(1); assertThat(scenarioRunnerData.getResults().get(0).getResult()).isFalse(); } @Test void verifyConditions_checksArePerformed_success() { // test 5 - check are performed (but success) ScenarioRunnerData scenarioRunnerData = new ScenarioRunnerData(); scenarioRunnerData.addExpect(new ScenarioExpect(personFactIdentifier, List.of(firstNameExpectedValue))); when(dmnResultMock.getDecisionResultByName(anyString())).thenReturn(dmnDecisionResultMock); when(dmnDecisionResultMock.getEvaluationStatus()).thenReturn(DecisionEvaluationStatus.SUCCEEDED); Map<String, Object> resultMap = new HashMap<>(); resultMap.put("firstName", NAME); when(dmnDecisionResultMock.getResult()).thenReturn(resultMap); when(requestContextMock.get(DMNScenarioExecutableBuilder.DMN_RESULT)).thenReturn(dmnResultMock); runnerHelper.verifyConditions(simulation.getScesimModelDescriptor(), scenarioRunnerData, expressionEvaluatorFactory, requestContextMock); assertThat(scenarioRunnerData.getResults()).hasSize(1); assertThat(scenarioRunnerData.getResults().get(0).getResult()).isTrue(); } @Test void verifyConditions_errorsAreReported() { // test 6 - verify that when expression evaluation fails the corresponding expression is marked as error ScenarioRunnerData scenarioRunnerData = new ScenarioRunnerData(); scenarioRunnerData.addExpect(new ScenarioExpect(personFactIdentifier, List.of(firstNameExpectedValue))); when(dmnResultMock.getDecisionResultByName(anyString())).thenReturn(dmnDecisionResultMock); when(dmnDecisionResultMock.getEvaluationStatus()).thenReturn(DecisionEvaluationStatus.SUCCEEDED); Map<String, Object> resultMap = new HashMap<>(); resultMap.put("firstName", NAME); when(requestContextMock.get(DMNScenarioExecutableBuilder.DMN_RESULT)).thenReturn(dmnResultMock); when(dmnDecisionResultMock.getResult()).thenReturn(resultMap); ExpressionEvaluatorFactory expressionEvaluatorFactoryMock = mock(ExpressionEvaluatorFactory.class); when(expressionEvaluatorFactoryMock.getOrCreate(any())).thenReturn(mock(ExpressionEvaluator.class)); runnerHelper.verifyConditions(simulation.getScesimModelDescriptor(), scenarioRunnerData, expressionEvaluatorFactoryMock, requestContextMock); assertThat(scenarioRunnerData.getResults().get(0).getFactMappingValue().getStatus()).isNotEqualTo(FactMappingValueStatus.SUCCESS); } @SuppressWarnings("unchecked") @Test void createObject() { Map<List<String>, Object> params = new HashMap<>(); params.put(List.of("creator", "name"), "TestName"); params.put(List.of("creator", "surname"), "TestSurname"); params.put(List.of("age"), BigDecimal.valueOf(10)); ValueWrapper<Object> initialInstance = runnerHelper.getDirectMapping(params); Object objectRaw = runnerHelper.createObject(initialInstance, String.class.getCanonicalName(), params, getClass().getClassLoader()); assertThat(objectRaw).isInstanceOf(Map.class); Map<String, Object> object = (Map<String, Object>) objectRaw; assertThat(object).containsEntry("age", BigDecimal.valueOf(10)); assertThat(object.get("creator")).isInstanceOf(Map.class); Map<String, Object> creator = (Map<String, Object>) object.get("creator"); assertThat(creator).containsEntry("name", "TestName").containsEntry("surname", "TestSurname"); } @Test void createObject_directMappingSimpleType() { Map<List<String>, Object> params = new HashMap<>(); String directMappingSimpleTypeValue = "TestName"; params.put(List.of(), directMappingSimpleTypeValue); ValueWrapper<Object> initialInstance = runnerHelper.getDirectMapping(params); Object objectRaw = runnerHelper.createObject(initialInstance, String.class.getCanonicalName(), params, getClass().getClassLoader()); assertThat(objectRaw).isInstanceOf(String.class).isEqualTo(directMappingSimpleTypeValue); } @Test void createObject_directMappingSimpleTypeNull() { Map<List<String>, Object> params = new HashMap<>(); params.put(List.of(), null); ValueWrapper<Object> initialInstance = runnerHelper.getDirectMapping(params); Object objectRaw = runnerHelper.createObject(initialInstance, String.class.getCanonicalName(), params, getClass().getClassLoader()); assertThat(objectRaw).isNull(); } @SuppressWarnings("unchecked") @Test void createObject_directMappingComplexType() { Map<List<String>, Object> params = new HashMap<>(); Map<String, Object> directMappingComplexTypeValue = new HashMap<>(); directMappingComplexTypeValue.put("key1", "value1"); params.put(List.of(), directMappingComplexTypeValue); params.put(List.of("key2"), "value2"); ValueWrapper<Object> initialInstance = runnerHelper.getDirectMapping(params); Object objectRaw = runnerHelper.createObject(initialInstance, Map.class.getCanonicalName(), params, getClass().getClassLoader()); assertThat(objectRaw).isInstanceOf(Map.class); Map<String, Object> object = (Map<String, Object>) objectRaw; assertThat(object).containsEntry("key1","value1").containsEntry("key2", "value2"); } @Test void extractResultMetadata_noDecisionResultMessages() { commonExtractResultMetadata(); } @Test void extractResultMetadata_decisionResultMessages() { List<DMNMessage> messages = getRandomlyGeneratedDMNMessageList(); commonExtractResultMetadata(messages); } @Test void getSingleFactValueResult_failDecision() { DMNDecisionResult failedDecision = createDecisionResultMock("Test", false, new ArrayList<>()); ValueWrapper<?> failedResult = runnerHelper.getSingleFactValueResult(null, null, failedDecision, null, expressionEvaluator); assertThat(failedResult.isValid()).isFalse(); assertThat(failedResult.getErrorMessage().get()).isEqualTo("The decision \"" + failedDecision.getDecisionName() + "\" has not been successfully evaluated: " + failedDecision.getEvaluationStatus()); } @Test void getSingleFactValueResult_failDecisionWithMessages() { DMNMessage errorMessage = new DMNMessageImpl(ERROR, "DMN Internal Error", DMNMessageType.FEEL_EVALUATION_ERROR, null); DMNMessage warnMessage = new DMNMessageImpl(WARN, "DMN Internal Warn", DMNMessageType.FEEL_EVALUATION_ERROR, null); DMNDecisionResult failedDecision = createDecisionResultMock("Test", false, new ArrayList<>()); ValueWrapper<?> failedResult = runnerHelper.getSingleFactValueResult(null, null, failedDecision, List.of(warnMessage, errorMessage), expressionEvaluator); assertThat(failedResult.isValid()).isFalse(); assertThat(failedResult.getErrorMessage().get()).isEqualTo("The decision \"" + failedDecision.getDecisionName() + "\" has not been successfully evaluated: DMN Internal Error"); } @Test void executeScenario() { when(dmnScenarioExecutableBuilderMock.run()).thenReturn(mock(RequestContext.class)); FactIdentifier bookFactIdentifier = FactIdentifier.create("Book", "Book"); FactIdentifier importedPersonFactIdentifier = FactIdentifier.create(IMPORTED_PREFIX + ".Person", IMPORTED_PREFIX + ".Person", IMPORTED_PREFIX); FactIdentifier importedDisputeFactIdentifier = FactIdentifier.create(IMPORTED_PREFIX + ".Dispute", IMPORTED_PREFIX + ".Dispute", IMPORTED_PREFIX); FactIdentifier importedBookFactIdentifier = FactIdentifier.create(IMPORTED_PREFIX + ".Book", IMPORTED_PREFIX + ".Book", IMPORTED_PREFIX); FactIdentifier importedWrBookFactIdentifier = FactIdentifier.create(IMPORTED_PREFIX + ".wr.Book", IMPORTED_PREFIX + ".wr.Book", IMPORTED_PREFIX); AbstractMap.SimpleEntry<String, Object> backgroundDisputeFactData = new AbstractMap.SimpleEntry<>("description", "Nice"); AbstractMap.SimpleEntry<String, Object> backgroundPersonFactData = new AbstractMap.SimpleEntry<>("name", "Carl"); AbstractMap.SimpleEntry<String, Object> backgroundPersonFactData2 = new AbstractMap.SimpleEntry<>("age", 2); AbstractMap.SimpleEntry<String, Object> backgroundImportedDisputeFactData = new AbstractMap.SimpleEntry<>("description", "Bad"); AbstractMap.SimpleEntry<String, Object> backgroundImportedPersonFactData = new AbstractMap.SimpleEntry<>("name", "Max"); AbstractMap.SimpleEntry<String, Object> backgroundImportedPersonFactData2 = new AbstractMap.SimpleEntry<>("age", 34); AbstractMap.SimpleEntry<String, Object> givenPersonFactData = new AbstractMap.SimpleEntry<>("surname", "Brown"); AbstractMap.SimpleEntry<String, Object> givenPersonFactData2 = new AbstractMap.SimpleEntry<>("age", 23); AbstractMap.SimpleEntry<String, Object> givenBookFactData = new AbstractMap.SimpleEntry<>("Author", "Resey Rema"); AbstractMap.SimpleEntry<String, Object> givenBookFactData2 = new AbstractMap.SimpleEntry<>("Name", "The mighty Test Scenario!"); AbstractMap.SimpleEntry<String, Object> givenImportedBookFactData = new AbstractMap.SimpleEntry<>("Author", "Mr Y"); AbstractMap.SimpleEntry<String, Object> givenImportedBookFactData2 = new AbstractMap.SimpleEntry<>("Title", "The awesome Test Scenario!"); AbstractMap.SimpleEntry<String, Object> givenImportedPersonFactData = new AbstractMap.SimpleEntry<>("surname", "White"); AbstractMap.SimpleEntry<String, Object> givenImportedPersonFactData2 = new AbstractMap.SimpleEntry<>("age", 67); AbstractMap.SimpleEntry<String, Object> givenImportedWrBookFactData = new AbstractMap.SimpleEntry<>("Title", "I hate name with multi dots"); ScenarioRunnerData scenarioRunnerData = new ScenarioRunnerData(); scenarioRunnerData.addBackground(new InstanceGiven(disputeFactIdentifier, Map.ofEntries(backgroundDisputeFactData))); scenarioRunnerData.addBackground(new InstanceGiven(personFactIdentifier, Map.ofEntries(backgroundPersonFactData, backgroundPersonFactData2))); scenarioRunnerData.addBackground(new InstanceGiven(importedPersonFactIdentifier, Map.ofEntries(backgroundImportedPersonFactData, backgroundImportedPersonFactData2))); scenarioRunnerData.addBackground(new InstanceGiven(importedDisputeFactIdentifier, Map.ofEntries(backgroundImportedDisputeFactData))); scenarioRunnerData.addGiven(new InstanceGiven(personFactIdentifier, Map.ofEntries(givenPersonFactData, givenPersonFactData2))); scenarioRunnerData.addGiven(new InstanceGiven(importedPersonFactIdentifier, Map.ofEntries(givenImportedPersonFactData, givenImportedPersonFactData2))); scenarioRunnerData.addGiven(new InstanceGiven(bookFactIdentifier, Map.ofEntries(givenBookFactData, givenBookFactData2))); scenarioRunnerData.addGiven(new InstanceGiven(importedBookFactIdentifier, Map.ofEntries(givenImportedBookFactData, givenImportedBookFactData2))); scenarioRunnerData.addGiven(new InstanceGiven(importedWrBookFactIdentifier, Map.ofEntries(givenImportedWrBookFactData))); FactMappingValue factMappingValue = new FactMappingValue(personFactIdentifier, firstNameExpectedExpressionIdentifier, NAME); scenarioRunnerData.addExpect(new ScenarioExpect(personFactIdentifier, List.of(factMappingValue), false)); scenarioRunnerData.addExpect(new ScenarioExpect(personFactIdentifier, List.of(factMappingValue), true)); List<String> expectedInputDataToLoad = List.of(personFactIdentifier.getName(), disputeFactIdentifier.getName(), bookFactIdentifier.getName(), IMPORTED_PREFIX); int inputObjects = expectedInputDataToLoad.size(); runnerHelper.executeScenario(kieContainerMock, scenarioRunnerData, expressionEvaluatorFactory, simulation.getScesimModelDescriptor(), settings); verify(dmnScenarioExecutableBuilderMock, times(1)).setActiveModel(DMN_FILE_PATH, NAME); verify(dmnScenarioExecutableBuilderMock, times(inputObjects)).setValue(keyCaptor.capture(), valueCaptor.capture()); assertThat(keyCaptor.getAllValues()).containsAll(expectedInputDataToLoad); for (int i = 0; i < inputObjects; i++) { String key = keyCaptor.getAllValues().get(i); Map<String, Object> value = (Map<String, Object>) valueCaptor.getAllValues().get(i); if (personFactIdentifier.getName().equals(key)) { assertThat(value).hasSize(3).contains(backgroundPersonFactData, givenPersonFactData, givenPersonFactData2); } else if (disputeFactIdentifier.getName().equals(key)) { assertThat(value).hasSize(1).contains(backgroundDisputeFactData); } else if (bookFactIdentifier.getName().equals(key)) { assertThat(value).hasSize(2).contains(givenBookFactData, givenBookFactData2); } else if (IMPORTED_PREFIX.equals(key)) { assertThat(value).hasSize(4); Map<String, Object> subValueDispute = (Map<String, Object>) value.get("Dispute"); assertThat(subValueDispute).hasSize(1).contains(backgroundImportedDisputeFactData); Map<String, Object> subValueBook = (Map<String, Object>) value.get("Book"); assertThat(subValueBook).hasSize(2).contains(givenImportedBookFactData, givenImportedBookFactData2); Map<String, Object> subValuePerson = (Map<String, Object>) value.get("Person"); assertThat(subValuePerson).hasSize(3).contains(backgroundImportedPersonFactData, givenImportedPersonFactData, givenImportedPersonFactData2); Map<String, Object> subValueWrBook = (Map<String, Object>) value.get("wr.Book"); assertThat(subValueWrBook).hasSize(1).contains(givenImportedWrBookFactData); } else { fail("Unexpected key: " + key); } } verify(dmnScenarioExecutableBuilderMock, times(1)).run(); // test not rule error settings.setType(ScenarioSimulationModel.Type.RULE); assertThatThrownBy(() -> runnerHelper.executeScenario(kieContainerMock, scenarioRunnerData, expressionEvaluatorFactory, simulation.getScesimModelDescriptor(), settings)) .isInstanceOf(ScenarioException.class) .hasMessageStartingWith("Impossible to run"); } @Test void validateScenario_wrongImportPrefix() { String wrongPrefix = "WrongPrefix"; FactIdentifier importedPersonFactIdentifier = FactIdentifier.create(IMPORTED_PREFIX + ".Person", IMPORTED_PREFIX + ".Person", wrongPrefix); ScenarioRunnerData scenarioRunnerData = new ScenarioRunnerData(); AbstractMap.SimpleEntry<String, Object> givenImportedPersonFactData = new AbstractMap.SimpleEntry<>("surname", "White"); AbstractMap.SimpleEntry<String, Object> givenImportedPersonFactData2 = new AbstractMap.SimpleEntry<>("age", 67); scenarioRunnerData.addGiven(new InstanceGiven(importedPersonFactIdentifier, Map.ofEntries(givenImportedPersonFactData, givenImportedPersonFactData2))); assertThatThrownBy(() -> runnerHelper.executeScenario(kieContainerMock, scenarioRunnerData, expressionEvaluatorFactory, simulation.getScesimModelDescriptor(), settings)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Fact name: " + IMPORTED_PREFIX + ".Person has defined an invalid import prefix: " + wrongPrefix); } /* If a malicious user injects a regex as a prefix in both importPrefix and as a part of fact name, the injected regex shouldn't be applied, but it should be used as a plain string */ @Test void validateUnSecureImportPrefix() { when(dmnScenarioExecutableBuilderMock.run()).thenReturn(mock(RequestContext.class)); String injectedPrefix = "/.(a+)+$/"; FactIdentifier importedPersonFactIdentifier = FactIdentifier.create(injectedPrefix + ".Person", injectedPrefix + ".Person", injectedPrefix); ScenarioRunnerData scenarioRunnerData = new ScenarioRunnerData(); AbstractMap.SimpleEntry<String, Object> givenImportedPersonFactData = new AbstractMap.SimpleEntry<>("surname", "White"); AbstractMap.SimpleEntry<String, Object> givenImportedPersonFactData2 = new AbstractMap.SimpleEntry<>("age", 67); scenarioRunnerData.addGiven(new InstanceGiven(importedPersonFactIdentifier, Map.ofEntries(givenImportedPersonFactData, givenImportedPersonFactData2))); List<String> expectedInputDataToLoad = List.of(injectedPrefix); int inputObjects = expectedInputDataToLoad.size(); runnerHelper.executeScenario(kieContainerMock, scenarioRunnerData, expressionEvaluatorFactory, simulation.getScesimModelDescriptor(), settings); verify(dmnScenarioExecutableBuilderMock, times(inputObjects)).setValue(keyCaptor.capture(), valueCaptor.capture()); assertThat(keyCaptor.getAllValues()).containsAll(expectedInputDataToLoad); String key = keyCaptor.getAllValues().get(0); Map<String, Object> value = (Map<String, Object>) valueCaptor.getAllValues().get(0); assertThat(key).isEqualTo(injectedPrefix); Map<String, Object> subValuePerson = (Map<String, Object>) value.get("Person"); assertThat(subValuePerson).hasSize(2).contains(givenImportedPersonFactData, givenImportedPersonFactData2); } private void commonExtractResultMetadata(List<DMNMessage> messages) { Set<DecisionNode> decisions = new HashSet<>(); IntStream.range(0, 5).forEach(index -> decisions.add(createDecisionMock("decision" + index))); when(dmnModelMock.getDecisions()).thenReturn(decisions); List<DMNDecisionResult> decisionResults = new ArrayList<>(); decisionResults.add(createDecisionResultMock("decision2", true, messages)); decisionResults.add(createDecisionResultMock("decision3", false, messages)); when(dmnResultMock.getDecisionResults()).thenReturn(decisionResults); when(requestContextMock.get(DMNScenarioExecutableBuilder.DMN_RESULT)).thenReturn(dmnResultMock); when(requestContextMock.get(DMNScenarioExecutableBuilder.DMN_MODEL)).thenReturn(dmnModelMock); ScenarioWithIndex scenarioWithIndex = new ScenarioWithIndex(1, scenario1); ScenarioResultMetadata scenarioResultMetadata = runnerHelper.extractResultMetadata(requestContextMock, scenarioWithIndex); assertThat(scenarioResultMetadata.getScenarioWithIndex()).isEqualTo(scenarioWithIndex); assertThat(scenarioResultMetadata.getAvailable()).hasSize(5).contains("decision1"); assertThat(scenarioResultMetadata.getExecuted()).hasSize(1).contains("decision2").doesNotContain("decision3"); final List<AuditLogLine> auditLogLines = scenarioResultMetadata.getAuditLogLines(); assertThat(auditLogLines).isNotNull(); List<String> expectedDecisions = List.of("decision2", "decision3"); List<String> expectedResults = List.of(DecisionEvaluationStatus.SUCCEEDED.toString(), DecisionEvaluationStatus.FAILED.toString()); int expectedLines = messages.size() * expectedDecisions.size(); assertThat(auditLogLines).hasSize(expectedLines); for (int i = 0; i < auditLogLines.size(); i++) { int messagesIndex = i < messages.size() ? i : i - messages.size(); String decisionName = i < messages.size() ? expectedDecisions.get(0) : expectedDecisions.get(1); String expectedResultName = i < messages.size() ? expectedResults.get(0) : expectedResults.get(1); commonCheckAuditLogLine(auditLogLines.get(i), decisionName, expectedResultName, messages.get(messagesIndex).getLevel().name() + ": " + messages.get(messagesIndex).getText()); } } private void commonExtractResultMetadata() { Set<DecisionNode> decisions = new HashSet<>(); IntStream.range(0, 5).forEach(index -> decisions.add(createDecisionMock("decision" + index))); when(dmnModelMock.getDecisions()).thenReturn(decisions); List<DMNDecisionResult> decisionResults = new ArrayList<>(); decisionResults.add(createDecisionResultMock("decision2", true, null)); decisionResults.add(createDecisionResultMock("decision3", false, null)); when(dmnResultMock.getDecisionResults()).thenReturn(decisionResults); when(requestContextMock.get(DMNScenarioExecutableBuilder.DMN_RESULT)).thenReturn(dmnResultMock); when(requestContextMock.get(DMNScenarioExecutableBuilder.DMN_MODEL)).thenReturn(dmnModelMock); ScenarioWithIndex scenarioWithIndex = new ScenarioWithIndex(1, scenario1); ScenarioResultMetadata scenarioResultMetadata = runnerHelper.extractResultMetadata(requestContextMock, scenarioWithIndex); assertThat(scenarioResultMetadata.getScenarioWithIndex()).isEqualTo(scenarioWithIndex); assertThat(scenarioResultMetadata.getAvailable()).hasSize(5).contains("decision1"); assertThat(scenarioResultMetadata.getExecuted()).hasSize(1).contains("decision2").doesNotContain("decision3"); final List<AuditLogLine> auditLogLines = scenarioResultMetadata.getAuditLogLines(); assertThat(auditLogLines).isNotNull().hasSameSizeAs(decisionResults); for (int i = 0; i < decisionResults.size(); i++) { commonCheckAuditLogLine(auditLogLines.get(i), decisionResults.get(i).getDecisionName(), decisionResults.get(i).getEvaluationStatus().name()); } } private DecisionNode createDecisionMock(String decisionName) { DecisionNode decisionMock = mock(DecisionNode.class); when(decisionMock.getName()).thenReturn(decisionName); return decisionMock; } private DMNDecisionResult createDecisionResultMock(String decisionName, boolean success, List<DMNMessage> messages) { DMNDecisionResult decisionResultMock = mock(DMNDecisionResult.class); when(decisionResultMock.getDecisionName()).thenReturn(decisionName); when(decisionResultMock.getEvaluationStatus()) .thenReturn(success ? DecisionEvaluationStatus.SUCCEEDED : DecisionEvaluationStatus.FAILED); if (messages != null) { Mockito.lenient().when(decisionResultMock.getMessages()).thenReturn(messages); } return decisionResultMock; } }
apache/incubator-tez
37,482
tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/shuffle/impl/MergeManager.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.runtime.library.common.shuffle.impl; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ChecksumFileSystem; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocalDirAllocator; import org.apache.hadoop.fs.LocalFileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.util.Progressable; import org.apache.tez.common.TezJobConfig; import org.apache.tez.common.TezUtils; import org.apache.tez.common.counters.TaskCounter; import org.apache.tez.common.counters.TezCounter; import org.apache.tez.dag.api.TezUncheckedException; import org.apache.tez.runtime.api.TezInputContext; import org.apache.tez.runtime.library.common.ConfigUtils; import org.apache.tez.runtime.library.common.Constants; import org.apache.tez.runtime.library.common.InputAttemptIdentifier; import org.apache.tez.runtime.library.common.combine.Combiner; import org.apache.tez.runtime.library.common.sort.impl.IFile; import org.apache.tez.runtime.library.common.sort.impl.TezMerger; import org.apache.tez.runtime.library.common.sort.impl.TezRawKeyValueIterator; import org.apache.tez.runtime.library.common.sort.impl.IFile.Writer; import org.apache.tez.runtime.library.common.sort.impl.TezMerger.Segment; import org.apache.tez.runtime.library.common.task.local.output.TezTaskOutputFiles; import org.apache.tez.runtime.library.hadoop.compat.NullProgressable; /** * Usage. Create instance. setInitialMemoryAvailable(long), configureAndStart() * */ @InterfaceAudience.Private @InterfaceStability.Unstable @SuppressWarnings(value={"rawtypes"}) public class MergeManager { private static final Log LOG = LogFactory.getLog(MergeManager.class); private final Configuration conf; private final FileSystem localFS; private final FileSystem rfs; private final LocalDirAllocator localDirAllocator; private final TezTaskOutputFiles mapOutputFile; private final Progressable nullProgressable = new NullProgressable(); private final Combiner combiner; private final Set<MapOutput> inMemoryMergedMapOutputs = new TreeSet<MapOutput>(new MapOutput.MapOutputComparator()); private final IntermediateMemoryToMemoryMerger memToMemMerger; private final Set<MapOutput> inMemoryMapOutputs = new TreeSet<MapOutput>(new MapOutput.MapOutputComparator()); private final InMemoryMerger inMemoryMerger; private final Set<Path> onDiskMapOutputs = new TreeSet<Path>(); private final OnDiskMerger onDiskMerger; private final long memoryLimit; private final int postMergeMemLimit; private long usedMemory; private long commitMemory; private final int ioSortFactor; private final long maxSingleShuffleLimit; private final int memToMemMergeOutputsThreshold; private final long mergeThreshold; private final long initialMemoryAvailable; private final ExceptionReporter exceptionReporter; private final TezInputContext inputContext; private final TezCounter spilledRecordsCounter; private final TezCounter reduceCombineInputCounter; private final TezCounter mergedMapOutputsCounter; private final TezCounter numMemToDiskMerges; private final TezCounter numDiskToDiskMerges; private final TezCounter additionalBytesWritten; private final TezCounter additionalBytesRead; private final CompressionCodec codec; private volatile boolean finalMergeComplete = false; private final boolean ifileReadAhead; private final int ifileReadAheadLength; private final int ifileBufferSize; /** * Construct the MergeManager. Must call start before it becomes usable. */ public MergeManager(Configuration conf, FileSystem localFS, LocalDirAllocator localDirAllocator, TezInputContext inputContext, Combiner combiner, TezCounter spilledRecordsCounter, TezCounter reduceCombineInputCounter, TezCounter mergedMapOutputsCounter, ExceptionReporter exceptionReporter, long initialMemoryAvailable, CompressionCodec codec, boolean ifileReadAheadEnabled, int ifileReadAheadLength) { this.inputContext = inputContext; this.conf = conf; this.localDirAllocator = localDirAllocator; this.exceptionReporter = exceptionReporter; this.initialMemoryAvailable = initialMemoryAvailable; this.combiner = combiner; this.reduceCombineInputCounter = reduceCombineInputCounter; this.spilledRecordsCounter = spilledRecordsCounter; this.mergedMapOutputsCounter = mergedMapOutputsCounter; this.mapOutputFile = new TezTaskOutputFiles(conf, inputContext.getUniqueIdentifier()); this.localFS = localFS; this.rfs = ((LocalFileSystem)localFS).getRaw(); this.numDiskToDiskMerges = inputContext.getCounters().findCounter(TaskCounter.NUM_DISK_TO_DISK_MERGES); this.numMemToDiskMerges = inputContext.getCounters().findCounter(TaskCounter.NUM_MEM_TO_DISK_MERGES); this.additionalBytesWritten = inputContext.getCounters().findCounter(TaskCounter.ADDITIONAL_SPILLS_BYTES_WRITTEN); this.additionalBytesRead = inputContext.getCounters().findCounter(TaskCounter.ADDITIONAL_SPILLS_BYTES_READ); this.codec = codec; this.ifileReadAhead = ifileReadAheadEnabled; if (this.ifileReadAhead) { this.ifileReadAheadLength = ifileReadAheadLength; } else { this.ifileReadAheadLength = 0; } this.ifileBufferSize = conf.getInt("io.file.buffer.size", TezJobConfig.TEZ_RUNTIME_IFILE_BUFFER_SIZE_DEFAULT); // Figure out initial memory req start final float maxInMemCopyUse = conf.getFloat( TezJobConfig.TEZ_RUNTIME_SHUFFLE_INPUT_BUFFER_PERCENT, TezJobConfig.TEZ_RUNTIME_SHUFFLE_INPUT_BUFFER_PERCENT_DEFAULT); if (maxInMemCopyUse > 1.0 || maxInMemCopyUse < 0.0) { throw new IllegalArgumentException("Invalid value for " + TezJobConfig.TEZ_RUNTIME_SHUFFLE_INPUT_BUFFER_PERCENT + ": " + maxInMemCopyUse); } // Allow unit tests to fix Runtime memory long memLimit = (long) (conf.getLong(Constants.TEZ_RUNTIME_TASK_MEMORY, Math.min(inputContext.getTotalMemoryAvailableToTask(), Integer.MAX_VALUE)) * maxInMemCopyUse); float maxRedPer = conf.getFloat(TezJobConfig.TEZ_RUNTIME_INPUT_BUFFER_PERCENT, TezJobConfig.TEZ_RUNTIME_INPUT_BUFFER_PERCENT_DEFAULT); if (maxRedPer > 1.0 || maxRedPer < 0.0) { throw new TezUncheckedException(TezJobConfig.TEZ_RUNTIME_INPUT_BUFFER_PERCENT + maxRedPer); } // TODO maxRedBuffer should be a long. int maxRedBuffer = (int) Math.min(inputContext.getTotalMemoryAvailableToTask() * maxRedPer, Integer.MAX_VALUE); // Figure out initial memory req end if (this.initialMemoryAvailable < memLimit) { this.memoryLimit = this.initialMemoryAvailable; } else { this.memoryLimit = memLimit; } if (this.initialMemoryAvailable < maxRedBuffer) { this.postMergeMemLimit = (int) this.initialMemoryAvailable; } else { this.postMergeMemLimit = maxRedBuffer; } LOG.info("InitialRequest: ShuffleMem=" + memLimit + ", postMergeMem=" + maxRedBuffer + ", RuntimeTotalAvailable=" + this.initialMemoryAvailable + "Updated to: ShuffleMem=" + this.memoryLimit + ", postMergeMem: " + this.postMergeMemLimit); this.ioSortFactor = conf.getInt( TezJobConfig.TEZ_RUNTIME_IO_SORT_FACTOR, TezJobConfig.TEZ_RUNTIME_IO_SORT_FACTOR_DEFAULT); final float singleShuffleMemoryLimitPercent = conf.getFloat( TezJobConfig.TEZ_RUNTIME_SHUFFLE_MEMORY_LIMIT_PERCENT, TezJobConfig.TEZ_RUNTIME_SHUFFLE_MEMORY_LIMIT_PERCENT_DEFAULT); if (singleShuffleMemoryLimitPercent <= 0.0f || singleShuffleMemoryLimitPercent > 1.0f) { throw new IllegalArgumentException("Invalid value for " + TezJobConfig.TEZ_RUNTIME_SHUFFLE_MEMORY_LIMIT_PERCENT + ": " + singleShuffleMemoryLimitPercent); } this.maxSingleShuffleLimit = (long)(memoryLimit * singleShuffleMemoryLimitPercent); this.memToMemMergeOutputsThreshold = conf.getInt( TezJobConfig.TEZ_RUNTIME_SHUFFLE_MEMTOMEM_SEGMENTS, ioSortFactor); this.mergeThreshold = (long)(this.memoryLimit * conf.getFloat( TezJobConfig.TEZ_RUNTIME_SHUFFLE_MERGE_PERCENT, TezJobConfig.TEZ_RUNTIME_SHUFFLE_MERGE_PERCENT_DEFAULT)); LOG.info("MergerManager: memoryLimit=" + memoryLimit + ", " + "maxSingleShuffleLimit=" + maxSingleShuffleLimit + ", " + "mergeThreshold=" + mergeThreshold + ", " + "ioSortFactor=" + ioSortFactor + ", " + "memToMemMergeOutputsThreshold=" + memToMemMergeOutputsThreshold); if (this.maxSingleShuffleLimit >= this.mergeThreshold) { throw new RuntimeException("Invlaid configuration: " + "maxSingleShuffleLimit should be less than mergeThreshold" + "maxSingleShuffleLimit: " + this.maxSingleShuffleLimit + "mergeThreshold: " + this.mergeThreshold); } boolean allowMemToMemMerge = conf.getBoolean( TezJobConfig.TEZ_RUNTIME_SHUFFLE_ENABLE_MEMTOMEM, TezJobConfig.TEZ_RUNTIME_SHUFFLE_ENABLE_MEMTOMEM_DEFAULT); if (allowMemToMemMerge) { this.memToMemMerger = new IntermediateMemoryToMemoryMerger(this, memToMemMergeOutputsThreshold); } else { this.memToMemMerger = null; } this.inMemoryMerger = new InMemoryMerger(this); this.onDiskMerger = new OnDiskMerger(this); } @Private void configureAndStart() { if (this.memToMemMerger != null) { memToMemMerger.start(); } this.inMemoryMerger.start(); this.onDiskMerger.start(); } /** * Exposing this to get an initial memory ask without instantiating the object. */ @Private static long getInitialMemoryRequirement(Configuration conf, long maxAvailableTaskMemory) { final float maxInMemCopyUse = conf.getFloat( TezJobConfig.TEZ_RUNTIME_SHUFFLE_INPUT_BUFFER_PERCENT, TezJobConfig.TEZ_RUNTIME_SHUFFLE_INPUT_BUFFER_PERCENT_DEFAULT); if (maxInMemCopyUse > 1.0 || maxInMemCopyUse < 0.0) { throw new IllegalArgumentException("Invalid value for " + TezJobConfig.TEZ_RUNTIME_SHUFFLE_INPUT_BUFFER_PERCENT + ": " + maxInMemCopyUse); } // Allow unit tests to fix Runtime memory long memLimit = (long) (conf.getLong(Constants.TEZ_RUNTIME_TASK_MEMORY, Math.min(maxAvailableTaskMemory, Integer.MAX_VALUE)) * maxInMemCopyUse); LOG.info("Initial Shuffle Memory Required: " + memLimit + ", based on INPUT_BUFFER_factor: " + maxInMemCopyUse); float maxRedPer = conf.getFloat(TezJobConfig.TEZ_RUNTIME_INPUT_BUFFER_PERCENT, TezJobConfig.TEZ_RUNTIME_INPUT_BUFFER_PERCENT_DEFAULT); if (maxRedPer > 1.0 || maxRedPer < 0.0) { throw new TezUncheckedException(TezJobConfig.TEZ_RUNTIME_INPUT_BUFFER_PERCENT + maxRedPer); } // TODO maxRedBuffer should be a long. int maxRedBuffer = (int) Math.min(maxAvailableTaskMemory * maxRedPer, Integer.MAX_VALUE); LOG.info("Initial Memory required for final merged output: " + maxRedBuffer + ", using factor: " + maxRedPer); long reqMem = Math.max(maxRedBuffer, memLimit); return reqMem; } public void waitForInMemoryMerge() throws InterruptedException { inMemoryMerger.waitForMerge(); } private boolean canShuffleToMemory(long requestedSize) { return (requestedSize < maxSingleShuffleLimit); } final private MapOutput stallShuffle = new MapOutput(null); public synchronized MapOutput reserve(InputAttemptIdentifier srcAttemptIdentifier, long requestedSize, int fetcher ) throws IOException { if (!canShuffleToMemory(requestedSize)) { LOG.info(srcAttemptIdentifier + ": Shuffling to disk since " + requestedSize + " is greater than maxSingleShuffleLimit (" + maxSingleShuffleLimit + ")"); return new MapOutput(srcAttemptIdentifier, this, requestedSize, conf, localDirAllocator, fetcher, true, mapOutputFile); } // Stall shuffle if we are above the memory limit // It is possible that all threads could just be stalling and not make // progress at all. This could happen when: // // requested size is causing the used memory to go above limit && // requested size < singleShuffleLimit && // current used size < mergeThreshold (merge will not get triggered) // // To avoid this from happening, we allow exactly one thread to go past // the memory limit. We check (usedMemory > memoryLimit) and not // (usedMemory + requestedSize > memoryLimit). When this thread is done // fetching, this will automatically trigger a merge thereby unlocking // all the stalled threads if (usedMemory > memoryLimit) { LOG.debug(srcAttemptIdentifier + ": Stalling shuffle since usedMemory (" + usedMemory + ") is greater than memoryLimit (" + memoryLimit + ")." + " CommitMemory is (" + commitMemory + ")"); return stallShuffle; } // Allow the in-memory shuffle to progress LOG.debug(srcAttemptIdentifier + ": Proceeding with shuffle since usedMemory (" + usedMemory + ") is lesser than memoryLimit (" + memoryLimit + ")." + "CommitMemory is (" + commitMemory + ")"); return unconditionalReserve(srcAttemptIdentifier, requestedSize, true); } /** * Unconditional Reserve is used by the Memory-to-Memory thread */ private synchronized MapOutput unconditionalReserve( InputAttemptIdentifier srcAttemptIdentifier, long requestedSize, boolean primaryMapOutput) { usedMemory += requestedSize; return new MapOutput(srcAttemptIdentifier, this, (int)requestedSize, primaryMapOutput); } synchronized void unreserve(long size) { commitMemory -= size; usedMemory -= size; } public synchronized void closeInMemoryFile(MapOutput mapOutput) { inMemoryMapOutputs.add(mapOutput); LOG.info("closeInMemoryFile -> map-output of size: " + mapOutput.getSize() + ", inMemoryMapOutputs.size() -> " + inMemoryMapOutputs.size() + ", commitMemory -> " + commitMemory + ", usedMemory ->" + usedMemory); commitMemory+= mapOutput.getSize(); synchronized (inMemoryMerger) { // Can hang if mergeThreshold is really low. // TODO Can avoid spilling in case total input size is between // mergeTghreshold and total available size. if (!inMemoryMerger.isInProgress() && commitMemory >= mergeThreshold) { LOG.info("Starting inMemoryMerger's merge since commitMemory=" + commitMemory + " > mergeThreshold=" + mergeThreshold + ". Current usedMemory=" + usedMemory); inMemoryMapOutputs.addAll(inMemoryMergedMapOutputs); inMemoryMergedMapOutputs.clear(); inMemoryMerger.startMerge(inMemoryMapOutputs); } } // This should likely run a Combiner. if (memToMemMerger != null) { synchronized (memToMemMerger) { if (!memToMemMerger.isInProgress() && inMemoryMapOutputs.size() >= memToMemMergeOutputsThreshold) { memToMemMerger.startMerge(inMemoryMapOutputs); } } } } public synchronized void closeInMemoryMergedFile(MapOutput mapOutput) { inMemoryMergedMapOutputs.add(mapOutput); LOG.info("closeInMemoryMergedFile -> size: " + mapOutput.getSize() + ", inMemoryMergedMapOutputs.size() -> " + inMemoryMergedMapOutputs.size()); } public synchronized void closeOnDiskFile(Path file) { onDiskMapOutputs.add(file); synchronized (onDiskMerger) { if (!onDiskMerger.isInProgress() && onDiskMapOutputs.size() >= (2 * ioSortFactor - 1)) { onDiskMerger.startMerge(onDiskMapOutputs); } } } /** * Should <b>only</b> be used after the Shuffle phaze is complete, otherwise can * return an invalid state since a merge may not be in progress dur to * inadequate inputs * * @return true if the merge process is complete, otherwise false */ @Private public boolean isMergeComplete() { return finalMergeComplete; } public TezRawKeyValueIterator close() throws Throwable { // Wait for on-going merges to complete if (memToMemMerger != null) { memToMemMerger.close(); } inMemoryMerger.close(); onDiskMerger.close(); List<MapOutput> memory = new ArrayList<MapOutput>(inMemoryMergedMapOutputs); inMemoryMergedMapOutputs.clear(); memory.addAll(inMemoryMapOutputs); inMemoryMapOutputs.clear(); List<Path> disk = new ArrayList<Path>(onDiskMapOutputs); onDiskMapOutputs.clear(); TezRawKeyValueIterator kvIter = finalMerge(conf, rfs, memory, disk); this.finalMergeComplete = true; return kvIter; } void runCombineProcessor(TezRawKeyValueIterator kvIter, Writer writer) throws IOException, InterruptedException { combiner.combine(kvIter, writer); } /** * Merges multiple in-memory segment to another in-memory segment */ private class IntermediateMemoryToMemoryMerger extends MergeThread<MapOutput> { public IntermediateMemoryToMemoryMerger(MergeManager manager, int mergeFactor) { super(manager, mergeFactor, exceptionReporter); setName("MemToMemMerger [" + TezUtils.cleanVertexName(inputContext.getSourceVertexName()) + "]"); setDaemon(true); } @Override public void merge(List<MapOutput> inputs) throws IOException { if (inputs == null || inputs.size() == 0) { return; } InputAttemptIdentifier dummyMapId = inputs.get(0).getAttemptIdentifier(); List<Segment> inMemorySegments = new ArrayList<Segment>(); long mergeOutputSize = createInMemorySegments(inputs, inMemorySegments, 0); int noInMemorySegments = inMemorySegments.size(); MapOutput mergedMapOutputs = unconditionalReserve(dummyMapId, mergeOutputSize, false); Writer writer = new InMemoryWriter(mergedMapOutputs.getArrayStream()); LOG.info("Initiating Memory-to-Memory merge with " + noInMemorySegments + " segments of total-size: " + mergeOutputSize); // Nothing will be materialized to disk because the sort factor is being // set to the number of in memory segments. // TODO Is this doing any combination ? TezRawKeyValueIterator rIter = TezMerger.merge(conf, rfs, ConfigUtils.getIntermediateInputKeyClass(conf), ConfigUtils.getIntermediateInputValueClass(conf), inMemorySegments, inMemorySegments.size(), new Path(inputContext.getUniqueIdentifier()), (RawComparator)ConfigUtils.getIntermediateInputKeyComparator(conf), nullProgressable, null, null, null, null); TezMerger.writeFile(rIter, writer, nullProgressable, TezJobConfig.TEZ_RUNTIME_RECORDS_BEFORE_PROGRESS_DEFAULT); writer.close(); LOG.info(inputContext.getUniqueIdentifier() + " Memory-to-Memory merge of the " + noInMemorySegments + " files in-memory complete."); // Note the output of the merge closeInMemoryMergedFile(mergedMapOutputs); } } /** * Merges multiple in-memory segment to a disk segment */ private class InMemoryMerger extends MergeThread<MapOutput> { public InMemoryMerger(MergeManager manager) { super(manager, Integer.MAX_VALUE, exceptionReporter); setName("MemtoDiskMerger [" + TezUtils.cleanVertexName(inputContext.getSourceVertexName()) + "]"); setDaemon(true); } @Override public void merge(List<MapOutput> inputs) throws IOException, InterruptedException { if (inputs == null || inputs.size() == 0) { return; } numMemToDiskMerges.increment(1); //name this output file same as the name of the first file that is //there in the current list of inmem files (this is guaranteed to //be absent on the disk currently. So we don't overwrite a prev. //created spill). Also we need to create the output file now since //it is not guaranteed that this file will be present after merge //is called (we delete empty files as soon as we see them //in the merge method) //figure out the mapId InputAttemptIdentifier srcTaskIdentifier = inputs.get(0).getAttemptIdentifier(); List<Segment> inMemorySegments = new ArrayList<Segment>(); long mergeOutputSize = createInMemorySegments(inputs, inMemorySegments,0); int noInMemorySegments = inMemorySegments.size(); // TODO Maybe track serialized vs deserialized bytes. // All disk writes done by this merge are overhead - due to the lac of // adequate memory to keep all segments in memory. Path outputPath = mapOutputFile.getInputFileForWrite( srcTaskIdentifier.getInputIdentifier().getInputIndex(), mergeOutputSize).suffix(Constants.MERGED_OUTPUT_PREFIX); Writer writer = null; try { writer = new Writer(conf, rfs, outputPath, (Class)ConfigUtils.getIntermediateInputKeyClass(conf), (Class)ConfigUtils.getIntermediateInputValueClass(conf), codec, null, null); TezRawKeyValueIterator rIter = null; LOG.info("Initiating in-memory merge with " + noInMemorySegments + " segments..."); // Nothing actually materialized to disk - controlled by setting sort-factor to #segments. rIter = TezMerger.merge(conf, rfs, (Class)ConfigUtils.getIntermediateInputKeyClass(conf), (Class)ConfigUtils.getIntermediateInputValueClass(conf), inMemorySegments, inMemorySegments.size(), new Path(inputContext.getUniqueIdentifier()), (RawComparator)ConfigUtils.getIntermediateInputKeyComparator(conf), nullProgressable, spilledRecordsCounter, null, additionalBytesRead, null); // spilledRecordsCounter is tracking the number of keys that will be // read from each of the segments being merged - which is essentially // what will be written to disk. if (null == combiner) { TezMerger.writeFile(rIter, writer, nullProgressable, TezJobConfig.TEZ_RUNTIME_RECORDS_BEFORE_PROGRESS_DEFAULT); } else { // TODO Counters for Combine runCombineProcessor(rIter, writer); } writer.close(); additionalBytesWritten.increment(writer.getCompressedLength()); writer = null; LOG.info(inputContext.getUniqueIdentifier() + " Merge of the " + noInMemorySegments + " files in-memory complete." + " Local file is " + outputPath + " of size " + localFS.getFileStatus(outputPath).getLen()); } catch (IOException e) { //make sure that we delete the ondisk file that we created //earlier when we invoked cloneFileAttributes localFS.delete(outputPath, true); throw e; } finally { if (writer != null) { writer.close(); } } // Note the output of the merge closeOnDiskFile(outputPath); } } /** * Merges multiple on-disk segments */ private class OnDiskMerger extends MergeThread<Path> { public OnDiskMerger(MergeManager manager) { super(manager, ioSortFactor, exceptionReporter); setName("DiskToDiskMerger [" + TezUtils.cleanVertexName(inputContext.getSourceVertexName()) + "]"); setDaemon(true); } @Override public void merge(List<Path> inputs) throws IOException { // sanity check if (inputs == null || inputs.isEmpty()) { LOG.info("No ondisk files to merge..."); return; } numDiskToDiskMerges.increment(1); long approxOutputSize = 0; int bytesPerSum = conf.getInt("io.bytes.per.checksum", 512); LOG.info("OnDiskMerger: We have " + inputs.size() + " map outputs on disk. Triggering merge..."); // 1. Prepare the list of files to be merged. for (Path file : inputs) { approxOutputSize += localFS.getFileStatus(file).getLen(); } // add the checksum length approxOutputSize += ChecksumFileSystem.getChecksumLength(approxOutputSize, bytesPerSum); // 2. Start the on-disk merge process Path outputPath = localDirAllocator.getLocalPathForWrite(inputs.get(0).toString(), approxOutputSize, conf).suffix(Constants.MERGED_OUTPUT_PREFIX); Writer writer = new Writer(conf, rfs, outputPath, (Class)ConfigUtils.getIntermediateInputKeyClass(conf), (Class)ConfigUtils.getIntermediateInputValueClass(conf), codec, null, null); TezRawKeyValueIterator iter = null; Path tmpDir = new Path(inputContext.getUniqueIdentifier()); try { iter = TezMerger.merge(conf, rfs, (Class)ConfigUtils.getIntermediateInputKeyClass(conf), (Class)ConfigUtils.getIntermediateInputValueClass(conf), codec, ifileReadAhead, ifileReadAheadLength, ifileBufferSize, inputs.toArray(new Path[inputs.size()]), true, ioSortFactor, tmpDir, (RawComparator)ConfigUtils.getIntermediateInputKeyComparator(conf), nullProgressable, spilledRecordsCounter, null, mergedMapOutputsCounter, null); // TODO Maybe differentiate between data written because of Merges and // the finalMerge (i.e. final mem available may be different from // initial merge mem) TezMerger.writeFile(iter, writer, nullProgressable, TezJobConfig.TEZ_RUNTIME_RECORDS_BEFORE_PROGRESS_DEFAULT); writer.close(); additionalBytesWritten.increment(writer.getCompressedLength()); } catch (IOException e) { localFS.delete(outputPath, true); throw e; } closeOnDiskFile(outputPath); LOG.info(inputContext.getUniqueIdentifier() + " Finished merging " + inputs.size() + " map output files on disk of total-size " + approxOutputSize + "." + " Local output file is " + outputPath + " of size " + localFS.getFileStatus(outputPath).getLen()); } } private long createInMemorySegments(List<MapOutput> inMemoryMapOutputs, List<Segment> inMemorySegments, long leaveBytes ) throws IOException { long totalSize = 0L; // We could use fullSize could come from the RamManager, but files can be // closed but not yet present in inMemoryMapOutputs long fullSize = 0L; for (MapOutput mo : inMemoryMapOutputs) { fullSize += mo.getMemory().length; } while(fullSize > leaveBytes) { MapOutput mo = inMemoryMapOutputs.remove(0); byte[] data = mo.getMemory(); long size = data.length; totalSize += size; fullSize -= size; IFile.Reader reader = new InMemoryReader(MergeManager.this, mo.getAttemptIdentifier(), data, 0, (int)size); inMemorySegments.add(new Segment(reader, true, (mo.isPrimaryMapOutput() ? mergedMapOutputsCounter : null))); } return totalSize; } class RawKVIteratorReader extends IFile.Reader { private final TezRawKeyValueIterator kvIter; public RawKVIteratorReader(TezRawKeyValueIterator kvIter, long size) throws IOException { super(null, size, null, spilledRecordsCounter, null, ifileReadAhead, ifileReadAheadLength, ifileBufferSize); this.kvIter = kvIter; } @Override public KeyState readRawKey(DataInputBuffer key) throws IOException { if (kvIter.next()) { final DataInputBuffer kb = kvIter.getKey(); final int kp = kb.getPosition(); final int klen = kb.getLength() - kp; key.reset(kb.getData(), kp, klen); bytesRead += klen; return KeyState.NEW_KEY; } return KeyState.NO_KEY; } public void nextRawValue(DataInputBuffer value) throws IOException { final DataInputBuffer vb = kvIter.getValue(); final int vp = vb.getPosition(); final int vlen = vb.getLength() - vp; value.reset(vb.getData(), vp, vlen); bytesRead += vlen; } public long getPosition() throws IOException { return bytesRead; } public void close() throws IOException { kvIter.close(); } } private TezRawKeyValueIterator finalMerge(Configuration job, FileSystem fs, List<MapOutput> inMemoryMapOutputs, List<Path> onDiskMapOutputs ) throws IOException { LOG.info("finalMerge called with " + inMemoryMapOutputs.size() + " in-memory map-outputs and " + onDiskMapOutputs.size() + " on-disk map-outputs"); // merge config params Class keyClass = (Class)ConfigUtils.getIntermediateInputKeyClass(job); Class valueClass = (Class)ConfigUtils.getIntermediateInputValueClass(job); final Path tmpDir = new Path(inputContext.getUniqueIdentifier()); final RawComparator comparator = (RawComparator)ConfigUtils.getIntermediateInputKeyComparator(job); // segments required to vacate memory List<Segment> memDiskSegments = new ArrayList<Segment>(); long inMemToDiskBytes = 0; boolean mergePhaseFinished = false; if (inMemoryMapOutputs.size() > 0) { int srcTaskId = inMemoryMapOutputs.get(0).getAttemptIdentifier().getInputIdentifier().getInputIndex(); inMemToDiskBytes = createInMemorySegments(inMemoryMapOutputs, memDiskSegments, this.postMergeMemLimit); final int numMemDiskSegments = memDiskSegments.size(); if (numMemDiskSegments > 0 && ioSortFactor > onDiskMapOutputs.size()) { // If we reach here, it implies that we have less than io.sort.factor // disk segments and this will be incremented by 1 (result of the // memory segments merge). Since this total would still be // <= io.sort.factor, we will not do any more intermediate merges, // the merge of all these disk segments would be directly fed to the // reduce method mergePhaseFinished = true; // must spill to disk, but can't retain in-mem for intermediate merge final Path outputPath = mapOutputFile.getInputFileForWrite(srcTaskId, inMemToDiskBytes).suffix( Constants.MERGED_OUTPUT_PREFIX); final TezRawKeyValueIterator rIter = TezMerger.merge(job, fs, keyClass, valueClass, memDiskSegments, numMemDiskSegments, tmpDir, comparator, nullProgressable, spilledRecordsCounter, null, additionalBytesRead, null); final Writer writer = new Writer(job, fs, outputPath, keyClass, valueClass, codec, null, null); try { TezMerger.writeFile(rIter, writer, nullProgressable, TezJobConfig.TEZ_RUNTIME_RECORDS_BEFORE_PROGRESS_DEFAULT); // add to list of final disk outputs. onDiskMapOutputs.add(outputPath); } catch (IOException e) { if (null != outputPath) { try { fs.delete(outputPath, true); } catch (IOException ie) { // NOTHING } } throw e; } finally { if (null != writer) { writer.close(); additionalBytesWritten.increment(writer.getCompressedLength()); } } LOG.info("Merged " + numMemDiskSegments + " segments, " + inMemToDiskBytes + " bytes to disk to satisfy " + "reduce memory limit"); inMemToDiskBytes = 0; memDiskSegments.clear(); } else if (inMemToDiskBytes != 0) { LOG.info("Keeping " + numMemDiskSegments + " segments, " + inMemToDiskBytes + " bytes in memory for " + "intermediate, on-disk merge"); } } // segments on disk List<Segment> diskSegments = new ArrayList<Segment>(); long onDiskBytes = inMemToDiskBytes; Path[] onDisk = onDiskMapOutputs.toArray(new Path[onDiskMapOutputs.size()]); for (Path file : onDisk) { onDiskBytes += fs.getFileStatus(file).getLen(); LOG.debug("Disk file: " + file + " Length is " + fs.getFileStatus(file).getLen()); diskSegments.add(new Segment(job, fs, file, codec, ifileReadAhead, ifileReadAheadLength, ifileBufferSize, false, (file.toString().endsWith( Constants.MERGED_OUTPUT_PREFIX) ? null : mergedMapOutputsCounter) )); } LOG.info("Merging " + onDisk.length + " files, " + onDiskBytes + " bytes from disk"); Collections.sort(diskSegments, new Comparator<Segment>() { public int compare(Segment o1, Segment o2) { if (o1.getLength() == o2.getLength()) { return 0; } return o1.getLength() < o2.getLength() ? -1 : 1; } }); // build final list of segments from merged backed by disk + in-mem List<Segment> finalSegments = new ArrayList<Segment>(); long inMemBytes = createInMemorySegments(inMemoryMapOutputs, finalSegments, 0); LOG.info("Merging " + finalSegments.size() + " segments, " + inMemBytes + " bytes from memory into reduce"); if (0 != onDiskBytes) { final int numInMemSegments = memDiskSegments.size(); diskSegments.addAll(0, memDiskSegments); memDiskSegments.clear(); TezRawKeyValueIterator diskMerge = TezMerger.merge( job, fs, keyClass, valueClass, codec, diskSegments, ioSortFactor, numInMemSegments, tmpDir, comparator, nullProgressable, false, spilledRecordsCounter, null, additionalBytesRead, null); diskSegments.clear(); if (0 == finalSegments.size()) { return diskMerge; } finalSegments.add(new Segment( new RawKVIteratorReader(diskMerge, onDiskBytes), true)); } // This is doing nothing but creating an iterator over the segments. return TezMerger.merge(job, fs, keyClass, valueClass, finalSegments, finalSegments.size(), tmpDir, comparator, nullProgressable, spilledRecordsCounter, null, additionalBytesRead, null); } }
apache/streampark
37,642
streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/watcher/FlinkAppHttpWatcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.streampark.console.core.watcher; import org.apache.streampark.common.enums.FlinkDeployMode; import org.apache.streampark.common.util.DateUtils; import org.apache.streampark.common.util.HttpClientUtils; import org.apache.streampark.common.util.YarnUtils; import org.apache.streampark.console.base.util.JacksonUtils; import org.apache.streampark.console.core.bean.AlertTemplate; import org.apache.streampark.console.core.component.FlinkCheckpointProcessor; import org.apache.streampark.console.core.entity.FlinkApplication; import org.apache.streampark.console.core.entity.FlinkCluster; import org.apache.streampark.console.core.entity.FlinkStateChangeEvent; import org.apache.streampark.console.core.enums.FlinkAppStateEnum; import org.apache.streampark.console.core.enums.OptionStateEnum; import org.apache.streampark.console.core.enums.ReleaseStateEnum; import org.apache.streampark.console.core.enums.StopFromEnum; import org.apache.streampark.console.core.metrics.flink.CheckPoints; import org.apache.streampark.console.core.metrics.flink.JobsOverview; import org.apache.streampark.console.core.metrics.flink.Overview; import org.apache.streampark.console.core.metrics.yarn.YarnAppInfo; import org.apache.streampark.console.core.service.FlinkClusterService; import org.apache.streampark.console.core.service.SavepointService; import org.apache.streampark.console.core.service.alert.AlertService; import org.apache.streampark.console.core.service.application.FlinkApplicationActionService; import org.apache.streampark.console.core.service.application.FlinkApplicationInfoService; import org.apache.streampark.console.core.service.application.FlinkApplicationManageService; import org.apache.streampark.console.core.util.AlertTemplateUtils; import org.apache.commons.lang3.StringUtils; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.core5.util.Timeout; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.IOException; import java.time.Duration; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** This implementation is currently used for tracing flink job on yarn,standalone,remote mode */ @Slf4j @Component public class FlinkAppHttpWatcher { @Autowired private FlinkApplicationManageService applicationManageService; @Autowired private FlinkApplicationActionService applicationActionService; @Autowired private FlinkApplicationInfoService applicationInfoService; @Autowired private AlertService alertService; @Autowired private FlinkCheckpointProcessor checkpointProcessor; @Autowired private FlinkClusterService flinkClusterService; @Autowired private SavepointService savepointService; // track interval every 5 seconds public static final Duration WATCHING_INTERVAL = Duration.ofSeconds(5); // option interval within 10 seconds private static final Duration OPTION_INTERVAL = Duration.ofSeconds(10); private static final Timeout HTTP_TIMEOUT = Timeout.ofSeconds(5); /** * * * <pre> * record task requires save points * It will only be used in the RUNNING state. If it is checked that the task is running and the save point is required, * set the state of the task to savepoint * </pre> */ private static final Cache<Long, Byte> SAVEPOINT_CACHE = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).build(); /** * Record the status of the first tracking task, because after the task is started, the overview * of the task will be obtained during the first tracking */ private static final Cache<Long, Byte> STARTING_CACHE = Caffeine.newBuilder().expireAfterWrite(5, TimeUnit.MINUTES).build(); private static final Cache<Long, Date> LOST_CACHE = Caffeine.newBuilder().expireAfterWrite(5, TimeUnit.MINUTES).build(); /** tracking task list */ private static final Map<Long, FlinkApplication> WATCHING_APPS = new ConcurrentHashMap<>(0); /** * * * <pre> * StopFrom: marked a task stopped from the stream-park web or other ways. * If stop from stream-park web, you can know whether to make a savepoint when you stop the task, and if you make a savepoint, * you can set the savepoint as the last effect savepoint, and the next time start, will be automatically choose to start. * In other words, if stop from other ways, there is no way to know the savepoint has been done, directly set all the savepoint * to expire, and needs to be manually specified when started again. * </pre> */ private static final Map<Long, StopFromEnum> STOP_FROM_MAP = new ConcurrentHashMap<>(0); /** * Cancelling tasks are placed in this cache with an expiration time of 10 seconds (the time of 2 * task monitoring polls). */ private static final Cache<Long, Byte> CANCELING_CACHE = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).build(); private static final Cache<Long, FlinkStateChangeEvent> PREVIOUS_STATUS = Caffeine.newBuilder().expireAfterWrite(24, TimeUnit.HOURS).build(); /** * Task canceled tracking list, record who cancelled the tracking task Map<applicationId,userId> */ private static final Map<Long, Long> CANCELLED_JOB_MAP = new ConcurrentHashMap<>(0); private static final Map<Long, FlinkCluster> FLINK_CLUSTER_MAP = new ConcurrentHashMap<>(0); private static final Map<Long, OptionStateEnum> OPTIONING = new ConcurrentHashMap<>(0); private Long lastWatchTime = 0L; private Long lastOptionTime = 0L; private static final Byte DEFAULT_FLAG_BYTE = Byte.valueOf("0"); @Qualifier("flinkRestAPIWatchingExecutor") @Autowired private Executor watchExecutor; @PostConstruct public void init() { WATCHING_APPS.clear(); List<FlinkApplication> applications = applicationManageService.list( new LambdaQueryWrapper<FlinkApplication>() .eq(FlinkApplication::getTracking, 1) .notIn(FlinkApplication::getDeployMode, FlinkDeployMode.getKubernetesMode())); applications.forEach(app -> { Long appId = app.getId(); WATCHING_APPS.put(appId, app); STARTING_CACHE.put(appId, DEFAULT_FLAG_BYTE); }); } @PreDestroy public void doStop() { log.info( "[StreamPark][FlinkAppHttpWatcher] StreamPark Console will be shutdown,persistent application to database."); WATCHING_APPS.forEach((k, v) -> applicationManageService.persistMetrics(v)); } /** * <strong>NOTE: The following conditions must be met for execution</strong> * * <p><strong>1) Program started or page operated task, such as start/stop, needs to return the * state immediately. (the frequency of 1 second once, continued 10 seconds (10 times))</strong> * * <p><strong>2) Normal information obtain, once every 5 seconds</strong> */ @Scheduled(fixedDelay = 1, initialDelay = 5, timeUnit = TimeUnit.SECONDS) public void start() { Long timeMillis = System.currentTimeMillis(); if (lastWatchTime == null || !OPTIONING.isEmpty() || timeMillis - lastOptionTime <= OPTION_INTERVAL.toMillis() || timeMillis - lastWatchTime >= WATCHING_INTERVAL.toMillis()) { lastWatchTime = timeMillis; WATCHING_APPS.forEach(this::watch); } } private void watch(Long id, FlinkApplication application) { watchExecutor.execute( () -> { try { // query status from flink rest api getStateFromFlink(application); cleanupLost(application); } catch (Exception flinkException) { // query status from yarn rest api try { getStateFromYarn(application); cleanupLost(application); } catch (Exception yarnException) { doStateFailed(application); } } }); } private void cleanupLost(FlinkApplication application) { LOST_CACHE.invalidate(application.getId()); } private void doStateFailed(FlinkApplication application) { /* * Query from flink's restAPI and yarn's restAPI both failed. In this case, it is necessary to decide whether to * return to the final state depending on the state being operated */ StopFromEnum stopFrom = getStopFrom(application); OptionStateEnum optionState = OPTIONING.get(application.getId()); if (optionState == null || !optionState.equals(OptionStateEnum.STARTING)) { // non-mapping if (application.getState() != FlinkAppStateEnum.MAPPING.getValue()) { log.error( "[StreamPark][FlinkAppHttpWatcher] getFromFlinkRestApi and getFromYarnRestApi error,job failed,savepoint expired!"); if (StopFromEnum.NONE.equals(stopFrom)) { Date lostTime = LOST_CACHE.getIfPresent(application.getId()); if (lostTime == null) { LOST_CACHE.put(application.getId(), new Date()); } else if (DateUtils.toSecondDuration(lostTime, new Date()) >= 30) { savepointService.expire(application.getId()); application.setState(FlinkAppStateEnum.LOST.getValue()); WATCHING_APPS.remove(application.getId()); LOST_CACHE.invalidate(application.getId()); } } else { application.setState(FlinkAppStateEnum.CANCELED.getValue()); } } /* * This step means that the above two ways to get information have failed, and this step is the last step, * which will directly identify the mission as cancelled or lost. Need clean savepoint. */ application.setEndTime(new Date()); cleanSavepoint(application); cleanOptioning(optionState, application.getId()); doPersistMetrics(application, true); FlinkAppStateEnum appState = application.getStateEnum(); if (appState.equals(FlinkAppStateEnum.FAILED) || appState.equals(FlinkAppStateEnum.LOST)) { doAlert(application, appState); if (appState.equals(FlinkAppStateEnum.FAILED)) { try { applicationActionService.start(application, true); } catch (Exception e) { log.error(e.getMessage(), e); } } } } } /** * Get the current task running status information from flink restapi * * @param application application */ private void getStateFromFlink(FlinkApplication application) throws Exception { StopFromEnum stopFrom = getStopFrom(application); JobsOverview jobsOverview = httpJobsOverview(application); Optional<JobsOverview.Job> optional; FlinkDeployMode deployMode = application.getDeployModeEnum(); if (FlinkDeployMode.YARN_APPLICATION.equals(deployMode) || FlinkDeployMode.YARN_PER_JOB.equals(deployMode)) { if (jobsOverview.getJobs() != null) { optional = jobsOverview.getJobs().size() > 1 ? jobsOverview.getJobs().stream() .filter(a -> StringUtils.equals(application.getJobId(), a.getId())) .findFirst() : jobsOverview.getJobs().stream().findFirst(); } else { optional = Optional.empty(); } } else { optional = jobsOverview.getJobs().stream() .filter(x -> x.getId().equals(application.getJobId())) .findFirst(); } if (optional.isPresent()) { JobsOverview.Job jobOverview = optional.get(); FlinkAppStateEnum currentState = FlinkAppStateEnum.getState(jobOverview.getState()); if (!FlinkAppStateEnum.OTHER.equals(currentState)) { try { // 1) set info from JobOverview handleJobOverview(application, jobOverview); } catch (Exception e) { log.error("get flink jobOverview error: {}", e.getMessage(), e); } try { // 2) CheckPoints handleCheckPoints(application); } catch (Exception e) { log.error("get flink jobOverview error: {}", e.getMessage(), e); } // 3) savepoint obsolete check and NEED_START check OptionStateEnum optionState = OPTIONING.get(application.getId()); if (currentState.equals(FlinkAppStateEnum.RUNNING)) { handleRunningState(application, optionState, currentState); } else { handleNotRunState(application, optionState, currentState, stopFrom); } } } } private StopFromEnum getStopFrom(FlinkApplication application) { return STOP_FROM_MAP.getOrDefault(application.getId(), null) == null ? StopFromEnum.NONE : STOP_FROM_MAP.get(application.getId()); } /** * handle job overview * * @param application application * @param jobOverview jobOverview */ private void handleJobOverview(FlinkApplication application, JobsOverview.Job jobOverview) throws IOException { // compute duration long startTime = jobOverview.getStartTime(); long endTime = jobOverview.getEndTime(); if (application.getStartTime() == null || startTime != application.getStartTime().getTime()) { application.setStartTime(new Date(startTime)); } if (endTime != -1) { if (application.getEndTime() == null || endTime != application.getEndTime().getTime()) { application.setEndTime(new Date(endTime)); } } application.setJobId(jobOverview.getId()); application.setDuration(jobOverview.getDuration()); application.setTotalTask(jobOverview.getTasks().getTotal()); application.setOverview(jobOverview.getTasks()); // get overview info at the first start time if (STARTING_CACHE.getIfPresent(application.getId()) != null) { Overview override = httpOverview(application); if (override != null && override.getSlotsTotal() > 0) { application.setTotalTM(override.getTaskmanagers()); application.setTotalSlot(override.getSlotsTotal()); application.setAvailableSlot(override.getSlotsAvailable()); } STARTING_CACHE.invalidate(application.getId()); } } /** get latest checkpoint */ private void handleCheckPoints(FlinkApplication application) throws Exception { CheckPoints checkPoints = httpCheckpoints(application); if (checkPoints != null) { checkpointProcessor.process(application, checkPoints); } } /** * Handle running task * * @param application application * @param optionState optionState * @param currentState currentState */ private void handleRunningState( FlinkApplication application, OptionStateEnum optionState, FlinkAppStateEnum currentState) { /* * if the last recorded state is STARTING and the latest state obtained this time is RUNNING, which means it is * the first tracking after restart. Then: the following the job status needs to be updated to the restart * status: NEED_RESTART_AFTER_CONF_UPDATE (Need to restart after modified configuration) * NEED_RESTART_AFTER_SQL_UPDATE (Need to restart after modified flink sql) NEED_RESTART_AFTER_ROLLBACK (Need to * restart after rollback) NEED_RESTART_AFTER_DEPLOY (Need to rollback after deploy) */ Long appId = application.getId(); if (OptionStateEnum.STARTING.equals(optionState)) { FlinkApplication latestApp = WATCHING_APPS.get(appId); ReleaseStateEnum releaseState = latestApp.getReleaseState(); switch (releaseState) { case NEED_RESTART: case NEED_ROLLBACK: LambdaUpdateWrapper<FlinkApplication> updateWrapper = new LambdaUpdateWrapper<FlinkApplication>() .eq(FlinkApplication::getId, appId) .set(FlinkApplication::getRelease, ReleaseStateEnum.DONE.get()); applicationManageService.update(updateWrapper); break; default: break; } } // The current state is running, and there is a current task in the savepointCache, // indicating that the task is doing savepoint if (SAVEPOINT_CACHE.getIfPresent(appId) != null) { application.setOptionState(OptionStateEnum.SAVEPOINTING.getValue()); } else { application.setOptionState(OptionStateEnum.NONE.getValue()); } application.setState(currentState.getValue()); doPersistMetrics(application, false); cleanOptioning(optionState, appId); } private void doPersistMetrics(FlinkApplication application, boolean stopWatch) { Long appId = application.getId(); if (FlinkAppStateEnum.isEndState(application.getState())) { application.setOverview(null); application.setTotalTM(null); application.setTotalSlot(null); application.setTotalTask(null); application.setAvailableSlot(null); application.setJmMemory(null); application.setTmMemory(null); unWatching(appId); } else if (stopWatch) { unWatching(appId); } else { WATCHING_APPS.put(appId, application); } FlinkStateChangeEvent event = PREVIOUS_STATUS.getIfPresent(appId); FlinkStateChangeEvent nowEvent = createStateChangeEvent(application); if (!nowEvent.equals(event)) { PREVIOUS_STATUS.put(appId, nowEvent); applicationManageService.persistMetrics(application); } } /** * Handle not running task * * @param application application * @param optionState optionState * @param currentState currentState * @param stopFrom stopFrom */ private void handleNotRunState( FlinkApplication application, OptionStateEnum optionState, FlinkAppStateEnum currentState, StopFromEnum stopFrom) throws Exception { switch (currentState) { case CANCELLING: CANCELING_CACHE.put(application.getId(), DEFAULT_FLAG_BYTE); cleanSavepoint(application); application.setState(currentState.getValue()); doPersistMetrics(application, false); break; case CANCELED: case FINISHED: log.info( "[StreamPark][FlinkAppHttpWatcher] getFromFlinkRestApi, job state {}, stop tracking and delete stopFrom!", currentState.name()); cleanSavepoint(application); application.setState(currentState.getValue()); if (StopFromEnum.NONE.equals(stopFrom) || applicationInfoService.checkAlter(application)) { if (StopFromEnum.NONE.equals(stopFrom)) { log.info( "[StreamPark][FlinkAppHttpWatcher] getFromFlinkRestApi, job cancel is not form StreamPark,savepoint expired!"); savepointService.expire(application.getId()); } stopCanceledJob(application.getId()); doAlert(application, FlinkAppStateEnum.CANCELED); } STOP_FROM_MAP.remove(application.getId()); doPersistMetrics(application, true); cleanOptioning(optionState, application.getId()); break; case FAILED: cleanSavepoint(application); STOP_FROM_MAP.remove(application.getId()); application.setState(FlinkAppStateEnum.FAILED.getValue()); doPersistMetrics(application, true); doAlert(application, FlinkAppStateEnum.FAILED); applicationActionService.start(application, true); break; case RESTARTING: log.info( "[StreamPark][FlinkAppHttpWatcher] getFromFlinkRestApi, job state {},add to starting", currentState.name()); STARTING_CACHE.put(application.getId(), DEFAULT_FLAG_BYTE); break; default: application.setState(currentState.getValue()); doPersistMetrics(application, false); break; } } /** * <strong>Query the job history in yarn, indicating that the task has stopped, and the final * status of the task is CANCELED</strong> * * @param application application */ private void getStateFromYarn(FlinkApplication application) throws Exception { log.debug("[StreamPark][FlinkAppHttpWatcher] getFromYarnRestApi starting..."); StopFromEnum stopFrom = getStopFrom(application); OptionStateEnum optionState = OPTIONING.get(application.getId()); /* * If the status of the last time is CANCELING (flink rest server is not closed at the time of getting * information) and the status is not obtained this time (flink rest server is closed), the task is considered * CANCELED */ Byte flag = CANCELING_CACHE.getIfPresent(application.getId()); if (flag != null) { log.info("[StreamPark][FlinkAppHttpWatcher] previous state: canceling."); FlinkAppStateEnum flinkAppState = FlinkAppStateEnum.CANCELED; try { YarnAppInfo yarnAppInfo = httpYarnAppInfo(application); if (yarnAppInfo != null) { String state = yarnAppInfo.getApp().getFinalStatus(); flinkAppState = FlinkAppStateEnum.getState(state); } } finally { if (StopFromEnum.NONE.equals(stopFrom)) { log.error( "[StreamPark][FlinkAppHttpWatcher] query previous state was canceling and stopFrom NotFound,savepoint expired!"); savepointService.expire(application.getId()); if (flinkAppState == FlinkAppStateEnum.KILLED || flinkAppState == FlinkAppStateEnum.FAILED) { doAlert(application, flinkAppState); } } application.setState(flinkAppState.getValue()); cleanSavepoint(application); cleanOptioning(optionState, application.getId()); doPersistMetrics(application, true); } } else { // query the status from the yarn rest Api YarnAppInfo yarnAppInfo = httpYarnAppInfo(application); if (yarnAppInfo == null) { if (!FlinkDeployMode.REMOTE.equals(application.getDeployModeEnum())) { throw new RuntimeException( "[StreamPark][FlinkAppHttpWatcher] getFromYarnRestApi failed "); } } else { try { String state = yarnAppInfo.getApp().getFinalStatus(); FlinkAppStateEnum flinkAppState = FlinkAppStateEnum.getState(state); if (FlinkAppStateEnum.OTHER.equals(flinkAppState)) { return; } if (FlinkAppStateEnum.KILLED.equals(flinkAppState)) { if (StopFromEnum.NONE.equals(stopFrom)) { log.error( "[StreamPark][FlinkAppHttpWatcher] getFromYarnRestApi,job was killed and stopFrom NotFound,savepoint expired!"); savepointService.expire(application.getId()); } flinkAppState = FlinkAppStateEnum.CANCELED; cleanSavepoint(application); application.setEndTime(new Date()); } if (FlinkAppStateEnum.SUCCEEDED.equals(flinkAppState)) { flinkAppState = FlinkAppStateEnum.FINISHED; } application.setState(flinkAppState.getValue()); cleanOptioning(optionState, application.getId()); doPersistMetrics(application, true); if (flinkAppState.equals(FlinkAppStateEnum.FAILED) || flinkAppState.equals(FlinkAppStateEnum.LOST) || (flinkAppState.equals(FlinkAppStateEnum.CANCELED) && StopFromEnum.NONE.equals(stopFrom)) || applicationInfoService.checkAlter(application)) { doAlert(application, flinkAppState); stopCanceledJob(application.getId()); if (flinkAppState.equals(FlinkAppStateEnum.FAILED)) { applicationActionService.start(application, true); } } } catch (Exception e) { if (!FlinkDeployMode.REMOTE.equals(application.getDeployModeEnum())) { throw new RuntimeException( "[StreamPark][FlinkAppHttpWatcher] getFromYarnRestApi error,", e); } } } } } private void doAlert(FlinkApplication application, FlinkAppStateEnum flinkAppState) { AlertTemplate alertTemplate = AlertTemplateUtils.createAlertTemplate(application, flinkAppState); alertService.alert(application.getAlertId(), alertTemplate); } private void cleanOptioning(OptionStateEnum optionState, Long key) { if (optionState != null) { lastOptionTime = System.currentTimeMillis(); OPTIONING.remove(key); } } public void cleanSavepoint(FlinkApplication application) { application.setOptionState(OptionStateEnum.NONE.getValue()); FlinkStateChangeEvent event = PREVIOUS_STATUS.getIfPresent(application.getId()); if (event != null && event.getOptionState() == OptionStateEnum.SAVEPOINTING) { doPersistMetrics(application, false); } SAVEPOINT_CACHE.invalidate(application.getId()); } /** set current option state */ public static void setOptionState(Long appId, OptionStateEnum state) { if (isKubernetesApp(appId)) { return; } log.info("[StreamPark][FlinkAppHttpWatcher] setOptioning"); OPTIONING.put(appId, state); if (state.equals(OptionStateEnum.CANCELLING)) { STOP_FROM_MAP.put(appId, StopFromEnum.STREAMPARK); } } public static void doWatching(FlinkApplication application) { if (application.isKubernetesModeJob()) { return; } log.info("[StreamPark][FlinkAppHttpWatcher] add app to tracking,appId:{}", application.getId()); WATCHING_APPS.put(application.getId(), application); STARTING_CACHE.put(application.getId(), DEFAULT_FLAG_BYTE); } public static void addSavepoint(Long appId) { if (isKubernetesApp(appId)) { return; } log.info("[StreamPark][FlinkAppHttpWatcher] add app to savepoint,appId:{}", appId); SAVEPOINT_CACHE.put(appId, DEFAULT_FLAG_BYTE); // update to PREVIOUS_STATUS FlinkStateChangeEvent event = PREVIOUS_STATUS.getIfPresent(appId); if (event != null) { event.setOptionState(OptionStateEnum.SAVEPOINTING); PREVIOUS_STATUS.put(appId, event); } } public static void unWatching(Long appId) { if (isKubernetesApp(appId)) { return; } log.info("[StreamPark][FlinkAppHttpWatcher] stop app,appId:{}", appId); WATCHING_APPS.remove(appId); } public static void stopCanceledJob(Long appId) { if (!CANCELLED_JOB_MAP.containsKey(appId)) { return; } log.info("flink job canceled app appId:{} by useId:{}", appId, CANCELLED_JOB_MAP.get(appId)); CANCELLED_JOB_MAP.remove(appId); } public static void addCanceledApp(Long appId, Long userId) { log.info("flink job addCanceledApp app appId:{}, useId:{}", appId, userId); CANCELLED_JOB_MAP.put(appId, userId); } public static Long getCanceledJobUserId(Long appId) { return CANCELLED_JOB_MAP.get(appId) == null ? Long.valueOf(-1) : CANCELLED_JOB_MAP.get(appId); } public static Collection<FlinkApplication> getWatchingApps() { return WATCHING_APPS.values(); } private static boolean isKubernetesApp(Long appId) { FlinkApplication app = WATCHING_APPS.get(appId); if (app == null) { return false; } return app.isKubernetesModeJob(); } private YarnAppInfo httpYarnAppInfo(FlinkApplication application) throws Exception { String reqURL = "ws/v1/cluster/apps/".concat(application.getClusterId()); return yarnRestRequest(reqURL, YarnAppInfo.class); } private Overview httpOverview(FlinkApplication application) throws IOException { String appId = application.getClusterId(); if (appId != null) { if (application.getDeployModeEnum().equals(FlinkDeployMode.YARN_APPLICATION) || application.getDeployModeEnum().equals(FlinkDeployMode.YARN_PER_JOB)) { String reqURL; if (StringUtils.isEmpty(application.getJobManagerUrl())) { String format = "proxy/%s/overview"; reqURL = String.format(format, appId); } else { String format = "%s/overview"; reqURL = String.format(format, application.getJobManagerUrl()); } return yarnRestRequest(reqURL, Overview.class); } } return null; } private JobsOverview httpJobsOverview(FlinkApplication application) throws Exception { final String flinkUrl = "jobs/overview"; FlinkDeployMode deployMode = application.getDeployModeEnum(); if (FlinkDeployMode.isYarnMode(deployMode)) { String reqURL; if (StringUtils.isEmpty(application.getJobManagerUrl())) { String format = "proxy/%s/" + flinkUrl; reqURL = String.format(format, application.getClusterId()); } else { String format = "%s/" + flinkUrl; reqURL = String.format(format, application.getJobManagerUrl()); } return yarnRestRequest(reqURL, JobsOverview.class); } if (application.getJobId() != null && FlinkDeployMode.isRemoteMode(deployMode)) { return httpRemoteCluster( application.getFlinkClusterId(), cluster -> { String remoteUrl = cluster.getAddress() + "/" + flinkUrl; JobsOverview jobsOverview = httpRestRequest(remoteUrl, JobsOverview.class); if (jobsOverview != null) { List<JobsOverview.Job> jobs = jobsOverview.getJobs().stream() .filter(x -> x.getId().equals(application.getJobId())) .collect(Collectors.toList()); jobsOverview.setJobs(jobs); } return jobsOverview; }); } return null; } private CheckPoints httpCheckpoints(FlinkApplication application) throws Exception { final String flinkUrl = "jobs/%s/checkpoints"; FlinkDeployMode deployMode = application.getDeployModeEnum(); if (FlinkDeployMode.isYarnMode(deployMode)) { String reqURL; if (StringUtils.isEmpty(application.getJobManagerUrl())) { String format = "proxy/%s/" + flinkUrl; reqURL = String.format(format, application.getClusterId(), application.getJobId()); } else { String format = "%s/" + flinkUrl; reqURL = String.format(format, application.getJobManagerUrl(), application.getJobId()); } return yarnRestRequest(reqURL, CheckPoints.class); } if (application.getJobId() != null && FlinkDeployMode.isRemoteMode(deployMode)) { return httpRemoteCluster( application.getFlinkClusterId(), cluster -> { String remoteUrl = cluster.getAddress() + "/" + String.format(flinkUrl, application.getJobId()); return httpRestRequest(remoteUrl, CheckPoints.class); }); } return null; } private <T> T yarnRestRequest(String url, Class<T> clazz) throws IOException { String result = YarnUtils.restRequest(url, HTTP_TIMEOUT); return JacksonUtils.read(result, clazz); } private <T> T httpRestRequest(String url, Class<T> clazz) throws IOException { String result = HttpClientUtils.httpGetRequest( url, RequestConfig.custom().setConnectTimeout(HTTP_TIMEOUT).build()); if (null == result) { return null; } return JacksonUtils.read(result, clazz); } public boolean isWatchingApp(Long id) { return WATCHING_APPS.containsKey(id); } private <T> T httpRemoteCluster(Long clusterId, Callback<FlinkCluster, T> function) throws Exception { FlinkCluster flinkCluster = getFlinkRemoteCluster(clusterId, false); try { return function.call(flinkCluster); } catch (Exception e) { flinkCluster = getFlinkRemoteCluster(clusterId, true); return function.call(flinkCluster); } } private FlinkCluster getFlinkRemoteCluster(Long clusterId, boolean flush) { FlinkCluster flinkCluster = FLINK_CLUSTER_MAP.get(clusterId); if (flinkCluster == null || flush) { flinkCluster = flinkClusterService.getById(clusterId); FLINK_CLUSTER_MAP.put(clusterId, flinkCluster); } return flinkCluster; } interface Callback<T, R> { R call(T e) throws Exception; } public static FlinkStateChangeEvent createStateChangeEvent(FlinkApplication application) { FlinkStateChangeEvent event = new FlinkStateChangeEvent(); event.setId(application.getId()); event.setOptionState(OptionStateEnum.getState(application.getOptionState())); event.setAppState(application.getStateEnum()); event.setJobId(application.getJobId()); event.setJobManagerUrl(application.getJobManagerUrl()); return event; } }
googleapis/google-cloud-java
37,575
java-dataplex/grpc-google-cloud-dataplex-v1/src/main/java/com/google/cloud/dataplex/v1/CmekServiceGrpc.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.dataplex.v1; import static io.grpc.MethodDescriptor.generateFullMethodName; /** * * * <pre> * Dataplex Universal Catalog Customer Managed Encryption Keys (CMEK) Service * </pre> */ @javax.annotation.Generated( value = "by gRPC proto compiler", comments = "Source: google/cloud/dataplex/v1/cmek.proto") @io.grpc.stub.annotations.GrpcGenerated public final class CmekServiceGrpc { private CmekServiceGrpc() {} public static final java.lang.String SERVICE_NAME = "google.cloud.dataplex.v1.CmekService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.CreateEncryptionConfigRequest, com.google.longrunning.Operation> getCreateEncryptionConfigMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "CreateEncryptionConfig", requestType = com.google.cloud.dataplex.v1.CreateEncryptionConfigRequest.class, responseType = com.google.longrunning.Operation.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.CreateEncryptionConfigRequest, com.google.longrunning.Operation> getCreateEncryptionConfigMethod() { io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.CreateEncryptionConfigRequest, com.google.longrunning.Operation> getCreateEncryptionConfigMethod; if ((getCreateEncryptionConfigMethod = CmekServiceGrpc.getCreateEncryptionConfigMethod) == null) { synchronized (CmekServiceGrpc.class) { if ((getCreateEncryptionConfigMethod = CmekServiceGrpc.getCreateEncryptionConfigMethod) == null) { CmekServiceGrpc.getCreateEncryptionConfigMethod = getCreateEncryptionConfigMethod = io.grpc.MethodDescriptor .<com.google.cloud.dataplex.v1.CreateEncryptionConfigRequest, com.google.longrunning.Operation> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName(SERVICE_NAME, "CreateEncryptionConfig")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.dataplex.v1.CreateEncryptionConfigRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.Operation.getDefaultInstance())) .setSchemaDescriptor( new CmekServiceMethodDescriptorSupplier("CreateEncryptionConfig")) .build(); } } } return getCreateEncryptionConfigMethod; } private static volatile io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest, com.google.longrunning.Operation> getUpdateEncryptionConfigMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "UpdateEncryptionConfig", requestType = com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest.class, responseType = com.google.longrunning.Operation.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest, com.google.longrunning.Operation> getUpdateEncryptionConfigMethod() { io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest, com.google.longrunning.Operation> getUpdateEncryptionConfigMethod; if ((getUpdateEncryptionConfigMethod = CmekServiceGrpc.getUpdateEncryptionConfigMethod) == null) { synchronized (CmekServiceGrpc.class) { if ((getUpdateEncryptionConfigMethod = CmekServiceGrpc.getUpdateEncryptionConfigMethod) == null) { CmekServiceGrpc.getUpdateEncryptionConfigMethod = getUpdateEncryptionConfigMethod = io.grpc.MethodDescriptor .<com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest, com.google.longrunning.Operation> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName(SERVICE_NAME, "UpdateEncryptionConfig")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.Operation.getDefaultInstance())) .setSchemaDescriptor( new CmekServiceMethodDescriptorSupplier("UpdateEncryptionConfig")) .build(); } } } return getUpdateEncryptionConfigMethod; } private static volatile io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.DeleteEncryptionConfigRequest, com.google.longrunning.Operation> getDeleteEncryptionConfigMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "DeleteEncryptionConfig", requestType = com.google.cloud.dataplex.v1.DeleteEncryptionConfigRequest.class, responseType = com.google.longrunning.Operation.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.DeleteEncryptionConfigRequest, com.google.longrunning.Operation> getDeleteEncryptionConfigMethod() { io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.DeleteEncryptionConfigRequest, com.google.longrunning.Operation> getDeleteEncryptionConfigMethod; if ((getDeleteEncryptionConfigMethod = CmekServiceGrpc.getDeleteEncryptionConfigMethod) == null) { synchronized (CmekServiceGrpc.class) { if ((getDeleteEncryptionConfigMethod = CmekServiceGrpc.getDeleteEncryptionConfigMethod) == null) { CmekServiceGrpc.getDeleteEncryptionConfigMethod = getDeleteEncryptionConfigMethod = io.grpc.MethodDescriptor .<com.google.cloud.dataplex.v1.DeleteEncryptionConfigRequest, com.google.longrunning.Operation> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName(SERVICE_NAME, "DeleteEncryptionConfig")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.dataplex.v1.DeleteEncryptionConfigRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.Operation.getDefaultInstance())) .setSchemaDescriptor( new CmekServiceMethodDescriptorSupplier("DeleteEncryptionConfig")) .build(); } } } return getDeleteEncryptionConfigMethod; } private static volatile io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.ListEncryptionConfigsRequest, com.google.cloud.dataplex.v1.ListEncryptionConfigsResponse> getListEncryptionConfigsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "ListEncryptionConfigs", requestType = com.google.cloud.dataplex.v1.ListEncryptionConfigsRequest.class, responseType = com.google.cloud.dataplex.v1.ListEncryptionConfigsResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.ListEncryptionConfigsRequest, com.google.cloud.dataplex.v1.ListEncryptionConfigsResponse> getListEncryptionConfigsMethod() { io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.ListEncryptionConfigsRequest, com.google.cloud.dataplex.v1.ListEncryptionConfigsResponse> getListEncryptionConfigsMethod; if ((getListEncryptionConfigsMethod = CmekServiceGrpc.getListEncryptionConfigsMethod) == null) { synchronized (CmekServiceGrpc.class) { if ((getListEncryptionConfigsMethod = CmekServiceGrpc.getListEncryptionConfigsMethod) == null) { CmekServiceGrpc.getListEncryptionConfigsMethod = getListEncryptionConfigsMethod = io.grpc.MethodDescriptor .<com.google.cloud.dataplex.v1.ListEncryptionConfigsRequest, com.google.cloud.dataplex.v1.ListEncryptionConfigsResponse> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName(SERVICE_NAME, "ListEncryptionConfigs")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.dataplex.v1.ListEncryptionConfigsRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.dataplex.v1.ListEncryptionConfigsResponse .getDefaultInstance())) .setSchemaDescriptor( new CmekServiceMethodDescriptorSupplier("ListEncryptionConfigs")) .build(); } } } return getListEncryptionConfigsMethod; } private static volatile io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.GetEncryptionConfigRequest, com.google.cloud.dataplex.v1.EncryptionConfig> getGetEncryptionConfigMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetEncryptionConfig", requestType = com.google.cloud.dataplex.v1.GetEncryptionConfigRequest.class, responseType = com.google.cloud.dataplex.v1.EncryptionConfig.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.GetEncryptionConfigRequest, com.google.cloud.dataplex.v1.EncryptionConfig> getGetEncryptionConfigMethod() { io.grpc.MethodDescriptor< com.google.cloud.dataplex.v1.GetEncryptionConfigRequest, com.google.cloud.dataplex.v1.EncryptionConfig> getGetEncryptionConfigMethod; if ((getGetEncryptionConfigMethod = CmekServiceGrpc.getGetEncryptionConfigMethod) == null) { synchronized (CmekServiceGrpc.class) { if ((getGetEncryptionConfigMethod = CmekServiceGrpc.getGetEncryptionConfigMethod) == null) { CmekServiceGrpc.getGetEncryptionConfigMethod = getGetEncryptionConfigMethod = io.grpc.MethodDescriptor .<com.google.cloud.dataplex.v1.GetEncryptionConfigRequest, com.google.cloud.dataplex.v1.EncryptionConfig> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName(SERVICE_NAME, "GetEncryptionConfig")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.dataplex.v1.GetEncryptionConfigRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.dataplex.v1.EncryptionConfig.getDefaultInstance())) .setSchemaDescriptor( new CmekServiceMethodDescriptorSupplier("GetEncryptionConfig")) .build(); } } } return getGetEncryptionConfigMethod; } /** Creates a new async stub that supports all call types for the service */ public static CmekServiceStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CmekServiceStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CmekServiceStub>() { @java.lang.Override public CmekServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CmekServiceStub(channel, callOptions); } }; return CmekServiceStub.newStub(factory, channel); } /** Creates a new blocking-style stub that supports all types of calls on the service */ public static CmekServiceBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CmekServiceBlockingV2Stub> factory = new io.grpc.stub.AbstractStub.StubFactory<CmekServiceBlockingV2Stub>() { @java.lang.Override public CmekServiceBlockingV2Stub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CmekServiceBlockingV2Stub(channel, callOptions); } }; return CmekServiceBlockingV2Stub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static CmekServiceBlockingStub newBlockingStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CmekServiceBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CmekServiceBlockingStub>() { @java.lang.Override public CmekServiceBlockingStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CmekServiceBlockingStub(channel, callOptions); } }; return CmekServiceBlockingStub.newStub(factory, channel); } /** Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static CmekServiceFutureStub newFutureStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CmekServiceFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CmekServiceFutureStub>() { @java.lang.Override public CmekServiceFutureStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CmekServiceFutureStub(channel, callOptions); } }; return CmekServiceFutureStub.newStub(factory, channel); } /** * * * <pre> * Dataplex Universal Catalog Customer Managed Encryption Keys (CMEK) Service * </pre> */ public interface AsyncService { /** * * * <pre> * Create an EncryptionConfig. * </pre> */ default void createEncryptionConfig( com.google.cloud.dataplex.v1.CreateEncryptionConfigRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getCreateEncryptionConfigMethod(), responseObserver); } /** * * * <pre> * Update an EncryptionConfig. * </pre> */ default void updateEncryptionConfig( com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getUpdateEncryptionConfigMethod(), responseObserver); } /** * * * <pre> * Delete an EncryptionConfig. * </pre> */ default void deleteEncryptionConfig( com.google.cloud.dataplex.v1.DeleteEncryptionConfigRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getDeleteEncryptionConfigMethod(), responseObserver); } /** * * * <pre> * List EncryptionConfigs. * </pre> */ default void listEncryptionConfigs( com.google.cloud.dataplex.v1.ListEncryptionConfigsRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dataplex.v1.ListEncryptionConfigsResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getListEncryptionConfigsMethod(), responseObserver); } /** * * * <pre> * Get an EncryptionConfig. * </pre> */ default void getEncryptionConfig( com.google.cloud.dataplex.v1.GetEncryptionConfigRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dataplex.v1.EncryptionConfig> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getGetEncryptionConfigMethod(), responseObserver); } } /** * Base class for the server implementation of the service CmekService. * * <pre> * Dataplex Universal Catalog Customer Managed Encryption Keys (CMEK) Service * </pre> */ public abstract static class CmekServiceImplBase implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return CmekServiceGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service CmekService. * * <pre> * Dataplex Universal Catalog Customer Managed Encryption Keys (CMEK) Service * </pre> */ public static final class CmekServiceStub extends io.grpc.stub.AbstractAsyncStub<CmekServiceStub> { private CmekServiceStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CmekServiceStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CmekServiceStub(channel, callOptions); } /** * * * <pre> * Create an EncryptionConfig. * </pre> */ public void createEncryptionConfig( com.google.cloud.dataplex.v1.CreateEncryptionConfigRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getCreateEncryptionConfigMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Update an EncryptionConfig. * </pre> */ public void updateEncryptionConfig( com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getUpdateEncryptionConfigMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Delete an EncryptionConfig. * </pre> */ public void deleteEncryptionConfig( com.google.cloud.dataplex.v1.DeleteEncryptionConfigRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getDeleteEncryptionConfigMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * List EncryptionConfigs. * </pre> */ public void listEncryptionConfigs( com.google.cloud.dataplex.v1.ListEncryptionConfigsRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dataplex.v1.ListEncryptionConfigsResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getListEncryptionConfigsMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Get an EncryptionConfig. * </pre> */ public void getEncryptionConfig( com.google.cloud.dataplex.v1.GetEncryptionConfigRequest request, io.grpc.stub.StreamObserver<com.google.cloud.dataplex.v1.EncryptionConfig> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetEncryptionConfigMethod(), getCallOptions()), request, responseObserver); } } /** * A stub to allow clients to do synchronous rpc calls to service CmekService. * * <pre> * Dataplex Universal Catalog Customer Managed Encryption Keys (CMEK) Service * </pre> */ public static final class CmekServiceBlockingV2Stub extends io.grpc.stub.AbstractBlockingStub<CmekServiceBlockingV2Stub> { private CmekServiceBlockingV2Stub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CmekServiceBlockingV2Stub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CmekServiceBlockingV2Stub(channel, callOptions); } /** * * * <pre> * Create an EncryptionConfig. * </pre> */ public com.google.longrunning.Operation createEncryptionConfig( com.google.cloud.dataplex.v1.CreateEncryptionConfigRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateEncryptionConfigMethod(), getCallOptions(), request); } /** * * * <pre> * Update an EncryptionConfig. * </pre> */ public com.google.longrunning.Operation updateEncryptionConfig( com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getUpdateEncryptionConfigMethod(), getCallOptions(), request); } /** * * * <pre> * Delete an EncryptionConfig. * </pre> */ public com.google.longrunning.Operation deleteEncryptionConfig( com.google.cloud.dataplex.v1.DeleteEncryptionConfigRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getDeleteEncryptionConfigMethod(), getCallOptions(), request); } /** * * * <pre> * List EncryptionConfigs. * </pre> */ public com.google.cloud.dataplex.v1.ListEncryptionConfigsResponse listEncryptionConfigs( com.google.cloud.dataplex.v1.ListEncryptionConfigsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getListEncryptionConfigsMethod(), getCallOptions(), request); } /** * * * <pre> * Get an EncryptionConfig. * </pre> */ public com.google.cloud.dataplex.v1.EncryptionConfig getEncryptionConfig( com.google.cloud.dataplex.v1.GetEncryptionConfigRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetEncryptionConfigMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do limited synchronous rpc calls to service CmekService. * * <pre> * Dataplex Universal Catalog Customer Managed Encryption Keys (CMEK) Service * </pre> */ public static final class CmekServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<CmekServiceBlockingStub> { private CmekServiceBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CmekServiceBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CmekServiceBlockingStub(channel, callOptions); } /** * * * <pre> * Create an EncryptionConfig. * </pre> */ public com.google.longrunning.Operation createEncryptionConfig( com.google.cloud.dataplex.v1.CreateEncryptionConfigRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateEncryptionConfigMethod(), getCallOptions(), request); } /** * * * <pre> * Update an EncryptionConfig. * </pre> */ public com.google.longrunning.Operation updateEncryptionConfig( com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getUpdateEncryptionConfigMethod(), getCallOptions(), request); } /** * * * <pre> * Delete an EncryptionConfig. * </pre> */ public com.google.longrunning.Operation deleteEncryptionConfig( com.google.cloud.dataplex.v1.DeleteEncryptionConfigRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getDeleteEncryptionConfigMethod(), getCallOptions(), request); } /** * * * <pre> * List EncryptionConfigs. * </pre> */ public com.google.cloud.dataplex.v1.ListEncryptionConfigsResponse listEncryptionConfigs( com.google.cloud.dataplex.v1.ListEncryptionConfigsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getListEncryptionConfigsMethod(), getCallOptions(), request); } /** * * * <pre> * Get an EncryptionConfig. * </pre> */ public com.google.cloud.dataplex.v1.EncryptionConfig getEncryptionConfig( com.google.cloud.dataplex.v1.GetEncryptionConfigRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetEncryptionConfigMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do ListenableFuture-style rpc calls to service CmekService. * * <pre> * Dataplex Universal Catalog Customer Managed Encryption Keys (CMEK) Service * </pre> */ public static final class CmekServiceFutureStub extends io.grpc.stub.AbstractFutureStub<CmekServiceFutureStub> { private CmekServiceFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CmekServiceFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CmekServiceFutureStub(channel, callOptions); } /** * * * <pre> * Create an EncryptionConfig. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation> createEncryptionConfig(com.google.cloud.dataplex.v1.CreateEncryptionConfigRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getCreateEncryptionConfigMethod(), getCallOptions()), request); } /** * * * <pre> * Update an EncryptionConfig. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation> updateEncryptionConfig(com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getUpdateEncryptionConfigMethod(), getCallOptions()), request); } /** * * * <pre> * Delete an EncryptionConfig. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation> deleteEncryptionConfig(com.google.cloud.dataplex.v1.DeleteEncryptionConfigRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getDeleteEncryptionConfigMethod(), getCallOptions()), request); } /** * * * <pre> * List EncryptionConfigs. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.cloud.dataplex.v1.ListEncryptionConfigsResponse> listEncryptionConfigs(com.google.cloud.dataplex.v1.ListEncryptionConfigsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getListEncryptionConfigsMethod(), getCallOptions()), request); } /** * * * <pre> * Get an EncryptionConfig. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.cloud.dataplex.v1.EncryptionConfig> getEncryptionConfig(com.google.cloud.dataplex.v1.GetEncryptionConfigRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetEncryptionConfigMethod(), getCallOptions()), request); } } private static final int METHODID_CREATE_ENCRYPTION_CONFIG = 0; private static final int METHODID_UPDATE_ENCRYPTION_CONFIG = 1; private static final int METHODID_DELETE_ENCRYPTION_CONFIG = 2; private static final int METHODID_LIST_ENCRYPTION_CONFIGS = 3; private static final int METHODID_GET_ENCRYPTION_CONFIG = 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_ENCRYPTION_CONFIG: serviceImpl.createEncryptionConfig( (com.google.cloud.dataplex.v1.CreateEncryptionConfigRequest) request, (io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) responseObserver); break; case METHODID_UPDATE_ENCRYPTION_CONFIG: serviceImpl.updateEncryptionConfig( (com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest) request, (io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) responseObserver); break; case METHODID_DELETE_ENCRYPTION_CONFIG: serviceImpl.deleteEncryptionConfig( (com.google.cloud.dataplex.v1.DeleteEncryptionConfigRequest) request, (io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) responseObserver); break; case METHODID_LIST_ENCRYPTION_CONFIGS: serviceImpl.listEncryptionConfigs( (com.google.cloud.dataplex.v1.ListEncryptionConfigsRequest) request, (io.grpc.stub.StreamObserver< com.google.cloud.dataplex.v1.ListEncryptionConfigsResponse>) responseObserver); break; case METHODID_GET_ENCRYPTION_CONFIG: serviceImpl.getEncryptionConfig( (com.google.cloud.dataplex.v1.GetEncryptionConfigRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.dataplex.v1.EncryptionConfig>) 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( getCreateEncryptionConfigMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.cloud.dataplex.v1.CreateEncryptionConfigRequest, com.google.longrunning.Operation>(service, METHODID_CREATE_ENCRYPTION_CONFIG))) .addMethod( getUpdateEncryptionConfigMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest, com.google.longrunning.Operation>(service, METHODID_UPDATE_ENCRYPTION_CONFIG))) .addMethod( getDeleteEncryptionConfigMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.cloud.dataplex.v1.DeleteEncryptionConfigRequest, com.google.longrunning.Operation>(service, METHODID_DELETE_ENCRYPTION_CONFIG))) .addMethod( getListEncryptionConfigsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.cloud.dataplex.v1.ListEncryptionConfigsRequest, com.google.cloud.dataplex.v1.ListEncryptionConfigsResponse>( service, METHODID_LIST_ENCRYPTION_CONFIGS))) .addMethod( getGetEncryptionConfigMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.cloud.dataplex.v1.GetEncryptionConfigRequest, com.google.cloud.dataplex.v1.EncryptionConfig>( service, METHODID_GET_ENCRYPTION_CONFIG))) .build(); } private abstract static class CmekServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { CmekServiceBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return com.google.cloud.dataplex.v1.CmekProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("CmekService"); } } private static final class CmekServiceFileDescriptorSupplier extends CmekServiceBaseDescriptorSupplier { CmekServiceFileDescriptorSupplier() {} } private static final class CmekServiceMethodDescriptorSupplier extends CmekServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final java.lang.String methodName; CmekServiceMethodDescriptorSupplier(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 (CmekServiceGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new CmekServiceFileDescriptorSupplier()) .addMethod(getCreateEncryptionConfigMethod()) .addMethod(getUpdateEncryptionConfigMethod()) .addMethod(getDeleteEncryptionConfigMethod()) .addMethod(getListEncryptionConfigsMethod()) .addMethod(getGetEncryptionConfigMethod()) .build(); } } } return result; } }
apache/stanbol
37,617
enhancement-engines/lucenefstlinking/src/main/java/org/apache/stanbol/enhancer/engines/lucenefstlinking/IndexConfiguration.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.stanbol.enhancer.engines.lucenefstlinking; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.clerezza.commons.rdf.Literal; import org.apache.clerezza.commons.rdf.RDFTerm; import org.apache.clerezza.commons.rdf.IRI; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.commons.lang.StringUtils; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.AtomicReader; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.FieldInfos; import org.apache.lucene.search.IndexSearcher; import org.apache.solr.core.SolrCore; import org.apache.solr.schema.FieldType; import org.apache.solr.schema.IndexSchema; import org.apache.solr.search.SolrIndexSearcher; import org.apache.solr.util.RefCounted; import org.apache.stanbol.commons.stanboltools.datafileprovider.DataFileProvider; import org.apache.stanbol.enhancer.engines.lucenefstlinking.cache.EntityCacheManager; import org.apache.stanbol.enhancer.nlp.utils.LanguageConfiguration; import org.opensextant.solrtexttagger.TaggerFstCorpus; import org.opensextant.solrtexttagger.UnsupportedTokenException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Holds the configuration of the index used by the FST linking engine. * * @author Rupert Westenthaler * */ public class IndexConfiguration { private static final Logger log = LoggerFactory.getLogger(IndexConfiguration.class); private final SolrCore index; /** * The type field */ private String typeField; /** * The redirect field */ private String redirectField; /** * The entityRanking field */ private String rankingField; /** * Used to sync access to {@link #corpusInfos} */ private ReadWriteLock corpusInfoLock = new ReentrantReadWriteLock(); /** * FST corpus configuration */ private Map<String,CorpusInfo> corpusInfos; /** * {@link ExecutorService} used to create {@link TaggerFstCorpus} instances * at runtime. */ protected ExecutorService executorService; /** * The encoding used by SolrFields (e.g. to define label fields for different * languages). */ private final FieldEncodingEnum fieldEncoding; /** * The instance used to retrieve/create the cache for Lucene {@link Document}s * of Entities. */ private EntityCacheManager entityCacheManager; private final LanguageConfiguration fstConfig; /** * If runtime generation is enabled by default (Note: explicitly configured * lanugages might override this) */ private final boolean runtimeGeneration; /** * used to track if this index configuration is active */ private boolean active = false; private long indexVersion = -1; private File fstDirectory; /** * The origin is added to <code>fise:TextAnnotation</code> created for * linked Entities. It is intended to be used for providing a reference to * dataset of the Entity. Both {@link IRI URI}s and {@link Literal}s can * be used here */ private RDFTerm origin; /** * If alternate tokens (<code>posInc == 0</code>) can be skipped or if such * tokens should cause an {@link UnsupportedTokenException}. */ private boolean skipAltTokens; /** * The default language */ private String defaultLanguage; /** * If alternate tokens (<code>posInc == 0</code>) can be skipped or if such * tokens should cause an {@link UnsupportedTokenException}. * <p> * While enabling this will allow to use FST linking with query time Lucene * {@link Analyzer}s that emit alternate tokens (e.g. the Kuromoji analyzers * for Japanese) but it also requires special care with index time * {@link Analyzer} configurations. If enabled the index time analyzer MUST * produce all possible tokens emited by the query time analyzer as only if * all such combinations are added to the FST model skipped alternate * tokens can not prevent mentions from being detected. * <p> * By default <code>skipAltTokens</code> is enabled for * {@link FieldEncodingEnum#SolrYard} and deactivated for all other field * encoding setting. This is because all Solr <code>schema.xml</code> used * by the Stanbol Entityhub SolrYard ensure the requirement stated above. * For other Solr configurations users will neet to explicitly activate this. */ public static final String SKIP_ALT_TOKENS = "enhancer.engines.linking.lucenefst.skipAltTokens"; /** * Property used to configure the FieldName encoding of the SolrIndex. This * is mainly needed for label fields of different languages (e.g. by using * the iso language code as prefix/suffix of Solr fields. However this also * adds support for SolrIndexes encoded as specified by the Stanbol * Entityhub SolrYard implementation. See {@link FieldEncodingEnum} for * supported values */ public static final String FIELD_ENCODING = "enhancer.engines.linking.lucenefst.fieldEncoding"; /** * The name of the Solr field storing rankings for entities. Entities with a * higher value are considered as better (more popular). */ public static final String SOLR_RANKING_FIELD = "enhancer.engines.linking.lucenefst.rankingField"; /** * The name of the Solr field holding the entity type information */ public static final String SOLR_TYPE_FIELD = "enhancer.engines.linking.lucenefst.typeField"; /** * Language configuration defining the language, solr field and the name of the * FST file. The FST file is looked up using the {@link DataFileProvider}. */ public static final String FST_CONFIG = "enhancer.engines.linking.lucenefst.fstconfig"; /** * The folder used to store the FST files. The {@link DEFAULT_FST_FOLDER default} is * '<code>${solr-data-dir}/fst</code>' - this is '<code>./fst</code>' relative to the * {@link SolrCore#getDataDir()} of the current SolrCore. */ public static final String FST_FOLDER = "enhancer.engines.linking.lucenefst.fstfolder"; /** * The default of the FST folder is '<code>${solr-data-dir}/fst</code>' - * this is '<code>./fst</code>' relative to the {@link SolrCore#getDataDir()} * of the current SolrCore. */ public static final String DEFAULT_FST_FOLDER = "${solr-data-dir}/fst"; /** * By default runtime generation for the FST is deactivated. Use the * {@link PARAM_RUNTIME_GENERATION} to enable it. */ public static final boolean DEFAULT_RUNTIME_GENERATION = false; /** * Parameter that specifies if FST files are allowed to be generated at runtime. * Enabling this will require (1) write access to the SolrCore directory and * (2) a lot of Memory and CPU usage during the generation. */ public static final String PARAM_RUNTIME_GENERATION = "generate"; /** * Parameter used by the {@link IndexConfiguration#FST_CONFIG} to configure the solrField with * the stored labels. If not defined this defaults to the configured * {@link PARAM_FIELD}. */ public static final String PARAM_STORE_FIELD = "stored"; /** * Parameter used by the {@link IndexConfiguration#FST_CONFIG} to configure the Solr Field * with the indexed labels used to buld the FST corpus. */ public static final String PARAM_FIELD = "field"; public static final String DEFAULT_FIELD = "rdfs:label"; /** * Parameter used by the {@link IndexConfiguration#FST_CONFIG} to configure the name of the fst * file for a language */ public static final String PARAM_FST = "fst"; public IndexConfiguration(LanguageConfiguration fstConfig, SolrCore index, FieldEncodingEnum fieldEncoding, String defaultLanguage){ if(fstConfig == null){ throw new IllegalArgumentException("The parsed FST configuration MUST NOT be NULL!"); } this.fstConfig = fstConfig; if(index == null || index.isClosed()){ throw new IllegalArgumentException("The parsed SolrCore MUST NOT be NULL nore closed!"); } //check if we have runtime generation String allowCreationString = fstConfig.getDefaultParameters().get(IndexConfiguration.PARAM_RUNTIME_GENERATION); if(allowCreationString == null){ runtimeGeneration = IndexConfiguration.DEFAULT_RUNTIME_GENERATION; } else { runtimeGeneration = Boolean.parseBoolean(allowCreationString); } this.index = index; if(fieldEncoding == null){ fieldEncoding = FieldEncodingEnum.None; } this.fieldEncoding = fieldEncoding; //In case of a SolrYard we can activate skipAltTokens (see javadoc for //#SKIP_ALT_TOKENS for more information) if(fieldEncoding == FieldEncodingEnum.SolrYard){ this.skipAltTokens = true; } else { this.skipAltTokens = false; } this.defaultLanguage = defaultLanguage == null ? "" : defaultLanguage; } /** * Assumed to be called in a write lock on {@link #corpusInfoLock} * @param corpus */ private void addCorpusInfo(CorpusInfo corpus){ if(corpus != null){ corpusInfos.put(corpus.language, corpus); } } protected CorpusInfo removeCorpus(String language){ return corpusInfos.remove(language); } /** * @return the fieldEncoding */ public final FieldEncodingEnum getFieldEncoding() { return fieldEncoding; } /** * @return the typeField */ public final String getEncodedTypeField() { return typeField; } /** * Sets AND encodes the parsed value (based on the specified * {@link #getFieldEncoding() FieldEncoding}) * @param typeField the typeField to set */ public final void setTypeField(String typeField) { this.typeField = typeField == null ? null : FieldEncodingEnum.encodeUri(typeField, fieldEncoding); } /** * @return the redirectField */ public final String getEncodedRedirectField() { return redirectField; } /** * Sets AND encodes the parsed value (based on the specified * {@link #getFieldEncoding() FieldEncoding}) * @param redirectField the redirectField to set */ public final void setRedirectField(String redirectField) { this.redirectField = redirectField == null ? null : FieldEncodingEnum.encodeUri(redirectField, fieldEncoding); } /** * @return the rankingField */ public final String getEncodedRankingField() { return rankingField; } /** * Sets AND encodes the parsed value (based on the specified * {@link #getFieldEncoding() FieldEncoding}) * @param rankingField the rankingField to set */ public final void setRankingField(String rankingField) { this.rankingField = rankingField == null ? null : FieldEncodingEnum.encodeFloat(rankingField, fieldEncoding); } /** * The version of the {@link #getIndex()} this configuration was built for. * @return the index version this configuration was built for. */ public long getVersion() { return indexVersion; } /** * Returns the CorpusInfo for the parsed language. If the language has an * extension (e.g. en-US) it first tires to load the corpus for the exact * match and falls back to the main lanugage (en) if such a corpus does not * exist. * @param language the language * @return the corpus information or <code>null</code> if not present */ public CorpusInfo getCorpus(String language) { corpusInfoLock.readLock().lock(); try { CorpusInfo langCorpusInfo = corpusInfos.get(language); if(langCorpusInfo == null && language.indexOf('-') > 0){ String rootLang = language.substring(0,language.indexOf('-')); log.debug(" - no FST corpus for {}. Fallback to {}", language,rootLang); langCorpusInfo = corpusInfos.get(rootLang); } return langCorpusInfo; } finally { corpusInfoLock.readLock().unlock(); } } /** * Getter for the languages of all configured FST corpora * @return a read-only copy of the languages of all configured FST corpora */ public Set<String> getCorpusLanguages(){ return Collections.unmodifiableSet(new HashSet<String>(corpusInfos.keySet())); } /** * Read-only collection of all {@link CorpusInfo}s defined for this * configuration. * @return a read only copy of the current {@link CorpusInfo}s */ public Collection<CorpusInfo> getCorpora(){ corpusInfoLock.readLock().lock(); try { return Collections.unmodifiableCollection(new ArrayList<CorpusInfo>(corpusInfos.values())); } finally { corpusInfoLock.readLock().unlock(); } } /** * The {@link CorpusInfo} for the default laugnage * @return the default corpus or <code>null</code> if no corpus is available * for the default language */ public CorpusInfo getDefaultCorpus() { corpusInfoLock.readLock().lock(); try { return corpusInfos.get(defaultLanguage); } finally { corpusInfoLock.readLock().unlock(); } } public void setExecutorService(ExecutorService executorService) { this.executorService = executorService; } public ExecutorService getExecutorService() { return executorService; } /** * The FST configuration * @return */ public LanguageConfiguration getFstConfig() { return fstConfig; } public SolrCore getIndex() { return index; } public void setEntityCacheManager(EntityCacheManager entityCacheManager) { this.entityCacheManager = entityCacheManager; } public EntityCacheManager getEntityCacheManager() { return entityCacheManager; } public File getFstDirectory() { return fstDirectory; } public void setFstDirectory(File fstDirectory) { this.fstDirectory = fstDirectory; } public void setOrigin(RDFTerm origin) { this.origin = origin; } /** * The Origin of the dataset or <code>null</code> if not defined. The * origin can be used to specify the dataset where the Entities described by * the configured FST originate from. If can be both an URI (e.g. * <code>http://dbpedia.org</code>) or an literal "<code>dbpedia</code>"). * If present the origin is added to any <code>fise:TextAnnotation</code> * created by the FstLinkingEngine with the property <code>fise:origin</code> * * @return the origin or <code>null</code> if none is configured */ public RDFTerm getOrigin() { return origin; } /** * Deactivates this {@link IndexConfiguration} */ public void deactivate(){ active = false; } /** * If this {@link IndexConfiguration} is still in sync with the version * of the {@link #getIndex() SolrCore}. This will return true if * <code>{@link #isRuntimeGeneration()} == false </code> * @return <code>true</code> if still active. Otherwise <code>false</code> */ public boolean isCurrent(){ if(!runtimeGeneration){ return true; } else { RefCounted<SolrIndexSearcher> searcherRef = index.getSearcher(); try { long version = searcherRef.get().getIndexReader().getVersion(); return indexVersion == version; } finally { searcherRef.decref(); } } } private long getIndexVersion(){ RefCounted<SolrIndexSearcher> searcherRef = index.getSearcher(); try { return getIndexVersion(searcherRef.get()); } finally { searcherRef.decref(); } } private long getIndexVersion(SolrIndexSearcher searcher){ return searcher.getIndexReader().getVersion(); } public boolean isRuntimeGeneration() { return runtimeGeneration; } public boolean isActive() { return active; } /** * Activated this indexing configuration by inspecting the {@link SolrCore} * based on the provided configuration * @return */ public void activate() throws IOException { active = true; if(index == null){ //do we have an SolrCore throw new IllegalArgumentException("No SolrCore set for this configuration"); } //if no fstDirectory is configured if(fstDirectory == null){ //use the default fstDirectory = new File(index.getDataDir(),"fst"); } //init the fstDirectory (may throw IOException) if(fstDirectory.isFile()){ throw new IOException("Default FST directory exists and " + "is a File. Use #setFstDirectory() to set different one"); } else if(!fstDirectory.exists()){ FileUtils.forceMkdir(fstDirectory); } //acquire the initial index configuration update(); } /** * Updates the configuration based on the current version of the * {@link #getIndex()}. If the SolrCore was not updated this will do * nothing. */ public void update(){ RefCounted<SolrIndexSearcher> searcherRef = index.getSearcher(); try { update(getIndexVersion(searcherRef.get()), searcherRef.get()); } finally { searcherRef.decref(); //decrease the count on the searcher } } /** * Version of {@link #update()} to be used in cases where the indexVersion * and a Solr searcher is already available in the calling method * @param indexVersion * @param searcher */ protected void update(long indexVersion, SolrIndexSearcher searcher){ assert searcher != null; assert searcher.getCore().equals(index); processFstConfig(indexVersion, searcher.getAtomicReader()); } /** * This method combines the {@link #fstConfig} with the data present in the * {@link SolrCore}. * <p> * As information for fields are only available when a * field was actually used by a document stored in the index one needs to * inspect the index after every change. * <p> * An empty Solr index will result in * an empty {@link #corpusInfos} map. The first document with an value * for the English field will cause an {@link CorpusInfo} for the English * language to be created. As soon as the last document with an label for * a given language will be deleted the {@link CorpusInfo} for that language * will also disappear. * @param indexVersion the current version of the {@link #index} to process * the FST config for. * <p> * This method acquires a write lock on {@link #corpusInfoLock} while it * inspects the Solr index * @param indexReader The {@link AtomicReader} has access to the actual * fields present in the {@link SolrCore}. It is used to compare field * configurations in the {@link #fstConfig} with fields present in the Solr * {@link #index}. * @return If any {@link CorpusInfo FST configuration} where found during * inspecting the Solr {@link #index} */ private boolean processFstConfig(long indexVersion, AtomicReader indexReader) { //first check if the Solr index was updated corpusInfoLock.readLock().lock(); try { if(indexVersion == this.indexVersion){ //no update? return !corpusInfos.isEmpty(); //nothing to do } } finally { corpusInfoLock.readLock().unlock(); } log.debug("> {} FST config for {} (FST dir: {})", corpusInfos == null ? "create" : "update", index.getName(), fstDirectory.getAbsolutePath()); boolean foundCorpus = false; corpusInfoLock.writeLock().lock(); try { this.indexVersion = indexVersion; IndexSchema schema = index.getLatestSchema(); Map<String,CorpusInfo> corpusInfosCopy; if(corpusInfos == null){ //first call corpusInfos = new HashMap<String,CorpusInfo>(); //init the field corpusInfosCopy = new HashMap<String,CorpusInfo>(); } else { corpusInfosCopy = new HashMap<String,CorpusInfo>(corpusInfos); corpusInfos.clear(); //clear the old data } //(0) get basic parameters of the default configuration log.debug(" - default config"); Map<String,String> defaultParams = fstConfig.getDefaultParameters(); String fstName = defaultParams.get(IndexConfiguration.PARAM_FST); String indexField = defaultParams.get(IndexConfiguration.PARAM_FIELD); String storeField = defaultParams.get(IndexConfiguration.PARAM_STORE_FIELD); if(storeField == null){ //apply indexField as default if indexField is NOT NULL storeField = indexField; } if(indexField == null){ //apply the defaults if null indexField = IndexConfiguration.DEFAULT_FIELD; } if(fstName == null){ //use default fstName = getDefaultFstFileName(indexField); } //This are all fields actually present in the index (distinguished with //those defined in the schema). This also includes actual instances of //dynamic field definition in the schema. FieldInfos fieldInfos = indexReader.getFieldInfos(); //we need this twice //(1) in case the fstConfig uses a wildcard we need to search for // languages present in the SolrIndex. For that we use the indexReader // to get the FieldInfos and match them against FST files in the FST // directory and FieldType definitions in the schema of the SolrCore //NOTE: this needs only do be done if wildcards are enabled in the fstConfig if(fstConfig.useWildcard()){ //(1.a) search for present FST files in the FST directory Map<String,File> presentFstFiles = new HashMap<String,File>(); WildcardFileFilter fstFilter = new WildcardFileFilter( fstName+".*.fst"); Iterator<File> fstFiles = FileUtils.iterateFiles(fstDirectory, fstFilter, null); while(fstFiles.hasNext()){ File fstFile = fstFiles.next(); String fstFileName = fstFile.getName(); //files are named such as "{name}.{lang}.fst" String language = FilenameUtils.getExtension( FilenameUtils.getBaseName(fstFileName)); presentFstFiles.put(language, fstFile); } //(1.b) iterate over the fields in the Solr index and search for // matches against the configured indexField name String fieldWildcard = FieldEncodingEnum.encodeLanguage(indexField, fieldEncoding, "*"); for(FieldInfo fieldInfo : fieldInfos){ //try to match the field names against the wildcard if(FilenameUtils.wildcardMatch(fieldInfo.name, fieldWildcard)){ //for matches parse the language from the field name String language = FieldEncodingEnum.parseLanguage( fieldInfo.name, fieldEncoding, indexField); if(language != null && //successfully parsed language //is current language is enabled? fstConfig.isLanguage(language) && //is there no explicit configuration for this language? !fstConfig.getExplicitlyIncluded().contains(language)){ //generate the FST file name StringBuilder fstFileName = new StringBuilder(fstName); if(!language.isEmpty()){ fstFileName.append('.').append(language); } fstFileName.append(".fst"); File fstFile = new File(fstDirectory,fstFileName.toString()); //get the FieldType of the field from the Solr schema FieldType fieldType = schema.getFieldTypeNoEx(fieldInfo.name); if(fieldType != null){ //if the fieldType is present if(runtimeGeneration || fstFile.isFile()){ //and FST is present or can be created //we need also to check if the stored field with //the labels is present //get the stored Field and check if it is present! String storeFieldName; if(storeField == null){ //storeField == indexField storeFieldName = fieldInfo.name; } else { // check that the storeField is present in the index storeFieldName = FieldEncodingEnum.encodeLanguage( storeField, fieldEncoding, language); FieldInfo storedFieldInfos = fieldInfos.fieldInfo(storeFieldName); if(storedFieldInfos == null){ log.debug(" ... ignore language {} because Stored Field {} " + "for IndexField {} does not exist! ", new Object[]{ language,storeFieldName,fieldInfo.name}); storeFieldName = null; } } if(storeFieldName != null){ // == valid configuration CorpusInfo fstInfo = corpusInfosCopy.get(language); if(fstInfo == null || //new one !fstInfo.indexedField.equals(fieldInfo.name) || //index field compatible !fstInfo.storedField.equals(storeFieldName)){ //store field compatible CorpusInfo newFstInfo = new CorpusInfo(language, fieldInfo.name, storeFieldName, fieldType, fstFile, runtimeGeneration); log.debug(" ... {} {} ", fstInfo == null ? "create" : "update", newFstInfo); addCorpusInfo(newFstInfo); corpusInfosCopy.put(language, newFstInfo); } else { //no change in the SolrIndex ... use the exsisting CorpusInfo addCorpusInfo(fstInfo); } foundCorpus = true; } } else { log.debug(" ... ignore language {} (field: {}) because " + "FST file '{}' does not exist and runtime creation " + "is deactivated!",new Object[]{ language, fieldInfo.name, fstFile.getAbsolutePath()}); } } else { log.debug(" ... ignore language {} becuase unknown fieldtype " + "for SolrFied {}",language,fieldInfo.name); } } //else the field matched the wildcard, but has not passed the //encoding test. } //Solr field does not match the field definition in the config } // end iterate over all fields in the SolrIndex } //else Wildcard not enabled in the fstConfig //(2) process explicit configuration for configured languages for(String language : fstConfig.getExplicitlyIncluded()){ //(2.a) get the language specific config (with fallback to default) Map<String,String> config = fstConfig.getParameters(language); String langIndexField = config.get(IndexConfiguration.PARAM_FIELD); String langStoreField = config.get(IndexConfiguration.PARAM_STORE_FIELD); String langFstFileName = config.get(IndexConfiguration.PARAM_FST); final boolean langAllowCreation; final String langAllowCreationString = config.get(IndexConfiguration.PARAM_RUNTIME_GENERATION); if(langIndexField != null){ //also consider explicit field names as default for the fst name if(langFstFileName == null){ StringBuilder fileName = new StringBuilder( getDefaultFstFileName(langIndexField)); if(!language.isEmpty()){ fileName.append('.').append(language); } fileName.append(".fst"); langFstFileName = fileName.toString(); } } else { langIndexField = indexField; } if(langStoreField == null){ //fallbacks if(storeField != null){ //first to default store field langStoreField = storeField; } else { //else to the lang index field langStoreField = langIndexField; } } if(langFstFileName == null){ //no fstFileName config // ... use the default langFstFileName = new StringBuilder(fstName).append('.') .append(language).append(".fst").toString(); } if(langAllowCreationString != null){ langAllowCreation = Boolean.parseBoolean(langAllowCreationString); } else { langAllowCreation = runtimeGeneration; } //(2.b) check if the Solr field is present String encodedLangIndexField = FieldEncodingEnum.encodeLanguage( langIndexField, fieldEncoding, language); String encodedLangStoreField = FieldEncodingEnum.encodeLanguage( langStoreField, fieldEncoding, language); FieldInfo langIndexFieldInfo = fieldInfos.fieldInfo(encodedLangIndexField); if(langIndexFieldInfo != null){ FieldInfo langStoreFieldInfo = fieldInfos.fieldInfo(encodedLangStoreField); if(langStoreFieldInfo != null){ FieldType fieldType = schema.getFieldTypeNoEx(langIndexFieldInfo.name); if(fieldType != null){ //(2.c) check the FST file File langFstFile = new File(fstDirectory,langFstFileName); if(langFstFile.isFile() || langAllowCreation){ CorpusInfo langFstInfo = corpusInfosCopy.get(language); if(langFstInfo == null || //new one !langFstInfo.indexedField.equals(encodedLangIndexField) || //index field compatible !langFstInfo.storedField.equals(encodedLangStoreField)){ //store field compatible CorpusInfo newLangFstInfo = new CorpusInfo(language, encodedLangIndexField,encodedLangStoreField, fieldType, langFstFile, langAllowCreation); log.debug(" ... {} {} for explicitly configured language", langFstInfo == null ? "create" : "update", newLangFstInfo); addCorpusInfo(newLangFstInfo); } else { //we can use the existing instance addCorpusInfo(langFstInfo); } foundCorpus = true; } else { log.debug(" ... ignore explicitly configured language {} (field: {}) because " + "FST file '{}' does not exist and runtime creation " + "is deactivated!",new Object[]{ language, langIndexFieldInfo.name, langFstFile.getAbsolutePath()}); } } else { log.debug(" ... ignore explicitly configured language {} becuase unknown fieldtype " + "for SolrFied {}", language, langIndexFieldInfo.name); } } else { log.debug(" ... ignore explicitly configured language {} because configured stored Field {} " + "for IndexField {} does not exist! ", new Object[]{ language,langStoreField,langIndexFieldInfo.name}); } } else { log.debug(" ... ignore explicitly configured language {} because configured field {} (encoded: {}) " + "is not present in the SolrIndex!", new Object[]{ language, langIndexField, encodedLangIndexField }); } } } finally { corpusInfoLock.writeLock().unlock(); } return foundCorpus; } /** * Getter for the default FST file name based on the configured field * name. This method returns the '<code>{name}</code>' part of the * '<code>{name}.{lang}.fst</code>' name. * @param fstFieldName the field name. * @return the '<code>{name}</code>' part of the'<code>{name}.{lang}.fst</code>' name */ private String getDefaultFstFileName(final String fstFieldName) { String fstName; if(!StringUtils.isAlphanumeric(fstFieldName)) { StringBuilder escaped = new StringBuilder(fstFieldName.length()); for(int i = 0; i < fstFieldName.length();i++){ int codepoint = fstFieldName.codePointAt(i); if(Character.isLetterOrDigit(codepoint)){ escaped.appendCodePoint(codepoint); } else { escaped.append('_'); } } fstName = escaped.toString(); } else { fstName = fstFieldName; } return fstName; } public boolean isSkipAltTokens() { return skipAltTokens; } public void setSkipAltTokens(boolean skipAltTokens) { this.skipAltTokens = skipAltTokens; } }
googleapis/google-cloud-java
37,306
java-cloudcommerceconsumerprocurement/proto-google-cloud-cloudcommerceconsumerprocurement-v1/src/main/java/com/google/cloud/commerce/consumer/procurement/v1/ListOrdersResponse.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/commerce/consumer/procurement/v1/procurement_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.commerce.consumer.procurement.v1; /** * * * <pre> * Response message for * [ConsumerProcurementService.ListOrders][google.cloud.commerce.consumer.procurement.v1.ConsumerProcurementService.ListOrders]. * </pre> * * Protobuf type {@code google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse} */ public final class ListOrdersResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse) ListOrdersResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListOrdersResponse.newBuilder() to construct. private ListOrdersResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListOrdersResponse() { orders_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListOrdersResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.commerce.consumer.procurement.v1.ProcurementService .internal_static_google_cloud_commerce_consumer_procurement_v1_ListOrdersResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.commerce.consumer.procurement.v1.ProcurementService .internal_static_google_cloud_commerce_consumer_procurement_v1_ListOrdersResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse.class, com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse.Builder.class); } public static final int ORDERS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.commerce.consumer.procurement.v1.Order> orders_; /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.commerce.consumer.procurement.v1.Order> getOrdersList() { return orders_; } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.commerce.consumer.procurement.v1.OrderOrBuilder> getOrdersOrBuilderList() { return orders_; } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ @java.lang.Override public int getOrdersCount() { return orders_.size(); } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ @java.lang.Override public com.google.cloud.commerce.consumer.procurement.v1.Order getOrders(int index) { return orders_.get(index); } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ @java.lang.Override public com.google.cloud.commerce.consumer.procurement.v1.OrderOrBuilder getOrdersOrBuilder( int index) { return orders_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The token for fetching the next page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * The token for fetching the next 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 < orders_.size(); i++) { output.writeMessage(1, orders_.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 < orders_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, orders_.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.commerce.consumer.procurement.v1.ListOrdersResponse)) { return super.equals(obj); } com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse other = (com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse) obj; if (!getOrdersList().equals(other.getOrdersList())) 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 (getOrdersCount() > 0) { hash = (37 * hash) + ORDERS_FIELD_NUMBER; hash = (53 * hash) + getOrdersList().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.commerce.consumer.procurement.v1.ListOrdersResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse 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.commerce.consumer.procurement.v1.ListOrdersResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse 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.commerce.consumer.procurement.v1.ListOrdersResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse 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.commerce.consumer.procurement.v1.ListOrdersResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse 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.commerce.consumer.procurement.v1.ListOrdersResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse 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.commerce.consumer.procurement.v1.ListOrdersResponse 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 * [ConsumerProcurementService.ListOrders][google.cloud.commerce.consumer.procurement.v1.ConsumerProcurementService.ListOrders]. * </pre> * * Protobuf type {@code google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse) com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.commerce.consumer.procurement.v1.ProcurementService .internal_static_google_cloud_commerce_consumer_procurement_v1_ListOrdersResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.commerce.consumer.procurement.v1.ProcurementService .internal_static_google_cloud_commerce_consumer_procurement_v1_ListOrdersResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse.class, com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse.Builder.class); } // Construct using // com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (ordersBuilder_ == null) { orders_ = java.util.Collections.emptyList(); } else { orders_ = null; ordersBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.commerce.consumer.procurement.v1.ProcurementService .internal_static_google_cloud_commerce_consumer_procurement_v1_ListOrdersResponse_descriptor; } @java.lang.Override public com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse getDefaultInstanceForType() { return com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse .getDefaultInstance(); } @java.lang.Override public com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse build() { com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse buildPartial() { com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse result = new com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse result) { if (ordersBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { orders_ = java.util.Collections.unmodifiableList(orders_); bitField0_ = (bitField0_ & ~0x00000001); } result.orders_ = orders_; } else { result.orders_ = ordersBuilder_.build(); } } private void buildPartial0( com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse 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.commerce.consumer.procurement.v1.ListOrdersResponse) { return mergeFrom( (com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse other) { if (other == com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse .getDefaultInstance()) return this; if (ordersBuilder_ == null) { if (!other.orders_.isEmpty()) { if (orders_.isEmpty()) { orders_ = other.orders_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureOrdersIsMutable(); orders_.addAll(other.orders_); } onChanged(); } } else { if (!other.orders_.isEmpty()) { if (ordersBuilder_.isEmpty()) { ordersBuilder_.dispose(); ordersBuilder_ = null; orders_ = other.orders_; bitField0_ = (bitField0_ & ~0x00000001); ordersBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getOrdersFieldBuilder() : null; } else { ordersBuilder_.addAllMessages(other.orders_); } } } 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.commerce.consumer.procurement.v1.Order m = input.readMessage( com.google.cloud.commerce.consumer.procurement.v1.Order.parser(), extensionRegistry); if (ordersBuilder_ == null) { ensureOrdersIsMutable(); orders_.add(m); } else { ordersBuilder_.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.commerce.consumer.procurement.v1.Order> orders_ = java.util.Collections.emptyList(); private void ensureOrdersIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { orders_ = new java.util.ArrayList<com.google.cloud.commerce.consumer.procurement.v1.Order>( orders_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.commerce.consumer.procurement.v1.Order, com.google.cloud.commerce.consumer.procurement.v1.Order.Builder, com.google.cloud.commerce.consumer.procurement.v1.OrderOrBuilder> ordersBuilder_; /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public java.util.List<com.google.cloud.commerce.consumer.procurement.v1.Order> getOrdersList() { if (ordersBuilder_ == null) { return java.util.Collections.unmodifiableList(orders_); } else { return ordersBuilder_.getMessageList(); } } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public int getOrdersCount() { if (ordersBuilder_ == null) { return orders_.size(); } else { return ordersBuilder_.getCount(); } } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public com.google.cloud.commerce.consumer.procurement.v1.Order getOrders(int index) { if (ordersBuilder_ == null) { return orders_.get(index); } else { return ordersBuilder_.getMessage(index); } } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public Builder setOrders( int index, com.google.cloud.commerce.consumer.procurement.v1.Order value) { if (ordersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOrdersIsMutable(); orders_.set(index, value); onChanged(); } else { ordersBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public Builder setOrders( int index, com.google.cloud.commerce.consumer.procurement.v1.Order.Builder builderForValue) { if (ordersBuilder_ == null) { ensureOrdersIsMutable(); orders_.set(index, builderForValue.build()); onChanged(); } else { ordersBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public Builder addOrders(com.google.cloud.commerce.consumer.procurement.v1.Order value) { if (ordersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOrdersIsMutable(); orders_.add(value); onChanged(); } else { ordersBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public Builder addOrders( int index, com.google.cloud.commerce.consumer.procurement.v1.Order value) { if (ordersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOrdersIsMutable(); orders_.add(index, value); onChanged(); } else { ordersBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public Builder addOrders( com.google.cloud.commerce.consumer.procurement.v1.Order.Builder builderForValue) { if (ordersBuilder_ == null) { ensureOrdersIsMutable(); orders_.add(builderForValue.build()); onChanged(); } else { ordersBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public Builder addOrders( int index, com.google.cloud.commerce.consumer.procurement.v1.Order.Builder builderForValue) { if (ordersBuilder_ == null) { ensureOrdersIsMutable(); orders_.add(index, builderForValue.build()); onChanged(); } else { ordersBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public Builder addAllOrders( java.lang.Iterable<? extends com.google.cloud.commerce.consumer.procurement.v1.Order> values) { if (ordersBuilder_ == null) { ensureOrdersIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, orders_); onChanged(); } else { ordersBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public Builder clearOrders() { if (ordersBuilder_ == null) { orders_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { ordersBuilder_.clear(); } return this; } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public Builder removeOrders(int index) { if (ordersBuilder_ == null) { ensureOrdersIsMutable(); orders_.remove(index); onChanged(); } else { ordersBuilder_.remove(index); } return this; } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public com.google.cloud.commerce.consumer.procurement.v1.Order.Builder getOrdersBuilder( int index) { return getOrdersFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public com.google.cloud.commerce.consumer.procurement.v1.OrderOrBuilder getOrdersOrBuilder( int index) { if (ordersBuilder_ == null) { return orders_.get(index); } else { return ordersBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public java.util.List< ? extends com.google.cloud.commerce.consumer.procurement.v1.OrderOrBuilder> getOrdersOrBuilderList() { if (ordersBuilder_ != null) { return ordersBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(orders_); } } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public com.google.cloud.commerce.consumer.procurement.v1.Order.Builder addOrdersBuilder() { return getOrdersFieldBuilder() .addBuilder(com.google.cloud.commerce.consumer.procurement.v1.Order.getDefaultInstance()); } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public com.google.cloud.commerce.consumer.procurement.v1.Order.Builder addOrdersBuilder( int index) { return getOrdersFieldBuilder() .addBuilder( index, com.google.cloud.commerce.consumer.procurement.v1.Order.getDefaultInstance()); } /** * * * <pre> * The list of orders in this response. * </pre> * * <code>repeated .google.cloud.commerce.consumer.procurement.v1.Order orders = 1;</code> */ public java.util.List<com.google.cloud.commerce.consumer.procurement.v1.Order.Builder> getOrdersBuilderList() { return getOrdersFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.commerce.consumer.procurement.v1.Order, com.google.cloud.commerce.consumer.procurement.v1.Order.Builder, com.google.cloud.commerce.consumer.procurement.v1.OrderOrBuilder> getOrdersFieldBuilder() { if (ordersBuilder_ == null) { ordersBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.commerce.consumer.procurement.v1.Order, com.google.cloud.commerce.consumer.procurement.v1.Order.Builder, com.google.cloud.commerce.consumer.procurement.v1.OrderOrBuilder>( orders_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); orders_ = null; } return ordersBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The token for fetching the next page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The token for fetching the next page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The token for fetching the next page. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The token for fetching the next page. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * The token for fetching the next 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.commerce.consumer.procurement.v1.ListOrdersResponse) } // @@protoc_insertion_point(class_scope:google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse) private static final com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse(); } public static com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListOrdersResponse> PARSER = new com.google.protobuf.AbstractParser<ListOrdersResponse>() { @java.lang.Override public ListOrdersResponse 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<ListOrdersResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListOrdersResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.commerce.consumer.procurement.v1.ListOrdersResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,359
java-datalabeling/proto-google-cloud-datalabeling-v1beta1/src/main/java/com/google/cloud/datalabeling/v1beta1/SearchEvaluationsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/datalabeling/v1beta1/data_labeling_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.datalabeling.v1beta1; /** * * * <pre> * Results of searching evaluations. * </pre> * * Protobuf type {@code google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse} */ public final class SearchEvaluationsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse) SearchEvaluationsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use SearchEvaluationsResponse.newBuilder() to construct. private SearchEvaluationsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SearchEvaluationsResponse() { evaluations_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SearchEvaluationsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_SearchEvaluationsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_SearchEvaluationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse.class, com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse.Builder.class); } public static final int EVALUATIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.datalabeling.v1beta1.Evaluation> evaluations_; /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.datalabeling.v1beta1.Evaluation> getEvaluationsList() { return evaluations_; } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.datalabeling.v1beta1.EvaluationOrBuilder> getEvaluationsOrBuilderList() { return evaluations_; } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ @java.lang.Override public int getEvaluationsCount() { return evaluations_.size(); } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ @java.lang.Override public com.google.cloud.datalabeling.v1beta1.Evaluation getEvaluations(int index) { return evaluations_.get(index); } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ @java.lang.Override public com.google.cloud.datalabeling.v1beta1.EvaluationOrBuilder getEvaluationsOrBuilder( int index) { return evaluations_.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. * </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. * </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 < evaluations_.size(); i++) { output.writeMessage(1, evaluations_.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 < evaluations_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, evaluations_.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.datalabeling.v1beta1.SearchEvaluationsResponse)) { return super.equals(obj); } com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse other = (com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse) obj; if (!getEvaluationsList().equals(other.getEvaluationsList())) 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 (getEvaluationsCount() > 0) { hash = (37 * hash) + EVALUATIONS_FIELD_NUMBER; hash = (53 * hash) + getEvaluationsList().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.datalabeling.v1beta1.SearchEvaluationsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse 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 of searching evaluations. * </pre> * * Protobuf type {@code google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse) com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_SearchEvaluationsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_SearchEvaluationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse.class, com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse.Builder.class); } // Construct using com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (evaluationsBuilder_ == null) { evaluations_ = java.util.Collections.emptyList(); } else { evaluations_ = null; evaluationsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_SearchEvaluationsResponse_descriptor; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse getDefaultInstanceForType() { return com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse build() { com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse buildPartial() { com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse result = new com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse result) { if (evaluationsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { evaluations_ = java.util.Collections.unmodifiableList(evaluations_); bitField0_ = (bitField0_ & ~0x00000001); } result.evaluations_ = evaluations_; } else { result.evaluations_ = evaluationsBuilder_.build(); } } private void buildPartial0( com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse 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.datalabeling.v1beta1.SearchEvaluationsResponse) { return mergeFrom((com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse other) { if (other == com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse.getDefaultInstance()) return this; if (evaluationsBuilder_ == null) { if (!other.evaluations_.isEmpty()) { if (evaluations_.isEmpty()) { evaluations_ = other.evaluations_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureEvaluationsIsMutable(); evaluations_.addAll(other.evaluations_); } onChanged(); } } else { if (!other.evaluations_.isEmpty()) { if (evaluationsBuilder_.isEmpty()) { evaluationsBuilder_.dispose(); evaluationsBuilder_ = null; evaluations_ = other.evaluations_; bitField0_ = (bitField0_ & ~0x00000001); evaluationsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getEvaluationsFieldBuilder() : null; } else { evaluationsBuilder_.addAllMessages(other.evaluations_); } } } 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.datalabeling.v1beta1.Evaluation m = input.readMessage( com.google.cloud.datalabeling.v1beta1.Evaluation.parser(), extensionRegistry); if (evaluationsBuilder_ == null) { ensureEvaluationsIsMutable(); evaluations_.add(m); } else { evaluationsBuilder_.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.datalabeling.v1beta1.Evaluation> evaluations_ = java.util.Collections.emptyList(); private void ensureEvaluationsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { evaluations_ = new java.util.ArrayList<com.google.cloud.datalabeling.v1beta1.Evaluation>(evaluations_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.datalabeling.v1beta1.Evaluation, com.google.cloud.datalabeling.v1beta1.Evaluation.Builder, com.google.cloud.datalabeling.v1beta1.EvaluationOrBuilder> evaluationsBuilder_; /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public java.util.List<com.google.cloud.datalabeling.v1beta1.Evaluation> getEvaluationsList() { if (evaluationsBuilder_ == null) { return java.util.Collections.unmodifiableList(evaluations_); } else { return evaluationsBuilder_.getMessageList(); } } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public int getEvaluationsCount() { if (evaluationsBuilder_ == null) { return evaluations_.size(); } else { return evaluationsBuilder_.getCount(); } } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.Evaluation getEvaluations(int index) { if (evaluationsBuilder_ == null) { return evaluations_.get(index); } else { return evaluationsBuilder_.getMessage(index); } } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public Builder setEvaluations( int index, com.google.cloud.datalabeling.v1beta1.Evaluation value) { if (evaluationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEvaluationsIsMutable(); evaluations_.set(index, value); onChanged(); } else { evaluationsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public Builder setEvaluations( int index, com.google.cloud.datalabeling.v1beta1.Evaluation.Builder builderForValue) { if (evaluationsBuilder_ == null) { ensureEvaluationsIsMutable(); evaluations_.set(index, builderForValue.build()); onChanged(); } else { evaluationsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public Builder addEvaluations(com.google.cloud.datalabeling.v1beta1.Evaluation value) { if (evaluationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEvaluationsIsMutable(); evaluations_.add(value); onChanged(); } else { evaluationsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public Builder addEvaluations( int index, com.google.cloud.datalabeling.v1beta1.Evaluation value) { if (evaluationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEvaluationsIsMutable(); evaluations_.add(index, value); onChanged(); } else { evaluationsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public Builder addEvaluations( com.google.cloud.datalabeling.v1beta1.Evaluation.Builder builderForValue) { if (evaluationsBuilder_ == null) { ensureEvaluationsIsMutable(); evaluations_.add(builderForValue.build()); onChanged(); } else { evaluationsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public Builder addEvaluations( int index, com.google.cloud.datalabeling.v1beta1.Evaluation.Builder builderForValue) { if (evaluationsBuilder_ == null) { ensureEvaluationsIsMutable(); evaluations_.add(index, builderForValue.build()); onChanged(); } else { evaluationsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public Builder addAllEvaluations( java.lang.Iterable<? extends com.google.cloud.datalabeling.v1beta1.Evaluation> values) { if (evaluationsBuilder_ == null) { ensureEvaluationsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, evaluations_); onChanged(); } else { evaluationsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public Builder clearEvaluations() { if (evaluationsBuilder_ == null) { evaluations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { evaluationsBuilder_.clear(); } return this; } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public Builder removeEvaluations(int index) { if (evaluationsBuilder_ == null) { ensureEvaluationsIsMutable(); evaluations_.remove(index); onChanged(); } else { evaluationsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.Evaluation.Builder getEvaluationsBuilder( int index) { return getEvaluationsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.EvaluationOrBuilder getEvaluationsOrBuilder( int index) { if (evaluationsBuilder_ == null) { return evaluations_.get(index); } else { return evaluationsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public java.util.List<? extends com.google.cloud.datalabeling.v1beta1.EvaluationOrBuilder> getEvaluationsOrBuilderList() { if (evaluationsBuilder_ != null) { return evaluationsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(evaluations_); } } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.Evaluation.Builder addEvaluationsBuilder() { return getEvaluationsFieldBuilder() .addBuilder(com.google.cloud.datalabeling.v1beta1.Evaluation.getDefaultInstance()); } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.Evaluation.Builder addEvaluationsBuilder( int index) { return getEvaluationsFieldBuilder() .addBuilder(index, com.google.cloud.datalabeling.v1beta1.Evaluation.getDefaultInstance()); } /** * * * <pre> * The list of evaluations matching the search. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Evaluation evaluations = 1;</code> */ public java.util.List<com.google.cloud.datalabeling.v1beta1.Evaluation.Builder> getEvaluationsBuilderList() { return getEvaluationsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.datalabeling.v1beta1.Evaluation, com.google.cloud.datalabeling.v1beta1.Evaluation.Builder, com.google.cloud.datalabeling.v1beta1.EvaluationOrBuilder> getEvaluationsFieldBuilder() { if (evaluationsBuilder_ == null) { evaluationsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.datalabeling.v1beta1.Evaluation, com.google.cloud.datalabeling.v1beta1.Evaluation.Builder, com.google.cloud.datalabeling.v1beta1.EvaluationOrBuilder>( evaluations_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); evaluations_ = null; } return evaluationsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve 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. * </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. * </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. * </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. * </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.datalabeling.v1beta1.SearchEvaluationsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse) private static final com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse(); } public static com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SearchEvaluationsResponse> PARSER = new com.google.protobuf.AbstractParser<SearchEvaluationsResponse>() { @java.lang.Override public SearchEvaluationsResponse 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<SearchEvaluationsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SearchEvaluationsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.SearchEvaluationsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,346
java-shopping-merchant-accounts/proto-google-shopping-merchant-accounts-v1/src/main/java/com/google/shopping/merchant/accounts/v1/ListAccountsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/shopping/merchant/accounts/v1/accounts.proto // Protobuf Java Version: 3.25.8 package com.google.shopping.merchant.accounts.v1; /** * * * <pre> * Response message for the `accounts.list` method. * </pre> * * Protobuf type {@code google.shopping.merchant.accounts.v1.ListAccountsResponse} */ public final class ListAccountsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.shopping.merchant.accounts.v1.ListAccountsResponse) ListAccountsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListAccountsResponse.newBuilder() to construct. private ListAccountsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListAccountsResponse() { accounts_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListAccountsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.accounts.v1.AccountsProto .internal_static_google_shopping_merchant_accounts_v1_ListAccountsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.accounts.v1.AccountsProto .internal_static_google_shopping_merchant_accounts_v1_ListAccountsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.accounts.v1.ListAccountsResponse.class, com.google.shopping.merchant.accounts.v1.ListAccountsResponse.Builder.class); } public static final int ACCOUNTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.shopping.merchant.accounts.v1.Account> accounts_; /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ @java.lang.Override public java.util.List<com.google.shopping.merchant.accounts.v1.Account> getAccountsList() { return accounts_; } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.shopping.merchant.accounts.v1.AccountOrBuilder> getAccountsOrBuilderList() { return accounts_; } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ @java.lang.Override public int getAccountsCount() { return accounts_.size(); } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ @java.lang.Override public com.google.shopping.merchant.accounts.v1.Account getAccounts(int index) { return accounts_.get(index); } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ @java.lang.Override public com.google.shopping.merchant.accounts.v1.AccountOrBuilder getAccountsOrBuilder(int index) { return accounts_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < accounts_.size(); i++) { output.writeMessage(1, accounts_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < accounts_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, accounts_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.shopping.merchant.accounts.v1.ListAccountsResponse)) { return super.equals(obj); } com.google.shopping.merchant.accounts.v1.ListAccountsResponse other = (com.google.shopping.merchant.accounts.v1.ListAccountsResponse) obj; if (!getAccountsList().equals(other.getAccountsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getAccountsCount() > 0) { hash = (37 * hash) + ACCOUNTS_FIELD_NUMBER; hash = (53 * hash) + getAccountsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.shopping.merchant.accounts.v1.ListAccountsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.accounts.v1.ListAccountsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.accounts.v1.ListAccountsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.accounts.v1.ListAccountsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.accounts.v1.ListAccountsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.accounts.v1.ListAccountsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.accounts.v1.ListAccountsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.accounts.v1.ListAccountsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.merchant.accounts.v1.ListAccountsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.shopping.merchant.accounts.v1.ListAccountsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.merchant.accounts.v1.ListAccountsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.accounts.v1.ListAccountsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.shopping.merchant.accounts.v1.ListAccountsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response message for the `accounts.list` method. * </pre> * * Protobuf type {@code google.shopping.merchant.accounts.v1.ListAccountsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.shopping.merchant.accounts.v1.ListAccountsResponse) com.google.shopping.merchant.accounts.v1.ListAccountsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.accounts.v1.AccountsProto .internal_static_google_shopping_merchant_accounts_v1_ListAccountsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.accounts.v1.AccountsProto .internal_static_google_shopping_merchant_accounts_v1_ListAccountsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.accounts.v1.ListAccountsResponse.class, com.google.shopping.merchant.accounts.v1.ListAccountsResponse.Builder.class); } // Construct using com.google.shopping.merchant.accounts.v1.ListAccountsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (accountsBuilder_ == null) { accounts_ = java.util.Collections.emptyList(); } else { accounts_ = null; accountsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.shopping.merchant.accounts.v1.AccountsProto .internal_static_google_shopping_merchant_accounts_v1_ListAccountsResponse_descriptor; } @java.lang.Override public com.google.shopping.merchant.accounts.v1.ListAccountsResponse getDefaultInstanceForType() { return com.google.shopping.merchant.accounts.v1.ListAccountsResponse.getDefaultInstance(); } @java.lang.Override public com.google.shopping.merchant.accounts.v1.ListAccountsResponse build() { com.google.shopping.merchant.accounts.v1.ListAccountsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.shopping.merchant.accounts.v1.ListAccountsResponse buildPartial() { com.google.shopping.merchant.accounts.v1.ListAccountsResponse result = new com.google.shopping.merchant.accounts.v1.ListAccountsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.shopping.merchant.accounts.v1.ListAccountsResponse result) { if (accountsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { accounts_ = java.util.Collections.unmodifiableList(accounts_); bitField0_ = (bitField0_ & ~0x00000001); } result.accounts_ = accounts_; } else { result.accounts_ = accountsBuilder_.build(); } } private void buildPartial0( com.google.shopping.merchant.accounts.v1.ListAccountsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.shopping.merchant.accounts.v1.ListAccountsResponse) { return mergeFrom((com.google.shopping.merchant.accounts.v1.ListAccountsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.shopping.merchant.accounts.v1.ListAccountsResponse other) { if (other == com.google.shopping.merchant.accounts.v1.ListAccountsResponse.getDefaultInstance()) return this; if (accountsBuilder_ == null) { if (!other.accounts_.isEmpty()) { if (accounts_.isEmpty()) { accounts_ = other.accounts_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureAccountsIsMutable(); accounts_.addAll(other.accounts_); } onChanged(); } } else { if (!other.accounts_.isEmpty()) { if (accountsBuilder_.isEmpty()) { accountsBuilder_.dispose(); accountsBuilder_ = null; accounts_ = other.accounts_; bitField0_ = (bitField0_ & ~0x00000001); accountsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getAccountsFieldBuilder() : null; } else { accountsBuilder_.addAllMessages(other.accounts_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.shopping.merchant.accounts.v1.Account m = input.readMessage( com.google.shopping.merchant.accounts.v1.Account.parser(), extensionRegistry); if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.add(m); } else { accountsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.shopping.merchant.accounts.v1.Account> accounts_ = java.util.Collections.emptyList(); private void ensureAccountsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { accounts_ = new java.util.ArrayList<com.google.shopping.merchant.accounts.v1.Account>(accounts_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.merchant.accounts.v1.Account, com.google.shopping.merchant.accounts.v1.Account.Builder, com.google.shopping.merchant.accounts.v1.AccountOrBuilder> accountsBuilder_; /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public java.util.List<com.google.shopping.merchant.accounts.v1.Account> getAccountsList() { if (accountsBuilder_ == null) { return java.util.Collections.unmodifiableList(accounts_); } else { return accountsBuilder_.getMessageList(); } } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public int getAccountsCount() { if (accountsBuilder_ == null) { return accounts_.size(); } else { return accountsBuilder_.getCount(); } } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public com.google.shopping.merchant.accounts.v1.Account getAccounts(int index) { if (accountsBuilder_ == null) { return accounts_.get(index); } else { return accountsBuilder_.getMessage(index); } } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public Builder setAccounts(int index, com.google.shopping.merchant.accounts.v1.Account value) { if (accountsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAccountsIsMutable(); accounts_.set(index, value); onChanged(); } else { accountsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public Builder setAccounts( int index, com.google.shopping.merchant.accounts.v1.Account.Builder builderForValue) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.set(index, builderForValue.build()); onChanged(); } else { accountsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public Builder addAccounts(com.google.shopping.merchant.accounts.v1.Account value) { if (accountsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAccountsIsMutable(); accounts_.add(value); onChanged(); } else { accountsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public Builder addAccounts(int index, com.google.shopping.merchant.accounts.v1.Account value) { if (accountsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAccountsIsMutable(); accounts_.add(index, value); onChanged(); } else { accountsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public Builder addAccounts( com.google.shopping.merchant.accounts.v1.Account.Builder builderForValue) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.add(builderForValue.build()); onChanged(); } else { accountsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public Builder addAccounts( int index, com.google.shopping.merchant.accounts.v1.Account.Builder builderForValue) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.add(index, builderForValue.build()); onChanged(); } else { accountsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public Builder addAllAccounts( java.lang.Iterable<? extends com.google.shopping.merchant.accounts.v1.Account> values) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, accounts_); onChanged(); } else { accountsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public Builder clearAccounts() { if (accountsBuilder_ == null) { accounts_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { accountsBuilder_.clear(); } return this; } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public Builder removeAccounts(int index) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.remove(index); onChanged(); } else { accountsBuilder_.remove(index); } return this; } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public com.google.shopping.merchant.accounts.v1.Account.Builder getAccountsBuilder(int index) { return getAccountsFieldBuilder().getBuilder(index); } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public com.google.shopping.merchant.accounts.v1.AccountOrBuilder getAccountsOrBuilder( int index) { if (accountsBuilder_ == null) { return accounts_.get(index); } else { return accountsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public java.util.List<? extends com.google.shopping.merchant.accounts.v1.AccountOrBuilder> getAccountsOrBuilderList() { if (accountsBuilder_ != null) { return accountsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(accounts_); } } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public com.google.shopping.merchant.accounts.v1.Account.Builder addAccountsBuilder() { return getAccountsFieldBuilder() .addBuilder(com.google.shopping.merchant.accounts.v1.Account.getDefaultInstance()); } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public com.google.shopping.merchant.accounts.v1.Account.Builder addAccountsBuilder(int index) { return getAccountsFieldBuilder() .addBuilder(index, com.google.shopping.merchant.accounts.v1.Account.getDefaultInstance()); } /** * * * <pre> * The accounts matching the `ListAccountsRequest`. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Account accounts = 1;</code> */ public java.util.List<com.google.shopping.merchant.accounts.v1.Account.Builder> getAccountsBuilderList() { return getAccountsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.merchant.accounts.v1.Account, com.google.shopping.merchant.accounts.v1.Account.Builder, com.google.shopping.merchant.accounts.v1.AccountOrBuilder> getAccountsFieldBuilder() { if (accountsBuilder_ == null) { accountsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.merchant.accounts.v1.Account, com.google.shopping.merchant.accounts.v1.Account.Builder, com.google.shopping.merchant.accounts.v1.AccountOrBuilder>( accounts_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); accounts_ = null; } return accountsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.shopping.merchant.accounts.v1.ListAccountsResponse) } // @@protoc_insertion_point(class_scope:google.shopping.merchant.accounts.v1.ListAccountsResponse) private static final com.google.shopping.merchant.accounts.v1.ListAccountsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.shopping.merchant.accounts.v1.ListAccountsResponse(); } public static com.google.shopping.merchant.accounts.v1.ListAccountsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListAccountsResponse> PARSER = new com.google.protobuf.AbstractParser<ListAccountsResponse>() { @java.lang.Override public ListAccountsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListAccountsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListAccountsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.shopping.merchant.accounts.v1.ListAccountsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/flink-cdc
37,453
flink-cdc-runtime/src/main/java/org/apache/flink/cdc/runtime/functions/SystemFunctionUtils.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.runtime.functions; import org.apache.flink.cdc.common.data.DateData; import org.apache.flink.cdc.common.data.DecimalData; import org.apache.flink.cdc.common.data.LocalZonedTimestampData; import org.apache.flink.cdc.common.data.TimeData; import org.apache.flink.cdc.common.data.TimestampData; import org.apache.flink.cdc.common.data.ZonedTimestampData; import org.apache.flink.cdc.common.utils.DateTimeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Arrays; import java.util.TimeZone; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.apache.flink.cdc.common.utils.DateTimeUtils.timestampMillisToDate; import static org.apache.flink.cdc.common.utils.DateTimeUtils.timestampMillisToTime; /** * System function utils to support the call of flink cdc pipeline transform. <br> * {@code castToXxx}-series function returns `null` when conversion is not viable. */ public class SystemFunctionUtils { private static final Logger LOG = LoggerFactory.getLogger(SystemFunctionUtils.class); public static LocalZonedTimestampData currentTimestamp(long epochTime) { return LocalZonedTimestampData.fromEpochMillis(epochTime); } // synonym with currentTimestamp public static LocalZonedTimestampData now(long epochTime) { return LocalZonedTimestampData.fromEpochMillis(epochTime); } public static TimestampData localtimestamp(long epochTime, String timezone) { return TimestampData.fromLocalDateTime( Instant.ofEpochMilli(epochTime).atZone(ZoneId.of(timezone)).toLocalDateTime()); } public static TimeData localtime(long epochTime, String timezone) { return timestampMillisToTime(localtimestamp(epochTime, timezone).getMillisecond()); } public static TimeData currentTime(long epochTime, String timezone) { // the time value of currentTimestamp under given session time zone return timestampMillisToTime(localtimestamp(epochTime, timezone).getMillisecond()); } public static DateData currentDate(long epochTime, String timezone) { // the date value of currentTimestamp under given session time zone return timestampMillisToDate(localtimestamp(epochTime, timezone).getMillisecond()); } public static String fromUnixtime(long seconds, String timezone) { return DateTimeUtils.formatUnixTimestamp(seconds, TimeZone.getTimeZone(timezone)); } public static String fromUnixtime(long seconds, String format, String timezone) { return DateTimeUtils.formatUnixTimestamp(seconds, format, TimeZone.getTimeZone(timezone)); } public static long unixTimestamp(long epochTime, String timezone) { return epochTime / 1000; } public static long unixTimestamp(String dateTimeStr, long epochTime, String timezone) { return DateTimeUtils.unixTimestamp(dateTimeStr, TimeZone.getTimeZone(timezone)); } public static long unixTimestamp( String dateTimeStr, String format, long epochTime, String timezone) { return DateTimeUtils.unixTimestamp(dateTimeStr, format, TimeZone.getTimeZone(timezone)); } public static String dateFormat(TimestampData timestamp, String format, String timezone) { if (timestamp == null) { return null; } // `timezone` is ignored since TimestampData is time-zone insensitive return DateTimeUtils.formatTimestampMillis( timestamp.getMillisecond(), format, TimeZone.getTimeZone("UTC")); } public static String dateFormat( LocalZonedTimestampData timestamp, String format, String timezone) { if (timestamp == null) { return null; } return DateTimeUtils.formatTimestampMillis( timestamp.getEpochMillisecond(), format, TimeZone.getTimeZone(timezone)); } public static DateData toDate(String str, String timezone) { return toDate(str, "yyyy-MM-dd", timezone); } public static DateData toDate(String str, String format, String timezone) { return DateTimeUtils.parseDate(str, format, timezone); } public static TimestampData toTimestamp(String str, String timezone) { return toTimestamp(str, "yyyy-MM-dd HH:mm:ss", timezone); } public static TimestampData toTimestamp(String str, String format, String timezone) { SimpleDateFormat dateFormat = new SimpleDateFormat(format); dateFormat.setTimeZone(TimeZone.getTimeZone(timezone)); try { return TimestampData.fromMillis(dateFormat.parse(str).getTime()); } catch (ParseException e) { LOG.error("Unsupported date type convert: {}", str); throw new RuntimeException(e); } } // Be compatible with the existing definition of Function TIMESTAMP_DIFF public static Integer timestampDiff( String timeIntervalUnit, LocalZonedTimestampData fromTimestamp, LocalZonedTimestampData toTimestamp, String timezone) { if (fromTimestamp == null || toTimestamp == null) { return null; } return DateTimeUtils.timestampDiff( timeIntervalUnit, fromTimestamp.getEpochMillisecond(), timezone, toTimestamp.getEpochMillisecond(), timezone); } // Be compatible with the existing definition of Function TIMESTAMP_DIFF public static Integer timestampDiff( String timeIntervalUnit, TimestampData fromTimestamp, TimestampData toTimestamp, String timezone) { if (fromTimestamp == null || toTimestamp == null) { return null; } return DateTimeUtils.timestampDiff( timeIntervalUnit, fromTimestamp.getMillisecond(), "UTC", toTimestamp.getMillisecond(), "UTC"); } // Be compatible with the existing definition of Function TIMESTAMP_DIFF public static Integer timestampDiff( String timeIntervalUnit, TimestampData fromTimestamp, LocalZonedTimestampData toTimestamp, String timezone) { if (fromTimestamp == null || toTimestamp == null) { return null; } return DateTimeUtils.timestampDiff( timeIntervalUnit, fromTimestamp.getMillisecond(), "UTC", toTimestamp.getEpochMillisecond(), timezone); } // Be compatible with the existing definition of Function TIMESTAMP_DIFF public static Integer timestampDiff( String timeIntervalUnit, LocalZonedTimestampData fromTimestamp, TimestampData toTimestamp, String timezone) { if (fromTimestamp == null || toTimestamp == null) { return null; } return DateTimeUtils.timestampDiff( timeIntervalUnit, fromTimestamp.getEpochMillisecond(), timezone, toTimestamp.getMillisecond(), "UTC"); } public static Integer timestampdiff( String timeIntervalUnit, LocalZonedTimestampData fromTimestamp, LocalZonedTimestampData toTimestamp, String timezone) { return timestampDiff(timeIntervalUnit, fromTimestamp, toTimestamp, timezone); } public static Integer timestampdiff( String timeIntervalUnit, TimestampData fromTimestamp, TimestampData toTimestamp, String timezone) { return timestampDiff(timeIntervalUnit, fromTimestamp, toTimestamp, timezone); } public static Integer timestampdiff( String timeIntervalUnit, TimestampData fromTimestamp, LocalZonedTimestampData toTimestamp, String timezone) { return timestampDiff(timeIntervalUnit, fromTimestamp, toTimestamp, timezone); } public static Integer timestampdiff( String timeIntervalUnit, LocalZonedTimestampData fromTimestamp, TimestampData toTimestamp, String timezone) { return timestampDiff(timeIntervalUnit, fromTimestamp, toTimestamp, timezone); } public static LocalZonedTimestampData timestampadd( String timeIntervalUnit, Integer interval, LocalZonedTimestampData timePoint, String timezone) { if (interval == null || timePoint == null) { return null; } return LocalZonedTimestampData.fromEpochMillis( DateTimeUtils.timestampAdd( timeIntervalUnit, interval, timePoint.getEpochMillisecond(), timezone)); } public static TimestampData timestampadd( String timeIntervalUnit, Integer interval, TimestampData timePoint, String timezone) { if (interval == null || timePoint == null) { return null; } return TimestampData.fromMillis( DateTimeUtils.timestampAdd( timeIntervalUnit, interval, timePoint.getMillisecond(), "UTC")); } public static boolean betweenAsymmetric(String value, String minValue, String maxValue) { if (value == null) { return false; } return value.compareTo(minValue) >= 0 && value.compareTo(maxValue) <= 0; } public static boolean betweenAsymmetric(Short value, short minValue, short maxValue) { if (value == null) { return false; } return value >= minValue && value <= maxValue; } public static boolean betweenAsymmetric(Integer value, int minValue, int maxValue) { if (value == null) { return false; } return value >= minValue && value <= maxValue; } public static boolean betweenAsymmetric(Long value, long minValue, long maxValue) { if (value == null) { return false; } return value >= minValue && value <= maxValue; } public static boolean betweenAsymmetric(Float value, float minValue, float maxValue) { if (value == null) { return false; } return value >= minValue && value <= maxValue; } public static boolean betweenAsymmetric(Double value, double minValue, double maxValue) { if (value == null) { return false; } return value >= minValue && value <= maxValue; } public static boolean betweenAsymmetric( BigDecimal value, BigDecimal minValue, BigDecimal maxValue) { if (value == null) { return false; } return value.compareTo(minValue) >= 0 && value.compareTo(maxValue) <= 0; } public static boolean betweenAsymmetric( DecimalData value, DecimalData minValue, DecimalData maxValue) { if (value == null) { return false; } return value.compareTo(minValue) >= 0 && value.compareTo(maxValue) <= 0; } public static boolean notBetweenAsymmetric(String value, String minValue, String maxValue) { return !betweenAsymmetric(value, minValue, maxValue); } public static boolean notBetweenAsymmetric(Short value, short minValue, short maxValue) { return !betweenAsymmetric(value, minValue, maxValue); } public static boolean notBetweenAsymmetric(Integer value, int minValue, int maxValue) { return !betweenAsymmetric(value, minValue, maxValue); } public static boolean notBetweenAsymmetric(Long value, long minValue, long maxValue) { return !betweenAsymmetric(value, minValue, maxValue); } public static boolean notBetweenAsymmetric(Float value, float minValue, float maxValue) { return !betweenAsymmetric(value, minValue, maxValue); } public static boolean notBetweenAsymmetric(Double value, double minValue, double maxValue) { return !betweenAsymmetric(value, minValue, maxValue); } public static boolean notBetweenAsymmetric( BigDecimal value, BigDecimal minValue, BigDecimal maxValue) { return !betweenAsymmetric(value, minValue, maxValue); } public static boolean notBetweenAsymmetric( DecimalData value, DecimalData minValue, DecimalData maxValue) { return !betweenAsymmetric(value, minValue, maxValue); } public static boolean in(String value, String... str) { return Arrays.stream(str).anyMatch(item -> value.equals(item)); } public static boolean in(Short value, Short... values) { return Arrays.stream(values).anyMatch(item -> value.equals(item)); } public static boolean in(Integer value, Integer... values) { return Arrays.stream(values).anyMatch(item -> value.equals(item)); } public static boolean in(Long value, Long... values) { return Arrays.stream(values).anyMatch(item -> value.equals(item)); } public static boolean in(Float value, Float... values) { return Arrays.stream(values).anyMatch(item -> value.equals(item)); } public static boolean in(Double value, Double... values) { return Arrays.stream(values).anyMatch(item -> value.equals(item)); } public static boolean in(BigDecimal value, BigDecimal... values) { return Arrays.stream(values).anyMatch(item -> value.equals(item)); } public static boolean in(DecimalData value, DecimalData... values) { return Arrays.stream(values).anyMatch(item -> value.equals(item)); } public static boolean notIn(String value, String... values) { return !in(value, values); } public static boolean notIn(Short value, Short... values) { return !in(value, values); } public static boolean notIn(Integer value, Integer... values) { return !in(value, values); } public static boolean notIn(Long value, Long... values) { return !in(value, values); } public static boolean notIn(Float value, Float... values) { return !in(value, values); } public static boolean notIn(Double value, Double... values) { return !in(value, values); } public static boolean notIn(BigDecimal value, BigDecimal... values) { return !in(value, values); } public static boolean notIn(DecimalData value, DecimalData... values) { return !in(value, values); } public static int charLength(String str) { return str.length(); } public static String trim(String symbol, String target, String str) { return str.trim(); } /** * Returns a string resulting from replacing all substrings that match the regular expression * with replacement. */ public static String regexpReplace(String str, String regex, String replacement) { if (str == null || regex == null || replacement == null) { return null; } try { return str.replaceAll(regex, Matcher.quoteReplacement(replacement)); } catch (Exception e) { LOG.error( String.format( "Exception in regexpReplace('%s', '%s', '%s')", str, regex, replacement), e); // return null if exception in regex replace return null; } } public static String concat(String... str) { return String.join("", str); } public static boolean like(String str, String regex) { return Pattern.compile(regex).matcher(str).find(); } public static boolean notLike(String str, String regex) { return !like(str, regex); } public static String substr(String str, int beginIndex) { return substring(str, beginIndex); } public static String substr(String str, int beginIndex, int length) { return substring(str, beginIndex, length); } public static String substring(String str, int beginIndex) { return substring(str, beginIndex, Integer.MAX_VALUE); } public static String substring(String str, int beginIndex, int length) { if (length < 0) { LOG.error( "length of 'substring(str, beginIndex, length)' must be >= 0 and Int type, but length = {}", length); throw new RuntimeException( "length of 'substring(str, beginIndex, length)' must be >= 0 and Int type, but length = " + length); } if (length > Integer.MAX_VALUE || beginIndex > Integer.MAX_VALUE) { LOG.error( "length or start of 'substring(str, beginIndex, length)' must be Int type, but length = {}, beginIndex = {}", beginIndex, length); throw new RuntimeException( "length or start of 'substring(str, beginIndex, length)' must be Int type, but length = " + beginIndex + ", beginIndex = " + length); } if (str.isEmpty()) { return ""; } int startPos; int endPos; if (beginIndex > 0) { startPos = beginIndex - 1; if (startPos >= str.length()) { return ""; } } else if (beginIndex < 0) { startPos = str.length() + beginIndex; if (startPos < 0) { return ""; } } else { startPos = 0; } if ((str.length() - startPos) < length) { endPos = str.length(); } else { endPos = startPos + length; } return str.substring(startPos, endPos); } public static String upper(String str) { return str.toUpperCase(); } public static String lower(String str) { return str.toLowerCase(); } /** SQL <code>ABS</code> operator applied to byte values. */ public static Byte abs(Byte value) { if (value == null) { return null; } return (byte) Math.abs(value); } /** SQL <code>ABS</code> operator applied to short values. */ public static Short abs(Short value) { if (value == null) { return null; } return (short) Math.abs(value); } /** SQL <code>ABS</code> operator applied to int values. */ public static Integer abs(Integer value) { if (value == null) { return null; } return Math.abs(value); } /** SQL <code>ABS</code> operator applied to long values. */ public static Long abs(Long value) { if (value == null) { return null; } return Math.abs(value); } /** SQL <code>ABS</code> operator applied to float values. */ public static Float abs(Float value) { if (value == null) { return null; } return Math.abs(value); } /** SQL <code>ABS</code> operator applied to double values. */ public static Double abs(Double value) { if (value == null) { return null; } return Math.abs(value); } /** SQL <code>ABS</code> operator applied to decimal values. */ public static DecimalData abs(DecimalData value) { if (value == null) { return null; } return DecimalData.fromBigDecimal( BigDecimal.valueOf(Math.abs(value.toBigDecimal().doubleValue())), value.precision(), value.scale()); } public static Byte floor(Byte value) { return value; } public static Short floor(Short value) { return value; } public static Integer floor(Integer value) { return value; } public static Long floor(Long value) { return value; } public static Double floor(Double value) { if (value == null) { return null; } return Math.floor(value); } public static Float floor(Float value) { if (value == null) { return null; } return (float) Math.floor(value); } public static DecimalData floor(DecimalData value) { if (value == null) { return null; } return DecimalData.fromBigDecimal( BigDecimal.valueOf(Math.floor(value.toBigDecimal().doubleValue())), value.precision(), 0); } public static Byte ceil(Byte value) { return value; } public static Short ceil(Short value) { return value; } public static Integer ceil(Integer value) { return value; } public static Long ceil(Long value) { return value; } public static Double ceil(Double value) { if (value == null) { return null; } return Math.ceil(value); } public static Float ceil(Float value) { if (value == null) { return null; } return (float) Math.ceil(value); } public static DecimalData ceil(DecimalData value) { if (value == null) { return null; } return DecimalData.fromBigDecimal( BigDecimal.valueOf(Math.ceil(value.toBigDecimal().doubleValue())), value.precision(), 0); } // SQL ROUND /** SQL <code>ROUND</code> operator applied to byte values. */ public static Byte round(Byte value, int pointOffset) { if (value == null) { return null; } return round(BigDecimal.valueOf(value), pointOffset).byteValue(); } /** SQL <code>ROUND</code> operator applied to short values. */ public static Short round(Short value, int pointOffset) { if (value == null) { return null; } return round(BigDecimal.valueOf(value), pointOffset).shortValue(); } /** SQL <code>ROUND</code> operator applied to int values. */ public static Integer round(Integer value, int pointOffset) { if (value == null) { return null; } return round(BigDecimal.valueOf(value), pointOffset).intValue(); } /** SQL <code>ROUND</code> operator applied to long values. */ public static Long round(Long value, int pointOffset) { if (value == null) { return null; } return round(BigDecimal.valueOf(value), pointOffset).longValue(); } /** SQL <code>ROUND</code> operator applied to DecimalData values. */ public static DecimalData round(DecimalData value, int pointOffset) { if (value == null) { return null; } return DecimalData.fromBigDecimal( value.toBigDecimal() .movePointRight(pointOffset) .setScale(0, RoundingMode.HALF_UP) .movePointLeft(pointOffset), value.precision(), pointOffset); } /** SQL <code>ROUND</code> operator applied to float values. */ public static Float round(Float value, int pointOffset) { if (value == null) { return null; } return round(new BigDecimal(value.toString()), pointOffset).floatValue(); } /** SQL <code>ROUND</code> operator applied to double values. */ public static Double round(Double value, int pointOffset) { if (value == null) { return null; } return round(BigDecimal.valueOf(value), pointOffset).doubleValue(); } private static BigDecimal round(BigDecimal value, int pointOffset) { if (value == null) { return null; } return value.movePointRight(pointOffset) .setScale(0, RoundingMode.HALF_UP) .movePointLeft(pointOffset); } public static String uuid() { return UUID.randomUUID().toString(); } public static String uuid(byte[] b) { return UUID.nameUUIDFromBytes(b).toString(); } public static boolean valueEquals(Object object1, Object object2) { return (object1 != null && object2 != null) && object1.equals(object2); } public static Object coalesce(Object... objects) { for (Object item : objects) { if (item != null) { return item; } } return null; } public static String castToString(Object object) { if (object == null) { return null; } return object.toString(); } public static Boolean castToBoolean(Object object) { if (object == null) { return null; } else if (object instanceof Boolean) { return (Boolean) object; } else if (object instanceof Byte) { return !object.equals((byte) 0); } else if (object instanceof Short) { return !object.equals((short) 0); } else if (object instanceof Integer) { return !object.equals(0); } else if (object instanceof Long) { return !object.equals(0L); } else if (object instanceof Float) { return !object.equals(0f); } else if (object instanceof Double) { return !object.equals(0d); } else if (object instanceof BigDecimal) { return ((BigDecimal) object).compareTo(BigDecimal.ZERO) != 0; } else if (object instanceof DecimalData) { return ((DecimalData) object).compareTo(DecimalData.zero(1, 0)) != 0; } return Boolean.valueOf(castToString(object)); } public static Byte castToByte(Object object) { if (object == null) { return null; } if (object instanceof Boolean) { return (byte) ((Boolean) object ? 1 : 0); } if (object instanceof BigDecimal) { return ((BigDecimal) object).byteValue(); } if (object instanceof DecimalData) { return ((DecimalData) object).toBigDecimal().byteValue(); } if (object instanceof Double) { return ((Double) object).byteValue(); } if (object instanceof Float) { return ((Float) object).byteValue(); } String stringRep = castToString(object); try { return Byte.valueOf(stringRep); } catch (NumberFormatException e) { // Ignore this exception because it could still represent a valid floating point number, // but could not be accepted by Byte#valueOf. } try { return Double.valueOf(stringRep).byteValue(); } catch (NumberFormatException ignored) { return null; } } public static Short castToShort(Object object) { if (object == null) { return null; } if (object instanceof Boolean) { return (short) ((Boolean) object ? 1 : 0); } if (object instanceof BigDecimal) { return ((BigDecimal) object).shortValue(); } if (object instanceof DecimalData) { return ((DecimalData) object).toBigDecimal().shortValue(); } if (object instanceof Double) { return ((Double) object).shortValue(); } if (object instanceof Float) { return ((Float) object).shortValue(); } String stringRep = castToString(object); try { return Short.valueOf(stringRep); } catch (NumberFormatException e) { // Ignore this exception because it could still represent a valid floating point number, // but could not be accepted by Short#valueOf. } try { return Double.valueOf(stringRep).shortValue(); } catch (NumberFormatException ignored) { return null; } } public static Integer castToInteger(Object object) { if (object == null) { return null; } if (object instanceof Boolean) { return (Boolean) object ? 1 : 0; } if (object instanceof BigDecimal) { return ((BigDecimal) object).intValue(); } if (object instanceof DecimalData) { return ((DecimalData) object).toBigDecimal().intValue(); } if (object instanceof Double) { return ((Double) object).intValue(); } if (object instanceof Float) { return ((Float) object).intValue(); } String stringRep = castToString(object); try { return Integer.valueOf(stringRep); } catch (NumberFormatException e) { // Ignore this exception because it could still represent a valid floating point number, // but could not be accepted by Integer#valueOf. } try { return Double.valueOf(stringRep).intValue(); } catch (NumberFormatException ignored) { return null; } } public static Long castToLong(Object object) { if (object == null) { return null; } if (object instanceof Boolean) { return (Boolean) object ? 1L : 0L; } if (object instanceof BigDecimal) { return ((BigDecimal) object).longValue(); } if (object instanceof DecimalData) { return ((DecimalData) object).toBigDecimal().longValue(); } if (object instanceof Double) { return ((Double) object).longValue(); } if (object instanceof Float) { return ((Float) object).longValue(); } String stringRep = castToString(object); try { return Long.valueOf(stringRep); } catch (NumberFormatException e) { // Ignore this exception because it could still represent a valid floating point number, // but could not be accepted by Long#valueOf. } try { return Double.valueOf(stringRep).longValue(); } catch (NumberFormatException ignored) { return null; } } public static Float castToFloat(Object object) { if (object == null) { return null; } if (object instanceof Boolean) { return (Boolean) object ? 1f : 0f; } if (object instanceof BigDecimal) { return ((BigDecimal) object).floatValue(); } if (object instanceof DecimalData) { return ((DecimalData) object).toBigDecimal().floatValue(); } if (object instanceof Double) { return ((Double) object).floatValue(); } if (object instanceof Float) { return (Float) object; } try { return Float.valueOf(castObjectIntoString(object)); } catch (NumberFormatException ignored) { return null; } } public static Double castToDouble(Object object) { if (object == null) { return null; } if (object instanceof Boolean) { return (Boolean) object ? 1d : 0d; } if (object instanceof BigDecimal) { return ((BigDecimal) object).doubleValue(); } if (object instanceof DecimalData) { return ((DecimalData) object).toBigDecimal().doubleValue(); } if (object instanceof Double) { return (Double) object; } if (object instanceof Float) { return ((Float) object).doubleValue(); } try { return Double.valueOf(castObjectIntoString(object)); } catch (NumberFormatException ignored) { return null; } } public static BigDecimal castToBigDecimal(Object object, int precision, int scale) { if (object == null) { return null; } if (object instanceof Boolean) { object = (Boolean) object ? 1 : 0; } BigDecimal bigDecimal; try { bigDecimal = new BigDecimal(castObjectIntoString(object), new MathContext(precision)); bigDecimal = bigDecimal.setScale(scale, RoundingMode.HALF_UP); } catch (NumberFormatException ignored) { return null; } // If the precision overflows, null will be returned. Otherwise, we may accidentally emit a // non-serializable object into the pipeline that breaks downstream. if (bigDecimal.precision() > precision) { return null; } return bigDecimal; } public static DecimalData castToDecimalData(Object object, int precision, int scale) { if (object == null) { return null; } if (object instanceof Boolean) { object = (Boolean) object ? 1 : 0; } BigDecimal bigDecimal; try { bigDecimal = new BigDecimal(castObjectIntoString(object), new MathContext(precision)); bigDecimal = bigDecimal.setScale(scale, RoundingMode.HALF_UP); } catch (NumberFormatException ignored) { return null; } // If the precision overflows, null will be returned. Otherwise, we may accidentally emit a // non-serializable object into the pipeline that breaks downstream. if (bigDecimal.precision() > precision) { return null; } return DecimalData.fromBigDecimal(bigDecimal, precision, scale); } public static TimestampData castToTimestamp(Object object, String timezone) { if (object == null) { return null; } if (object instanceof LocalZonedTimestampData) { return TimestampData.fromLocalDateTime( LocalDateTime.ofInstant( ((LocalZonedTimestampData) object).toInstant(), ZoneId.of(timezone))); } else if (object instanceof ZonedTimestampData) { return TimestampData.fromLocalDateTime( LocalDateTime.ofInstant( ((ZonedTimestampData) object).toInstant(), ZoneId.of(timezone))); } else { return TimestampData.fromLocalDateTime( LocalDateTime.parse(castObjectIntoString(object))); } } private static String castObjectIntoString(Object object) { if (object instanceof Boolean) { return Boolean.valueOf(castToString(object)) ? "1" : "0"; } return String.valueOf(object); } private static int universalCompares(Object lhs, Object rhs) { Class<?> leftClass = lhs.getClass(); Class<?> rightClass = rhs.getClass(); if (leftClass.equals(rightClass) && lhs instanceof Comparable) { return ((Comparable) lhs).compareTo(rhs); } else if (lhs instanceof Number && rhs instanceof Number) { return Double.compare(((Number) lhs).doubleValue(), ((Number) rhs).doubleValue()); } else { throw new RuntimeException( "Comparison of unsupported data types: " + leftClass.getName() + " and " + rightClass.getName()); } } public static boolean greaterThan(Object lhs, Object rhs) { if (lhs == null || rhs == null) { return false; } return universalCompares(lhs, rhs) > 0; } public static boolean greaterThanOrEqual(Object lhs, Object rhs) { if (lhs == null || rhs == null) { return false; } return universalCompares(lhs, rhs) >= 0; } public static boolean lessThan(Object lhs, Object rhs) { if (lhs == null || rhs == null) { return false; } return universalCompares(lhs, rhs) < 0; } public static boolean lessThanOrEqual(Object lhs, Object rhs) { if (lhs == null || rhs == null) { return false; } return universalCompares(lhs, rhs) <= 0; } }
apache/lucene
37,594
lucene/core/src/java/org/apache/lucene/codecs/lucene90/Lucene90DocValuesConsumer.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.codecs.lucene90; import static org.apache.lucene.codecs.lucene90.Lucene90DocValuesFormat.DIRECT_MONOTONIC_BLOCK_SHIFT; import static org.apache.lucene.codecs.lucene90.Lucene90DocValuesFormat.NUMERIC_BLOCK_SHIFT; import static org.apache.lucene.codecs.lucene90.Lucene90DocValuesFormat.NUMERIC_BLOCK_SIZE; import static org.apache.lucene.codecs.lucene90.Lucene90DocValuesFormat.SKIP_INDEX_LEVEL_SHIFT; import static org.apache.lucene.codecs.lucene90.Lucene90DocValuesFormat.SKIP_INDEX_MAX_LEVEL; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.lucene.codecs.CodecUtil; import org.apache.lucene.codecs.DocValuesConsumer; import org.apache.lucene.codecs.DocValuesProducer; import org.apache.lucene.index.BinaryDocValues; import org.apache.lucene.index.DocValues; import org.apache.lucene.index.DocValuesSkipIndexType; import org.apache.lucene.index.EmptyDocValuesProducer; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.IndexFileNames; import org.apache.lucene.index.NumericDocValues; import org.apache.lucene.index.SegmentWriteState; import org.apache.lucene.index.SortedDocValues; import org.apache.lucene.index.SortedNumericDocValues; import org.apache.lucene.index.SortedSetDocValues; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.internal.hppc.LongHashSet; import org.apache.lucene.internal.hppc.LongIntHashMap; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.search.SortedSetSelector; import org.apache.lucene.store.ByteArrayDataOutput; import org.apache.lucene.store.ByteBuffersDataOutput; import org.apache.lucene.store.ByteBuffersIndexOutput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.util.ArrayUtil; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefBuilder; import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.LongsRef; import org.apache.lucene.util.MathUtil; import org.apache.lucene.util.StringHelper; import org.apache.lucene.util.compress.LZ4; import org.apache.lucene.util.packed.DirectMonotonicWriter; import org.apache.lucene.util.packed.DirectWriter; /** writer for {@link Lucene90DocValuesFormat} */ final class Lucene90DocValuesConsumer extends DocValuesConsumer { IndexOutput data, meta; final int maxDoc; private byte[] termsDictBuffer; private final int skipIndexIntervalSize; /** expert: Creates a new writer */ public Lucene90DocValuesConsumer( SegmentWriteState state, int skipIndexIntervalSize, String dataCodec, String dataExtension, String metaCodec, String metaExtension) throws IOException { this.termsDictBuffer = new byte[1 << 14]; try { String dataName = IndexFileNames.segmentFileName( state.segmentInfo.name, state.segmentSuffix, dataExtension); data = state.directory.createOutput(dataName, state.context); CodecUtil.writeIndexHeader( data, dataCodec, Lucene90DocValuesFormat.VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix); String metaName = IndexFileNames.segmentFileName( state.segmentInfo.name, state.segmentSuffix, metaExtension); meta = state.directory.createOutput(metaName, state.context); CodecUtil.writeIndexHeader( meta, metaCodec, Lucene90DocValuesFormat.VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix); maxDoc = state.segmentInfo.maxDoc(); this.skipIndexIntervalSize = skipIndexIntervalSize; } catch (Throwable t) { IOUtils.closeWhileSuppressingExceptions(t, this); throw t; } } @Override public void close() throws IOException { try { try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } } catch (Throwable t) { IOUtils.closeWhileSuppressingExceptions(t, data, meta); throw t; } IOUtils.close(data, meta); } finally { meta = data = null; } } @Override public void addNumericField(FieldInfo field, DocValuesProducer valuesProducer) throws IOException { meta.writeInt(field.number); meta.writeByte(Lucene90DocValuesFormat.NUMERIC); DocValuesProducer producer = new EmptyDocValuesProducer() { @Override public SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException { return DocValues.singleton(valuesProducer.getNumeric(field)); } }; if (field.docValuesSkipIndexType() != DocValuesSkipIndexType.NONE) { writeSkipIndex(field, producer); } writeValues(field, producer, false); } private static class MinMaxTracker { long min, max, numValues, spaceInBits; MinMaxTracker() { reset(); spaceInBits = 0; } private void reset() { min = Long.MAX_VALUE; max = Long.MIN_VALUE; numValues = 0; } /** Accumulate a new value. */ void update(long v) { min = Math.min(min, v); max = Math.max(max, v); ++numValues; } /** Accumulate state from another tracker. */ void update(MinMaxTracker other) { min = Math.min(min, other.min); max = Math.max(max, other.max); numValues += other.numValues; } /** Update the required space. */ void finish() { if (max > min) { spaceInBits += DirectWriter.unsignedBitsRequired(max - min) * numValues; } } /** Update space usage and get ready for accumulating values for the next block. */ void nextBlock() { finish(); reset(); } } private static class SkipAccumulator { int minDocID; int maxDocID; int docCount; long minValue; long maxValue; SkipAccumulator(int docID) { minDocID = docID; minValue = Long.MAX_VALUE; maxValue = Long.MIN_VALUE; docCount = 0; } boolean isDone(int skipIndexIntervalSize, int valueCount, long nextValue, int nextDoc) { if (docCount < skipIndexIntervalSize) { return false; } // Once we reach the interval size, we will keep accepting documents if // - next doc value is not a multi-value // - current accumulator only contains a single value and next value is the same value // - the accumulator is dense and the next doc keeps the density (no gaps) return valueCount > 1 || minValue != maxValue || minValue != nextValue || docCount != nextDoc - minDocID; } void accumulate(long value) { minValue = Math.min(minValue, value); maxValue = Math.max(maxValue, value); } void accumulate(SkipAccumulator other) { assert minDocID <= other.minDocID && maxDocID < other.maxDocID; maxDocID = other.maxDocID; minValue = Math.min(minValue, other.minValue); maxValue = Math.max(maxValue, other.maxValue); docCount += other.docCount; } void nextDoc(int docID) { maxDocID = docID; ++docCount; } public static SkipAccumulator merge(List<SkipAccumulator> list, int index, int length) { SkipAccumulator acc = new SkipAccumulator(list.get(index).minDocID); for (int i = 0; i < length; i++) { acc.accumulate(list.get(index + i)); } return acc; } } private void writeSkipIndex(FieldInfo field, DocValuesProducer valuesProducer) throws IOException { assert field.docValuesSkipIndexType() != DocValuesSkipIndexType.NONE; final long start = data.getFilePointer(); final SortedNumericDocValues values = valuesProducer.getSortedNumeric(field); long globalMaxValue = Long.MIN_VALUE; long globalMinValue = Long.MAX_VALUE; int globalDocCount = 0; int maxDocId = -1; final List<SkipAccumulator> accumulators = new ArrayList<>(); SkipAccumulator accumulator = null; final int maxAccumulators = 1 << (SKIP_INDEX_LEVEL_SHIFT * (SKIP_INDEX_MAX_LEVEL - 1)); for (int doc = values.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = values.nextDoc()) { final long firstValue = values.nextValue(); if (accumulator != null && accumulator.isDone(skipIndexIntervalSize, values.docValueCount(), firstValue, doc)) { globalMaxValue = Math.max(globalMaxValue, accumulator.maxValue); globalMinValue = Math.min(globalMinValue, accumulator.minValue); globalDocCount += accumulator.docCount; maxDocId = accumulator.maxDocID; accumulator = null; if (accumulators.size() == maxAccumulators) { writeLevels(accumulators); accumulators.clear(); } } if (accumulator == null) { accumulator = new SkipAccumulator(doc); accumulators.add(accumulator); } accumulator.nextDoc(doc); accumulator.accumulate(firstValue); for (int i = 1, end = values.docValueCount(); i < end; ++i) { accumulator.accumulate(values.nextValue()); } } if (accumulators.isEmpty() == false) { globalMaxValue = Math.max(globalMaxValue, accumulator.maxValue); globalMinValue = Math.min(globalMinValue, accumulator.minValue); globalDocCount += accumulator.docCount; maxDocId = accumulator.maxDocID; writeLevels(accumulators); } meta.writeLong(start); // record the start in meta meta.writeLong(data.getFilePointer() - start); // record the length assert globalDocCount == 0 || globalMaxValue >= globalMinValue; meta.writeLong(globalMaxValue); meta.writeLong(globalMinValue); assert globalDocCount <= maxDocId + 1; meta.writeInt(globalDocCount); meta.writeInt(maxDocId); } private void writeLevels(List<SkipAccumulator> accumulators) throws IOException { final List<List<SkipAccumulator>> accumulatorsLevels = new ArrayList<>(SKIP_INDEX_MAX_LEVEL); accumulatorsLevels.add(accumulators); for (int i = 0; i < SKIP_INDEX_MAX_LEVEL - 1; i++) { accumulatorsLevels.add(buildLevel(accumulatorsLevels.get(i))); } int totalAccumulators = accumulators.size(); for (int index = 0; index < totalAccumulators; index++) { // compute how many levels we need to write for the current accumulator final int levels = getLevels(index, totalAccumulators); // write the number of levels data.writeByte((byte) levels); // write intervals in reverse order. This is done so we don't // need to read all of them in case of slipping for (int level = levels - 1; level >= 0; level--) { final SkipAccumulator accumulator = accumulatorsLevels.get(level).get(index >> (SKIP_INDEX_LEVEL_SHIFT * level)); data.writeInt(accumulator.maxDocID); data.writeInt(accumulator.minDocID); data.writeLong(accumulator.maxValue); data.writeLong(accumulator.minValue); data.writeInt(accumulator.docCount); } } } private static List<SkipAccumulator> buildLevel(List<SkipAccumulator> accumulators) { final int levelSize = 1 << SKIP_INDEX_LEVEL_SHIFT; final List<SkipAccumulator> collector = new ArrayList<>(); for (int i = 0; i < accumulators.size() - levelSize + 1; i += levelSize) { collector.add(SkipAccumulator.merge(accumulators, i, levelSize)); } return collector; } private static int getLevels(int index, int size) { if (Integer.numberOfTrailingZeros(index) >= SKIP_INDEX_LEVEL_SHIFT) { // TODO: can we do it in constant time rather than linearly with SKIP_INDEX_MAX_LEVEL? final int left = size - index; for (int level = SKIP_INDEX_MAX_LEVEL - 1; level > 0; level--) { final int numberIntervals = 1 << (SKIP_INDEX_LEVEL_SHIFT * level); if (left >= numberIntervals && index % numberIntervals == 0) { return level + 1; } } } return 1; } private long[] writeValues(FieldInfo field, DocValuesProducer valuesProducer, boolean ords) throws IOException { SortedNumericDocValues values = valuesProducer.getSortedNumeric(field); final long firstValue; if (values.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) { firstValue = values.nextValue(); } else { firstValue = 0L; } values = valuesProducer.getSortedNumeric(field); int numDocsWithValue = 0; MinMaxTracker minMax = new MinMaxTracker(); MinMaxTracker blockMinMax = new MinMaxTracker(); long gcd = 0; LongHashSet uniqueValues = ords ? null : new LongHashSet(); for (int doc = values.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = values.nextDoc()) { for (int i = 0, count = values.docValueCount(); i < count; ++i) { long v = values.nextValue(); if (gcd != 1) { if (v < Long.MIN_VALUE / 2 || v > Long.MAX_VALUE / 2) { // in that case v - minValue might overflow and make the GCD computation return // wrong results. Since these extreme values are unlikely, we just discard // GCD computation for them gcd = 1; } else { gcd = MathUtil.gcd(gcd, v - firstValue); } } blockMinMax.update(v); if (blockMinMax.numValues == NUMERIC_BLOCK_SIZE) { minMax.update(blockMinMax); blockMinMax.nextBlock(); } if (uniqueValues != null && uniqueValues.add(v) && uniqueValues.size() > 256) { uniqueValues = null; } } numDocsWithValue++; } minMax.update(blockMinMax); minMax.finish(); blockMinMax.finish(); if (ords && minMax.numValues > 0) { if (minMax.min != 0) { throw new IllegalStateException( "The min value for ordinals should always be 0, got " + minMax.min); } if (minMax.max != 0 && gcd != 1) { throw new IllegalStateException( "GCD compression should never be used on ordinals, found gcd=" + gcd); } } final long numValues = minMax.numValues; long min = minMax.min; final long max = minMax.max; assert blockMinMax.spaceInBits <= minMax.spaceInBits; if (numDocsWithValue == 0) { // meta[-2, 0]: No documents with values meta.writeLong(-2); // docsWithFieldOffset meta.writeLong(0L); // docsWithFieldLength meta.writeShort((short) -1); // jumpTableEntryCount meta.writeByte((byte) -1); // denseRankPower } else if (numDocsWithValue == maxDoc) { // meta[-1, 0]: All documents has values meta.writeLong(-1); // docsWithFieldOffset meta.writeLong(0L); // docsWithFieldLength meta.writeShort((short) -1); // jumpTableEntryCount meta.writeByte((byte) -1); // denseRankPower } else { // meta[data.offset, data.length]: IndexedDISI structure for documents with values long offset = data.getFilePointer(); meta.writeLong(offset); // docsWithFieldOffset values = valuesProducer.getSortedNumeric(field); final short jumpTableEntryCount = IndexedDISI.writeBitSet(values, data, IndexedDISI.DEFAULT_DENSE_RANK_POWER); meta.writeLong(data.getFilePointer() - offset); // docsWithFieldLength meta.writeShort(jumpTableEntryCount); meta.writeByte(IndexedDISI.DEFAULT_DENSE_RANK_POWER); } meta.writeLong(numValues); final int numBitsPerValue; boolean doBlocks = false; LongIntHashMap encode = null; if (min >= max) { // meta[-1]: All values are 0 numBitsPerValue = 0; meta.writeInt(-1); // tablesize } else { if (uniqueValues != null && uniqueValues.size() > 1 && DirectWriter.unsignedBitsRequired(uniqueValues.size() - 1) < DirectWriter.unsignedBitsRequired((max - min) / gcd)) { numBitsPerValue = DirectWriter.unsignedBitsRequired(uniqueValues.size() - 1); final long[] sortedUniqueValues = uniqueValues.toArray(); Arrays.sort(sortedUniqueValues); meta.writeInt(sortedUniqueValues.length); // tablesize for (long v : sortedUniqueValues) { meta.writeLong(v); // table[] entry } encode = new LongIntHashMap(); for (int i = 0; i < sortedUniqueValues.length; ++i) { encode.put(sortedUniqueValues[i], i); } min = 0; gcd = 1; } else { uniqueValues = null; // we do blocks if that appears to save 10+% storage doBlocks = minMax.spaceInBits > 0 && (double) blockMinMax.spaceInBits / minMax.spaceInBits <= 0.9; if (doBlocks) { numBitsPerValue = 0xFF; meta.writeInt(-2 - NUMERIC_BLOCK_SHIFT); // tablesize } else { numBitsPerValue = DirectWriter.unsignedBitsRequired((max - min) / gcd); if (gcd == 1 && min > 0 && DirectWriter.unsignedBitsRequired(max) == DirectWriter.unsignedBitsRequired(max - min)) { min = 0; } meta.writeInt(-1); // tablesize } } } meta.writeByte((byte) numBitsPerValue); meta.writeLong(min); meta.writeLong(gcd); long startOffset = data.getFilePointer(); meta.writeLong(startOffset); // valueOffset long jumpTableOffset = -1; if (doBlocks) { jumpTableOffset = writeValuesMultipleBlocks(valuesProducer.getSortedNumeric(field), gcd); } else if (numBitsPerValue != 0) { writeValuesSingleBlock( valuesProducer.getSortedNumeric(field), numValues, numBitsPerValue, min, gcd, encode); } meta.writeLong(data.getFilePointer() - startOffset); // valuesLength meta.writeLong(jumpTableOffset); return new long[] {numDocsWithValue, numValues}; } private void writeValuesSingleBlock( SortedNumericDocValues values, long numValues, int numBitsPerValue, long min, long gcd, LongIntHashMap encode) throws IOException { DirectWriter writer = DirectWriter.getInstance(data, numValues, numBitsPerValue); for (int doc = values.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = values.nextDoc()) { for (int i = 0, count = values.docValueCount(); i < count; ++i) { long v = values.nextValue(); if (encode == null) { writer.add((v - min) / gcd); } else { writer.add(encode.get(v)); } } } writer.finish(); } // Returns the offset to the jump-table for vBPV private long writeValuesMultipleBlocks(SortedNumericDocValues values, long gcd) throws IOException { long[] offsets = new long[ArrayUtil.oversize(1, Long.BYTES)]; int offsetsIndex = 0; final long[] buffer = new long[NUMERIC_BLOCK_SIZE]; final ByteBuffersDataOutput encodeBuffer = ByteBuffersDataOutput.newResettableInstance(); int upTo = 0; for (int doc = values.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = values.nextDoc()) { for (int i = 0, count = values.docValueCount(); i < count; ++i) { buffer[upTo++] = values.nextValue(); if (upTo == NUMERIC_BLOCK_SIZE) { offsets = ArrayUtil.grow(offsets, offsetsIndex + 1); offsets[offsetsIndex++] = data.getFilePointer(); writeBlock(buffer, NUMERIC_BLOCK_SIZE, gcd, encodeBuffer); upTo = 0; } } } if (upTo > 0) { offsets = ArrayUtil.grow(offsets, offsetsIndex + 1); offsets[offsetsIndex++] = data.getFilePointer(); writeBlock(buffer, upTo, gcd, encodeBuffer); } // All blocks has been written. Flush the offset jump-table final long offsetsOrigo = data.getFilePointer(); for (int i = 0; i < offsetsIndex; i++) { data.writeLong(offsets[i]); } data.writeLong(offsetsOrigo); return offsetsOrigo; } private void writeBlock(long[] values, int length, long gcd, ByteBuffersDataOutput buffer) throws IOException { assert length > 0; long min = values[0]; long max = values[0]; for (int i = 1; i < length; ++i) { final long v = values[i]; assert Math.floorMod(values[i] - min, gcd) == 0; min = Math.min(min, v); max = Math.max(max, v); } if (min == max) { data.writeByte((byte) 0); data.writeLong(min); } else { final int bitsPerValue = DirectWriter.unsignedBitsRequired((max - min) / gcd); buffer.reset(); assert buffer.size() == 0; final DirectWriter w = DirectWriter.getInstance(buffer, length, bitsPerValue); for (int i = 0; i < length; ++i) { w.add((values[i] - min) / gcd); } w.finish(); data.writeByte((byte) bitsPerValue); data.writeLong(min); data.writeInt(Math.toIntExact(buffer.size())); buffer.copyTo(data); } } @Override public void addBinaryField(FieldInfo field, DocValuesProducer valuesProducer) throws IOException { meta.writeInt(field.number); meta.writeByte(Lucene90DocValuesFormat.BINARY); BinaryDocValues values = valuesProducer.getBinary(field); long start = data.getFilePointer(); meta.writeLong(start); // dataOffset int numDocsWithField = 0; int minLength = Integer.MAX_VALUE; int maxLength = 0; for (int doc = values.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = values.nextDoc()) { numDocsWithField++; BytesRef v = values.binaryValue(); int length = v.length; data.writeBytes(v.bytes, v.offset, v.length); minLength = Math.min(length, minLength); maxLength = Math.max(length, maxLength); } assert numDocsWithField <= maxDoc; meta.writeLong(data.getFilePointer() - start); // dataLength if (numDocsWithField == 0) { meta.writeLong(-2); // docsWithFieldOffset meta.writeLong(0L); // docsWithFieldLength meta.writeShort((short) -1); // jumpTableEntryCount meta.writeByte((byte) -1); // denseRankPower } else if (numDocsWithField == maxDoc) { meta.writeLong(-1); // docsWithFieldOffset meta.writeLong(0L); // docsWithFieldLength meta.writeShort((short) -1); // jumpTableEntryCount meta.writeByte((byte) -1); // denseRankPower } else { long offset = data.getFilePointer(); meta.writeLong(offset); // docsWithFieldOffset values = valuesProducer.getBinary(field); final short jumpTableEntryCount = IndexedDISI.writeBitSet(values, data, IndexedDISI.DEFAULT_DENSE_RANK_POWER); meta.writeLong(data.getFilePointer() - offset); // docsWithFieldLength meta.writeShort(jumpTableEntryCount); meta.writeByte(IndexedDISI.DEFAULT_DENSE_RANK_POWER); } meta.writeInt(numDocsWithField); meta.writeInt(minLength); meta.writeInt(maxLength); if (maxLength > minLength) { start = data.getFilePointer(); meta.writeLong(start); meta.writeVInt(DIRECT_MONOTONIC_BLOCK_SHIFT); final DirectMonotonicWriter writer = DirectMonotonicWriter.getInstance( meta, data, numDocsWithField + 1, DIRECT_MONOTONIC_BLOCK_SHIFT); long addr = 0; writer.add(addr); values = valuesProducer.getBinary(field); for (int doc = values.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = values.nextDoc()) { addr += values.binaryValue().length; writer.add(addr); } writer.finish(); meta.writeLong(data.getFilePointer() - start); } } @Override public void addSortedField(FieldInfo field, DocValuesProducer valuesProducer) throws IOException { meta.writeInt(field.number); meta.writeByte(Lucene90DocValuesFormat.SORTED); doAddSortedField(field, valuesProducer, false); } private void doAddSortedField( FieldInfo field, DocValuesProducer valuesProducer, boolean addTypeByte) throws IOException { DocValuesProducer producer = new EmptyDocValuesProducer() { @Override public SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException { SortedDocValues sorted = valuesProducer.getSorted(field); NumericDocValues sortedOrds = new NumericDocValues() { @Override public long longValue() throws IOException { return sorted.ordValue(); } @Override public boolean advanceExact(int target) throws IOException { return sorted.advanceExact(target); } @Override public int docID() { return sorted.docID(); } @Override public int nextDoc() throws IOException { return sorted.nextDoc(); } @Override public int advance(int target) throws IOException { return sorted.advance(target); } @Override public long cost() { return sorted.cost(); } }; return DocValues.singleton(sortedOrds); } }; if (field.docValuesSkipIndexType() != DocValuesSkipIndexType.NONE) { writeSkipIndex(field, producer); } if (addTypeByte) { meta.writeByte((byte) 0); // multiValued (0 = singleValued) } writeValues(field, producer, true); addTermsDict(DocValues.singleton(valuesProducer.getSorted(field))); } private void addTermsDict(SortedSetDocValues values) throws IOException { final long size = values.getValueCount(); meta.writeVLong(size); int blockMask = Lucene90DocValuesFormat.TERMS_DICT_BLOCK_LZ4_MASK; int shift = Lucene90DocValuesFormat.TERMS_DICT_BLOCK_LZ4_SHIFT; meta.writeInt(DIRECT_MONOTONIC_BLOCK_SHIFT); ByteBuffersDataOutput addressBuffer = new ByteBuffersDataOutput(); ByteBuffersIndexOutput addressOutput = new ByteBuffersIndexOutput(addressBuffer, "temp", "temp"); long numBlocks = (size + blockMask) >>> shift; DirectMonotonicWriter writer = DirectMonotonicWriter.getInstance( meta, addressOutput, numBlocks, DIRECT_MONOTONIC_BLOCK_SHIFT); BytesRefBuilder previous = new BytesRefBuilder(); long ord = 0; long start = data.getFilePointer(); int maxLength = 0, maxBlockLength = 0; TermsEnum iterator = values.termsEnum(); LZ4.FastCompressionHashTable ht = new LZ4.FastCompressionHashTable(); ByteArrayDataOutput bufferedOutput = new ByteArrayDataOutput(termsDictBuffer); int dictLength = 0; for (BytesRef term = iterator.next(); term != null; term = iterator.next()) { if ((ord & blockMask) == 0) { if (ord != 0) { // flush the previous block final int uncompressedLength = compressAndGetTermsDictBlockLength(bufferedOutput, dictLength, ht); maxBlockLength = Math.max(maxBlockLength, uncompressedLength); bufferedOutput.reset(termsDictBuffer); } writer.add(data.getFilePointer() - start); // Write the first term both to the index output, and to the buffer where we'll use it as a // dictionary for compression data.writeVInt(term.length); data.writeBytes(term.bytes, term.offset, term.length); bufferedOutput = maybeGrowBuffer(bufferedOutput, term.length); bufferedOutput.writeBytes(term.bytes, term.offset, term.length); dictLength = term.length; } else { final int prefixLength = StringHelper.bytesDifference(previous.get(), term); final int suffixLength = term.length - prefixLength; assert suffixLength > 0; // terms are unique // Will write (suffixLength + 1 byte + 2 vint) bytes. Grow the buffer in need. bufferedOutput = maybeGrowBuffer(bufferedOutput, suffixLength + 11); bufferedOutput.writeByte( (byte) (Math.min(prefixLength, 15) | (Math.min(15, suffixLength - 1) << 4))); if (prefixLength >= 15) { bufferedOutput.writeVInt(prefixLength - 15); } if (suffixLength >= 16) { bufferedOutput.writeVInt(suffixLength - 16); } bufferedOutput.writeBytes(term.bytes, term.offset + prefixLength, suffixLength); } maxLength = Math.max(maxLength, term.length); previous.copyBytes(term); ++ord; } // Compress and write out the last block if (bufferedOutput.getPosition() > dictLength) { final int uncompressedLength = compressAndGetTermsDictBlockLength(bufferedOutput, dictLength, ht); maxBlockLength = Math.max(maxBlockLength, uncompressedLength); } writer.finish(); meta.writeInt(maxLength); // Write one more int for storing max block length. meta.writeInt(maxBlockLength); meta.writeLong(start); meta.writeLong(data.getFilePointer() - start); start = data.getFilePointer(); addressBuffer.copyTo(data); meta.writeLong(start); meta.writeLong(data.getFilePointer() - start); // Now write the reverse terms index writeTermsIndex(values); } private int compressAndGetTermsDictBlockLength( ByteArrayDataOutput bufferedOutput, int dictLength, LZ4.FastCompressionHashTable ht) throws IOException { int uncompressedLength = bufferedOutput.getPosition() - dictLength; data.writeVInt(uncompressedLength); LZ4.compressWithDictionary(termsDictBuffer, 0, dictLength, uncompressedLength, data, ht); return uncompressedLength; } private ByteArrayDataOutput maybeGrowBuffer(ByteArrayDataOutput bufferedOutput, int termLength) { int pos = bufferedOutput.getPosition(), originalLength = termsDictBuffer.length; if (pos + termLength >= originalLength - 1) { termsDictBuffer = ArrayUtil.grow(termsDictBuffer, originalLength + termLength); bufferedOutput = new ByteArrayDataOutput(termsDictBuffer, pos, termsDictBuffer.length - pos); } return bufferedOutput; } private void writeTermsIndex(SortedSetDocValues values) throws IOException { final long size = values.getValueCount(); meta.writeInt(Lucene90DocValuesFormat.TERMS_DICT_REVERSE_INDEX_SHIFT); long start = data.getFilePointer(); long numBlocks = 1L + ((size + Lucene90DocValuesFormat.TERMS_DICT_REVERSE_INDEX_MASK) >>> Lucene90DocValuesFormat.TERMS_DICT_REVERSE_INDEX_SHIFT); ByteBuffersDataOutput addressBuffer = new ByteBuffersDataOutput(); DirectMonotonicWriter writer; try (ByteBuffersIndexOutput addressOutput = new ByteBuffersIndexOutput(addressBuffer, "temp", "temp")) { writer = DirectMonotonicWriter.getInstance( meta, addressOutput, numBlocks, DIRECT_MONOTONIC_BLOCK_SHIFT); TermsEnum iterator = values.termsEnum(); BytesRefBuilder previous = new BytesRefBuilder(); long offset = 0; long ord = 0; for (BytesRef term = iterator.next(); term != null; term = iterator.next()) { if ((ord & Lucene90DocValuesFormat.TERMS_DICT_REVERSE_INDEX_MASK) == 0) { writer.add(offset); final int sortKeyLength; if (ord == 0) { // no previous term: no bytes to write sortKeyLength = 0; } else { sortKeyLength = StringHelper.sortKeyLength(previous.get(), term); } offset += sortKeyLength; data.writeBytes(term.bytes, term.offset, sortKeyLength); } else if ((ord & Lucene90DocValuesFormat.TERMS_DICT_REVERSE_INDEX_MASK) == Lucene90DocValuesFormat.TERMS_DICT_REVERSE_INDEX_MASK) { previous.copyBytes(term); } ++ord; } writer.add(offset); writer.finish(); meta.writeLong(start); meta.writeLong(data.getFilePointer() - start); start = data.getFilePointer(); addressBuffer.copyTo(data); meta.writeLong(start); meta.writeLong(data.getFilePointer() - start); } } @Override public void addSortedNumericField(FieldInfo field, DocValuesProducer valuesProducer) throws IOException { meta.writeInt(field.number); meta.writeByte(Lucene90DocValuesFormat.SORTED_NUMERIC); doAddSortedNumericField(field, valuesProducer, false); } private void doAddSortedNumericField( FieldInfo field, DocValuesProducer valuesProducer, boolean ords) throws IOException { if (field.docValuesSkipIndexType() != DocValuesSkipIndexType.NONE) { writeSkipIndex(field, valuesProducer); } if (ords) { meta.writeByte((byte) 1); // multiValued (1 = multiValued) } long[] stats = writeValues(field, valuesProducer, ords); int numDocsWithField = Math.toIntExact(stats[0]); long numValues = stats[1]; assert numValues >= numDocsWithField; meta.writeInt(numDocsWithField); if (numValues > numDocsWithField) { long start = data.getFilePointer(); meta.writeLong(start); meta.writeVInt(DIRECT_MONOTONIC_BLOCK_SHIFT); final DirectMonotonicWriter addressesWriter = DirectMonotonicWriter.getInstance( meta, data, numDocsWithField + 1L, DIRECT_MONOTONIC_BLOCK_SHIFT); long addr = 0; addressesWriter.add(addr); SortedNumericDocValues values = valuesProducer.getSortedNumeric(field); for (int doc = values.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = values.nextDoc()) { addr += values.docValueCount(); addressesWriter.add(addr); } addressesWriter.finish(); meta.writeLong(data.getFilePointer() - start); } } private static boolean isSingleValued(SortedSetDocValues values) throws IOException { if (DocValues.unwrapSingleton(values) != null) { return true; } assert values.docID() == -1; for (int doc = values.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = values.nextDoc()) { int docValueCount = values.docValueCount(); assert docValueCount > 0; if (docValueCount > 1) { return false; } } return true; } @Override public void addSortedSetField(FieldInfo field, DocValuesProducer valuesProducer) throws IOException { meta.writeInt(field.number); meta.writeByte(Lucene90DocValuesFormat.SORTED_SET); if (isSingleValued(valuesProducer.getSortedSet(field))) { doAddSortedField( field, new EmptyDocValuesProducer() { @Override public SortedDocValues getSorted(FieldInfo field) throws IOException { return SortedSetSelector.wrap( valuesProducer.getSortedSet(field), SortedSetSelector.Type.MIN); } }, true); return; } doAddSortedNumericField( field, new EmptyDocValuesProducer() { @Override public SortedNumericDocValues getSortedNumeric(FieldInfo field) throws IOException { SortedSetDocValues values = valuesProducer.getSortedSet(field); return new SortedNumericDocValues() { long[] ords = LongsRef.EMPTY_LONGS; int i, docValueCount; @Override public long nextValue() throws IOException { return ords[i++]; } @Override public int docValueCount() { return docValueCount; } @Override public boolean advanceExact(int target) throws IOException { throw new UnsupportedOperationException(); } @Override public int docID() { return values.docID(); } @Override public int nextDoc() throws IOException { int doc = values.nextDoc(); if (doc != NO_MORE_DOCS) { docValueCount = values.docValueCount(); ords = ArrayUtil.grow(ords, docValueCount); for (int j = 0; j < docValueCount; j++) { ords[j] = values.nextOrd(); } i = 0; } return doc; } @Override public int advance(int target) throws IOException { throw new UnsupportedOperationException(); } @Override public long cost() { return values.cost(); } }; } }, true); addTermsDict(valuesProducer.getSortedSet(field)); } }
apache/fluss
37,609
fluss-common/src/main/java/org/apache/fluss/row/BinaryString.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.row; import org.apache.fluss.annotation.PublicStable; import org.apache.fluss.memory.MemorySegment; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.nio.charset.StandardCharsets; import java.util.Arrays; import static org.apache.fluss.row.BinarySegmentUtils.allocateReuseBytes; import static org.apache.fluss.row.BinarySegmentUtils.allocateReuseChars; import static org.apache.fluss.utils.Preconditions.checkArgument; /* This file is based on source code of Apache Flink Project (https://flink.apache.org/), licensed by the Apache * Software Foundation (ASF) under the Apache License, Version 2.0. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ /** * A string which is backed by {@link MemorySegment}s. * * @since 0.1 */ @PublicStable public final class BinaryString extends BinarySection implements Comparable<BinaryString>, MemoryAwareGetters { private static final long serialVersionUID = 1L; public static final BinaryString EMPTY_UTF8 = BinaryString.fromBytes(encodeUTF8("")); BinaryString(MemorySegment[] segments, int offset, int sizeInBytes) { super(segments, offset, sizeInBytes); this.segments = segments; this.offset = offset; this.sizeInBytes = sizeInBytes; } // ------------------------------------------------------------------------------------------ // Construction Utilities // ------------------------------------------------------------------------------------------ public static BinaryString fromAddress(MemorySegment[] segments, int offset, int numBytes) { return new BinaryString(segments, offset, numBytes); } @Nullable public static BinaryString fromString(String str) { if (str == null) { return null; } return fromBytes(encodeUTF8(str)); } /** Creates a {@link BinaryString} instance from the given UTF-8 bytes. */ public static BinaryString fromBytes(byte[] bytes) { return fromBytes(bytes, 0, bytes.length); } /** * Creates a {@link BinaryString} instance from the given UTF-8 bytes with offset and number of * bytes. */ public static BinaryString fromBytes(byte[] bytes, int offset, int numBytes) { return new BinaryString(new MemorySegment[] {MemorySegment.wrap(bytes)}, offset, numBytes); } /** Creates a {@link BinaryString} instance that contains `length` spaces. */ public static BinaryString blankString(int length) { byte[] spaces = new byte[length]; Arrays.fill(spaces, (byte) ' '); return fromBytes(spaces); } // ------------------------------------------------------------------------------------------ // Public Interfaces // ------------------------------------------------------------------------------------------ @Override public String toString() { byte[] bytes = allocateReuseBytes(sizeInBytes); BinarySegmentUtils.copyToBytes(segments, offset, bytes, 0, sizeInBytes); return decodeUTF8(bytes, 0, sizeInBytes); } /** * Compares two strings lexicographically. Since UTF-8 uses groups of six bits, it is sometimes * useful to use octal notation which uses 3-bit groups. With a calculator which can convert * between hexadecimal and octal it can be easier to manually create or interpret UTF-8 compared * with using binary. So we just compare the binary. */ @Override public int compareTo(@Nonnull BinaryString other) { if (segments.length == 1 && other.segments.length == 1) { int len = Math.min(sizeInBytes, other.sizeInBytes); MemorySegment seg1 = segments[0]; MemorySegment seg2 = other.segments[0]; for (int i = 0; i < len; i++) { int res = (seg1.get(offset + i) & 0xFF) - (seg2.get(other.offset + i) & 0xFF); if (res != 0) { return res; } } return sizeInBytes - other.sizeInBytes; } // if there are multi segments. return compareMultiSegments(other); } /** Find the boundaries of segments, and then compare MemorySegment. */ private int compareMultiSegments(BinaryString other) { if (sizeInBytes == 0 || other.sizeInBytes == 0) { return sizeInBytes - other.sizeInBytes; } int len = Math.min(sizeInBytes, other.sizeInBytes); MemorySegment seg1 = segments[0]; MemorySegment seg2 = other.segments[0]; int segmentSize = segments[0].size(); int otherSegmentSize = other.segments[0].size(); int sizeOfFirst1 = segmentSize - offset; int sizeOfFirst2 = otherSegmentSize - other.offset; int varSegIndex1 = 1; int varSegIndex2 = 1; // find the first segment of this string. while (sizeOfFirst1 <= 0) { sizeOfFirst1 += segmentSize; seg1 = segments[varSegIndex1++]; } while (sizeOfFirst2 <= 0) { sizeOfFirst2 += otherSegmentSize; seg2 = other.segments[varSegIndex2++]; } int offset1 = segmentSize - sizeOfFirst1; int offset2 = otherSegmentSize - sizeOfFirst2; int needCompare = Math.min(Math.min(sizeOfFirst1, sizeOfFirst2), len); while (needCompare > 0) { // compare in one segment. for (int i = 0; i < needCompare; i++) { int res = (seg1.get(offset1 + i) & 0xFF) - (seg2.get(offset2 + i) & 0xFF); if (res != 0) { return res; } } if (needCompare == len) { break; } len -= needCompare; // next segment if (sizeOfFirst1 < sizeOfFirst2) { // I am smaller seg1 = segments[varSegIndex1++]; offset1 = 0; offset2 += needCompare; sizeOfFirst1 = segmentSize; sizeOfFirst2 -= needCompare; } else if (sizeOfFirst1 > sizeOfFirst2) { // other is smaller seg2 = other.segments[varSegIndex2++]; offset2 = 0; offset1 += needCompare; sizeOfFirst2 = otherSegmentSize; sizeOfFirst1 -= needCompare; } else { // same, should go ahead both. seg1 = segments[varSegIndex1++]; seg2 = other.segments[varSegIndex2++]; offset1 = 0; offset2 = 0; sizeOfFirst1 = segmentSize; sizeOfFirst2 = otherSegmentSize; } needCompare = Math.min(Math.min(sizeOfFirst1, sizeOfFirst2), len); } checkArgument(needCompare == len); return sizeInBytes - other.sizeInBytes; } // ------------------------------------------------------------------------------------------ // Public methods on BinaryString // ------------------------------------------------------------------------------------------ /** Returns the number of UTF-8 code points in the string. */ public int numChars() { if (inFirstSegment()) { int len = 0; for (int i = 0; i < sizeInBytes; i += numBytesForFirstByte(getByteOneSegment(i))) { len++; } return len; } else { return numCharsMultiSegs(); } } private int numCharsMultiSegs() { int len = 0; int segSize = segments[0].size(); BinaryString.SegmentAndOffset index = firstSegmentAndOffset(segSize); int i = 0; while (i < sizeInBytes) { int charBytes = numBytesForFirstByte(index.value()); i += charBytes; len++; index.skipBytes(charBytes, segSize); } return len; } /** * Returns the {@code byte} value at the specified index. An index ranges from {@code 0} to * {@code sizeInBytes - 1}. * * @param index the index of the {@code byte} value. * @return the {@code byte} value at the specified index of this UTF-8 bytes. * @exception IndexOutOfBoundsException if the {@code index} argument is negative or not less * than the length of this UTF-8 bytes. */ public byte byteAt(int index) { int globalOffset = offset + index; int size = segments[0].size(); if (globalOffset < size) { return segments[0].get(globalOffset); } else { return segments[globalOffset / size].get(globalOffset % size); } } /** Copy a new {@code BinaryString}. */ public BinaryString copy() { byte[] copy = BinarySegmentUtils.copyToBytes(segments, offset, sizeInBytes); return BinaryString.fromBytes(copy); } /** * Returns a binary string that is a substring of this binary string. The substring begins at * the specified {@code beginIndex} and extends to the character at index {@code endIndex - 1}. * * <p>Examples: * * <blockquote> * * <pre> * fromString("hamburger").substring(4, 8) returns binary string "urge" * fromString("smiles").substring(1, 5) returns binary string "mile" * </pre> * * </blockquote> * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring, return EMPTY_UTF8 when index out of bounds instead of * StringIndexOutOfBoundsException. */ public BinaryString substring(int beginIndex, int endIndex) { if (endIndex <= beginIndex || beginIndex >= sizeInBytes) { return EMPTY_UTF8; } if (inFirstSegment()) { MemorySegment segment = segments[0]; int i = 0; int c = 0; while (i < sizeInBytes && c < beginIndex) { i += numBytesForFirstByte(segment.get(i + offset)); c += 1; } int j = i; while (i < sizeInBytes && c < endIndex) { i += numBytesForFirstByte(segment.get(i + offset)); c += 1; } if (i > j) { byte[] bytes = new byte[i - j]; segment.get(offset + j, bytes, 0, i - j); return fromBytes(bytes); } else { return EMPTY_UTF8; } } else { return substringMultiSegs(beginIndex, endIndex); } } private BinaryString substringMultiSegs(final int start, final int until) { int segSize = segments[0].size(); BinaryString.SegmentAndOffset index = firstSegmentAndOffset(segSize); int i = 0; int c = 0; while (i < sizeInBytes && c < start) { int charSize = numBytesForFirstByte(index.value()); i += charSize; index.skipBytes(charSize, segSize); c += 1; } int j = i; while (i < sizeInBytes && c < until) { int charSize = numBytesForFirstByte(index.value()); i += charSize; index.skipBytes(charSize, segSize); c += 1; } if (i > j) { return fromBytes(BinarySegmentUtils.copyToBytes(segments, offset + j, i - j)); } else { return EMPTY_UTF8; } } /** * Returns true if and only if this BinaryString contains the specified sequence of bytes * values. * * @param s the sequence to search for * @return true if this BinaryString contains {@code s}, false otherwise */ public boolean contains(final BinaryString s) { if (s.sizeInBytes == 0) { return true; } int find = BinarySegmentUtils.find( segments, offset, sizeInBytes, s.segments, s.offset, s.sizeInBytes); return find != -1; } /** * Tests if this BinaryString starts with the specified prefix. * * @param prefix the prefix. * @return {@code true} if the bytes represented by the argument is a prefix of the bytes * represented by this string; {@code false} otherwise. Note also that {@code true} will be * returned if the argument is an empty BinaryString or is equal to this {@code * BinaryString} object as determined by the {@link #equals(Object)} method. */ public boolean startsWith(final BinaryString prefix) { return matchAt(prefix, 0); } /** * Tests if this BinaryString ends with the specified suffix. * * @param suffix the suffix. * @return {@code true} if the bytes represented by the argument is a suffix of the bytes * represented by this object; {@code false} otherwise. Note that the result will be {@code * true} if the argument is the empty string or is equal to this {@code BinaryString} object * as determined by the {@link #equals(Object)} method. */ public boolean endsWith(final BinaryString suffix) { return matchAt(suffix, sizeInBytes - suffix.sizeInBytes); } /** * Returns a string whose value is this string, with any leading and trailing whitespace * removed. * * @return A string whose value is this string, with any leading and trailing white space * removed, or this string if it has no leading or trailing white space. */ public BinaryString trim() { if (inFirstSegment()) { int s = 0; int e = this.sizeInBytes - 1; // skip all the space (0x20) on the left side while (s < this.sizeInBytes && getByteOneSegment(s) == 0x20) { s++; } // skip all the space (0x20) on the right side while (e >= s && getByteOneSegment(e) == 0x20) { e--; } if (s > e) { // empty string return EMPTY_UTF8; } else { return copyBinaryStringInOneSeg(s, e - s + 1); } } else { return trimMultiSegs(); } } private BinaryString trimMultiSegs() { int s = 0; int e = this.sizeInBytes - 1; int segSize = segments[0].size(); BinaryString.SegmentAndOffset front = firstSegmentAndOffset(segSize); // skip all the space (0x20) on the left side while (s < this.sizeInBytes && front.value() == 0x20) { s++; front.nextByte(segSize); } BinaryString.SegmentAndOffset behind = lastSegmentAndOffset(segSize); // skip all the space (0x20) on the right side while (e >= s && behind.value() == 0x20) { e--; behind.previousByte(segSize); } if (s > e) { // empty string return EMPTY_UTF8; } else { return copyBinaryString(s, e); } } /** * Returns the index within this string of the first occurrence of the specified substring, * starting at the specified index. * * @param str the substring to search for. * @param fromIndex the index from which to start the search. * @return the index of the first occurrence of the specified substring, starting at the * specified index, or {@code -1} if there is no such occurrence. */ public int indexOf(BinaryString str, int fromIndex) { if (str.sizeInBytes == 0) { return 0; } if (inFirstSegment()) { // position in byte int byteIdx = 0; // position is char int charIdx = 0; while (byteIdx < sizeInBytes && charIdx < fromIndex) { byteIdx += numBytesForFirstByte(getByteOneSegment(byteIdx)); charIdx++; } do { if (byteIdx + str.sizeInBytes > sizeInBytes) { return -1; } if (BinarySegmentUtils.equals( segments, offset + byteIdx, str.segments, str.offset, str.sizeInBytes)) { return charIdx; } byteIdx += numBytesForFirstByte(getByteOneSegment(byteIdx)); charIdx++; } while (byteIdx < sizeInBytes); return -1; } else { return indexOfMultiSegs(str, fromIndex); } } private int indexOfMultiSegs(BinaryString str, int fromIndex) { // position in byte int byteIdx = 0; // position is char int charIdx = 0; int segSize = segments[0].size(); BinaryString.SegmentAndOffset index = firstSegmentAndOffset(segSize); while (byteIdx < sizeInBytes && charIdx < fromIndex) { int charBytes = numBytesForFirstByte(index.value()); byteIdx += charBytes; charIdx++; index.skipBytes(charBytes, segSize); } do { if (byteIdx + str.sizeInBytes > sizeInBytes) { return -1; } if (BinarySegmentUtils.equals( segments, offset + byteIdx, str.segments, str.offset, str.sizeInBytes)) { return charIdx; } int charBytes = numBytesForFirstByte(index.segment.get(index.offset)); byteIdx += charBytes; charIdx++; index.skipBytes(charBytes, segSize); } while (byteIdx < sizeInBytes); return -1; } /** * Converts all of the characters in this {@code BinaryString} to upper case. * * @return the {@code BinaryString}, converted to uppercase. */ public BinaryString toUpperCase() { if (sizeInBytes == 0) { return EMPTY_UTF8; } int size = segments[0].size(); BinaryString.SegmentAndOffset segmentAndOffset = startSegmentAndOffset(size); byte[] bytes = new byte[sizeInBytes]; bytes[0] = (byte) Character.toTitleCase(segmentAndOffset.value()); for (int i = 0; i < sizeInBytes; i++) { byte b = segmentAndOffset.value(); if (numBytesForFirstByte(b) != 1) { // fallback return javaToUpperCase(); } int upper = Character.toUpperCase(b); if (upper > 127) { // fallback return javaToUpperCase(); } bytes[i] = (byte) upper; segmentAndOffset.nextByte(size); } return fromBytes(bytes); } private BinaryString javaToUpperCase() { return fromString(toString().toUpperCase()); } /** * Converts all of the characters in this {@code BinaryString} to lower case. * * @return the {@code BinaryString}, converted to lowercase. */ public BinaryString toLowerCase() { if (sizeInBytes == 0) { return EMPTY_UTF8; } int size = segments[0].size(); BinaryString.SegmentAndOffset segmentAndOffset = startSegmentAndOffset(size); byte[] bytes = new byte[sizeInBytes]; bytes[0] = (byte) Character.toTitleCase(segmentAndOffset.value()); for (int i = 0; i < sizeInBytes; i++) { byte b = segmentAndOffset.value(); if (numBytesForFirstByte(b) != 1) { // fallback return javaToLowerCase(); } int lower = Character.toLowerCase(b); if (lower > 127) { // fallback return javaToLowerCase(); } bytes[i] = (byte) lower; segmentAndOffset.nextByte(size); } return fromBytes(bytes); } private BinaryString javaToLowerCase() { return fromString(toString().toLowerCase()); } // ------------------------------------------------------------------------------------------ // Internal methods on BinaryString // ------------------------------------------------------------------------------------------ byte getByteOneSegment(int i) { return segments[0].get(offset + i); } boolean inFirstSegment() { return sizeInBytes + offset <= segments[0].size(); } private boolean matchAt(final BinaryString s, int pos) { return (inFirstSegment() && s.inFirstSegment()) ? matchAtOneSeg(s, pos) : matchAtVarSeg(s, pos); } private boolean matchAtOneSeg(final BinaryString s, int pos) { return s.sizeInBytes + pos <= sizeInBytes && pos >= 0 && segments[0].equalTo(s.segments[0], offset + pos, s.offset, s.sizeInBytes); } private boolean matchAtVarSeg(final BinaryString s, int pos) { return s.sizeInBytes + pos <= sizeInBytes && pos >= 0 && BinarySegmentUtils.equals( segments, offset + pos, s.segments, s.offset, s.sizeInBytes); } BinaryString copyBinaryStringInOneSeg(int start, int len) { byte[] newBytes = new byte[len]; segments[0].get(offset + start, newBytes, 0, len); return fromBytes(newBytes); } BinaryString copyBinaryString(int start, int end) { int len = end - start + 1; byte[] newBytes = new byte[len]; BinarySegmentUtils.copyToBytes(segments, offset + start, newBytes, 0, len); return fromBytes(newBytes); } BinaryString.SegmentAndOffset firstSegmentAndOffset(int segSize) { int segIndex = offset / segSize; return new BinaryString.SegmentAndOffset(segIndex, offset % segSize); } BinaryString.SegmentAndOffset lastSegmentAndOffset(int segSize) { int lastOffset = offset + sizeInBytes - 1; int segIndex = lastOffset / segSize; return new BinaryString.SegmentAndOffset(segIndex, lastOffset % segSize); } private BinaryString.SegmentAndOffset startSegmentAndOffset(int segSize) { return inFirstSegment() ? new BinaryString.SegmentAndOffset(0, offset) : firstSegmentAndOffset(segSize); } /** CurrentSegment and positionInSegment. */ class SegmentAndOffset { int segIndex; MemorySegment segment; int offset; private SegmentAndOffset(int segIndex, int offset) { this.segIndex = segIndex; this.segment = segments[segIndex]; this.offset = offset; } private void assignSegment() { segment = segIndex >= 0 && segIndex < segments.length ? segments[segIndex] : null; } void previousByte(int segSize) { offset--; if (offset == -1) { segIndex--; assignSegment(); offset = segSize - 1; } } void nextByte(int segSize) { offset++; checkAdvance(segSize); } private void checkAdvance(int segSize) { if (offset == segSize) { advance(); } } private void advance() { segIndex++; assignSegment(); offset = 0; } void skipBytes(int n, int segSize) { int remaining = segSize - this.offset; if (remaining > n) { this.offset += n; } else { while (true) { int toSkip = Math.min(remaining, n); n -= toSkip; if (n <= 0) { this.offset += toSkip; checkAdvance(segSize); return; } advance(); remaining = segSize - this.offset; } } } byte value() { return this.segment.get(this.offset); } } /** * Returns the number of bytes for a code point with the first byte as `b`. * * @param b The first byte of a code point */ static int numBytesForFirstByte(final byte b) { if (b >= 0) { // 1 byte, 7 bits: 0xxxxxxx return 1; } else if ((b >> 5) == -2 && (b & 0x1e) != 0) { // 2 bytes, 11 bits: 110xxxxx 10xxxxxx return 2; } else if ((b >> 4) == -2) { // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx return 3; } else if ((b >> 3) == -2) { // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx return 4; } else { // Skip the first byte disallowed in UTF-8 // Handling errors quietly, same semantics to java String. return 1; } } // ------------------------------------------------------------------------ // UTF-8 encoding and decoding (High-speed version, 30% faster+) // ------------------------------------------------------------------------ private static final int MAX_BYTES_PER_CHAR = 3; /** This method must have the same result with JDK's String.getBytes. */ public static byte[] encodeUTF8(String str) { byte[] bytes = allocateReuseBytes(str.length() * MAX_BYTES_PER_CHAR); int len = encodeUTF8(str, bytes); return Arrays.copyOf(bytes, len); } public static int encodeUTF8(String str, byte[] bytes) { int offset = 0; int len = str.length(); int sl = offset + len; int dp = 0; int dlASCII = dp + Math.min(len, bytes.length); // ASCII only optimized loop while (dp < dlASCII && str.charAt(offset) < '\u0080') { bytes[dp++] = (byte) str.charAt(offset++); } while (offset < sl) { char c = str.charAt(offset++); if (c < 0x80) { // Have at most seven bits bytes[dp++] = (byte) c; } else if (c < 0x800) { // 2 bytes, 11 bits bytes[dp++] = (byte) (0xc0 | (c >> 6)); bytes[dp++] = (byte) (0x80 | (c & 0x3f)); } else if (Character.isSurrogate(c)) { final int uc; int ip = offset - 1; if (Character.isHighSurrogate(c)) { if (sl - ip < 2) { uc = -1; } else { char d = str.charAt(ip + 1); if (Character.isLowSurrogate(d)) { uc = Character.toCodePoint(c, d); } else { // for some illegal character // the jdk will ignore the origin character and cast it to '?' // this acts the same with jdk return defaultEncodeUTF8(str, bytes); } } } else { if (Character.isLowSurrogate(c)) { // for some illegal character // the jdk will ignore the origin character and cast it to '?' // this acts the same with jdk return defaultEncodeUTF8(str, bytes); } else { uc = c; } } if (uc < 0) { bytes[dp++] = (byte) '?'; } else { bytes[dp++] = (byte) (0xf0 | ((uc >> 18))); bytes[dp++] = (byte) (0x80 | ((uc >> 12) & 0x3f)); bytes[dp++] = (byte) (0x80 | ((uc >> 6) & 0x3f)); bytes[dp++] = (byte) (0x80 | (uc & 0x3f)); offset++; // 2 chars } } else { // 3 bytes, 16 bits bytes[dp++] = (byte) (0xe0 | ((c >> 12))); bytes[dp++] = (byte) (0x80 | ((c >> 6) & 0x3f)); bytes[dp++] = (byte) (0x80 | (c & 0x3f)); } } return dp; } public static int defaultEncodeUTF8(String str, byte[] bytes) { byte[] buffer = str.getBytes(StandardCharsets.UTF_8); System.arraycopy(buffer, 0, bytes, 0, buffer.length); return buffer.length; } public static String decodeUTF8(byte[] input, int offset, int byteLen) { char[] chars = allocateReuseChars(byteLen); int len = decodeUTF8Strict(input, offset, byteLen, chars); if (len < 0) { return defaultDecodeUTF8(input, offset, byteLen); } return new String(chars, 0, len); } public static int decodeUTF8Strict(byte[] sa, int sp, int len, char[] da) { final int sl = sp + len; int dp = 0; int dlASCII = Math.min(len, da.length); // ASCII only optimized loop while (dp < dlASCII && sa[sp] >= 0) { da[dp++] = (char) sa[sp++]; } while (sp < sl) { int b1 = sa[sp++]; if (b1 >= 0) { // 1 byte, 7 bits: 0xxxxxxx da[dp++] = (char) b1; } else if ((b1 >> 5) == -2 && (b1 & 0x1e) != 0) { // 2 bytes, 11 bits: 110xxxxx 10xxxxxx if (sp < sl) { int b2 = sa[sp++]; if ((b2 & 0xc0) != 0x80) { // isNotContinuation(b2) return -1; } else { da[dp++] = (char) (((b1 << 6) ^ b2) ^ (((byte) 0xC0 << 6) ^ ((byte) 0x80))); } continue; } return -1; } else if ((b1 >> 4) == -2) { // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx if (sp + 1 < sl) { int b2 = sa[sp++]; int b3 = sa[sp++]; if ((b1 == (byte) 0xe0 && (b2 & 0xe0) == 0x80) || (b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80) { // isMalformed3(b1, b2, b3) return -1; } else { char c = (char) ((b1 << 12) ^ (b2 << 6) ^ (b3 ^ (((byte) 0xE0 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80)))); if (Character.isSurrogate(c)) { return -1; } else { da[dp++] = c; } } continue; } return -1; } else if ((b1 >> 3) == -2) { // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx if (sp + 2 < sl) { int b2 = sa[sp++]; int b3 = sa[sp++]; int b4 = sa[sp++]; int uc = ((b1 << 18) ^ (b2 << 12) ^ (b3 << 6) ^ (b4 ^ (((byte) 0xF0 << 18) ^ ((byte) 0x80 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80)))); // isMalformed4 and shortest form check if (((b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80 || (b4 & 0xc0) != 0x80) || !Character.isSupplementaryCodePoint(uc)) { return -1; } else { da[dp++] = Character.highSurrogate(uc); da[dp++] = Character.lowSurrogate(uc); } continue; } return -1; } else { return -1; } } return dp; } public static String decodeUTF8(MemorySegment input, int offset, int byteLen) { char[] chars = allocateReuseChars(byteLen); int len = decodeUTF8Strict(input, offset, byteLen, chars); if (len < 0) { byte[] bytes = allocateReuseBytes(byteLen); input.get(offset, bytes, 0, byteLen); return defaultDecodeUTF8(bytes, 0, byteLen); } return new String(chars, 0, len); } public static int decodeUTF8Strict(MemorySegment segment, int sp, int len, char[] da) { final int sl = sp + len; int dp = 0; int dlASCII = Math.min(len, da.length); // ASCII only optimized loop while (dp < dlASCII && segment.get(sp) >= 0) { da[dp++] = (char) segment.get(sp++); } while (sp < sl) { int b1 = segment.get(sp++); if (b1 >= 0) { // 1 byte, 7 bits: 0xxxxxxx da[dp++] = (char) b1; } else if ((b1 >> 5) == -2 && (b1 & 0x1e) != 0) { // 2 bytes, 11 bits: 110xxxxx 10xxxxxx if (sp < sl) { int b2 = segment.get(sp++); if ((b2 & 0xc0) != 0x80) { // isNotContinuation(b2) return -1; } else { da[dp++] = (char) (((b1 << 6) ^ b2) ^ (((byte) 0xC0 << 6) ^ ((byte) 0x80))); } continue; } return -1; } else if ((b1 >> 4) == -2) { // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx if (sp + 1 < sl) { int b2 = segment.get(sp++); int b3 = segment.get(sp++); if ((b1 == (byte) 0xe0 && (b2 & 0xe0) == 0x80) || (b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80) { // isMalformed3(b1, b2, b3) return -1; } else { char c = (char) ((b1 << 12) ^ (b2 << 6) ^ (b3 ^ (((byte) 0xE0 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80)))); if (Character.isSurrogate(c)) { return -1; } else { da[dp++] = c; } } continue; } return -1; } else if ((b1 >> 3) == -2) { // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx if (sp + 2 < sl) { int b2 = segment.get(sp++); int b3 = segment.get(sp++); int b4 = segment.get(sp++); int uc = ((b1 << 18) ^ (b2 << 12) ^ (b3 << 6) ^ (b4 ^ (((byte) 0xF0 << 18) ^ ((byte) 0x80 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80)))); // isMalformed4 and shortest form check if (((b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80 || (b4 & 0xc0) != 0x80) || !Character.isSupplementaryCodePoint(uc)) { return -1; } else { da[dp++] = Character.highSurrogate(uc); da[dp++] = Character.lowSurrogate(uc); } continue; } return -1; } else { return -1; } } return dp; } public static String defaultDecodeUTF8(byte[] bytes, int offset, int len) { return new String(bytes, offset, len, StandardCharsets.UTF_8); } }
googleapis/google-cloud-java
37,255
java-discoveryengine/proto-google-cloud-discoveryengine-v1/src/main/java/com/google/cloud/discoveryengine/v1/Schema.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/discoveryengine/v1/schema.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.discoveryengine.v1; /** * * * <pre> * Defines the structure and layout of a type of document data. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1.Schema} */ public final class Schema extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1.Schema) SchemaOrBuilder { private static final long serialVersionUID = 0L; // Use Schema.newBuilder() to construct. private Schema(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Schema() { name_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new Schema(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1.SchemaProto .internal_static_google_cloud_discoveryengine_v1_Schema_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1.SchemaProto .internal_static_google_cloud_discoveryengine_v1_Schema_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1.Schema.class, com.google.cloud.discoveryengine.v1.Schema.Builder.class); } private int schemaCase_ = 0; @SuppressWarnings("serial") private java.lang.Object schema_; public enum SchemaCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { STRUCT_SCHEMA(2), JSON_SCHEMA(3), SCHEMA_NOT_SET(0); private final int value; private SchemaCase(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 SchemaCase valueOf(int value) { return forNumber(value); } public static SchemaCase forNumber(int value) { switch (value) { case 2: return STRUCT_SCHEMA; case 3: return JSON_SCHEMA; case 0: return SCHEMA_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public SchemaCase getSchemaCase() { return SchemaCase.forNumber(schemaCase_); } public static final int STRUCT_SCHEMA_FIELD_NUMBER = 2; /** * * * <pre> * The structured representation of the schema. * </pre> * * <code>.google.protobuf.Struct struct_schema = 2;</code> * * @return Whether the structSchema field is set. */ @java.lang.Override public boolean hasStructSchema() { return schemaCase_ == 2; } /** * * * <pre> * The structured representation of the schema. * </pre> * * <code>.google.protobuf.Struct struct_schema = 2;</code> * * @return The structSchema. */ @java.lang.Override public com.google.protobuf.Struct getStructSchema() { if (schemaCase_ == 2) { return (com.google.protobuf.Struct) schema_; } return com.google.protobuf.Struct.getDefaultInstance(); } /** * * * <pre> * The structured representation of the schema. * </pre> * * <code>.google.protobuf.Struct struct_schema = 2;</code> */ @java.lang.Override public com.google.protobuf.StructOrBuilder getStructSchemaOrBuilder() { if (schemaCase_ == 2) { return (com.google.protobuf.Struct) schema_; } return com.google.protobuf.Struct.getDefaultInstance(); } public static final int JSON_SCHEMA_FIELD_NUMBER = 3; /** * * * <pre> * The JSON representation of the schema. * </pre> * * <code>string json_schema = 3;</code> * * @return Whether the jsonSchema field is set. */ public boolean hasJsonSchema() { return schemaCase_ == 3; } /** * * * <pre> * The JSON representation of the schema. * </pre> * * <code>string json_schema = 3;</code> * * @return The jsonSchema. */ public java.lang.String getJsonSchema() { java.lang.Object ref = ""; if (schemaCase_ == 3) { ref = schema_; } if (ref instanceof java.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 (schemaCase_ == 3) { schema_ = s; } return s; } } /** * * * <pre> * The JSON representation of the schema. * </pre> * * <code>string json_schema = 3;</code> * * @return The bytes for jsonSchema. */ public com.google.protobuf.ByteString getJsonSchemaBytes() { java.lang.Object ref = ""; if (schemaCase_ == 3) { ref = schema_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (schemaCase_ == 3) { schema_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Immutable. The full resource name of the schema, in the format of * `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}`. * * This field must be a UTF-8 encoded string with a length limit of 1024 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IMMUTABLE];</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> * Immutable. The full resource name of the schema, in the format of * `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}`. * * This field must be a UTF-8 encoded string with a length limit of 1024 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IMMUTABLE];</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; } } 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 (schemaCase_ == 2) { output.writeMessage(2, (com.google.protobuf.Struct) schema_); } if (schemaCase_ == 3) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, schema_); } 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 (schemaCase_ == 2) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 2, (com.google.protobuf.Struct) schema_); } if (schemaCase_ == 3) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, schema_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.discoveryengine.v1.Schema)) { return super.equals(obj); } com.google.cloud.discoveryengine.v1.Schema other = (com.google.cloud.discoveryengine.v1.Schema) obj; if (!getName().equals(other.getName())) return false; if (!getSchemaCase().equals(other.getSchemaCase())) return false; switch (schemaCase_) { case 2: if (!getStructSchema().equals(other.getStructSchema())) return false; break; case 3: if (!getJsonSchema().equals(other.getJsonSchema())) return false; break; case 0: default: } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); switch (schemaCase_) { case 2: hash = (37 * hash) + STRUCT_SCHEMA_FIELD_NUMBER; hash = (53 * hash) + getStructSchema().hashCode(); break; case 3: hash = (37 * hash) + JSON_SCHEMA_FIELD_NUMBER; hash = (53 * hash) + getJsonSchema().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.discoveryengine.v1.Schema parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.Schema parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.discoveryengine.v1.Schema parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.Schema parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.discoveryengine.v1.Schema parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.Schema parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.discoveryengine.v1.Schema parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1.Schema parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.discoveryengine.v1.Schema parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1.Schema parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.discoveryengine.v1.Schema parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1.Schema parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.discoveryengine.v1.Schema 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> * Defines the structure and layout of a type of document data. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1.Schema} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1.Schema) com.google.cloud.discoveryengine.v1.SchemaOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1.SchemaProto .internal_static_google_cloud_discoveryengine_v1_Schema_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1.SchemaProto .internal_static_google_cloud_discoveryengine_v1_Schema_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1.Schema.class, com.google.cloud.discoveryengine.v1.Schema.Builder.class); } // Construct using com.google.cloud.discoveryengine.v1.Schema.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (structSchemaBuilder_ != null) { structSchemaBuilder_.clear(); } name_ = ""; schemaCase_ = 0; schema_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.discoveryengine.v1.SchemaProto .internal_static_google_cloud_discoveryengine_v1_Schema_descriptor; } @java.lang.Override public com.google.cloud.discoveryengine.v1.Schema getDefaultInstanceForType() { return com.google.cloud.discoveryengine.v1.Schema.getDefaultInstance(); } @java.lang.Override public com.google.cloud.discoveryengine.v1.Schema build() { com.google.cloud.discoveryengine.v1.Schema result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.discoveryengine.v1.Schema buildPartial() { com.google.cloud.discoveryengine.v1.Schema result = new com.google.cloud.discoveryengine.v1.Schema(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.cloud.discoveryengine.v1.Schema result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000004) != 0)) { result.name_ = name_; } } private void buildPartialOneofs(com.google.cloud.discoveryengine.v1.Schema result) { result.schemaCase_ = schemaCase_; result.schema_ = this.schema_; if (schemaCase_ == 2 && structSchemaBuilder_ != null) { result.schema_ = structSchemaBuilder_.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.discoveryengine.v1.Schema) { return mergeFrom((com.google.cloud.discoveryengine.v1.Schema) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.discoveryengine.v1.Schema other) { if (other == com.google.cloud.discoveryengine.v1.Schema.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000004; onChanged(); } switch (other.getSchemaCase()) { case STRUCT_SCHEMA: { mergeStructSchema(other.getStructSchema()); break; } case JSON_SCHEMA: { schemaCase_ = 3; schema_ = other.schema_; onChanged(); break; } case SCHEMA_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: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 10 case 18: { input.readMessage(getStructSchemaFieldBuilder().getBuilder(), extensionRegistry); schemaCase_ = 2; break; } // case 18 case 26: { java.lang.String s = input.readStringRequireUtf8(); schemaCase_ = 3; schema_ = s; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int schemaCase_ = 0; private java.lang.Object schema_; public SchemaCase getSchemaCase() { return SchemaCase.forNumber(schemaCase_); } public Builder clearSchema() { schemaCase_ = 0; schema_ = null; onChanged(); return this; } private int bitField0_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Struct, com.google.protobuf.Struct.Builder, com.google.protobuf.StructOrBuilder> structSchemaBuilder_; /** * * * <pre> * The structured representation of the schema. * </pre> * * <code>.google.protobuf.Struct struct_schema = 2;</code> * * @return Whether the structSchema field is set. */ @java.lang.Override public boolean hasStructSchema() { return schemaCase_ == 2; } /** * * * <pre> * The structured representation of the schema. * </pre> * * <code>.google.protobuf.Struct struct_schema = 2;</code> * * @return The structSchema. */ @java.lang.Override public com.google.protobuf.Struct getStructSchema() { if (structSchemaBuilder_ == null) { if (schemaCase_ == 2) { return (com.google.protobuf.Struct) schema_; } return com.google.protobuf.Struct.getDefaultInstance(); } else { if (schemaCase_ == 2) { return structSchemaBuilder_.getMessage(); } return com.google.protobuf.Struct.getDefaultInstance(); } } /** * * * <pre> * The structured representation of the schema. * </pre> * * <code>.google.protobuf.Struct struct_schema = 2;</code> */ public Builder setStructSchema(com.google.protobuf.Struct value) { if (structSchemaBuilder_ == null) { if (value == null) { throw new NullPointerException(); } schema_ = value; onChanged(); } else { structSchemaBuilder_.setMessage(value); } schemaCase_ = 2; return this; } /** * * * <pre> * The structured representation of the schema. * </pre> * * <code>.google.protobuf.Struct struct_schema = 2;</code> */ public Builder setStructSchema(com.google.protobuf.Struct.Builder builderForValue) { if (structSchemaBuilder_ == null) { schema_ = builderForValue.build(); onChanged(); } else { structSchemaBuilder_.setMessage(builderForValue.build()); } schemaCase_ = 2; return this; } /** * * * <pre> * The structured representation of the schema. * </pre> * * <code>.google.protobuf.Struct struct_schema = 2;</code> */ public Builder mergeStructSchema(com.google.protobuf.Struct value) { if (structSchemaBuilder_ == null) { if (schemaCase_ == 2 && schema_ != com.google.protobuf.Struct.getDefaultInstance()) { schema_ = com.google.protobuf.Struct.newBuilder((com.google.protobuf.Struct) schema_) .mergeFrom(value) .buildPartial(); } else { schema_ = value; } onChanged(); } else { if (schemaCase_ == 2) { structSchemaBuilder_.mergeFrom(value); } else { structSchemaBuilder_.setMessage(value); } } schemaCase_ = 2; return this; } /** * * * <pre> * The structured representation of the schema. * </pre> * * <code>.google.protobuf.Struct struct_schema = 2;</code> */ public Builder clearStructSchema() { if (structSchemaBuilder_ == null) { if (schemaCase_ == 2) { schemaCase_ = 0; schema_ = null; onChanged(); } } else { if (schemaCase_ == 2) { schemaCase_ = 0; schema_ = null; } structSchemaBuilder_.clear(); } return this; } /** * * * <pre> * The structured representation of the schema. * </pre> * * <code>.google.protobuf.Struct struct_schema = 2;</code> */ public com.google.protobuf.Struct.Builder getStructSchemaBuilder() { return getStructSchemaFieldBuilder().getBuilder(); } /** * * * <pre> * The structured representation of the schema. * </pre> * * <code>.google.protobuf.Struct struct_schema = 2;</code> */ @java.lang.Override public com.google.protobuf.StructOrBuilder getStructSchemaOrBuilder() { if ((schemaCase_ == 2) && (structSchemaBuilder_ != null)) { return structSchemaBuilder_.getMessageOrBuilder(); } else { if (schemaCase_ == 2) { return (com.google.protobuf.Struct) schema_; } return com.google.protobuf.Struct.getDefaultInstance(); } } /** * * * <pre> * The structured representation of the schema. * </pre> * * <code>.google.protobuf.Struct struct_schema = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Struct, com.google.protobuf.Struct.Builder, com.google.protobuf.StructOrBuilder> getStructSchemaFieldBuilder() { if (structSchemaBuilder_ == null) { if (!(schemaCase_ == 2)) { schema_ = com.google.protobuf.Struct.getDefaultInstance(); } structSchemaBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Struct, com.google.protobuf.Struct.Builder, com.google.protobuf.StructOrBuilder>( (com.google.protobuf.Struct) schema_, getParentForChildren(), isClean()); schema_ = null; } schemaCase_ = 2; onChanged(); return structSchemaBuilder_; } /** * * * <pre> * The JSON representation of the schema. * </pre> * * <code>string json_schema = 3;</code> * * @return Whether the jsonSchema field is set. */ @java.lang.Override public boolean hasJsonSchema() { return schemaCase_ == 3; } /** * * * <pre> * The JSON representation of the schema. * </pre> * * <code>string json_schema = 3;</code> * * @return The jsonSchema. */ @java.lang.Override public java.lang.String getJsonSchema() { java.lang.Object ref = ""; if (schemaCase_ == 3) { ref = schema_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (schemaCase_ == 3) { schema_ = s; } return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The JSON representation of the schema. * </pre> * * <code>string json_schema = 3;</code> * * @return The bytes for jsonSchema. */ @java.lang.Override public com.google.protobuf.ByteString getJsonSchemaBytes() { java.lang.Object ref = ""; if (schemaCase_ == 3) { ref = schema_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (schemaCase_ == 3) { schema_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The JSON representation of the schema. * </pre> * * <code>string json_schema = 3;</code> * * @param value The jsonSchema to set. * @return This builder for chaining. */ public Builder setJsonSchema(java.lang.String value) { if (value == null) { throw new NullPointerException(); } schemaCase_ = 3; schema_ = value; onChanged(); return this; } /** * * * <pre> * The JSON representation of the schema. * </pre> * * <code>string json_schema = 3;</code> * * @return This builder for chaining. */ public Builder clearJsonSchema() { if (schemaCase_ == 3) { schemaCase_ = 0; schema_ = null; onChanged(); } return this; } /** * * * <pre> * The JSON representation of the schema. * </pre> * * <code>string json_schema = 3;</code> * * @param value The bytes for jsonSchema to set. * @return This builder for chaining. */ public Builder setJsonSchemaBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); schemaCase_ = 3; schema_ = value; onChanged(); return this; } private java.lang.Object name_ = ""; /** * * * <pre> * Immutable. The full resource name of the schema, in the format of * `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}`. * * This field must be a UTF-8 encoded string with a length limit of 1024 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IMMUTABLE];</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> * Immutable. The full resource name of the schema, in the format of * `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}`. * * This field must be a UTF-8 encoded string with a length limit of 1024 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IMMUTABLE];</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> * Immutable. The full resource name of the schema, in the format of * `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}`. * * This field must be a UTF-8 encoded string with a length limit of 1024 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IMMUTABLE];</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_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Immutable. The full resource name of the schema, in the format of * `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}`. * * This field must be a UTF-8 encoded string with a length limit of 1024 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IMMUTABLE];</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Immutable. The full resource name of the schema, in the format of * `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}`. * * This field must be a UTF-8 encoded string with a length limit of 1024 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IMMUTABLE];</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_ |= 0x00000004; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.discoveryengine.v1.Schema) } // @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1.Schema) private static final com.google.cloud.discoveryengine.v1.Schema DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1.Schema(); } public static com.google.cloud.discoveryengine.v1.Schema getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Schema> PARSER = new com.google.protobuf.AbstractParser<Schema>() { @java.lang.Override public Schema 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<Schema> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Schema> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.discoveryengine.v1.Schema getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,323
java-telcoautomation/proto-google-cloud-telcoautomation-v1alpha1/src/main/java/com/google/cloud/telcoautomation/v1alpha1/CreateBlueprintRequest.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/telcoautomation/v1alpha1/telcoautomation.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.telcoautomation.v1alpha1; /** * * * <pre> * Request object for `CreateBlueprint`. * </pre> * * Protobuf type {@code google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest} */ public final class CreateBlueprintRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest) CreateBlueprintRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateBlueprintRequest.newBuilder() to construct. private CreateBlueprintRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateBlueprintRequest() { parent_ = ""; blueprintId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateBlueprintRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_CreateBlueprintRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_CreateBlueprintRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest.class, com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </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 BLUEPRINT_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object blueprintId_ = ""; /** * * * <pre> * Optional. The name of the blueprint. * </pre> * * <code>string blueprint_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The blueprintId. */ @java.lang.Override public java.lang.String getBlueprintId() { java.lang.Object ref = blueprintId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); blueprintId_ = s; return s; } } /** * * * <pre> * Optional. The name of the blueprint. * </pre> * * <code>string blueprint_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for blueprintId. */ @java.lang.Override public com.google.protobuf.ByteString getBlueprintIdBytes() { java.lang.Object ref = blueprintId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); blueprintId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int BLUEPRINT_FIELD_NUMBER = 3; private com.google.cloud.telcoautomation.v1alpha1.Blueprint blueprint_; /** * * * <pre> * Required. The `Blueprint` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Blueprint blueprint = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the blueprint field is set. */ @java.lang.Override public boolean hasBlueprint() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The `Blueprint` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Blueprint blueprint = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The blueprint. */ @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.Blueprint getBlueprint() { return blueprint_ == null ? com.google.cloud.telcoautomation.v1alpha1.Blueprint.getDefaultInstance() : blueprint_; } /** * * * <pre> * Required. The `Blueprint` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Blueprint blueprint = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.BlueprintOrBuilder getBlueprintOrBuilder() { return blueprint_ == null ? com.google.cloud.telcoautomation.v1alpha1.Blueprint.getDefaultInstance() : blueprint_; } 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(blueprintId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, blueprintId_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getBlueprint()); } 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(blueprintId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, blueprintId_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getBlueprint()); } 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.telcoautomation.v1alpha1.CreateBlueprintRequest)) { return super.equals(obj); } com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest other = (com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getBlueprintId().equals(other.getBlueprintId())) return false; if (hasBlueprint() != other.hasBlueprint()) return false; if (hasBlueprint()) { if (!getBlueprint().equals(other.getBlueprint())) 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) + BLUEPRINT_ID_FIELD_NUMBER; hash = (53 * hash) + getBlueprintId().hashCode(); if (hasBlueprint()) { hash = (37 * hash) + BLUEPRINT_FIELD_NUMBER; hash = (53 * hash) + getBlueprint().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest 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.telcoautomation.v1alpha1.CreateBlueprintRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest 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.telcoautomation.v1alpha1.CreateBlueprintRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest 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.telcoautomation.v1alpha1.CreateBlueprintRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest 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.telcoautomation.v1alpha1.CreateBlueprintRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest 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.telcoautomation.v1alpha1.CreateBlueprintRequest 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 object for `CreateBlueprint`. * </pre> * * Protobuf type {@code google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest) com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_CreateBlueprintRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_CreateBlueprintRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest.class, com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest.Builder.class); } // Construct using com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getBlueprintFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; blueprintId_ = ""; blueprint_ = null; if (blueprintBuilder_ != null) { blueprintBuilder_.dispose(); blueprintBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_CreateBlueprintRequest_descriptor; } @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest getDefaultInstanceForType() { return com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest build() { com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest buildPartial() { com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest result = new com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.blueprintId_ = blueprintId_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.blueprint_ = blueprintBuilder_ == null ? blueprint_ : blueprintBuilder_.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.telcoautomation.v1alpha1.CreateBlueprintRequest) { return mergeFrom((com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest other) { if (other == com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getBlueprintId().isEmpty()) { blueprintId_ = other.blueprintId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasBlueprint()) { mergeBlueprint(other.getBlueprint()); } 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: { blueprintId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getBlueprintFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </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 blueprintId_ = ""; /** * * * <pre> * Optional. The name of the blueprint. * </pre> * * <code>string blueprint_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The blueprintId. */ public java.lang.String getBlueprintId() { java.lang.Object ref = blueprintId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); blueprintId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. The name of the blueprint. * </pre> * * <code>string blueprint_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for blueprintId. */ public com.google.protobuf.ByteString getBlueprintIdBytes() { java.lang.Object ref = blueprintId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); blueprintId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. The name of the blueprint. * </pre> * * <code>string blueprint_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The blueprintId to set. * @return This builder for chaining. */ public Builder setBlueprintId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } blueprintId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. The name of the blueprint. * </pre> * * <code>string blueprint_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearBlueprintId() { blueprintId_ = getDefaultInstance().getBlueprintId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Optional. The name of the blueprint. * </pre> * * <code>string blueprint_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for blueprintId to set. * @return This builder for chaining. */ public Builder setBlueprintIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); blueprintId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.telcoautomation.v1alpha1.Blueprint blueprint_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.telcoautomation.v1alpha1.Blueprint, com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder, com.google.cloud.telcoautomation.v1alpha1.BlueprintOrBuilder> blueprintBuilder_; /** * * * <pre> * Required. The `Blueprint` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Blueprint blueprint = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the blueprint field is set. */ public boolean hasBlueprint() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. The `Blueprint` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Blueprint blueprint = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The blueprint. */ public com.google.cloud.telcoautomation.v1alpha1.Blueprint getBlueprint() { if (blueprintBuilder_ == null) { return blueprint_ == null ? com.google.cloud.telcoautomation.v1alpha1.Blueprint.getDefaultInstance() : blueprint_; } else { return blueprintBuilder_.getMessage(); } } /** * * * <pre> * Required. The `Blueprint` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Blueprint blueprint = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setBlueprint(com.google.cloud.telcoautomation.v1alpha1.Blueprint value) { if (blueprintBuilder_ == null) { if (value == null) { throw new NullPointerException(); } blueprint_ = value; } else { blueprintBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The `Blueprint` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Blueprint blueprint = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setBlueprint( com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder builderForValue) { if (blueprintBuilder_ == null) { blueprint_ = builderForValue.build(); } else { blueprintBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The `Blueprint` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Blueprint blueprint = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeBlueprint(com.google.cloud.telcoautomation.v1alpha1.Blueprint value) { if (blueprintBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && blueprint_ != null && blueprint_ != com.google.cloud.telcoautomation.v1alpha1.Blueprint.getDefaultInstance()) { getBlueprintBuilder().mergeFrom(value); } else { blueprint_ = value; } } else { blueprintBuilder_.mergeFrom(value); } if (blueprint_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. The `Blueprint` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Blueprint blueprint = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearBlueprint() { bitField0_ = (bitField0_ & ~0x00000004); blueprint_ = null; if (blueprintBuilder_ != null) { blueprintBuilder_.dispose(); blueprintBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The `Blueprint` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Blueprint blueprint = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder getBlueprintBuilder() { bitField0_ |= 0x00000004; onChanged(); return getBlueprintFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The `Blueprint` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Blueprint blueprint = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.telcoautomation.v1alpha1.BlueprintOrBuilder getBlueprintOrBuilder() { if (blueprintBuilder_ != null) { return blueprintBuilder_.getMessageOrBuilder(); } else { return blueprint_ == null ? com.google.cloud.telcoautomation.v1alpha1.Blueprint.getDefaultInstance() : blueprint_; } } /** * * * <pre> * Required. The `Blueprint` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Blueprint blueprint = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.telcoautomation.v1alpha1.Blueprint, com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder, com.google.cloud.telcoautomation.v1alpha1.BlueprintOrBuilder> getBlueprintFieldBuilder() { if (blueprintBuilder_ == null) { blueprintBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.telcoautomation.v1alpha1.Blueprint, com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder, com.google.cloud.telcoautomation.v1alpha1.BlueprintOrBuilder>( getBlueprint(), getParentForChildren(), isClean()); blueprint_ = null; } return blueprintBuilder_; } @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.telcoautomation.v1alpha1.CreateBlueprintRequest) } // @@protoc_insertion_point(class_scope:google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest) private static final com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest(); } public static com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateBlueprintRequest> PARSER = new com.google.protobuf.AbstractParser<CreateBlueprintRequest>() { @java.lang.Override public CreateBlueprintRequest 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<CreateBlueprintRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateBlueprintRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.CreateBlueprintRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,363
java-datalabeling/proto-google-cloud-datalabeling-v1beta1/src/main/java/com/google/cloud/datalabeling/v1beta1/ListInstructionsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/datalabeling/v1beta1/data_labeling_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.datalabeling.v1beta1; /** * * * <pre> * Results of listing instructions under a project. * </pre> * * Protobuf type {@code google.cloud.datalabeling.v1beta1.ListInstructionsResponse} */ public final class ListInstructionsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datalabeling.v1beta1.ListInstructionsResponse) ListInstructionsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListInstructionsResponse.newBuilder() to construct. private ListInstructionsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListInstructionsResponse() { instructions_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListInstructionsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListInstructionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListInstructionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse.class, com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse.Builder.class); } public static final int INSTRUCTIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.datalabeling.v1beta1.Instruction> instructions_; /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.datalabeling.v1beta1.Instruction> getInstructionsList() { return instructions_; } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.datalabeling.v1beta1.InstructionOrBuilder> getInstructionsOrBuilderList() { return instructions_; } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ @java.lang.Override public int getInstructionsCount() { return instructions_.size(); } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ @java.lang.Override public com.google.cloud.datalabeling.v1beta1.Instruction getInstructions(int index) { return instructions_.get(index); } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ @java.lang.Override public com.google.cloud.datalabeling.v1beta1.InstructionOrBuilder getInstructionsOrBuilder( int index) { return instructions_.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. * </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. * </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 < instructions_.size(); i++) { output.writeMessage(1, instructions_.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 < instructions_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, instructions_.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.datalabeling.v1beta1.ListInstructionsResponse)) { return super.equals(obj); } com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse other = (com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse) obj; if (!getInstructionsList().equals(other.getInstructionsList())) 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 (getInstructionsCount() > 0) { hash = (37 * hash) + INSTRUCTIONS_FIELD_NUMBER; hash = (53 * hash) + getInstructionsList().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.datalabeling.v1beta1.ListInstructionsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse 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 of listing instructions under a project. * </pre> * * Protobuf type {@code google.cloud.datalabeling.v1beta1.ListInstructionsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datalabeling.v1beta1.ListInstructionsResponse) com.google.cloud.datalabeling.v1beta1.ListInstructionsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListInstructionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListInstructionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse.class, com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse.Builder.class); } // Construct using com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (instructionsBuilder_ == null) { instructions_ = java.util.Collections.emptyList(); } else { instructions_ = null; instructionsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListInstructionsResponse_descriptor; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse getDefaultInstanceForType() { return com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse build() { com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse buildPartial() { com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse result = new com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse result) { if (instructionsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { instructions_ = java.util.Collections.unmodifiableList(instructions_); bitField0_ = (bitField0_ & ~0x00000001); } result.instructions_ = instructions_; } else { result.instructions_ = instructionsBuilder_.build(); } } private void buildPartial0( com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse 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.datalabeling.v1beta1.ListInstructionsResponse) { return mergeFrom((com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse other) { if (other == com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse.getDefaultInstance()) return this; if (instructionsBuilder_ == null) { if (!other.instructions_.isEmpty()) { if (instructions_.isEmpty()) { instructions_ = other.instructions_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureInstructionsIsMutable(); instructions_.addAll(other.instructions_); } onChanged(); } } else { if (!other.instructions_.isEmpty()) { if (instructionsBuilder_.isEmpty()) { instructionsBuilder_.dispose(); instructionsBuilder_ = null; instructions_ = other.instructions_; bitField0_ = (bitField0_ & ~0x00000001); instructionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getInstructionsFieldBuilder() : null; } else { instructionsBuilder_.addAllMessages(other.instructions_); } } } 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.datalabeling.v1beta1.Instruction m = input.readMessage( com.google.cloud.datalabeling.v1beta1.Instruction.parser(), extensionRegistry); if (instructionsBuilder_ == null) { ensureInstructionsIsMutable(); instructions_.add(m); } else { instructionsBuilder_.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.datalabeling.v1beta1.Instruction> instructions_ = java.util.Collections.emptyList(); private void ensureInstructionsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { instructions_ = new java.util.ArrayList<com.google.cloud.datalabeling.v1beta1.Instruction>( instructions_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.datalabeling.v1beta1.Instruction, com.google.cloud.datalabeling.v1beta1.Instruction.Builder, com.google.cloud.datalabeling.v1beta1.InstructionOrBuilder> instructionsBuilder_; /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public java.util.List<com.google.cloud.datalabeling.v1beta1.Instruction> getInstructionsList() { if (instructionsBuilder_ == null) { return java.util.Collections.unmodifiableList(instructions_); } else { return instructionsBuilder_.getMessageList(); } } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public int getInstructionsCount() { if (instructionsBuilder_ == null) { return instructions_.size(); } else { return instructionsBuilder_.getCount(); } } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.Instruction getInstructions(int index) { if (instructionsBuilder_ == null) { return instructions_.get(index); } else { return instructionsBuilder_.getMessage(index); } } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public Builder setInstructions( int index, com.google.cloud.datalabeling.v1beta1.Instruction value) { if (instructionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureInstructionsIsMutable(); instructions_.set(index, value); onChanged(); } else { instructionsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public Builder setInstructions( int index, com.google.cloud.datalabeling.v1beta1.Instruction.Builder builderForValue) { if (instructionsBuilder_ == null) { ensureInstructionsIsMutable(); instructions_.set(index, builderForValue.build()); onChanged(); } else { instructionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public Builder addInstructions(com.google.cloud.datalabeling.v1beta1.Instruction value) { if (instructionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureInstructionsIsMutable(); instructions_.add(value); onChanged(); } else { instructionsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public Builder addInstructions( int index, com.google.cloud.datalabeling.v1beta1.Instruction value) { if (instructionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureInstructionsIsMutable(); instructions_.add(index, value); onChanged(); } else { instructionsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public Builder addInstructions( com.google.cloud.datalabeling.v1beta1.Instruction.Builder builderForValue) { if (instructionsBuilder_ == null) { ensureInstructionsIsMutable(); instructions_.add(builderForValue.build()); onChanged(); } else { instructionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public Builder addInstructions( int index, com.google.cloud.datalabeling.v1beta1.Instruction.Builder builderForValue) { if (instructionsBuilder_ == null) { ensureInstructionsIsMutable(); instructions_.add(index, builderForValue.build()); onChanged(); } else { instructionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public Builder addAllInstructions( java.lang.Iterable<? extends com.google.cloud.datalabeling.v1beta1.Instruction> values) { if (instructionsBuilder_ == null) { ensureInstructionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, instructions_); onChanged(); } else { instructionsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public Builder clearInstructions() { if (instructionsBuilder_ == null) { instructions_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { instructionsBuilder_.clear(); } return this; } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public Builder removeInstructions(int index) { if (instructionsBuilder_ == null) { ensureInstructionsIsMutable(); instructions_.remove(index); onChanged(); } else { instructionsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.Instruction.Builder getInstructionsBuilder( int index) { return getInstructionsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.InstructionOrBuilder getInstructionsOrBuilder( int index) { if (instructionsBuilder_ == null) { return instructions_.get(index); } else { return instructionsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public java.util.List<? extends com.google.cloud.datalabeling.v1beta1.InstructionOrBuilder> getInstructionsOrBuilderList() { if (instructionsBuilder_ != null) { return instructionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(instructions_); } } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.Instruction.Builder addInstructionsBuilder() { return getInstructionsFieldBuilder() .addBuilder(com.google.cloud.datalabeling.v1beta1.Instruction.getDefaultInstance()); } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.Instruction.Builder addInstructionsBuilder( int index) { return getInstructionsFieldBuilder() .addBuilder( index, com.google.cloud.datalabeling.v1beta1.Instruction.getDefaultInstance()); } /** * * * <pre> * The list of Instructions to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.Instruction instructions = 1;</code> */ public java.util.List<com.google.cloud.datalabeling.v1beta1.Instruction.Builder> getInstructionsBuilderList() { return getInstructionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.datalabeling.v1beta1.Instruction, com.google.cloud.datalabeling.v1beta1.Instruction.Builder, com.google.cloud.datalabeling.v1beta1.InstructionOrBuilder> getInstructionsFieldBuilder() { if (instructionsBuilder_ == null) { instructionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.datalabeling.v1beta1.Instruction, com.google.cloud.datalabeling.v1beta1.Instruction.Builder, com.google.cloud.datalabeling.v1beta1.InstructionOrBuilder>( instructions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); instructions_ = null; } return instructionsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve 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. * </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. * </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. * </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. * </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.datalabeling.v1beta1.ListInstructionsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.datalabeling.v1beta1.ListInstructionsResponse) private static final com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse(); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListInstructionsResponse> PARSER = new com.google.protobuf.AbstractParser<ListInstructionsResponse>() { @java.lang.Override public ListInstructionsResponse 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<ListInstructionsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListInstructionsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListInstructionsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,345
java-bigqueryconnection/proto-google-cloud-bigqueryconnection-v1/src/main/java/com/google/cloud/bigquery/connection/v1/CreateConnectionRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/bigquery/connection/v1/connection.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.bigquery.connection.v1; /** * * * <pre> * The request for * [ConnectionService.CreateConnection][google.cloud.bigquery.connection.v1.ConnectionService.CreateConnection]. * </pre> * * Protobuf type {@code google.cloud.bigquery.connection.v1.CreateConnectionRequest} */ public final class CreateConnectionRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.bigquery.connection.v1.CreateConnectionRequest) CreateConnectionRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateConnectionRequest.newBuilder() to construct. private CreateConnectionRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateConnectionRequest() { parent_ = ""; connectionId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateConnectionRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.connection.v1.ConnectionOuterClass .internal_static_google_cloud_bigquery_connection_v1_CreateConnectionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.connection.v1.ConnectionOuterClass .internal_static_google_cloud_bigquery_connection_v1_CreateConnectionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.connection.v1.CreateConnectionRequest.class, com.google.cloud.bigquery.connection.v1.CreateConnectionRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Parent resource name. * Must be in the format `projects/{project_id}/locations/{location_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. Parent resource name. * Must be in the format `projects/{project_id}/locations/{location_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CONNECTION_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object connectionId_ = ""; /** * * * <pre> * Optional. Connection id that should be assigned to the created connection. * </pre> * * <code>string connection_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The connectionId. */ @java.lang.Override public java.lang.String getConnectionId() { java.lang.Object ref = connectionId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); connectionId_ = s; return s; } } /** * * * <pre> * Optional. Connection id that should be assigned to the created connection. * </pre> * * <code>string connection_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for connectionId. */ @java.lang.Override public com.google.protobuf.ByteString getConnectionIdBytes() { java.lang.Object ref = connectionId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); connectionId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CONNECTION_FIELD_NUMBER = 3; private com.google.cloud.bigquery.connection.v1.Connection connection_; /** * * * <pre> * Required. Connection to create. * </pre> * * <code> * .google.cloud.bigquery.connection.v1.Connection connection = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the connection field is set. */ @java.lang.Override public boolean hasConnection() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Connection to create. * </pre> * * <code> * .google.cloud.bigquery.connection.v1.Connection connection = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The connection. */ @java.lang.Override public com.google.cloud.bigquery.connection.v1.Connection getConnection() { return connection_ == null ? com.google.cloud.bigquery.connection.v1.Connection.getDefaultInstance() : connection_; } /** * * * <pre> * Required. Connection to create. * </pre> * * <code> * .google.cloud.bigquery.connection.v1.Connection connection = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.bigquery.connection.v1.ConnectionOrBuilder getConnectionOrBuilder() { return connection_ == null ? com.google.cloud.bigquery.connection.v1.Connection.getDefaultInstance() : connection_; } 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(connectionId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, connectionId_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getConnection()); } 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(connectionId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, connectionId_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getConnection()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.bigquery.connection.v1.CreateConnectionRequest)) { return super.equals(obj); } com.google.cloud.bigquery.connection.v1.CreateConnectionRequest other = (com.google.cloud.bigquery.connection.v1.CreateConnectionRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getConnectionId().equals(other.getConnectionId())) return false; if (hasConnection() != other.hasConnection()) return false; if (hasConnection()) { if (!getConnection().equals(other.getConnection())) 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) + CONNECTION_ID_FIELD_NUMBER; hash = (53 * hash) + getConnectionId().hashCode(); if (hasConnection()) { hash = (37 * hash) + CONNECTION_FIELD_NUMBER; hash = (53 * hash) + getConnection().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.bigquery.connection.v1.CreateConnectionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.connection.v1.CreateConnectionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.connection.v1.CreateConnectionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.connection.v1.CreateConnectionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.connection.v1.CreateConnectionRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.connection.v1.CreateConnectionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.connection.v1.CreateConnectionRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.connection.v1.CreateConnectionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.connection.v1.CreateConnectionRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.bigquery.connection.v1.CreateConnectionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.connection.v1.CreateConnectionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.connection.v1.CreateConnectionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.bigquery.connection.v1.CreateConnectionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The request for * [ConnectionService.CreateConnection][google.cloud.bigquery.connection.v1.ConnectionService.CreateConnection]. * </pre> * * Protobuf type {@code google.cloud.bigquery.connection.v1.CreateConnectionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.bigquery.connection.v1.CreateConnectionRequest) com.google.cloud.bigquery.connection.v1.CreateConnectionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.connection.v1.ConnectionOuterClass .internal_static_google_cloud_bigquery_connection_v1_CreateConnectionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.connection.v1.ConnectionOuterClass .internal_static_google_cloud_bigquery_connection_v1_CreateConnectionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.connection.v1.CreateConnectionRequest.class, com.google.cloud.bigquery.connection.v1.CreateConnectionRequest.Builder.class); } // Construct using com.google.cloud.bigquery.connection.v1.CreateConnectionRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getConnectionFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; connectionId_ = ""; connection_ = null; if (connectionBuilder_ != null) { connectionBuilder_.dispose(); connectionBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.bigquery.connection.v1.ConnectionOuterClass .internal_static_google_cloud_bigquery_connection_v1_CreateConnectionRequest_descriptor; } @java.lang.Override public com.google.cloud.bigquery.connection.v1.CreateConnectionRequest getDefaultInstanceForType() { return com.google.cloud.bigquery.connection.v1.CreateConnectionRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.bigquery.connection.v1.CreateConnectionRequest build() { com.google.cloud.bigquery.connection.v1.CreateConnectionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.bigquery.connection.v1.CreateConnectionRequest buildPartial() { com.google.cloud.bigquery.connection.v1.CreateConnectionRequest result = new com.google.cloud.bigquery.connection.v1.CreateConnectionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.bigquery.connection.v1.CreateConnectionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.connectionId_ = connectionId_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.connection_ = connectionBuilder_ == null ? connection_ : connectionBuilder_.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.bigquery.connection.v1.CreateConnectionRequest) { return mergeFrom((com.google.cloud.bigquery.connection.v1.CreateConnectionRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.bigquery.connection.v1.CreateConnectionRequest other) { if (other == com.google.cloud.bigquery.connection.v1.CreateConnectionRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getConnectionId().isEmpty()) { connectionId_ = other.connectionId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasConnection()) { mergeConnection(other.getConnection()); } 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: { connectionId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getConnectionFieldBuilder().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. Parent resource name. * Must be in the format `projects/{project_id}/locations/{location_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Parent resource name. * Must be in the format `projects/{project_id}/locations/{location_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Parent resource name. * Must be in the format `projects/{project_id}/locations/{location_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Parent resource name. * Must be in the format `projects/{project_id}/locations/{location_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. Parent resource name. * Must be in the format `projects/{project_id}/locations/{location_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object connectionId_ = ""; /** * * * <pre> * Optional. Connection id that should be assigned to the created connection. * </pre> * * <code>string connection_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The connectionId. */ public java.lang.String getConnectionId() { java.lang.Object ref = connectionId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); connectionId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Connection id that should be assigned to the created connection. * </pre> * * <code>string connection_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for connectionId. */ public com.google.protobuf.ByteString getConnectionIdBytes() { java.lang.Object ref = connectionId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); connectionId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Connection id that should be assigned to the created connection. * </pre> * * <code>string connection_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The connectionId to set. * @return This builder for chaining. */ public Builder setConnectionId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } connectionId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Connection id that should be assigned to the created connection. * </pre> * * <code>string connection_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearConnectionId() { connectionId_ = getDefaultInstance().getConnectionId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Optional. Connection id that should be assigned to the created connection. * </pre> * * <code>string connection_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for connectionId to set. * @return This builder for chaining. */ public Builder setConnectionIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); connectionId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.bigquery.connection.v1.Connection connection_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.connection.v1.Connection, com.google.cloud.bigquery.connection.v1.Connection.Builder, com.google.cloud.bigquery.connection.v1.ConnectionOrBuilder> connectionBuilder_; /** * * * <pre> * Required. Connection to create. * </pre> * * <code> * .google.cloud.bigquery.connection.v1.Connection connection = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the connection field is set. */ public boolean hasConnection() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. Connection to create. * </pre> * * <code> * .google.cloud.bigquery.connection.v1.Connection connection = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The connection. */ public com.google.cloud.bigquery.connection.v1.Connection getConnection() { if (connectionBuilder_ == null) { return connection_ == null ? com.google.cloud.bigquery.connection.v1.Connection.getDefaultInstance() : connection_; } else { return connectionBuilder_.getMessage(); } } /** * * * <pre> * Required. Connection to create. * </pre> * * <code> * .google.cloud.bigquery.connection.v1.Connection connection = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setConnection(com.google.cloud.bigquery.connection.v1.Connection value) { if (connectionBuilder_ == null) { if (value == null) { throw new NullPointerException(); } connection_ = value; } else { connectionBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. Connection to create. * </pre> * * <code> * .google.cloud.bigquery.connection.v1.Connection connection = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setConnection( com.google.cloud.bigquery.connection.v1.Connection.Builder builderForValue) { if (connectionBuilder_ == null) { connection_ = builderForValue.build(); } else { connectionBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. Connection to create. * </pre> * * <code> * .google.cloud.bigquery.connection.v1.Connection connection = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeConnection(com.google.cloud.bigquery.connection.v1.Connection value) { if (connectionBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && connection_ != null && connection_ != com.google.cloud.bigquery.connection.v1.Connection.getDefaultInstance()) { getConnectionBuilder().mergeFrom(value); } else { connection_ = value; } } else { connectionBuilder_.mergeFrom(value); } if (connection_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. Connection to create. * </pre> * * <code> * .google.cloud.bigquery.connection.v1.Connection connection = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearConnection() { bitField0_ = (bitField0_ & ~0x00000004); connection_ = null; if (connectionBuilder_ != null) { connectionBuilder_.dispose(); connectionBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. Connection to create. * </pre> * * <code> * .google.cloud.bigquery.connection.v1.Connection connection = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.bigquery.connection.v1.Connection.Builder getConnectionBuilder() { bitField0_ |= 0x00000004; onChanged(); return getConnectionFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Connection to create. * </pre> * * <code> * .google.cloud.bigquery.connection.v1.Connection connection = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.bigquery.connection.v1.ConnectionOrBuilder getConnectionOrBuilder() { if (connectionBuilder_ != null) { return connectionBuilder_.getMessageOrBuilder(); } else { return connection_ == null ? com.google.cloud.bigquery.connection.v1.Connection.getDefaultInstance() : connection_; } } /** * * * <pre> * Required. Connection to create. * </pre> * * <code> * .google.cloud.bigquery.connection.v1.Connection connection = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.connection.v1.Connection, com.google.cloud.bigquery.connection.v1.Connection.Builder, com.google.cloud.bigquery.connection.v1.ConnectionOrBuilder> getConnectionFieldBuilder() { if (connectionBuilder_ == null) { connectionBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.connection.v1.Connection, com.google.cloud.bigquery.connection.v1.Connection.Builder, com.google.cloud.bigquery.connection.v1.ConnectionOrBuilder>( getConnection(), getParentForChildren(), isClean()); connection_ = null; } return connectionBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.bigquery.connection.v1.CreateConnectionRequest) } // @@protoc_insertion_point(class_scope:google.cloud.bigquery.connection.v1.CreateConnectionRequest) private static final com.google.cloud.bigquery.connection.v1.CreateConnectionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.bigquery.connection.v1.CreateConnectionRequest(); } public static com.google.cloud.bigquery.connection.v1.CreateConnectionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateConnectionRequest> PARSER = new com.google.protobuf.AbstractParser<CreateConnectionRequest>() { @java.lang.Override public CreateConnectionRequest 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<CreateConnectionRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateConnectionRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.bigquery.connection.v1.CreateConnectionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,346
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/AddExecutionEventsRequest.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/metadata_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1beta1; /** * * * <pre> * Request message for * [MetadataService.AddExecutionEvents][google.cloud.aiplatform.v1beta1.MetadataService.AddExecutionEvents]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest} */ public final class AddExecutionEventsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest) AddExecutionEventsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use AddExecutionEventsRequest.newBuilder() to construct. private AddExecutionEventsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AddExecutionEventsRequest() { execution_ = ""; events_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new AddExecutionEventsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_AddExecutionEventsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_AddExecutionEventsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest.class, com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest.Builder.class); } public static final int EXECUTION_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object execution_ = ""; /** * * * <pre> * Required. The resource name of the Execution that the Events connect * Artifacts with. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}/executions/{execution}` * </pre> * * <code> * string execution = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The execution. */ @java.lang.Override public java.lang.String getExecution() { java.lang.Object ref = execution_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); execution_ = s; return s; } } /** * * * <pre> * Required. The resource name of the Execution that the Events connect * Artifacts with. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}/executions/{execution}` * </pre> * * <code> * string execution = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for execution. */ @java.lang.Override public com.google.protobuf.ByteString getExecutionBytes() { java.lang.Object ref = execution_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); execution_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int EVENTS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private java.util.List<com.google.cloud.aiplatform.v1beta1.Event> events_; /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ @java.lang.Override public java.util.List<com.google.cloud.aiplatform.v1beta1.Event> getEventsList() { return events_; } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.EventOrBuilder> getEventsOrBuilderList() { return events_; } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ @java.lang.Override public int getEventsCount() { return events_.size(); } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.Event getEvents(int index) { return events_.get(index); } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.EventOrBuilder getEventsOrBuilder(int index) { return events_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(execution_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, execution_); } for (int i = 0; i < events_.size(); i++) { output.writeMessage(2, events_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(execution_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, execution_); } for (int i = 0; i < events_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, events_.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.AddExecutionEventsRequest)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest other = (com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest) obj; if (!getExecution().equals(other.getExecution())) return false; if (!getEventsList().equals(other.getEventsList())) 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) + EXECUTION_FIELD_NUMBER; hash = (53 * hash) + getExecution().hashCode(); if (getEventsCount() > 0) { hash = (37 * hash) + EVENTS_FIELD_NUMBER; hash = (53 * hash) + getEventsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest 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.AddExecutionEventsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest 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.AddExecutionEventsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest 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.AddExecutionEventsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest 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.AddExecutionEventsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest 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.AddExecutionEventsRequest 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.AddExecutionEventsRequest 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.AddExecutionEventsRequest 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 * [MetadataService.AddExecutionEvents][google.cloud.aiplatform.v1beta1.MetadataService.AddExecutionEvents]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest) com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_AddExecutionEventsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_AddExecutionEventsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest.class, com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest.Builder.class); } // Construct using com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; execution_ = ""; if (eventsBuilder_ == null) { events_ = java.util.Collections.emptyList(); } else { events_ = null; eventsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_AddExecutionEventsRequest_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest build() { com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest buildPartial() { com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest result = new com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest result) { if (eventsBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { events_ = java.util.Collections.unmodifiableList(events_); bitField0_ = (bitField0_ & ~0x00000002); } result.events_ = events_; } else { result.events_ = eventsBuilder_.build(); } } private void buildPartial0( com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.execution_ = execution_; } } @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.AddExecutionEventsRequest) { return mergeFrom((com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest other) { if (other == com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest.getDefaultInstance()) return this; if (!other.getExecution().isEmpty()) { execution_ = other.execution_; bitField0_ |= 0x00000001; onChanged(); } if (eventsBuilder_ == null) { if (!other.events_.isEmpty()) { if (events_.isEmpty()) { events_ = other.events_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureEventsIsMutable(); events_.addAll(other.events_); } onChanged(); } } else { if (!other.events_.isEmpty()) { if (eventsBuilder_.isEmpty()) { eventsBuilder_.dispose(); eventsBuilder_ = null; events_ = other.events_; bitField0_ = (bitField0_ & ~0x00000002); eventsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getEventsFieldBuilder() : null; } else { eventsBuilder_.addAllMessages(other.events_); } } } 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: { execution_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { com.google.cloud.aiplatform.v1beta1.Event m = input.readMessage( com.google.cloud.aiplatform.v1beta1.Event.parser(), extensionRegistry); if (eventsBuilder_ == null) { ensureEventsIsMutable(); events_.add(m); } else { eventsBuilder_.addMessage(m); } break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object execution_ = ""; /** * * * <pre> * Required. The resource name of the Execution that the Events connect * Artifacts with. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}/executions/{execution}` * </pre> * * <code> * string execution = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The execution. */ public java.lang.String getExecution() { java.lang.Object ref = execution_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); execution_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The resource name of the Execution that the Events connect * Artifacts with. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}/executions/{execution}` * </pre> * * <code> * string execution = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for execution. */ public com.google.protobuf.ByteString getExecutionBytes() { java.lang.Object ref = execution_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); execution_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The resource name of the Execution that the Events connect * Artifacts with. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}/executions/{execution}` * </pre> * * <code> * string execution = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The execution to set. * @return This builder for chaining. */ public Builder setExecution(java.lang.String value) { if (value == null) { throw new NullPointerException(); } execution_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The resource name of the Execution that the Events connect * Artifacts with. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}/executions/{execution}` * </pre> * * <code> * string execution = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearExecution() { execution_ = getDefaultInstance().getExecution(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The resource name of the Execution that the Events connect * Artifacts with. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}/executions/{execution}` * </pre> * * <code> * string execution = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for execution to set. * @return This builder for chaining. */ public Builder setExecutionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); execution_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.util.List<com.google.cloud.aiplatform.v1beta1.Event> events_ = java.util.Collections.emptyList(); private void ensureEventsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { events_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.Event>(events_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.Event, com.google.cloud.aiplatform.v1beta1.Event.Builder, com.google.cloud.aiplatform.v1beta1.EventOrBuilder> eventsBuilder_; /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.Event> getEventsList() { if (eventsBuilder_ == null) { return java.util.Collections.unmodifiableList(events_); } else { return eventsBuilder_.getMessageList(); } } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public int getEventsCount() { if (eventsBuilder_ == null) { return events_.size(); } else { return eventsBuilder_.getCount(); } } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public com.google.cloud.aiplatform.v1beta1.Event getEvents(int index) { if (eventsBuilder_ == null) { return events_.get(index); } else { return eventsBuilder_.getMessage(index); } } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public Builder setEvents(int index, com.google.cloud.aiplatform.v1beta1.Event value) { if (eventsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEventsIsMutable(); events_.set(index, value); onChanged(); } else { eventsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public Builder setEvents( int index, com.google.cloud.aiplatform.v1beta1.Event.Builder builderForValue) { if (eventsBuilder_ == null) { ensureEventsIsMutable(); events_.set(index, builderForValue.build()); onChanged(); } else { eventsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public Builder addEvents(com.google.cloud.aiplatform.v1beta1.Event value) { if (eventsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEventsIsMutable(); events_.add(value); onChanged(); } else { eventsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public Builder addEvents(int index, com.google.cloud.aiplatform.v1beta1.Event value) { if (eventsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEventsIsMutable(); events_.add(index, value); onChanged(); } else { eventsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public Builder addEvents(com.google.cloud.aiplatform.v1beta1.Event.Builder builderForValue) { if (eventsBuilder_ == null) { ensureEventsIsMutable(); events_.add(builderForValue.build()); onChanged(); } else { eventsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public Builder addEvents( int index, com.google.cloud.aiplatform.v1beta1.Event.Builder builderForValue) { if (eventsBuilder_ == null) { ensureEventsIsMutable(); events_.add(index, builderForValue.build()); onChanged(); } else { eventsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public Builder addAllEvents( java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.Event> values) { if (eventsBuilder_ == null) { ensureEventsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, events_); onChanged(); } else { eventsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public Builder clearEvents() { if (eventsBuilder_ == null) { events_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { eventsBuilder_.clear(); } return this; } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public Builder removeEvents(int index) { if (eventsBuilder_ == null) { ensureEventsIsMutable(); events_.remove(index); onChanged(); } else { eventsBuilder_.remove(index); } return this; } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public com.google.cloud.aiplatform.v1beta1.Event.Builder getEventsBuilder(int index) { return getEventsFieldBuilder().getBuilder(index); } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public com.google.cloud.aiplatform.v1beta1.EventOrBuilder getEventsOrBuilder(int index) { if (eventsBuilder_ == null) { return events_.get(index); } else { return eventsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.EventOrBuilder> getEventsOrBuilderList() { if (eventsBuilder_ != null) { return eventsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(events_); } } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public com.google.cloud.aiplatform.v1beta1.Event.Builder addEventsBuilder() { return getEventsFieldBuilder() .addBuilder(com.google.cloud.aiplatform.v1beta1.Event.getDefaultInstance()); } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public com.google.cloud.aiplatform.v1beta1.Event.Builder addEventsBuilder(int index) { return getEventsFieldBuilder() .addBuilder(index, com.google.cloud.aiplatform.v1beta1.Event.getDefaultInstance()); } /** * * * <pre> * The Events to create and add. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Event events = 2;</code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.Event.Builder> getEventsBuilderList() { return getEventsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.Event, com.google.cloud.aiplatform.v1beta1.Event.Builder, com.google.cloud.aiplatform.v1beta1.EventOrBuilder> getEventsFieldBuilder() { if (eventsBuilder_ == null) { eventsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.Event, com.google.cloud.aiplatform.v1beta1.Event.Builder, com.google.cloud.aiplatform.v1beta1.EventOrBuilder>( events_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); events_ = null; } return eventsBuilder_; } @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.AddExecutionEventsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest) private static final com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest(); } public static com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AddExecutionEventsRequest> PARSER = new com.google.protobuf.AbstractParser<AddExecutionEventsRequest>() { @java.lang.Override public AddExecutionEventsRequest 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<AddExecutionEventsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AddExecutionEventsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.AddExecutionEventsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hbase
37,533
hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/SimpleRegionObserver.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.coprocessor; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; 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.CompareOperator; import org.apache.hadoop.hbase.CoprocessorEnvironment; import org.apache.hadoop.hbase.KeepDeletedCells; import org.apache.hadoop.hbase.client.Append; import org.apache.hadoop.hbase.client.CheckAndMutate; import org.apache.hadoop.hbase.client.CheckAndMutateResult; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Durability; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Increment; import org.apache.hadoop.hbase.client.Mutation; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.RegionInfo; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.ByteArrayComparable; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.io.FSDataInputStreamWrapper; import org.apache.hadoop.hbase.io.Reference; import org.apache.hadoop.hbase.io.hfile.CacheConfig; import org.apache.hadoop.hbase.regionserver.FlushLifeCycleTracker; import org.apache.hadoop.hbase.regionserver.InternalScanner; import org.apache.hadoop.hbase.regionserver.MiniBatchOperationInProgress; import org.apache.hadoop.hbase.regionserver.Region.Operation; import org.apache.hadoop.hbase.regionserver.RegionScanner; import org.apache.hadoop.hbase.regionserver.ScanOptions; import org.apache.hadoop.hbase.regionserver.ScanType; import org.apache.hadoop.hbase.regionserver.Store; import org.apache.hadoop.hbase.regionserver.StoreFile; import org.apache.hadoop.hbase.regionserver.StoreFileReader; import org.apache.hadoop.hbase.regionserver.compactions.CompactionLifeCycleTracker; import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Pair; import org.apache.hadoop.hbase.wal.WALEdit; import org.apache.hadoop.hbase.wal.WALKey; /** * A sample region observer that tests the RegionObserver interface. It works with * TestRegionObserverInterface to provide the test case. */ public class SimpleRegionObserver implements RegionCoprocessor, RegionObserver { final AtomicInteger ctBeforeDelete = new AtomicInteger(1); final AtomicInteger ctPreOpen = new AtomicInteger(0); final AtomicInteger ctPostOpen = new AtomicInteger(0); final AtomicInteger ctPreClose = new AtomicInteger(0); final AtomicInteger ctPostClose = new AtomicInteger(0); final AtomicInteger ctPreFlush = new AtomicInteger(0); final AtomicInteger ctPostFlush = new AtomicInteger(0); final AtomicInteger ctPreCompactSelect = new AtomicInteger(0); final AtomicInteger ctPostCompactSelect = new AtomicInteger(0); final AtomicInteger ctPreCompact = new AtomicInteger(0); final AtomicInteger ctPostCompact = new AtomicInteger(0); final AtomicInteger ctPreGet = new AtomicInteger(0); final AtomicInteger ctPostGet = new AtomicInteger(0); final AtomicInteger ctPrePut = new AtomicInteger(0); final AtomicInteger ctPostPut = new AtomicInteger(0); final AtomicInteger ctPreDeleted = new AtomicInteger(0); final AtomicInteger ctPrePrepareDeleteTS = new AtomicInteger(0); final AtomicInteger ctPostDeleted = new AtomicInteger(0); final AtomicInteger ctPreIncrement = new AtomicInteger(0); final AtomicInteger ctPreIncrementAfterRowLock = new AtomicInteger(0); final AtomicInteger ctPreAppend = new AtomicInteger(0); final AtomicInteger ctPreAppendAfterRowLock = new AtomicInteger(0); final AtomicInteger ctPostIncrement = new AtomicInteger(0); final AtomicInteger ctPostAppend = new AtomicInteger(0); final AtomicInteger ctPreCheckAndPut = new AtomicInteger(0); final AtomicInteger ctPreCheckAndPutWithFilter = new AtomicInteger(0); final AtomicInteger ctPreCheckAndPutAfterRowLock = new AtomicInteger(0); final AtomicInteger ctPreCheckAndPutWithFilterAfterRowLock = new AtomicInteger(0); final AtomicInteger ctPostCheckAndPut = new AtomicInteger(0); final AtomicInteger ctPostCheckAndPutWithFilter = new AtomicInteger(0); final AtomicInteger ctPreCheckAndDelete = new AtomicInteger(0); final AtomicInteger ctPreCheckAndDeleteWithFilter = new AtomicInteger(0); final AtomicInteger ctPreCheckAndDeleteAfterRowLock = new AtomicInteger(0); final AtomicInteger ctPreCheckAndDeleteWithFilterAfterRowLock = new AtomicInteger(0); final AtomicInteger ctPostCheckAndDelete = new AtomicInteger(0); final AtomicInteger ctPostCheckAndDeleteWithFilter = new AtomicInteger(0); final AtomicInteger ctPreCheckAndMutate = new AtomicInteger(0); final AtomicInteger ctPreCheckAndMutateAfterRowLock = new AtomicInteger(0); final AtomicInteger ctPostCheckAndMutate = new AtomicInteger(0); final AtomicInteger ctPreScannerNext = new AtomicInteger(0); final AtomicInteger ctPostScannerNext = new AtomicInteger(0); final AtomicInteger ctPostScannerFilterRow = new AtomicInteger(0); final AtomicInteger ctPreScannerClose = new AtomicInteger(0); final AtomicInteger ctPostScannerClose = new AtomicInteger(0); final AtomicInteger ctPreScannerOpen = new AtomicInteger(0); final AtomicInteger ctPostScannerOpen = new AtomicInteger(0); final AtomicInteger ctPreBulkLoadHFile = new AtomicInteger(0); final AtomicInteger ctPostBulkLoadHFile = new AtomicInteger(0); final AtomicInteger ctPreBatchMutate = new AtomicInteger(0); final AtomicInteger ctPostBatchMutate = new AtomicInteger(0); final AtomicInteger ctPreReplayWALs = new AtomicInteger(0); final AtomicInteger ctPostReplayWALs = new AtomicInteger(0); final AtomicInteger ctPreWALRestore = new AtomicInteger(0); final AtomicInteger ctPostWALRestore = new AtomicInteger(0); final AtomicInteger ctPreStoreFileReaderOpen = new AtomicInteger(0); final AtomicInteger ctPostStoreFileReaderOpen = new AtomicInteger(0); final AtomicInteger ctPostBatchMutateIndispensably = new AtomicInteger(0); final AtomicInteger ctPostStartRegionOperation = new AtomicInteger(0); final AtomicInteger ctPostCloseRegionOperation = new AtomicInteger(0); final AtomicBoolean throwOnPostFlush = new AtomicBoolean(false); final AtomicInteger ctPreWALAppend = new AtomicInteger(0); static final String TABLE_SKIPPED = "SKIPPED_BY_PREWALRESTORE"; Map<String, byte[]> extendedAttributes = new HashMap<String, byte[]>(); static final byte[] WAL_EXTENDED_ATTRIBUTE_BYTES = Bytes.toBytes("foo"); public void setThrowOnPostFlush(Boolean val) { throwOnPostFlush.set(val); } @Override public Optional<RegionObserver> getRegionObserver() { return Optional.of(this); } @Override public void start(CoprocessorEnvironment e) throws IOException { } @Override public void preOpen(ObserverContext<? extends RegionCoprocessorEnvironment> c) { ctPreOpen.incrementAndGet(); } @Override public void postOpen(ObserverContext<? extends RegionCoprocessorEnvironment> c) { ctPostOpen.incrementAndGet(); } public boolean wasOpened() { return ctPreOpen.get() > 0 && ctPostOpen.get() > 0; } @Override public void preClose(ObserverContext<? extends RegionCoprocessorEnvironment> c, boolean abortRequested) { ctPreClose.incrementAndGet(); } @Override public void postClose(ObserverContext<? extends RegionCoprocessorEnvironment> c, boolean abortRequested) { ctPostClose.incrementAndGet(); } public boolean wasClosed() { return ctPreClose.get() > 0 && ctPostClose.get() > 0; } @Override public InternalScanner preFlush(ObserverContext<? extends RegionCoprocessorEnvironment> c, Store store, InternalScanner scanner, FlushLifeCycleTracker tracker) throws IOException { ctPreFlush.incrementAndGet(); return scanner; } @Override public void postFlush(ObserverContext<? extends RegionCoprocessorEnvironment> c, Store store, StoreFile resultFile, FlushLifeCycleTracker tracker) throws IOException { ctPostFlush.incrementAndGet(); if (throwOnPostFlush.get()) { throw new IOException("throwOnPostFlush is true in postFlush"); } } public boolean wasFlushed() { return ctPreFlush.get() > 0 && ctPostFlush.get() > 0; } @Override public void preCompactSelection(ObserverContext<? extends RegionCoprocessorEnvironment> c, Store store, List<? extends StoreFile> candidates, CompactionLifeCycleTracker tracker) throws IOException { ctPreCompactSelect.incrementAndGet(); } @Override public void postCompactSelection(ObserverContext<? extends RegionCoprocessorEnvironment> c, Store store, List<? extends StoreFile> selected, CompactionLifeCycleTracker tracker, CompactionRequest request) { ctPostCompactSelect.incrementAndGet(); } @Override public InternalScanner preCompact(ObserverContext<? extends RegionCoprocessorEnvironment> c, Store store, InternalScanner scanner, ScanType scanType, CompactionLifeCycleTracker tracker, CompactionRequest request) throws IOException { ctPreCompact.incrementAndGet(); return scanner; } @Override public void postCompact(ObserverContext<? extends RegionCoprocessorEnvironment> c, Store store, StoreFile resultFile, CompactionLifeCycleTracker tracker, CompactionRequest request) throws IOException { ctPostCompact.incrementAndGet(); } public boolean wasCompacted() { return ctPreCompact.get() > 0 && ctPostCompact.get() > 0; } @Override public void preScannerOpen(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final Scan scan) throws IOException { ctPreScannerOpen.incrementAndGet(); } @Override public RegionScanner postScannerOpen( final ObserverContext<? extends RegionCoprocessorEnvironment> c, final Scan scan, final RegionScanner s) throws IOException { ctPostScannerOpen.incrementAndGet(); return s; } @Override public boolean preScannerNext(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final InternalScanner s, final List<Result> results, final int limit, final boolean hasMore) throws IOException { ctPreScannerNext.incrementAndGet(); return hasMore; } @Override public boolean postScannerNext(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final InternalScanner s, final List<Result> results, final int limit, final boolean hasMore) throws IOException { ctPostScannerNext.incrementAndGet(); return hasMore; } @Override public boolean postScannerFilterRow( final ObserverContext<? extends RegionCoprocessorEnvironment> e, final InternalScanner s, final Cell currentRow, final boolean hasMore) throws IOException { ctPostScannerFilterRow.incrementAndGet(); return hasMore; } @Override public void preScannerClose(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final InternalScanner s) throws IOException { ctPreScannerClose.incrementAndGet(); } @Override public void postScannerClose(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final InternalScanner s) throws IOException { ctPostScannerClose.incrementAndGet(); } @Override public void preGetOp(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final Get get, final List<Cell> results) throws IOException { RegionCoprocessorEnvironment e = c.getEnvironment(); assertNotNull(e); assertNotNull(e.getRegion()); assertNotNull(get); assertNotNull(results); ctPreGet.incrementAndGet(); } @Override public void postGetOp(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final Get get, final List<Cell> results) { RegionCoprocessorEnvironment e = c.getEnvironment(); assertNotNull(e); assertNotNull(e.getRegion()); assertNotNull(get); assertNotNull(results); if ( e.getRegion().getTableDescriptor().getTableName() .equals(TestRegionObserverInterface.TEST_TABLE) ) { boolean foundA = false; boolean foundB = false; boolean foundC = false; for (Cell kv : results) { if (CellUtil.matchingFamily(kv, TestRegionObserverInterface.A)) { foundA = true; } if (CellUtil.matchingFamily(kv, TestRegionObserverInterface.B)) { foundB = true; } if (CellUtil.matchingFamily(kv, TestRegionObserverInterface.C)) { foundC = true; } } assertTrue(foundA); assertTrue(foundB); assertTrue(foundC); } ctPostGet.incrementAndGet(); } @Override public void prePut(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final Put put, final WALEdit edit, final Durability durability) throws IOException { Map<byte[], List<Cell>> familyMap = put.getFamilyCellMap(); RegionCoprocessorEnvironment e = c.getEnvironment(); assertNotNull(e); assertNotNull(e.getRegion()); assertNotNull(familyMap); if ( e.getRegion().getTableDescriptor().getTableName() .equals(TestRegionObserverInterface.TEST_TABLE) ) { List<Cell> cells = familyMap.get(TestRegionObserverInterface.A); assertNotNull(cells); assertNotNull(cells.get(0)); Cell cell = cells.get(0); assertTrue( Bytes.equals(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(), TestRegionObserverInterface.A, 0, TestRegionObserverInterface.A.length)); cells = familyMap.get(TestRegionObserverInterface.B); assertNotNull(cells); assertNotNull(cells.get(0)); cell = cells.get(0); assertTrue( Bytes.equals(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(), TestRegionObserverInterface.B, 0, TestRegionObserverInterface.B.length)); cells = familyMap.get(TestRegionObserverInterface.C); assertNotNull(cells); assertNotNull(cells.get(0)); cell = cells.get(0); assertTrue( Bytes.equals(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(), TestRegionObserverInterface.C, 0, TestRegionObserverInterface.C.length)); } ctPrePut.incrementAndGet(); } @Override public void postPut(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final Put put, final WALEdit edit, final Durability durability) throws IOException { Map<byte[], List<Cell>> familyMap = put.getFamilyCellMap(); RegionCoprocessorEnvironment e = c.getEnvironment(); assertNotNull(e); assertNotNull(e.getRegion()); assertNotNull(familyMap); List<Cell> cells = familyMap.get(TestRegionObserverInterface.A); if ( e.getRegion().getTableDescriptor().getTableName() .equals(TestRegionObserverInterface.TEST_TABLE) ) { assertNotNull(cells); assertNotNull(cells.get(0)); // KeyValue v1 expectation. Cast for now until we go all Cell all the time. TODO Cell cell = cells.get(0); assertTrue( Bytes.equals(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(), TestRegionObserverInterface.A, 0, TestRegionObserverInterface.A.length)); cells = familyMap.get(TestRegionObserverInterface.B); assertNotNull(cells); assertNotNull(cells.get(0)); // KeyValue v1 expectation. Cast for now until we go all Cell all the time. TODO cell = cells.get(0); assertTrue( Bytes.equals(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(), TestRegionObserverInterface.B, 0, TestRegionObserverInterface.B.length)); cells = familyMap.get(TestRegionObserverInterface.C); assertNotNull(cells); assertNotNull(cells.get(0)); // KeyValue v1 expectation. Cast for now until we go all Cell all the time. TODO cell = cells.get(0); assertTrue( Bytes.equals(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(), TestRegionObserverInterface.C, 0, TestRegionObserverInterface.C.length)); } ctPostPut.incrementAndGet(); } @Override public void preDelete(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final Delete delete, final WALEdit edit, final Durability durability) throws IOException { Map<byte[], List<Cell>> familyMap = delete.getFamilyCellMap(); RegionCoprocessorEnvironment e = c.getEnvironment(); assertNotNull(e); assertNotNull(e.getRegion()); assertNotNull(familyMap); if (ctBeforeDelete.get() > 0) { ctPreDeleted.incrementAndGet(); } } @Override public void prePrepareTimeStampForDeleteVersion( ObserverContext<? extends RegionCoprocessorEnvironment> e, Mutation delete, Cell cell, byte[] byteNow, Get get) throws IOException { ctPrePrepareDeleteTS.incrementAndGet(); } @Override public void postDelete(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final Delete delete, final WALEdit edit, final Durability durability) throws IOException { Map<byte[], List<Cell>> familyMap = delete.getFamilyCellMap(); RegionCoprocessorEnvironment e = c.getEnvironment(); assertNotNull(e); assertNotNull(e.getRegion()); assertNotNull(familyMap); ctBeforeDelete.set(0); ctPostDeleted.incrementAndGet(); } @Override public void preBatchMutate(ObserverContext<? extends RegionCoprocessorEnvironment> c, MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException { RegionCoprocessorEnvironment e = c.getEnvironment(); assertNotNull(e); assertNotNull(e.getRegion()); assertNotNull(miniBatchOp); ctPreBatchMutate.incrementAndGet(); } @Override public void postBatchMutate(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException { RegionCoprocessorEnvironment e = c.getEnvironment(); assertNotNull(e); assertNotNull(e.getRegion()); assertNotNull(miniBatchOp); ctPostBatchMutate.incrementAndGet(); } @Override public void postStartRegionOperation( final ObserverContext<? extends RegionCoprocessorEnvironment> ctx, Operation op) throws IOException { ctPostStartRegionOperation.incrementAndGet(); } @Override public void postCloseRegionOperation( final ObserverContext<? extends RegionCoprocessorEnvironment> ctx, Operation op) throws IOException { if (ctPostStartRegionOperation.get() > 0) { ctPostCloseRegionOperation.incrementAndGet(); } } @Override public void postBatchMutateIndispensably( final ObserverContext<? extends RegionCoprocessorEnvironment> ctx, MiniBatchOperationInProgress<Mutation> miniBatchOp, final boolean success) throws IOException { ctPostBatchMutateIndispensably.incrementAndGet(); } @Override public Result preIncrement(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final Increment increment) throws IOException { ctPreIncrement.incrementAndGet(); return null; } @Override public Result preIncrementAfterRowLock(ObserverContext<? extends RegionCoprocessorEnvironment> e, Increment increment) throws IOException { ctPreIncrementAfterRowLock.incrementAndGet(); return null; } @Override public Result postIncrement(final ObserverContext<? extends RegionCoprocessorEnvironment> c, final Increment increment, final Result result) throws IOException { ctPostIncrement.incrementAndGet(); return result; } @Override public boolean preCheckAndPut(ObserverContext<? extends RegionCoprocessorEnvironment> e, byte[] row, byte[] family, byte[] qualifier, CompareOperator compareOp, ByteArrayComparable comparator, Put put, boolean result) throws IOException { ctPreCheckAndPut.incrementAndGet(); return true; } @Override public boolean preCheckAndPut(ObserverContext<? extends RegionCoprocessorEnvironment> c, byte[] row, Filter filter, Put put, boolean result) throws IOException { ctPreCheckAndPutWithFilter.incrementAndGet(); return true; } @Override public boolean preCheckAndPutAfterRowLock( ObserverContext<? extends RegionCoprocessorEnvironment> e, byte[] row, byte[] family, byte[] qualifier, CompareOperator compareOp, ByteArrayComparable comparator, Put put, boolean result) throws IOException { ctPreCheckAndPutAfterRowLock.incrementAndGet(); return true; } @Override public boolean preCheckAndPutAfterRowLock( ObserverContext<? extends RegionCoprocessorEnvironment> c, byte[] row, Filter filter, Put put, boolean result) throws IOException { ctPreCheckAndPutWithFilterAfterRowLock.incrementAndGet(); return true; } @Override public boolean postCheckAndPut(ObserverContext<? extends RegionCoprocessorEnvironment> e, byte[] row, byte[] family, byte[] qualifier, CompareOperator compareOp, ByteArrayComparable comparator, Put put, boolean result) throws IOException { ctPostCheckAndPut.incrementAndGet(); return true; } @Override public boolean postCheckAndPut(ObserverContext<? extends RegionCoprocessorEnvironment> c, byte[] row, Filter filter, Put put, boolean result) throws IOException { ctPostCheckAndPutWithFilter.incrementAndGet(); return true; } @Override public boolean preCheckAndDelete(ObserverContext<? extends RegionCoprocessorEnvironment> e, byte[] row, byte[] family, byte[] qualifier, CompareOperator compareOp, ByteArrayComparable comparator, Delete delete, boolean result) throws IOException { ctPreCheckAndDelete.incrementAndGet(); return true; } @Override public boolean preCheckAndDelete(ObserverContext<? extends RegionCoprocessorEnvironment> c, byte[] row, Filter filter, Delete delete, boolean result) throws IOException { ctPreCheckAndDeleteWithFilter.incrementAndGet(); return true; } @Override public boolean preCheckAndDeleteAfterRowLock( ObserverContext<? extends RegionCoprocessorEnvironment> e, byte[] row, byte[] family, byte[] qualifier, CompareOperator compareOp, ByteArrayComparable comparator, Delete delete, boolean result) throws IOException { ctPreCheckAndDeleteAfterRowLock.incrementAndGet(); return true; } @Override public boolean preCheckAndDeleteAfterRowLock( ObserverContext<? extends RegionCoprocessorEnvironment> c, byte[] row, Filter filter, Delete delete, boolean result) throws IOException { ctPreCheckAndDeleteWithFilterAfterRowLock.incrementAndGet(); return true; } @Override public boolean postCheckAndDelete(ObserverContext<? extends RegionCoprocessorEnvironment> e, byte[] row, byte[] family, byte[] qualifier, CompareOperator compareOp, ByteArrayComparable comparator, Delete delete, boolean result) throws IOException { ctPostCheckAndDelete.incrementAndGet(); return true; } @Override public boolean postCheckAndDelete(ObserverContext<? extends RegionCoprocessorEnvironment> e, byte[] row, Filter filter, Delete delete, boolean result) throws IOException { ctPostCheckAndDeleteWithFilter.incrementAndGet(); return true; } @Override public CheckAndMutateResult preCheckAndMutate( ObserverContext<? extends RegionCoprocessorEnvironment> c, CheckAndMutate checkAndMutate, CheckAndMutateResult result) throws IOException { ctPreCheckAndMutate.incrementAndGet(); return RegionObserver.super.preCheckAndMutate(c, checkAndMutate, result); } @Override public CheckAndMutateResult preCheckAndMutateAfterRowLock( ObserverContext<? extends RegionCoprocessorEnvironment> c, CheckAndMutate checkAndMutate, CheckAndMutateResult result) throws IOException { ctPreCheckAndMutateAfterRowLock.incrementAndGet(); return RegionObserver.super.preCheckAndMutateAfterRowLock(c, checkAndMutate, result); } @Override public CheckAndMutateResult postCheckAndMutate( ObserverContext<? extends RegionCoprocessorEnvironment> c, CheckAndMutate checkAndMutate, CheckAndMutateResult result) throws IOException { ctPostCheckAndMutate.incrementAndGet(); return RegionObserver.super.postCheckAndMutate(c, checkAndMutate, result); } @Override public Result preAppendAfterRowLock(ObserverContext<? extends RegionCoprocessorEnvironment> e, Append append) throws IOException { ctPreAppendAfterRowLock.incrementAndGet(); return null; } @Override public Result preAppend(ObserverContext<? extends RegionCoprocessorEnvironment> e, Append append) throws IOException { ctPreAppend.incrementAndGet(); return null; } @Override public Result postAppend(ObserverContext<? extends RegionCoprocessorEnvironment> e, Append append, Result result) throws IOException { ctPostAppend.incrementAndGet(); return null; } @Override public void preBulkLoadHFile(ObserverContext<? extends RegionCoprocessorEnvironment> ctx, List<Pair<byte[], String>> familyPaths) throws IOException { RegionCoprocessorEnvironment e = ctx.getEnvironment(); assertNotNull(e); assertNotNull(e.getRegion()); if ( e.getRegion().getTableDescriptor().getTableName() .equals(TestRegionObserverInterface.TEST_TABLE) ) { assertNotNull(familyPaths); assertEquals(1, familyPaths.size()); assertArrayEquals(TestRegionObserverInterface.A, familyPaths.get(0).getFirst()); String familyPath = familyPaths.get(0).getSecond(); String familyName = Bytes.toString(TestRegionObserverInterface.A); assertEquals(familyPath.substring(familyPath.length() - familyName.length() - 1), "/" + familyName); } ctPreBulkLoadHFile.incrementAndGet(); } @Override public void postBulkLoadHFile(ObserverContext<? extends RegionCoprocessorEnvironment> ctx, List<Pair<byte[], String>> familyPaths, Map<byte[], List<Path>> map) throws IOException { RegionCoprocessorEnvironment e = ctx.getEnvironment(); assertNotNull(e); assertNotNull(e.getRegion()); if ( e.getRegion().getTableDescriptor().getTableName() .equals(TestRegionObserverInterface.TEST_TABLE) ) { assertNotNull(familyPaths); assertEquals(1, familyPaths.size()); assertArrayEquals(TestRegionObserverInterface.A, familyPaths.get(0).getFirst()); String familyPath = familyPaths.get(0).getSecond(); String familyName = Bytes.toString(TestRegionObserverInterface.A); assertEquals(familyPath.substring(familyPath.length() - familyName.length() - 1), "/" + familyName); } ctPostBulkLoadHFile.incrementAndGet(); } @Override public void preReplayWALs(ObserverContext<? extends RegionCoprocessorEnvironment> env, RegionInfo info, Path edits) throws IOException { ctPreReplayWALs.incrementAndGet(); } @Override public void postReplayWALs(ObserverContext<? extends RegionCoprocessorEnvironment> env, RegionInfo info, Path edits) throws IOException { ctPostReplayWALs.incrementAndGet(); } @Override public void preWALRestore(ObserverContext<? extends RegionCoprocessorEnvironment> env, RegionInfo info, WALKey logKey, WALEdit logEdit) throws IOException { String tableName = logKey.getTableName().getNameAsString(); if (tableName.equals(TABLE_SKIPPED)) { // skip recovery of TABLE_SKIPPED for testing purpose env.bypass(); return; } ctPreWALRestore.incrementAndGet(); } @Override public void postWALRestore(ObserverContext<? extends RegionCoprocessorEnvironment> env, RegionInfo info, WALKey logKey, WALEdit logEdit) throws IOException { ctPostWALRestore.incrementAndGet(); } @Override public StoreFileReader preStoreFileReaderOpen( ObserverContext<? extends RegionCoprocessorEnvironment> ctx, FileSystem fs, Path p, FSDataInputStreamWrapper in, long size, CacheConfig cacheConf, Reference r, StoreFileReader reader) throws IOException { ctPreStoreFileReaderOpen.incrementAndGet(); return null; } @Override public StoreFileReader postStoreFileReaderOpen( ObserverContext<? extends RegionCoprocessorEnvironment> ctx, FileSystem fs, Path p, FSDataInputStreamWrapper in, long size, CacheConfig cacheConf, Reference r, StoreFileReader reader) throws IOException { ctPostStoreFileReaderOpen.incrementAndGet(); return reader; } @Override public void preStoreScannerOpen(ObserverContext<? extends RegionCoprocessorEnvironment> ctx, Store store, ScanOptions options) throws IOException { if (options.getScan().getTimeRange().isAllTime()) { setScanOptions(options); } } @Override public void preCompactScannerOpen(ObserverContext<? extends RegionCoprocessorEnvironment> c, Store store, ScanType scanType, ScanOptions options, CompactionLifeCycleTracker tracker, CompactionRequest request) throws IOException { setScanOptions(options); } public void preFlushScannerOpen(ObserverContext<? extends RegionCoprocessorEnvironment> c, Store store, ScanOptions options, FlushLifeCycleTracker tracker) throws IOException { setScanOptions(options); } public void preMemStoreCompactionCompactScannerOpen( ObserverContext<? extends RegionCoprocessorEnvironment> c, Store store, ScanOptions options) throws IOException { setScanOptions(options); } private void setScanOptions(ScanOptions options) { options.setMaxVersions(TestRegionCoprocessorHost.MAX_VERSIONS); options.setMinVersions(TestRegionCoprocessorHost.MIN_VERSIONS); options.setKeepDeletedCells(KeepDeletedCells.TRUE); options.setTTL(TestRegionCoprocessorHost.TTL); options.setTimeToPurgeDeletes(TestRegionCoprocessorHost.TIME_TO_PURGE_DELETES); } @Override public void preWALAppend(ObserverContext<? extends RegionCoprocessorEnvironment> ctx, WALKey key, WALEdit edit) throws IOException { ctPreWALAppend.incrementAndGet(); key.addExtendedAttribute(Integer.toString(ctPreWALAppend.get()), Bytes.toBytes("foo")); } public boolean hadPreGet() { return ctPreGet.get() > 0; } public boolean hadPostGet() { return ctPostGet.get() > 0; } public boolean hadPrePut() { return ctPrePut.get() > 0; } public boolean hadPostPut() { return ctPostPut.get() > 0; } public boolean hadPreBatchMutate() { return ctPreBatchMutate.get() > 0; } public int getPreBatchMutate() { return ctPreBatchMutate.get(); } public boolean hadPostBatchMutate() { return ctPostBatchMutate.get() > 0; } public int getPostBatchMutate() { return ctPostBatchMutate.get(); } public boolean hadPostBatchMutateIndispensably() { return ctPostBatchMutateIndispensably.get() > 0; } public int getPostBatchMutateIndispensably() { return ctPostBatchMutateIndispensably.get(); } public boolean hadPostStartRegionOperation() { return ctPostStartRegionOperation.get() > 0; } public boolean hadPostCloseRegionOperation() { return ctPostCloseRegionOperation.get() > 0; } public boolean hadDelete() { return !(ctBeforeDelete.get() > 0); } public int getCtPostStartRegionOperation() { return ctPostStartRegionOperation.get(); } public int getCtPostCloseRegionOperation() { return ctPostCloseRegionOperation.get(); } public int getPreCheckAndPut() { return ctPreCheckAndPut.get(); } public int getPreCheckAndPutWithFilter() { return ctPreCheckAndPutWithFilter.get(); } public int getPreCheckAndPutAfterRowLock() { return ctPreCheckAndPutAfterRowLock.get(); } public int getPreCheckAndPutWithFilterAfterRowLock() { return ctPreCheckAndPutWithFilterAfterRowLock.get(); } public int getPostCheckAndPut() { return ctPostCheckAndPut.get(); } public int getPostCheckAndPutWithFilter() { return ctPostCheckAndPutWithFilter.get(); } public int getPreCheckAndDelete() { return ctPreCheckAndDelete.get(); } public int getPreCheckAndDeleteWithFilter() { return ctPreCheckAndDeleteWithFilter.get(); } public int getPreCheckAndDeleteAfterRowLock() { return ctPreCheckAndDeleteAfterRowLock.get(); } public int getPreCheckAndDeleteWithFilterAfterRowLock() { return ctPreCheckAndDeleteWithFilterAfterRowLock.get(); } public int getPostCheckAndDelete() { return ctPostCheckAndDelete.get(); } public int getPostCheckAndDeleteWithFilter() { return ctPostCheckAndDeleteWithFilter.get(); } public int getPreCheckAndMutate() { return ctPreCheckAndMutate.get(); } public int getPreCheckAndMutateAfterRowLock() { return ctPreCheckAndMutateAfterRowLock.get(); } public int getPostCheckAndMutate() { return ctPostCheckAndMutate.get(); } public boolean hadPreIncrement() { return ctPreIncrement.get() > 0; } public boolean hadPreIncrementAfterRowLock() { return ctPreIncrementAfterRowLock.get() > 0; } public boolean hadPostIncrement() { return ctPostIncrement.get() > 0; } public boolean hadPreAppend() { return ctPreAppend.get() > 0; } public boolean hadPreAppendAfterRowLock() { return ctPreAppendAfterRowLock.get() > 0; } public boolean hadPostAppend() { return ctPostAppend.get() > 0; } public boolean hadPrePreparedDeleteTS() { return ctPrePrepareDeleteTS.get() > 0; } public boolean hadPreReplayWALs() { return ctPreReplayWALs.get() > 0; } public boolean hadPostReplayWALs() { return ctPostReplayWALs.get() > 0; } public boolean hadPreWALRestore() { return ctPreWALRestore.get() > 0; } public boolean hadPostWALRestore() { return ctPostWALRestore.get() > 0; } public boolean wasScannerNextCalled() { return ctPreScannerNext.get() > 0 && ctPostScannerNext.get() > 0; } public boolean wasScannerFilterRowCalled() { return ctPostScannerFilterRow.get() > 0; } public boolean wasScannerCloseCalled() { return ctPreScannerClose.get() > 0 && ctPostScannerClose.get() > 0; } public boolean wasScannerOpenCalled() { return ctPreScannerOpen.get() > 0 && ctPostScannerOpen.get() > 0; } public boolean hadDeleted() { return ctPreDeleted.get() > 0 && ctPostDeleted.get() > 0; } public boolean hadPostBulkLoadHFile() { return ctPostBulkLoadHFile.get() > 0; } public boolean hadPreBulkLoadHFile() { return ctPreBulkLoadHFile.get() > 0; } public int getCtBeforeDelete() { return ctBeforeDelete.get(); } public int getCtPreOpen() { return ctPreOpen.get(); } public int getCtPostOpen() { return ctPostOpen.get(); } public int getCtPreClose() { return ctPreClose.get(); } public int getCtPostClose() { return ctPostClose.get(); } public int getCtPreFlush() { return ctPreFlush.get(); } public int getCtPostFlush() { return ctPostFlush.get(); } public int getCtPreCompactSelect() { return ctPreCompactSelect.get(); } public int getCtPostCompactSelect() { return ctPostCompactSelect.get(); } public int getCtPreCompact() { return ctPreCompact.get(); } public int getCtPostCompact() { return ctPostCompact.get(); } public int getCtPreGet() { return ctPreGet.get(); } public int getCtPostGet() { return ctPostGet.get(); } public int getCtPrePut() { return ctPrePut.get(); } public int getCtPostPut() { return ctPostPut.get(); } public int getCtPreDeleted() { return ctPreDeleted.get(); } public int getCtPostDeleted() { return ctPostDeleted.get(); } public int getCtPreIncrement() { return ctPreIncrement.get(); } public int getCtPostIncrement() { return ctPostIncrement.get(); } public int getCtPreReplayWALs() { return ctPreReplayWALs.get(); } public int getCtPostReplayWALs() { return ctPostReplayWALs.get(); } public int getCtPreWALRestore() { return ctPreWALRestore.get(); } public int getCtPostWALRestore() { return ctPostWALRestore.get(); } public int getCtPreWALAppend() { return ctPreWALAppend.get(); } public boolean wasStoreFileReaderOpenCalled() { return ctPreStoreFileReaderOpen.get() > 0 && ctPostStoreFileReaderOpen.get() > 0; } }
apache/phoenix
37,767
phoenix-core-client/src/main/java/org/apache/phoenix/compile/SubqueryRewriter.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.compile; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Collections; import java.util.List; import org.apache.hadoop.hbase.CompareOperator; import org.apache.phoenix.exception.SQLExceptionCode; import org.apache.phoenix.exception.SQLExceptionInfo; import org.apache.phoenix.expression.function.DistinctValueAggregateFunction; import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.parse.AliasedNode; import org.apache.phoenix.parse.AndParseNode; import org.apache.phoenix.parse.AndRewriterBooleanParseNodeVisitor; import org.apache.phoenix.parse.ArrayAllComparisonNode; import org.apache.phoenix.parse.ArrayAnyComparisonNode; import org.apache.phoenix.parse.ColumnParseNode; import org.apache.phoenix.parse.ComparisonParseNode; import org.apache.phoenix.parse.CompoundParseNode; import org.apache.phoenix.parse.DerivedTableNode; import org.apache.phoenix.parse.ExistsParseNode; import org.apache.phoenix.parse.HintNode; import org.apache.phoenix.parse.InParseNode; import org.apache.phoenix.parse.JoinTableNode.JoinType; import org.apache.phoenix.parse.LiteralParseNode; import org.apache.phoenix.parse.OrderByNode; import org.apache.phoenix.parse.ParseNode; import org.apache.phoenix.parse.ParseNodeFactory; import org.apache.phoenix.parse.ParseNodeRewriter; import org.apache.phoenix.parse.RowValueConstructorParseNode; import org.apache.phoenix.parse.SelectStatement; import org.apache.phoenix.parse.StatelessTraverseAllParseNodeVisitor; import org.apache.phoenix.parse.SubqueryParseNode; import org.apache.phoenix.parse.TableName; import org.apache.phoenix.parse.TableNode; import org.apache.phoenix.schema.ColumnFamilyNotFoundException; import org.apache.phoenix.schema.ColumnNotFoundException; import org.apache.phoenix.schema.TableNotFoundException; import org.apache.phoenix.thirdparty.com.google.common.collect.Lists; /** * Class for rewriting where-clause sub-queries into join queries. If the where-clause sub-query is * one of those top-node conditions (being the only condition node or direct descendant of AND * nodes), we convert the sub-query directly into semi-joins, anti-joins or inner-joins, and * meanwhile remove the original condition node from the where clause. Otherwise, we convert the * sub-query into left-joins and change the original condition node into a null test of a join table * field (ONE if matched, NULL if not matched). */ public class SubqueryRewriter extends ParseNodeRewriter { private static final ParseNodeFactory NODE_FACTORY = new ParseNodeFactory(); private final ColumnResolver columnResolver; private final PhoenixConnection connection; private TableNode tableNode; private ParseNode topNode; public static SelectStatement transform(SelectStatement select, ColumnResolver resolver, PhoenixConnection connection) throws SQLException { ParseNode where = select.getWhere(); if (where == null) return select; SubqueryRewriter rewriter = new SubqueryRewriter(select, resolver, connection); ParseNode normWhere = rewrite(where, rewriter); if (normWhere == where) return select; return NODE_FACTORY.select(select, rewriter.tableNode, normWhere); } protected SubqueryRewriter(SelectStatement select, ColumnResolver resolver, PhoenixConnection connection) { this.columnResolver = resolver; this.connection = connection; this.tableNode = select.getFrom(); this.topNode = null; } @Override protected void enterParseNode(ParseNode node) { if (topNode == null) { topNode = node; } super.enterParseNode(node); } @Override protected ParseNode leaveCompoundNode(CompoundParseNode node, List<ParseNode> children, ParseNodeRewriter.CompoundNodeFactory factory) { if (topNode == node) { topNode = null; } return super.leaveCompoundNode(node, children, factory); } @Override public boolean visitEnter(AndParseNode node) throws SQLException { return true; } @Override public ParseNode visitLeave(AndParseNode node, List<ParseNode> l) throws SQLException { return leaveCompoundNode(node, l, new CompoundNodeFactory() { @Override public ParseNode createNode(List<ParseNode> children) { if (children.isEmpty()) { return null; } if (children.size() == 1) { return children.get(0); } return NODE_FACTORY.and(children); } }); } /** * <pre> * {@code * Rewrite the In Subquery to semi/anti/left join for both NonCorrelated and Correlated subquery. * * 1.If the {@link InParseNode} is the only node in where clause or is the ANDed part of the where clause, * then we would rewrite the In Subquery to semi/anti join: * For NonCorrelated subquery, an example is: * SELECT item_id, name FROM item i WHERE i.item_id IN * (SELECT item_id FROM order o where o.price > 8) * * The above sql would be rewritten as: * SELECT ITEM_ID,NAME FROM item I Semi JOIN * (SELECT DISTINCT 1 $35,ITEM_ID $36 FROM order O WHERE O.PRICE > 8) $34 * ON (I.ITEM_ID = $34.$36) * * For Correlated subquery, an example is: * SELECT item_id, name FROM item i WHERE i.item_id IN * (SELECT item_id FROM order o where o.price = i.price) * * The above sql would be rewritten as: * SELECT ITEM_ID,NAME FROM item I Semi JOIN * (SELECT DISTINCT 1 $3,ITEM_ID $4,O.PRICE $2 FROM order O ) $1 * ON ((I.ITEM_ID = $1.$4 AND $1.$2 = I.PRICE)) * * 2.If the {@link InParseNode} is the ORed part of the where clause,then we would rewrite the In Subquery to * Left Join. * * For NonCorrelated subquery, an example is: * SELECT item_id, name FROM item i WHERE i.item_id IN * (SELECT max(item_id) FROM order o where o.price > 8 group by o.customer_id,o.item_id) or i.discount1 > 10 * * The above sql would be rewritten as: * SELECT ITEM_ID,NAME FROM item I Left JOIN * (SELECT DISTINCT 1 $56, MAX(ITEM_ID) $57 FROM order O WHERE O.PRICE > 8 GROUP BY O.CUSTOMER_ID,O.ITEM_ID) $55 * ON (I.ITEM_ID = $55.$57) WHERE ($55.$56 IS NOT NULL OR I.DISCOUNT1 > 10) * * For Correlated subquery, an example is: * SELECT item_id, name FROM item i WHERE i.item_id IN * (SELECT max(item_id) FROM order o where o.price = i.price group by o.customer_id) or i.discount1 > 10; * * The above sql would be rewritten as: * SELECT ITEM_ID,NAME FROM item I Left JOIN * (SELECT DISTINCT 1 $28, MAX(ITEM_ID) $29,O.PRICE $27 FROM order O GROUP BY O.PRICE,O.CUSTOMER_ID) $26 * ON ((I.ITEM_ID = $26.$29 AND $26.$27 = I.PRICE)) WHERE ($26.$28 IS NOT NULL OR I.DISCOUNT1 > 10) * } * </pre> */ @Override public ParseNode visitLeave(InParseNode inParseNode, List<ParseNode> childParseNodes) throws SQLException { boolean isTopNode = topNode == inParseNode; if (isTopNode) { topNode = null; } SubqueryParseNode subqueryParseNode = (SubqueryParseNode) childParseNodes.get(1); SelectStatement subquerySelectStatementToUse = fixSubqueryStatement(subqueryParseNode.getSelectNode()); String subqueryTableTempAlias = ParseNodeFactory.createTempAlias(); JoinConditionExtractor joinConditionExtractor = new JoinConditionExtractor( subquerySelectStatementToUse, columnResolver, connection, subqueryTableTempAlias); List<AliasedNode> newSubquerySelectAliasedNodes = null; ParseNode extractedJoinConditionParseNode = null; int extractedSelectAliasNodeCount = 0; List<AliasedNode> oldSubqueryAliasedNodes = subquerySelectStatementToUse.getSelect(); ParseNode whereParseNodeAfterExtract = subquerySelectStatementToUse.getWhere() == null ? null : subquerySelectStatementToUse.getWhere().accept(joinConditionExtractor); if (whereParseNodeAfterExtract == subquerySelectStatementToUse.getWhere()) { /** * It is an NonCorrelated subquery. */ newSubquerySelectAliasedNodes = Lists.<AliasedNode> newArrayListWithExpectedSize(oldSubqueryAliasedNodes.size() + 1); newSubquerySelectAliasedNodes .add(NODE_FACTORY.aliasedNode(ParseNodeFactory.createTempAlias(), LiteralParseNode.ONE)); this.addNewAliasedNodes(newSubquerySelectAliasedNodes, oldSubqueryAliasedNodes); subquerySelectStatementToUse = NODE_FACTORY.select(subquerySelectStatementToUse, !inParseNode.isSubqueryDistinct(), newSubquerySelectAliasedNodes, whereParseNodeAfterExtract); } else { /** * It is an Correlated subquery. */ List<AliasedNode> extractedAdditionalSelectAliasNodes = joinConditionExtractor.getAdditionalSubselectSelectAliasedNodes(); extractedSelectAliasNodeCount = extractedAdditionalSelectAliasNodes.size(); newSubquerySelectAliasedNodes = Lists.<AliasedNode> newArrayListWithExpectedSize( oldSubqueryAliasedNodes.size() + 1 + extractedAdditionalSelectAliasNodes.size()); newSubquerySelectAliasedNodes .add(NODE_FACTORY.aliasedNode(ParseNodeFactory.createTempAlias(), LiteralParseNode.ONE)); this.addNewAliasedNodes(newSubquerySelectAliasedNodes, oldSubqueryAliasedNodes); newSubquerySelectAliasedNodes.addAll(extractedAdditionalSelectAliasNodes); extractedJoinConditionParseNode = joinConditionExtractor.getJoinConditionParseNode(); boolean isAggregate = subquerySelectStatementToUse.isAggregate(); if (!isAggregate) { subquerySelectStatementToUse = NODE_FACTORY.select(subquerySelectStatementToUse, !inParseNode.isSubqueryDistinct(), newSubquerySelectAliasedNodes, whereParseNodeAfterExtract); } else { /** * If exists AggregateFunction,we must add the correlated join condition to both the groupBy * clause and select lists of the subquery. */ List<ParseNode> newGroupByParseNodes = this.createNewGroupByParseNodes( extractedAdditionalSelectAliasNodes, subquerySelectStatementToUse); subquerySelectStatementToUse = NODE_FACTORY.select(subquerySelectStatementToUse, !inParseNode.isSubqueryDistinct(), newSubquerySelectAliasedNodes, whereParseNodeAfterExtract, newGroupByParseNodes, true); } } ParseNode joinOnConditionParseNode = getJoinConditionNodeForInSubquery(childParseNodes.get(0), newSubquerySelectAliasedNodes, subqueryTableTempAlias, extractedJoinConditionParseNode, extractedSelectAliasNodeCount); DerivedTableNode subqueryDerivedTableNode = NODE_FACTORY.derivedTable(subqueryTableTempAlias, subquerySelectStatementToUse); JoinType joinType = isTopNode ? (inParseNode.isNegate() ? JoinType.Anti : JoinType.Semi) : JoinType.Left; ParseNode resultWhereParseNode = isTopNode ? null : NODE_FACTORY.isNull(NODE_FACTORY.column(NODE_FACTORY.table(null, subqueryTableTempAlias), newSubquerySelectAliasedNodes.get(0).getAlias(), null), !inParseNode.isNegate()); tableNode = NODE_FACTORY.join(joinType, tableNode, subqueryDerivedTableNode, joinOnConditionParseNode, false); return resultWhereParseNode; } /** * <pre> * {@code * Rewrite the Exists Subquery to semi/anti/left join for both NonCorrelated and Correlated subquery. * * 1.If the {@link ExistsParseNode} is NonCorrelated subquery,the just add LIMIT 1. * an example is: * SELECT item_id, name FROM item i WHERE exists * (SELECT 1 FROM order o where o.price > 8) * * The above sql would be rewritten as: * SELECT ITEM_ID,NAME FROM item I WHERE EXISTS * (SELECT 1 FROM ORDER_TABLE O WHERE O.PRICE > 8 LIMIT 1) * * another example is: * SELECT item_id, name FROM item i WHERE exists * (SELECT 1 FROM order o where o.price > 8 group by o.customer_id,o.item_id having count(order_id) > 1) * or i.discount1 > 10 * * The above sql would be rewritten as: * SELECT ITEM_ID,NAME FROM item I WHERE * ( EXISTS (SELECT 1 FROM ORDER_TABLE O WHERE O.PRICE > 8 GROUP BY O.CUSTOMER_ID,O.ITEM_ID HAVING COUNT(ORDER_ID) > 1 LIMIT 1) * OR I.DISCOUNT1 > 10) * * 2.If the {@link ExistsParseNode} is Correlated subquery and is the only node in where clause or * is the ANDed part of the where clause, then we would rewrite the Exists Subquery to semi/anti join: * an example is: * SELECT item_id, name FROM item i WHERE exists * (SELECT 1 FROM order o where o.price = i.price and o.quantity = 5 ) * * The above sql would be rewritten as: * SELECT ITEM_ID,NAME FROM item I Semi JOIN * (SELECT DISTINCT 1 $3,O.PRICE $2 FROM ORDER_TABLE O WHERE O.QUANTITY = 5) $1 * ON ($1.$2 = I.PRICE) * * another example with AggregateFunction and groupBy is * SELECT item_id, name FROM item i WHERE exists * (SELECT 1 FROM order o where o.item_id = i.item_id group by customer_id having count(order_id) > 1) * * The above sql would be rewritten as: * SELECT ITEM_ID,NAME FROM item I Semi JOIN * (SELECT DISTINCT 1 $3,O.ITEM_ID $2 FROM order O GROUP BY O.ITEM_ID,CUSTOMER_ID HAVING COUNT(ORDER_ID) > 1) $1 * ON ($1.$2 = I.ITEM_ID) * * 3.If the {@link ExistsParseNode} is Correlated subquery and is the ORed part of the where clause, * then we would rewrite the Exists Subquery to Left Join. * an example is: * SELECT item_id, name FROM item i WHERE exists * (SELECT 1 FROM order o where o.item_id = i.item_id group by customer_id having count(order_id) > 1) * or i.discount1 > 10 * * The above sql would be rewritten as: * SELECT ITEM_ID,NAME FROM item I Left JOIN * (SELECT DISTINCT 1 $3,O.ITEM_ID $2 FROM order O GROUP BY O.ITEM_ID,CUSTOMER_ID HAVING COUNT(ORDER_ID) > 1) $1 * ON ($1.$2 = I.ITEM_ID) WHERE ($1.$3 IS NOT NULL OR I.DISCOUNT1 > 10) * } * </pre> */ @Override public ParseNode visitLeave(ExistsParseNode existsParseNode, List<ParseNode> childParseNodes) throws SQLException { boolean isTopNode = topNode == existsParseNode; if (isTopNode) { topNode = null; } SubqueryParseNode subqueryParseNode = (SubqueryParseNode) childParseNodes.get(0); SelectStatement subquerySelectStatementToUse = fixSubqueryStatement(subqueryParseNode.getSelectNode()); String subqueryTableTempAlias = ParseNodeFactory.createTempAlias(); JoinConditionExtractor joinConditionExtractor = new JoinConditionExtractor( subquerySelectStatementToUse, columnResolver, connection, subqueryTableTempAlias); ParseNode whereParseNodeAfterExtract = subquerySelectStatementToUse.getWhere() == null ? null : subquerySelectStatementToUse.getWhere().accept(joinConditionExtractor); if (whereParseNodeAfterExtract == subquerySelectStatementToUse.getWhere()) { /** * It is non-correlated EXISTS subquery, add LIMIT 1 */ subquerySelectStatementToUse = NODE_FACTORY.select(subquerySelectStatementToUse, NODE_FACTORY.limit(NODE_FACTORY.literal(1))); subqueryParseNode = NODE_FACTORY.subquery(subquerySelectStatementToUse, false); existsParseNode = NODE_FACTORY.exists(subqueryParseNode, existsParseNode.isNegate()); return super.visitLeave(existsParseNode, Collections.<ParseNode> singletonList(subqueryParseNode)); } List<AliasedNode> extractedAdditionalSelectAliasNodes = joinConditionExtractor.getAdditionalSubselectSelectAliasedNodes(); List<AliasedNode> newSubquerySelectAliasedNodes = Lists.newArrayListWithExpectedSize(extractedAdditionalSelectAliasNodes.size() + 1); /** * Just overwrite original subquery selectAliasNodes. */ newSubquerySelectAliasedNodes .add(NODE_FACTORY.aliasedNode(ParseNodeFactory.createTempAlias(), LiteralParseNode.ONE)); newSubquerySelectAliasedNodes.addAll(extractedAdditionalSelectAliasNodes); boolean isAggregate = subquerySelectStatementToUse.isAggregate(); if (!isAggregate) { subquerySelectStatementToUse = NODE_FACTORY.select(subquerySelectStatementToUse, true, newSubquerySelectAliasedNodes, whereParseNodeAfterExtract); } else { /** * If exists AggregateFunction,we must add the correlated join condition to both the groupBy * clause and select lists of the subquery. */ List<ParseNode> newGroupByParseNodes = this.createNewGroupByParseNodes( extractedAdditionalSelectAliasNodes, subquerySelectStatementToUse); subquerySelectStatementToUse = NODE_FACTORY.select(subquerySelectStatementToUse, true, newSubquerySelectAliasedNodes, whereParseNodeAfterExtract, newGroupByParseNodes, true); } ParseNode joinOnConditionParseNode = joinConditionExtractor.getJoinConditionParseNode(); DerivedTableNode subqueryDerivedTableNode = NODE_FACTORY.derivedTable(subqueryTableTempAlias, subquerySelectStatementToUse); JoinType joinType = isTopNode ? (existsParseNode.isNegate() ? JoinType.Anti : JoinType.Semi) : JoinType.Left; ParseNode resultWhereParseNode = isTopNode ? null : NODE_FACTORY.isNull(NODE_FACTORY.column(NODE_FACTORY.table(null, subqueryTableTempAlias), newSubquerySelectAliasedNodes.get(0).getAlias(), null), !existsParseNode.isNegate()); tableNode = NODE_FACTORY.join(joinType, tableNode, subqueryDerivedTableNode, joinOnConditionParseNode, false); return resultWhereParseNode; } @Override public ParseNode visitLeave(ComparisonParseNode node, List<ParseNode> l) throws SQLException { boolean isTopNode = topNode == node; if (isTopNode) { topNode = null; } ParseNode secondChild = l.get(1); if (!(secondChild instanceof SubqueryParseNode)) { return super.visitLeave(node, l); } SubqueryParseNode subqueryNode = (SubqueryParseNode) secondChild; SelectStatement subquery = fixSubqueryStatement(subqueryNode.getSelectNode()); String rhsTableAlias = ParseNodeFactory.createTempAlias(); JoinConditionExtractor conditionExtractor = new JoinConditionExtractor(subquery, columnResolver, connection, rhsTableAlias); ParseNode where = subquery.getWhere() == null ? null : subquery.getWhere().accept(conditionExtractor); if (where == subquery.getWhere()) { // non-correlated comparison subquery, add LIMIT 2, // expectSingleRow = true subquery = NODE_FACTORY.select(subquery, NODE_FACTORY.limit(NODE_FACTORY.literal(2))); subqueryNode = NODE_FACTORY.subquery(subquery, true); l = Lists.newArrayList(l.get(0), subqueryNode); node = NODE_FACTORY.comparison(node.getFilterOp(), l.get(0), l.get(1)); return super.visitLeave(node, l); } ParseNode rhsNode = null; boolean isGroupby = !subquery.getGroupBy().isEmpty(); boolean isAggregate = subquery.isAggregate(); List<AliasedNode> aliasedNodes = subquery.getSelect(); if (aliasedNodes.size() == 1) { rhsNode = aliasedNodes.get(0).getNode(); } else { List<ParseNode> nodes = Lists.<ParseNode> newArrayListWithExpectedSize(aliasedNodes.size()); for (AliasedNode aliasedNode : aliasedNodes) { nodes.add(aliasedNode.getNode()); } rhsNode = NODE_FACTORY.rowValueConstructor(nodes); } List<AliasedNode> additionalSelectNodes = conditionExtractor.getAdditionalSubselectSelectAliasedNodes(); List<AliasedNode> selectNodes = Lists.newArrayListWithExpectedSize(additionalSelectNodes.size() + 1); selectNodes.add(NODE_FACTORY.aliasedNode(ParseNodeFactory.createTempAlias(), rhsNode)); selectNodes.addAll(additionalSelectNodes); if (!isAggregate) { subquery = NODE_FACTORY.select(subquery, subquery.isDistinct(), selectNodes, where); } else { List<ParseNode> groupbyNodes = this.createNewGroupByParseNodes(additionalSelectNodes, subquery); subquery = NODE_FACTORY.select(subquery, subquery.isDistinct(), selectNodes, where, groupbyNodes, true); } ParseNode onNode = conditionExtractor.getJoinConditionParseNode(); TableNode rhsTable = NODE_FACTORY.derivedTable(rhsTableAlias, subquery); JoinType joinType = isTopNode ? JoinType.Inner : JoinType.Left; ParseNode ret = NODE_FACTORY.comparison(node.getFilterOp(), l.get(0), NODE_FACTORY .column(NODE_FACTORY.table(null, rhsTableAlias), selectNodes.get(0).getAlias(), null)); tableNode = NODE_FACTORY.join(joinType, tableNode, rhsTable, onNode, !isAggregate || isGroupby); return ret; } @Override public ParseNode visitLeave(ArrayAnyComparisonNode node, List<ParseNode> l) throws SQLException { List<ParseNode> children = leaveArrayComparisonNode(node, l); if (children == l) return super.visitLeave(node, l); node = NODE_FACTORY.arrayAny(children.get(0), (ComparisonParseNode) children.get(1)); return node; } @Override public ParseNode visitLeave(ArrayAllComparisonNode node, List<ParseNode> l) throws SQLException { List<ParseNode> children = leaveArrayComparisonNode(node, l); if (children == l) return super.visitLeave(node, l); node = NODE_FACTORY.arrayAll(children.get(0), (ComparisonParseNode) children.get(1)); return node; } protected List<ParseNode> leaveArrayComparisonNode(ParseNode node, List<ParseNode> l) throws SQLException { boolean isTopNode = topNode == node; if (isTopNode) { topNode = null; } ParseNode firstChild = l.get(0); if (!(firstChild instanceof SubqueryParseNode)) { return l; } SubqueryParseNode subqueryNode = (SubqueryParseNode) firstChild; SelectStatement subquery = fixSubqueryStatement(subqueryNode.getSelectNode()); String rhsTableAlias = ParseNodeFactory.createTempAlias(); JoinConditionExtractor conditionExtractor = new JoinConditionExtractor(subquery, columnResolver, connection, rhsTableAlias); ParseNode where = subquery.getWhere() == null ? null : subquery.getWhere().accept(conditionExtractor); if (where == subquery.getWhere()) { // non-correlated any/all comparison subquery return l; } ParseNode rhsNode = null; boolean isNonGroupByAggregate = subquery.getGroupBy().isEmpty() && subquery.isAggregate(); List<AliasedNode> aliasedNodes = subquery.getSelect(); String derivedTableAlias = null; if (!subquery.getGroupBy().isEmpty()) { derivedTableAlias = ParseNodeFactory.createTempAlias(); aliasedNodes = createNewAliasedNodes(aliasedNodes); } if (aliasedNodes.size() == 1) { rhsNode = derivedTableAlias == null ? aliasedNodes.get(0).getNode() : NODE_FACTORY.column(NODE_FACTORY.table(null, derivedTableAlias), aliasedNodes.get(0).getAlias(), null); } else { List<ParseNode> nodes = Lists.<ParseNode> newArrayListWithExpectedSize(aliasedNodes.size()); for (AliasedNode aliasedNode : aliasedNodes) { nodes.add(derivedTableAlias == null ? aliasedNode.getNode() : NODE_FACTORY.column(NODE_FACTORY.table(null, derivedTableAlias), aliasedNode.getAlias(), null)); } rhsNode = NODE_FACTORY.rowValueConstructor(nodes); } if (!isNonGroupByAggregate) { rhsNode = NODE_FACTORY.function(DistinctValueAggregateFunction.NAME, Collections.singletonList(rhsNode)); } List<AliasedNode> additionalSelectNodes = conditionExtractor.getAdditionalSubselectSelectAliasedNodes(); List<AliasedNode> selectNodes = Lists.newArrayListWithExpectedSize(additionalSelectNodes.size() + 1); selectNodes.add(NODE_FACTORY.aliasedNode(ParseNodeFactory.createTempAlias(), rhsNode)); selectNodes.addAll(additionalSelectNodes); List<ParseNode> groupbyNodes = Lists.newArrayListWithExpectedSize(additionalSelectNodes.size()); for (AliasedNode aliasedNode : additionalSelectNodes) { groupbyNodes.add(aliasedNode.getNode()); } if (derivedTableAlias == null) { subquery = NODE_FACTORY.select(subquery, false, selectNodes, where, groupbyNodes, true); } else { List<ParseNode> derivedTableGroupBy = Lists.newArrayListWithExpectedSize(subquery.getGroupBy().size() + groupbyNodes.size()); derivedTableGroupBy.addAll(groupbyNodes); derivedTableGroupBy.addAll(subquery.getGroupBy()); List<AliasedNode> derivedTableSelect = Lists.newArrayListWithExpectedSize(aliasedNodes.size() + selectNodes.size() - 1); derivedTableSelect.addAll(aliasedNodes); for (int i = 1; i < selectNodes.size(); i++) { AliasedNode aliasedNode = selectNodes.get(i); String alias = ParseNodeFactory.createTempAlias(); derivedTableSelect.add(NODE_FACTORY.aliasedNode(alias, aliasedNode.getNode())); aliasedNode = NODE_FACTORY.aliasedNode(aliasedNode.getAlias(), NODE_FACTORY.column(NODE_FACTORY.table(null, derivedTableAlias), alias, null)); selectNodes.set(i, aliasedNode); groupbyNodes.set(i - 1, aliasedNode.getNode()); } SelectStatement derivedTableStmt = NODE_FACTORY.select(subquery, subquery.isDistinct(), derivedTableSelect, where, derivedTableGroupBy, true); subquery = NODE_FACTORY.select(NODE_FACTORY.derivedTable(derivedTableAlias, derivedTableStmt), subquery.getHint(), false, selectNodes, null, groupbyNodes, null, Collections.<OrderByNode> emptyList(), null, null, subquery.getBindCount(), true, false, Collections.<SelectStatement> emptyList(), subquery.getUdfParseNodes()); } ParseNode onNode = conditionExtractor.getJoinConditionParseNode(); TableNode rhsTable = NODE_FACTORY.derivedTable(rhsTableAlias, subquery); JoinType joinType = isTopNode ? JoinType.Inner : JoinType.Left; tableNode = NODE_FACTORY.join(joinType, tableNode, rhsTable, onNode, false); firstChild = NODE_FACTORY.column(NODE_FACTORY.table(null, rhsTableAlias), selectNodes.get(0).getAlias(), null); if (isNonGroupByAggregate) { firstChild = NODE_FACTORY.upsertStmtArrayNode(Collections.singletonList(firstChild)); } ComparisonParseNode secondChild = (ComparisonParseNode) l.get(1); secondChild = NODE_FACTORY.comparison(secondChild.getFilterOp(), secondChild.getLHS(), NODE_FACTORY.elementRef(Lists.newArrayList(firstChild, NODE_FACTORY.literal(1)))); return Lists.newArrayList(firstChild, secondChild); } private SelectStatement fixSubqueryStatement(SelectStatement select) { if (!select.isUnion()) return select; // Wrap as a derived table. return NODE_FACTORY.select( NODE_FACTORY.derivedTable(ParseNodeFactory.createTempAlias(), select), HintNode.EMPTY_HINT_NODE, false, select.getSelect(), null, null, null, null, null, null, select.getBindCount(), false, false, Collections.<SelectStatement> emptyList(), select.getUdfParseNodes()); } /** * Create new {@link AliasedNode}s by every {@link ParseNode} in subquerySelectAliasedNodes and * generate new aliases by {@link ParseNodeFactory#createTempAlias}. and generate new Aliases for * subquerySelectAliasedNodes, */ private List<AliasedNode> createNewAliasedNodes(List<AliasedNode> subquerySelectAliasedNodes) { List<AliasedNode> newAliasedNodes = Lists.<AliasedNode> newArrayListWithExpectedSize(subquerySelectAliasedNodes.size()); this.addNewAliasedNodes(newAliasedNodes, subquerySelectAliasedNodes); return newAliasedNodes; } /** * Add every {@link ParseNode} in oldSelectAliasedNodes to newSelectAliasedNodes and generate new * aliases by {@link ParseNodeFactory#createTempAlias}. */ private void addNewAliasedNodes(List<AliasedNode> newSelectAliasedNodes, List<AliasedNode> oldSelectAliasedNodes) { for (int index = 0; index < oldSelectAliasedNodes.size(); index++) { AliasedNode oldSelectAliasedNode = oldSelectAliasedNodes.get(index); newSelectAliasedNodes.add(NODE_FACTORY.aliasedNode(ParseNodeFactory.createTempAlias(), oldSelectAliasedNode.getNode())); } } /** * Get the join conditions in order to rewrite InSubquery to Join. * @param rhsSubquerySelectAliasedNodes the first element is {@link LiteralParseNode#ONE}. * @param extractedJoinConditionParseNode For NonCorrelated subquery, it is null. * @param extractedSelectAliasNodeCount For NonCorrelated subquery, it is 0. */ private ParseNode getJoinConditionNodeForInSubquery(ParseNode lhsParseNode, List<AliasedNode> rhsSubquerySelectAliasedNodes, String rhsSubqueryTableAlias, ParseNode extractedJoinConditionParseNode, int extractedSelectAliasNodeCount) throws SQLException { List<ParseNode> lhsParseNodes; if (lhsParseNode instanceof RowValueConstructorParseNode) { lhsParseNodes = ((RowValueConstructorParseNode) lhsParseNode).getChildren(); } else { lhsParseNodes = Collections.singletonList(lhsParseNode); } if ( lhsParseNodes.size() != (rhsSubquerySelectAliasedNodes.size() - 1 - extractedSelectAliasNodeCount) ) { throw new SQLExceptionInfo.Builder( SQLExceptionCode.SUBQUERY_RETURNS_DIFFERENT_NUMBER_OF_FIELDS).build().buildException(); } int count = lhsParseNodes.size(); TableName rhsSubqueryTableName = NODE_FACTORY.table(null, rhsSubqueryTableAlias); List<ParseNode> joinEqualParseNodes = Lists.newArrayListWithExpectedSize(count + (extractedJoinConditionParseNode == null ? 0 : 1)); for (int index = 0; index < count; index++) { /** * The +1 is to skip the first {@link LiteralParseNode#ONE} */ ParseNode rhsNode = NODE_FACTORY.column(rhsSubqueryTableName, rhsSubquerySelectAliasedNodes.get(index + 1).getAlias(), null); joinEqualParseNodes.add(NODE_FACTORY.equal(lhsParseNodes.get(index), rhsNode)); } if (extractedJoinConditionParseNode != null) { joinEqualParseNodes.add(extractedJoinConditionParseNode); } return joinEqualParseNodes.size() == 1 ? joinEqualParseNodes.get(0) : NODE_FACTORY.and(joinEqualParseNodes); } /** * Combine every {@link ParseNode} in extractedAdditionalSelectAliasNodes and GroupBy clause of * the subquerySelectStatementToUse to get new GroupBy ParseNodes. */ private List<ParseNode> createNewGroupByParseNodes( List<AliasedNode> extractedAdditionalSelectAliasNodes, SelectStatement subquerySelectStatementToUse) { List<ParseNode> newGroupByParseNodes = Lists.newArrayListWithExpectedSize(extractedAdditionalSelectAliasNodes.size() + subquerySelectStatementToUse.getGroupBy().size()); for (AliasedNode aliasedNode : extractedAdditionalSelectAliasNodes) { newGroupByParseNodes.add(aliasedNode.getNode()); } newGroupByParseNodes.addAll(subquerySelectStatementToUse.getGroupBy()); return newGroupByParseNodes; } private static class JoinConditionExtractor extends AndRewriterBooleanParseNodeVisitor { private final TableName tableName; private ColumnResolveVisitor columnResolveVisitor; private List<AliasedNode> additionalSubselectSelectAliasedNodes; private List<ParseNode> joinConditionParseNodes; public JoinConditionExtractor(SelectStatement subquery, ColumnResolver outerResolver, PhoenixConnection connection, String tableAlias) throws SQLException { super(NODE_FACTORY); this.tableName = NODE_FACTORY.table(null, tableAlias); ColumnResolver localResolver = FromCompiler.getResolverForQuery(subquery, connection); this.columnResolveVisitor = new ColumnResolveVisitor(localResolver, outerResolver); this.additionalSubselectSelectAliasedNodes = Lists.<AliasedNode> newArrayList(); this.joinConditionParseNodes = Lists.<ParseNode> newArrayList(); } public List<AliasedNode> getAdditionalSubselectSelectAliasedNodes() { return this.additionalSubselectSelectAliasedNodes; } public ParseNode getJoinConditionParseNode() { if (this.joinConditionParseNodes.isEmpty()) { return null; } if (this.joinConditionParseNodes.size() == 1) { return this.joinConditionParseNodes.get(0); } return NODE_FACTORY.and(this.joinConditionParseNodes); } @Override protected ParseNode leaveBooleanNode(ParseNode node, List<ParseNode> l) throws SQLException { columnResolveVisitor.reset(); node.accept(columnResolveVisitor); ColumnResolveVisitor.ColumnResolveType type = columnResolveVisitor.getColumnResolveType(); if ( type != ColumnResolveVisitor.ColumnResolveType.NONE && type != ColumnResolveVisitor.ColumnResolveType.LOCAL ) throw new SQLFeatureNotSupportedException( "Does not support non-standard or non-equi correlated-subquery conditions."); return node; } @Override public ParseNode visitLeave(ComparisonParseNode node, List<ParseNode> l) throws SQLException { if (node.getFilterOp() != CompareOperator.EQUAL) return leaveBooleanNode(node, l); columnResolveVisitor.reset(); node.getLHS().accept(columnResolveVisitor); ColumnResolveVisitor.ColumnResolveType lhsType = columnResolveVisitor.getColumnResolveType(); columnResolveVisitor.reset(); node.getRHS().accept(columnResolveVisitor); ColumnResolveVisitor.ColumnResolveType rhsType = columnResolveVisitor.getColumnResolveType(); if ( (lhsType == ColumnResolveVisitor.ColumnResolveType.NONE || lhsType == ColumnResolveVisitor.ColumnResolveType.LOCAL) && (rhsType == ColumnResolveVisitor.ColumnResolveType.NONE || rhsType == ColumnResolveVisitor.ColumnResolveType.LOCAL) ) { return node; } if ( lhsType == ColumnResolveVisitor.ColumnResolveType.LOCAL && rhsType == ColumnResolveVisitor.ColumnResolveType.OUTER ) { String alias = ParseNodeFactory.createTempAlias(); this.additionalSubselectSelectAliasedNodes .add(NODE_FACTORY.aliasedNode(alias, node.getLHS())); ParseNode lhsNode = NODE_FACTORY.column(tableName, alias, null); this.joinConditionParseNodes.add(NODE_FACTORY.equal(lhsNode, node.getRHS())); return null; } if ( lhsType == ColumnResolveVisitor.ColumnResolveType.OUTER && rhsType == ColumnResolveVisitor.ColumnResolveType.LOCAL ) { String alias = ParseNodeFactory.createTempAlias(); this.additionalSubselectSelectAliasedNodes .add(NODE_FACTORY.aliasedNode(alias, node.getRHS())); ParseNode rhsNode = NODE_FACTORY.column(tableName, alias, null); this.joinConditionParseNodes.add(NODE_FACTORY.equal(node.getLHS(), rhsNode)); return null; } throw new SQLFeatureNotSupportedException( "Does not support non-standard or non-equi correlated-subquery conditions."); } } /* * Class for resolving inner query column references */ private static class ColumnResolveVisitor extends StatelessTraverseAllParseNodeVisitor { public enum ColumnResolveType { NONE, LOCAL, OUTER, MIXED }; private final ColumnResolver localResolver; private final ColumnResolver outerResolver; private ColumnResolveType type; public ColumnResolveVisitor(ColumnResolver localResolver, ColumnResolver outerResolver) { this.localResolver = localResolver; this.outerResolver = outerResolver; this.type = ColumnResolveType.NONE; } public void reset() { this.type = ColumnResolveType.NONE; } public ColumnResolveType getColumnResolveType() { return this.type; } @Override public Void visit(ColumnParseNode node) throws SQLException { // Inner query column definitions should shade those of outer query. try { localResolver.resolveColumn(node.getSchemaName(), node.getTableName(), node.getName()); addType(true); return null; } catch (TableNotFoundException e) { } catch (ColumnNotFoundException e) { } catch (ColumnFamilyNotFoundException e) { } outerResolver.resolveColumn(node.getSchemaName(), node.getTableName(), node.getName()); addType(false); return null; } private void addType(boolean isLocal) { switch (this.type) { case NONE: this.type = isLocal ? ColumnResolveType.LOCAL : ColumnResolveType.OUTER; break; case LOCAL: this.type = isLocal ? ColumnResolveType.LOCAL : ColumnResolveType.MIXED; break; case OUTER: this.type = isLocal ? ColumnResolveType.MIXED : ColumnResolveType.OUTER; break; default: // MIXED do nothing break; } } } }
google/sagetv
37,552
java/sage/api/MediaNodeAPI.java
/* * Copyright 2015 The SageTV Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sage.api; import sage.*; import sage.vfs.*; /** * Virtual content directory abstraction. */ public class MediaNodeAPI { private MediaNodeAPI() {} public static void init(Catbert.ReflectionFunctionTable rft) { rft.put(new PredefinedJEPFunction("MediaNode", "GetMediaSource", new String[] { "Name" }) { /** * Retrieves a MediaNode which is the root of the specified 'Media Source'. All names are case insensitive. * Valid names are: * Filesystem - provides a view of the native filesystem * VideoNavigator - provides various views of the imported videos * MusicNavigator - provides various views of the imported music * MusicVideosNavigator - provides various views of the imported videos with the 'music videos' category * MoviesNavigator - provides various views of all content with the 'Movie' category or that are DVDs or BluRays * TVNavigator - provides various views of recorded TV content * <br> * You can also use names that are "ContentByGrouping" or just "Content". * Valid values for "Content" are: * Clips - all video files with a duration under 10 mins (controlled by the property max_duration_to_be_a_clip) * Music or ImportedMusic - all imported music files * Videos or ImportedVideso - all imported video files * Picture or Photos or ImportedPictures or ImportedPhotos - all imported picture files * DVDs or ImportedDVDs - all imported DVDs * BluRays or ImportedBluRays - all imported BluRays * Movies - all videos or TV recordings with the 'Movie' category or that are DVDs or BluRays * MusicVideos - all imported videos with the 'Music Video' category * TV - all recorded TV content * MediaFiles - all files in SageTV * Compilations - all music files that are by 'Various Artist' * MusicPlaylists - all music playlists * VideoPlaylists - all video playlists * <br> * Valid values for "Grouping" are: * Folder - grouped according to their relative import path * Category or Genre - grouped by category, for music files they are then subgrouped by Artist and then Album * Year - grouped by year, for music files they are subgrouped by Album * Director - grouped by Director * Actor - grouped by actors/actress * Studio - grouped by the studio that produced the content if known * Title - grouped by title * Series - grouped by television series if known (SeriesInfo object) * Album - grouped by album * Artist - grouped by artist and then subgrouped by album * Channel - grouped by channel * * @param Name the name of the media source * @return a MediaNode which contains the hierarchy for the specified media source * @since 7.0 * * @declaration public MediaNode GetMediaSource(String Name); */ public Object runSafely(Catbert.FastStack stack) throws Exception { return sage.vfs.VFSFactory.getInstance().createMediaSource(getString(stack), null); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetMediaView", new String[] { "Name", "Data" }) { /** * Similar to the GetMediaSource API call; but the second argument allows specifying the actual data set to * be used for the view. The name describes the type of content or grouping just like in GetMediaSource. Can be used for * presenting a subset of another view or for creating a MediaNode view of a fixed list of data such as a list of MediaFiles or Actors. * @param Name the view name to use * @param Data the dataset that defines the content in the view, can be a Collection, Object[] or a single object * @return a MediaNode that represents the specified Data using the specified view Name * @since 7.0 * * @declaration public MediaNode GetMediaView(String Name, Object Data); */ public Object runSafely(Catbert.FastStack stack) throws Exception { Object dataObj = stack.pop(); String view = getString(stack); java.util.Collection coll = null; if (dataObj instanceof java.util.Collection) coll = (java.util.Collection) dataObj; else if (dataObj instanceof Object[]) coll = new java.util.Vector(java.util.Arrays.asList((Object[]) dataObj)); else if (dataObj != null) { coll = new java.util.Vector(); coll.add(dataObj); } return sage.vfs.VFSFactory.getInstance().createCollectionView(view, coll); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetRelativeMediaSource", new String[] { "Name", "RelativeRoot" }) { /** * Creates a MediaNode view with a relative root for a specified media source. This is currently only useable * with the 'Filesystem' media source * @param Name should be Filesystem; anything else will behave like the GetMediaSource API call * @param RelativeRoot the subdirectory which should be the root of this view * @return a MediaNode that represents the relative view of the specified media source * @since 7.0 * * @declaration public MediaNode GetRelativeMediaSource(String Name, Object RelativeRoot); */ public Object runSafely(Catbert.FastStack stack) throws Exception { Object relativeRoot = stack.pop(); return sage.vfs.VFSFactory.getInstance().createMediaSource(getString(stack), relativeRoot); } }); rft.put(new PredefinedJEPFunction("MediaNode", "IsNodeFolder", new String[] { "MediaNode" }) { /** * Returns true if the specified MediaNode has children * @param MediaNode the specified MediaNode * @return true if the specified MediaNode has children, false otherwise * @since 7.0 * * @declaration public boolean IsNodeFolder(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); return Boolean.valueOf(node != null && node.isFolder()); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeChildren", new String[] { "MediaNode" }) { /** * Returns an array of the children of the specified MediaNode * @param MediaNode the specified MediaNode * @return an array of the children of the specified MediaNode * @since 7.0 * * @declaration public MediaNode[] GetNodeChildren(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); MediaNode[] rv = node != null ? node.getChildren() : null; return (rv == null) ? null : rv.clone(); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeNumChildren", new String[] { "MediaNode" }) { /** * Returns the number of children of the specified MediaNode * @param MediaNode the specified MediaNode * @return the number of children of the specified MediaNode * @since 7.0 * * @declaration public int GetNodeNumChildren(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); return new Integer(node == null ? 0 : node.getNumChildren()); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeChildAt", new String[] { "MediaNode", "Index" }) { /** * Returns the child of the specified MediaNode at the given index * @param MediaNode the specified MediaNode * @param Index the index of the child to return (0-based) * @return the child of the specified MediaNode at the given index * @since 7.0 * * @declaration public MediaNode GetNodeChildAt(MediaNode MediaNode, int Index); */ public Object runSafely(Catbert.FastStack stack) throws Exception { int idx = getInt(stack); MediaNode node = getMediaNode(stack); return node != null ? node.getChildAt(idx) : null; } }); rft.put(new PredefinedJEPFunction("MediaNode", "SetNodeSort", new String[] { "MediaNode", "Technique", "Ascending" }) { /** * Sets the sorting technique used by the specified MediaNode hierarchy. This effects all levels of the hierarchy. * MediaNodes that are folders are always listed first when sorting. Some of the sorting techniques * can also ignore 'the' as a prefix; this is controlled by the property "ui/ignore_the_when_sorting" which defaults to true. * Valid sorting technique names are: Date, Size, Name (can ignore the), Filename, Track, Duration, Title (can ignore the), * Artist (can ignore the), Album (can ignore the), Category, Year, Rating, Count, EpisodeName, EpisodeID, Rated, Runtime, * Studio (can ignore the), Fullpath, OriginalAirDate, ChannelName, Intelligent * @param MediaNode the specified MediaNode * @param Technique the name of the sorting technique to use, case insensitive * @param Ascending true if the sorting should occur in ascending order, false otherwise * @since 7.0 * * @declaration public void SetNodeSort(MediaNode MediaNode, String Technique, boolean Ascending); */ public Object runSafely(Catbert.FastStack stack) throws Exception { boolean ascending = getBool(stack); String technique = getString(stack); MediaNode node = getMediaNode(stack); if (node != null) node.setSorter(VFSFactory.getInstance().getSorter(technique, ascending)); return null; } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeSortTechnique", new String[] { "MediaNode" }) { /** * Returns the name of the current sorting technique used by the specified MediaNode hierarchy. * @param MediaNode the specified MediaNode * @return the name of the current sorting technique used by the specified MediaNode hierarchy. * @since 7.0 * * @declaration public String GetNodeSortTechnique(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); if (node != null && node.getSorter() != null) return node.getSorter().getName(); return null; } }); rft.put(new PredefinedJEPFunction("MediaNode", "IsNodeSortAscending", new String[] { "MediaNode" }) { /** * Returns true if the current sorting technique used by the specified MediaNode hierarchy is in ascending order, false otherwise * @param MediaNode the specified MediaNode * @return true if the current sorting technique used by the specified MediaNode hierarchy is in ascending order, false otherwise * @since 7.0 * * @declaration public boolean IsNodeSortAscending(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); if (node != null && node.getSorter() != null) return Boolean.valueOf(node.getSorter().isAscending()); return Boolean.FALSE; } }); rft.put(new PredefinedJEPFunction("MediaNode", "SetNodeFilter", new String[] { "MediaNode", "Technique", "MatchPasses" }) { /** * Sets the filtering techniques used by the specified MediaNode hierarchy. This effects all levels of the hierarchy. * Filters can either be inclusive or exclusive. This method will clear all other filters and set this as the only filter. * Valid filtering technique names are: Directories, Pictures, Videos, Music, DVD, BluRay, TV, Watched, Archived, DontLike, Favorite, * HDTV, ManualRecord, FirstRun, CompleteRecording * @param MediaNode the specified MediaNode * @param Technique the name of the filtering technique to use, case insensitive * @param MatchPasses true if the items matching the filter should be retained, false if matching items should be removed * @since 7.0 * * @declaration public void SetNodeFilter(MediaNode MediaNode, String Technique, boolean MatchPasses); */ public Object runSafely(Catbert.FastStack stack) throws Exception { boolean matchPasses = getBool(stack); String technique = getString(stack); MediaNode node = getMediaNode(stack); node.setFiltering(VFSFactory.getInstance().getFilter(technique, matchPasses)); return null; } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeNumFilters", new String[] { "MediaNode" }) { /** * Gets the number of filters that are currently set for the specified MediaNode. * @param MediaNode the specified MediaNode * @return the number of filters that are currently set for the specified MediaNode. * @since 7.0 * * @declaration int GetNodeNumFilters(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); if (node != null) { DataObjectFilter[] filts = node.getFilters(); if (filts != null) return new Integer(filts.length); } return new Integer(0); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeFilterTechnique", new String[] { "MediaNode", "FilterIndex" }) { /** * Returns the name of the current filtering technique used by the specified MediaNode hierarchy. Since * multiple filters can be set; an index must be specified to determine which one to get the technique of * @param MediaNode the specified MediaNode * @param FilterIndex the 0-based index of the filtering technique to retrieve * @return the name of the current filtering technique used by the specified MediaNode hierarchy at the specified index, null if the index is out of bounds * @since 7.0 * * @declaration public String GetNodeFilterTechnique(MediaNode MediaNode, int FilterIndex); */ public Object runSafely(Catbert.FastStack stack) throws Exception { int idx = getInt(stack); MediaNode node = getMediaNode(stack); if (node != null) { DataObjectFilter[] filts = node.getFilters(); if (filts != null && idx >= 0 && idx < filts.length) return filts[idx].getTechnique(); } return null; } }); rft.put(new PredefinedJEPFunction("MediaNode", "IsNodeFilterMatching", new String[] { "MediaNode", "FilterIndex" }) { /** * Returns the match state of the current filtering technique used by the specified MediaNode hierarchy. Since * multiple filters can be set; an index must be specified to determine which one to get the matching state of * @param MediaNode the specified MediaNode * @param FilterIndex the 0-based index of the filtering match state to retrieve * @return true if the current filtering technique used by the specified MediaNode hierarchy at the specified index is MatchPasses, false otherwise or if the index is out of bounds * @since 7.0 * * @declaration public boolean IsNodeFilterMatching(MediaNode MediaNode, int FilterIndex); */ public Object runSafely(Catbert.FastStack stack) throws Exception { int idx = getInt(stack); MediaNode node = getMediaNode(stack); if (node != null) { DataObjectFilter[] filts = node.getFilters(); if (filts != null && idx >= 0 && idx < filts.length) return Boolean.valueOf(filts[idx].isMatchingFilter()); } return Boolean.FALSE; } }); rft.put(new PredefinedJEPFunction("MediaNode", "AppendNodeFilter", new String[] { "MediaNode", "Technique", "MatchPasses" }) { /** * Adds a filtering technique to used by the specified MediaNode hierarchy. This effects all levels of the hierarchy. * Filters can either be inclusive or exclusive. This method will not clear other filters that have been set. * Valid filtering technique names are: Directories, Pictures, Videos, Music, DVD, BluRay, TV, Watched, Archived, DontLike, Favorite, * HDTV, ManualRecord, FirstRun, CompleteRecording * @param MediaNode the specified MediaNode * @param Technique the name of the filtering technique to use, case insensitive * @param MatchPasses true if the items matching the filter should be retained, false if matching items should be removed * @since 7.0 * * @declaration public void AppendNodeFilter(MediaNode MediaNode, String Technique, boolean MatchPasses); */ public Object runSafely(Catbert.FastStack stack) throws Exception { boolean matchPasses = getBool(stack); String technique = getString(stack); MediaNode node = getMediaNode(stack); node.appendFiltering(VFSFactory.getInstance().getFilter(technique, matchPasses)); return null; } }); rft.put(new PredefinedJEPFunction("MediaNode", "IsNodeHierarchyRealized", new String[] { "MediaNode" }) { /** * Returns true if the entire set of data objects that back this MediaNode hierarchy has already been realized. * This will be true for fixed sets of data; but false for abstractions like the filesystem. When this is true the * API call GetAllNodeDescendants will return a valid result. * @param MediaNode the specified MediaNode * @return true if the entire set of data objects that back this MediaNode hierarchy has already been realized, false otherwise * @since 7.0 * * @declaration public boolean IsNodeHierarchyRealized(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); return Boolean.valueOf(node != null && node.isHierarchyRealized()); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetAllNodeDescendants", new String[] { "MediaNode" }) { /** * Returns the data set that represents all the children under the specified MediaNode if that * data set has already been realized. * @param MediaNode the specified MediaNode * @return a Collection which holds all of the resulting descendants of the specified Media Node; this Collection should NOT be modified * @since 7.0 * * @declaration public java.util.Collection GetAllNodeDescendants(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); return node == null ? null : node.getFinalDescendants(); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeIcon", new String[] { "MediaNode" }) { /** * Returns the icon image associated with the specified MediaNode. This is currently the same as GetNodeThumbnail. * @param MediaNode the specified MediaNode * @return an Object which represents the icon for this MediaNode; this may be a MetaImage or a resource path that can be used to load an image * @since 7.0 * * @declaration public Object GetNodeIcon(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); return node == null ? null : node.getIcon(stack.getUIComponent()); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeThumbnail", new String[] { "MediaNode" }) { /** * Returns the thumbnail image associated with the specified MediaNode. * @param MediaNode the specified MediaNode * @return an Object which represents the thumbnail for this MediaNode; this may be a MetaImage or a resource path that can be used to load an image * @since 7.0 * * @declaration public Object GetNodeThumbnail(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); return node == null ? null : node.getThumbnail(stack.getUIComponent()); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodePrimaryLabel", new String[] { "MediaNode" }) { /** * Returns a string representation of the primary data associated with the specified MediaNode suitable for display in the UI. * @param MediaNode the specified MediaNode * @return a string representation of the primary data associated with the specified MediaNode suitable for display in the UI * @since 7.0 * * @declaration public String GetNodePrimaryLabel(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { Object o = stack.pop(); if (o instanceof MediaNode) return ((MediaNode) o).getPrimaryLabel(); else if (o != null) return o.toString(); else return ""; } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeSecondaryLabel", new String[] { "MediaNode" }) { /** * Returns a string representation of the secondary data associated with the specified MediaNode suitable for display in the UI. * This will usually relate to whatever the current sorting technique is. * @param MediaNode the specified MediaNode * @return a string representation of the secondary data associated with the specified MediaNode suitable for display in the UI * @since 7.0 * * @declaration public String GetNodeSecondaryLabel(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); return node == null ? "" : node.getSecondaryLabel(); } }); rft.put(new PredefinedJEPFunction("MediaNode", "IsNodePlayable", new String[] { "MediaNode" }) { /** * Returns true if the Object that this MediaNode wraps is suitable for passing to the Watch API call. * @param MediaNode the specified MediaNode * @return true if the Object that this MediaNode wraps is suitable for passing to the Watch API call * @since 7.0 * * @declaration public boolean IsNodePlayable(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); return Boolean.valueOf(node != null && node.isPlayable()); } }); rft.put(new PredefinedJEPFunction("MediaNode", "IsNodeVirtual", new String[] { "MediaNode" }) { /** * Returns true if the specified MediaNode doesn't wrap an actual data object; but just an abstraction of a hierarchy * @param MediaNode the specified MediaNode * @return true if the specified MediaNode doesn't wrap an actual data object; but just an abstraction of a hierarchy * @since 7.0 * * @declaration public boolean IsNodeVirtual(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); return Boolean.valueOf(node != null && node.isVirtual()); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeDataObject", new String[] { "MediaNode" }) { /** * Returns the Object that is wrapped by the specified MediaNode * @param MediaNode the specified MediaNode * @return the Object that is wrapped by the specified MediaNode * @since 7.0 * * @declaration public Object GetNodeDataObject(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); return node == null ? null : node.getDataObject(); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeDataType", new String[] { "MediaNode" }) { /** * Returns the type of the Object that is wrapped by the specified MediaNode * @param MediaNode the specified MediaNode * @return the type of the Object that is wrapped by the specified MediaNode * @since 7.0 * * @declaration public String GetNodeDataType(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); return node == null ? "" : node.getDataType(); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeProperty", new String[] { "MediaNode", "PropertyName" }) { /** * Returns a specific property associated with this MediaNode. This varies depending upon the data type of the * MediaNode. For MediaFile based nodes this will end up calling GetMediaFileMetadata. * @param MediaNode the specified MediaNode * @param PropertyName the name of the property * @return the value of the specified property for the specified MediaNode * @since 7.0 * * @declaration public String GetNodeProperty(MediaNode MediaNode, String PropertyName); */ public Object runSafely(Catbert.FastStack stack) throws Exception { String name = getString(stack); MediaNode node = getMediaNode(stack); return node == null ? "" : node.getProperty(name); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeParent", new String[] { "MediaNode" }) { /** * Returns the MediaNode parent of the specified MediaNode * @param MediaNode the specified MediaNode * @return the MediaNode parent of the specified MediaNode or null if it doesn't have a parent * @since 7.0 * * @declaration public MediaNode GetNodeParent(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); return node == null ? null : node.getParent(); } }); rft.put(new PredefinedJEPFunction("MediaNode", "RefreshNode", new String[] { "MediaNode" }) { /** * Refreshes the hierarchy associated with the specified MediaNode. * @param MediaNode the specified MediaNode * @since 7.0 * * @declaration public void RefreshNode(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); if (node != null) node.refresh(); return null; } }); rft.put(new PredefinedJEPFunction("MediaNode", "SetNodeChecked", new String[] { "MediaNode", "State" }) { /** * Sets a flag on this MediaNode to indicate it is in the checked state. Useful for tracking multi-selection of * child MediaNodes. * @param MediaNode the specified MediaNode * @param State true if the MediaNode should be marked as being in the checked state, false otherwise * @since 7.0 * * @declaration public void SetNodeChecked(MediaNode MediaNode, boolean State); */ public Object runSafely(Catbert.FastStack stack) throws Exception { boolean x = getBool(stack); MediaNode node = getMediaNode(stack); if (node != null) node.setChecked(x); return null; } }); rft.put(new PredefinedJEPFunction("MediaNode", "IsNodeChecked", new String[] { "MediaNode" }) { /** * Returns true if the specified MediaNode had its state set to checked by the SetNodeChecked or SetAllChildrenChecked API calls. * @param MediaNode the specified MediaNode * @return true if the specified MediaNode had its state set to checked by the SetNodeChecked or SetAllChildrenChecked API calls, false otherwise * @since 7.0 * * @declaration public boolean IsNodeChecked(MediaNode MediaNode); * */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); return (node == null) ? Boolean.FALSE : Boolean.valueOf(node.isChecked()); } }); rft.put(new PredefinedJEPFunction("MediaNode", "SetAllChildrenChecked", new String[] { "MediaNode", "State" }) { /** * Sets a flag on all the children of this MediaNode to indicate they are in the checked state. Useful for tracking multi-selection of * child MediaNodes. * @param MediaNode the specified MediaNode * @param State true if all the children of the MediaNode should be marked as being in the checked state, false if they should be marked as unchecked * @since 7.0 * * @declaration public void SetAllChildrenChecked(MediaNode MediaNode, boolean State); */ public Object runSafely(Catbert.FastStack stack) throws Exception { boolean x = getBool(stack); MediaNode node = getMediaNode(stack); if (node != null) { MediaNode[] kids = node.getChildren(); for (int i = 0; kids != null && i < kids.length; i++) kids[i].setChecked(x); } return null; } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetChildrenCheckedCount", new String[] { "MediaNode", "State" }) { /** * Returns the number of children of the specified MediaNode that are in the specified checked state. * @param MediaNode the specified MediaNode * @param State true if the returned count should be for checked children, false if it should be for unchecked children * @return the number of children of the specified MediaNode that are in the specified checked state * @since 7.0 * * @declaration public int GetChildrenCheckedCount(MediaNode MediaNode, boolean State); */ public Object runSafely(Catbert.FastStack stack) throws Exception { boolean x = getBool(stack); MediaNode node = getMediaNode(stack); int count = 0; if (node != null) { MediaNode[] kids = node.getChildren(); for (int i = 0; kids != null && i < kids.length; i++) if (kids[i].isChecked() == x) count++; } return new Integer(count); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetChildrenCheckedNodes", new String[] { "MediaNode", "State" }) { /** * Returns the children of the specified MediaNode that are in the specified checked state. * @param MediaNode the specified MediaNode * @param State true if the returned list should be for checked children, false if it should be for unchecked children * @return an array of children of the specified MediaNode that are in the specified checked state * @since 7.0 * * @declaration public java.util.Vector GetChildrenCheckedNodes(MediaNode MediaNode, boolean State); */ public Object runSafely(Catbert.FastStack stack) throws Exception { boolean x = getBool(stack); MediaNode node = getMediaNode(stack); if (node != null) { MediaNode[] kids = node.getChildren(); java.util.Vector rv = new java.util.Vector(); for (int i = 0; kids != null && i < kids.length; i++) if (kids[i].isChecked() == x) rv.add(kids[i]); return rv; } return null; } }); rft.put(new PredefinedJEPFunction("MediaNode", "CreateMediaNode", new String[] { "PrimaryLabel", "SecondaryLabel", "Thumbnail", "Icon", "DataObject" }) { /** * Creates a static MediaNode that has no parents and no children. Can be used to add arbitrary items to MediaNode lists for display in * the UI. The data type for the node will be Virtual. * @param PrimaryLabel the value to set as the primary label for the MediaNode * @param SecondaryLabel the value to set as the secondary label for the MediaNode * @param Thumbnail the Object to use as the thumbnail for the MediaNode * @param Icon the Object to use as the icon for the MediaNode * @param DataObject the Object that should be the data object for the MediaNode * @return a new MediaNode object that has the specified attributes * @since 7.0 * * @declaration public MediaNode CreateMediaNode(String PrimaryLabel, String SecondaryLabel, Object Thumbnail, Object Icon, Object DataObject); */ public Object runSafely(Catbert.FastStack stack) throws Exception { Object data = stack.pop(); Object icon = stack.pop(); Object thumb = stack.pop(); String secondary = getString(stack); String primary = getString(stack); return new StaticMediaNode(primary, secondary, thumb, icon, data); } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeFullPath", new String[] { "MediaNode" }) { /** * Returns a string which represents the hierarchical path to this MediaNode. This is created by appending the primary labels * of all the parents up to the root of the hierarchy. The forward slash is used as a separator. * @param MediaNode the specified MediaNode * @return a string which represents the hierarchical path to this MediaNode * @since 7.0 * * @declaration String GetNodeFullPath(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); if (node != null) { String rv = ""; node = node.getParent(); while (node != null) { rv = node.getPrimaryLabel() + (rv.length() == 0 ? "" : "/") + rv; node = node.getParent(); } return rv; } return ""; } }); rft.put(new PredefinedJEPFunction("MediaNode", "GetNodeTypePath", new String[] { "MediaNode" }) { /** * Returns a string which represents the hierarchical path to this MediaNode with type information only. This is created by appending the data types * of all the parents up to the root of the hierarchy. The forward slash is used as a separator. For Virtual nodes, it will use F if it represents * a folder in the import hierarchy; otherwise it'll use the primary label unless that is null, in which case it'll use V. * @param MediaNode the specified MediaNode * @return a string which represents the hierarchical type path to this MediaNode * @since 7.0 * * @declaration String GetNodeTypePath(MediaNode MediaNode); */ public Object runSafely(Catbert.FastStack stack) throws Exception { MediaNode node = getMediaNode(stack); if (node != null) { String rv = ""; while (node != null) { String currType; if (MediaNode.DATATYPE_VIRTUAL.equals(node.getDataType())) { if (node instanceof BrowserMediaFileNode) currType = "F"; else { currType = node.getPrimaryLabel(); if (currType == null) currType = "V"; } } else currType = node.getDataType(); rv = currType + (rv.length() == 0 ? "" : "/") + rv; node = node.getParent(); } return rv; } return ""; } }); rft.put(new PredefinedJEPFunction("MediaNode", "IsMediaNodeObject", 1, new String[] { "Object" }) { /** * Returns true if the specified object is a MediaNode object. No automatic type conversion will be performed on the argument. * @param Object the object to test to see if it is a MediaNode object * @return true if the argument is a MediaNode object, false otherwise * @since 7.1 * * @declaration public boolean IsMediaNodeObject(Object Object); */ public Object runSafely(Catbert.FastStack stack) throws Exception{ Object o = stack.pop(); return Boolean.valueOf(o instanceof sage.vfs.MediaNode); }}); } }
googleapis/google-cloud-java
37,392
java-channel/proto-google-cloud-channel-v1/src/main/java/com/google/cloud/channel/v1/ListPurchasableOffersResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/channel/v1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.channel.v1; /** * * * <pre> * Response message for ListPurchasableOffers. * </pre> * * Protobuf type {@code google.cloud.channel.v1.ListPurchasableOffersResponse} */ public final class ListPurchasableOffersResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.channel.v1.ListPurchasableOffersResponse) ListPurchasableOffersResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListPurchasableOffersResponse.newBuilder() to construct. private ListPurchasableOffersResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListPurchasableOffersResponse() { purchasableOffers_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListPurchasableOffersResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.channel.v1.ServiceProto .internal_static_google_cloud_channel_v1_ListPurchasableOffersResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.channel.v1.ServiceProto .internal_static_google_cloud_channel_v1_ListPurchasableOffersResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.channel.v1.ListPurchasableOffersResponse.class, com.google.cloud.channel.v1.ListPurchasableOffersResponse.Builder.class); } public static final int PURCHASABLE_OFFERS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.channel.v1.PurchasableOffer> purchasableOffers_; /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.channel.v1.PurchasableOffer> getPurchasableOffersList() { return purchasableOffers_; } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.channel.v1.PurchasableOfferOrBuilder> getPurchasableOffersOrBuilderList() { return purchasableOffers_; } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ @java.lang.Override public int getPurchasableOffersCount() { return purchasableOffers_.size(); } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ @java.lang.Override public com.google.cloud.channel.v1.PurchasableOffer getPurchasableOffers(int index) { return purchasableOffers_.get(index); } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ @java.lang.Override public com.google.cloud.channel.v1.PurchasableOfferOrBuilder getPurchasableOffersOrBuilder( int index) { return purchasableOffers_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve the next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token to retrieve the next page of results. * </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 < purchasableOffers_.size(); i++) { output.writeMessage(1, purchasableOffers_.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 < purchasableOffers_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, purchasableOffers_.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.channel.v1.ListPurchasableOffersResponse)) { return super.equals(obj); } com.google.cloud.channel.v1.ListPurchasableOffersResponse other = (com.google.cloud.channel.v1.ListPurchasableOffersResponse) obj; if (!getPurchasableOffersList().equals(other.getPurchasableOffersList())) 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 (getPurchasableOffersCount() > 0) { hash = (37 * hash) + PURCHASABLE_OFFERS_FIELD_NUMBER; hash = (53 * hash) + getPurchasableOffersList().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.channel.v1.ListPurchasableOffersResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.channel.v1.ListPurchasableOffersResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.channel.v1.ListPurchasableOffersResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.channel.v1.ListPurchasableOffersResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.channel.v1.ListPurchasableOffersResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.channel.v1.ListPurchasableOffersResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.channel.v1.ListPurchasableOffersResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.channel.v1.ListPurchasableOffersResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.channel.v1.ListPurchasableOffersResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.channel.v1.ListPurchasableOffersResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.channel.v1.ListPurchasableOffersResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.channel.v1.ListPurchasableOffersResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.channel.v1.ListPurchasableOffersResponse 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 ListPurchasableOffers. * </pre> * * Protobuf type {@code google.cloud.channel.v1.ListPurchasableOffersResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.channel.v1.ListPurchasableOffersResponse) com.google.cloud.channel.v1.ListPurchasableOffersResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.channel.v1.ServiceProto .internal_static_google_cloud_channel_v1_ListPurchasableOffersResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.channel.v1.ServiceProto .internal_static_google_cloud_channel_v1_ListPurchasableOffersResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.channel.v1.ListPurchasableOffersResponse.class, com.google.cloud.channel.v1.ListPurchasableOffersResponse.Builder.class); } // Construct using com.google.cloud.channel.v1.ListPurchasableOffersResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (purchasableOffersBuilder_ == null) { purchasableOffers_ = java.util.Collections.emptyList(); } else { purchasableOffers_ = null; purchasableOffersBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.channel.v1.ServiceProto .internal_static_google_cloud_channel_v1_ListPurchasableOffersResponse_descriptor; } @java.lang.Override public com.google.cloud.channel.v1.ListPurchasableOffersResponse getDefaultInstanceForType() { return com.google.cloud.channel.v1.ListPurchasableOffersResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.channel.v1.ListPurchasableOffersResponse build() { com.google.cloud.channel.v1.ListPurchasableOffersResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.channel.v1.ListPurchasableOffersResponse buildPartial() { com.google.cloud.channel.v1.ListPurchasableOffersResponse result = new com.google.cloud.channel.v1.ListPurchasableOffersResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.channel.v1.ListPurchasableOffersResponse result) { if (purchasableOffersBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { purchasableOffers_ = java.util.Collections.unmodifiableList(purchasableOffers_); bitField0_ = (bitField0_ & ~0x00000001); } result.purchasableOffers_ = purchasableOffers_; } else { result.purchasableOffers_ = purchasableOffersBuilder_.build(); } } private void buildPartial0(com.google.cloud.channel.v1.ListPurchasableOffersResponse 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.channel.v1.ListPurchasableOffersResponse) { return mergeFrom((com.google.cloud.channel.v1.ListPurchasableOffersResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.channel.v1.ListPurchasableOffersResponse other) { if (other == com.google.cloud.channel.v1.ListPurchasableOffersResponse.getDefaultInstance()) return this; if (purchasableOffersBuilder_ == null) { if (!other.purchasableOffers_.isEmpty()) { if (purchasableOffers_.isEmpty()) { purchasableOffers_ = other.purchasableOffers_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensurePurchasableOffersIsMutable(); purchasableOffers_.addAll(other.purchasableOffers_); } onChanged(); } } else { if (!other.purchasableOffers_.isEmpty()) { if (purchasableOffersBuilder_.isEmpty()) { purchasableOffersBuilder_.dispose(); purchasableOffersBuilder_ = null; purchasableOffers_ = other.purchasableOffers_; bitField0_ = (bitField0_ & ~0x00000001); purchasableOffersBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getPurchasableOffersFieldBuilder() : null; } else { purchasableOffersBuilder_.addAllMessages(other.purchasableOffers_); } } } 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.channel.v1.PurchasableOffer m = input.readMessage( com.google.cloud.channel.v1.PurchasableOffer.parser(), extensionRegistry); if (purchasableOffersBuilder_ == null) { ensurePurchasableOffersIsMutable(); purchasableOffers_.add(m); } else { purchasableOffersBuilder_.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.channel.v1.PurchasableOffer> purchasableOffers_ = java.util.Collections.emptyList(); private void ensurePurchasableOffersIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { purchasableOffers_ = new java.util.ArrayList<com.google.cloud.channel.v1.PurchasableOffer>( purchasableOffers_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.channel.v1.PurchasableOffer, com.google.cloud.channel.v1.PurchasableOffer.Builder, com.google.cloud.channel.v1.PurchasableOfferOrBuilder> purchasableOffersBuilder_; /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public java.util.List<com.google.cloud.channel.v1.PurchasableOffer> getPurchasableOffersList() { if (purchasableOffersBuilder_ == null) { return java.util.Collections.unmodifiableList(purchasableOffers_); } else { return purchasableOffersBuilder_.getMessageList(); } } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public int getPurchasableOffersCount() { if (purchasableOffersBuilder_ == null) { return purchasableOffers_.size(); } else { return purchasableOffersBuilder_.getCount(); } } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public com.google.cloud.channel.v1.PurchasableOffer getPurchasableOffers(int index) { if (purchasableOffersBuilder_ == null) { return purchasableOffers_.get(index); } else { return purchasableOffersBuilder_.getMessage(index); } } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public Builder setPurchasableOffers( int index, com.google.cloud.channel.v1.PurchasableOffer value) { if (purchasableOffersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePurchasableOffersIsMutable(); purchasableOffers_.set(index, value); onChanged(); } else { purchasableOffersBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public Builder setPurchasableOffers( int index, com.google.cloud.channel.v1.PurchasableOffer.Builder builderForValue) { if (purchasableOffersBuilder_ == null) { ensurePurchasableOffersIsMutable(); purchasableOffers_.set(index, builderForValue.build()); onChanged(); } else { purchasableOffersBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public Builder addPurchasableOffers(com.google.cloud.channel.v1.PurchasableOffer value) { if (purchasableOffersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePurchasableOffersIsMutable(); purchasableOffers_.add(value); onChanged(); } else { purchasableOffersBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public Builder addPurchasableOffers( int index, com.google.cloud.channel.v1.PurchasableOffer value) { if (purchasableOffersBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePurchasableOffersIsMutable(); purchasableOffers_.add(index, value); onChanged(); } else { purchasableOffersBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public Builder addPurchasableOffers( com.google.cloud.channel.v1.PurchasableOffer.Builder builderForValue) { if (purchasableOffersBuilder_ == null) { ensurePurchasableOffersIsMutable(); purchasableOffers_.add(builderForValue.build()); onChanged(); } else { purchasableOffersBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public Builder addPurchasableOffers( int index, com.google.cloud.channel.v1.PurchasableOffer.Builder builderForValue) { if (purchasableOffersBuilder_ == null) { ensurePurchasableOffersIsMutable(); purchasableOffers_.add(index, builderForValue.build()); onChanged(); } else { purchasableOffersBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public Builder addAllPurchasableOffers( java.lang.Iterable<? extends com.google.cloud.channel.v1.PurchasableOffer> values) { if (purchasableOffersBuilder_ == null) { ensurePurchasableOffersIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, purchasableOffers_); onChanged(); } else { purchasableOffersBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public Builder clearPurchasableOffers() { if (purchasableOffersBuilder_ == null) { purchasableOffers_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { purchasableOffersBuilder_.clear(); } return this; } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public Builder removePurchasableOffers(int index) { if (purchasableOffersBuilder_ == null) { ensurePurchasableOffersIsMutable(); purchasableOffers_.remove(index); onChanged(); } else { purchasableOffersBuilder_.remove(index); } return this; } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public com.google.cloud.channel.v1.PurchasableOffer.Builder getPurchasableOffersBuilder( int index) { return getPurchasableOffersFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public com.google.cloud.channel.v1.PurchasableOfferOrBuilder getPurchasableOffersOrBuilder( int index) { if (purchasableOffersBuilder_ == null) { return purchasableOffers_.get(index); } else { return purchasableOffersBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public java.util.List<? extends com.google.cloud.channel.v1.PurchasableOfferOrBuilder> getPurchasableOffersOrBuilderList() { if (purchasableOffersBuilder_ != null) { return purchasableOffersBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(purchasableOffers_); } } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public com.google.cloud.channel.v1.PurchasableOffer.Builder addPurchasableOffersBuilder() { return getPurchasableOffersFieldBuilder() .addBuilder(com.google.cloud.channel.v1.PurchasableOffer.getDefaultInstance()); } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public com.google.cloud.channel.v1.PurchasableOffer.Builder addPurchasableOffersBuilder( int index) { return getPurchasableOffersFieldBuilder() .addBuilder(index, com.google.cloud.channel.v1.PurchasableOffer.getDefaultInstance()); } /** * * * <pre> * The list of Offers requested. * </pre> * * <code>repeated .google.cloud.channel.v1.PurchasableOffer purchasable_offers = 1;</code> */ public java.util.List<com.google.cloud.channel.v1.PurchasableOffer.Builder> getPurchasableOffersBuilderList() { return getPurchasableOffersFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.channel.v1.PurchasableOffer, com.google.cloud.channel.v1.PurchasableOffer.Builder, com.google.cloud.channel.v1.PurchasableOfferOrBuilder> getPurchasableOffersFieldBuilder() { if (purchasableOffersBuilder_ == null) { purchasableOffersBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.channel.v1.PurchasableOffer, com.google.cloud.channel.v1.PurchasableOffer.Builder, com.google.cloud.channel.v1.PurchasableOfferOrBuilder>( purchasableOffers_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); purchasableOffers_ = null; } return purchasableOffersBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token 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 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 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 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 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.cloud.channel.v1.ListPurchasableOffersResponse) } // @@protoc_insertion_point(class_scope:google.cloud.channel.v1.ListPurchasableOffersResponse) private static final com.google.cloud.channel.v1.ListPurchasableOffersResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.channel.v1.ListPurchasableOffersResponse(); } public static com.google.cloud.channel.v1.ListPurchasableOffersResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListPurchasableOffersResponse> PARSER = new com.google.protobuf.AbstractParser<ListPurchasableOffersResponse>() { @java.lang.Override public ListPurchasableOffersResponse 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<ListPurchasableOffersResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListPurchasableOffersResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.channel.v1.ListPurchasableOffersResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,322
java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/OutputFieldSpec.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/data_foundry_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1; /** * * * <pre> * Defines a specification for a single output field. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.OutputFieldSpec} */ public final class OutputFieldSpec extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.OutputFieldSpec) OutputFieldSpecOrBuilder { private static final long serialVersionUID = 0L; // Use OutputFieldSpec.newBuilder() to construct. private OutputFieldSpec(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private OutputFieldSpec() { fieldName_ = ""; guidance_ = ""; fieldType_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new OutputFieldSpec(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.DataFoundryServiceProto .internal_static_google_cloud_aiplatform_v1_OutputFieldSpec_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.DataFoundryServiceProto .internal_static_google_cloud_aiplatform_v1_OutputFieldSpec_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.OutputFieldSpec.class, com.google.cloud.aiplatform.v1.OutputFieldSpec.Builder.class); } /** * * * <pre> * The data type of the field. * </pre> * * Protobuf enum {@code google.cloud.aiplatform.v1.OutputFieldSpec.FieldType} */ public enum FieldType implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Field type is unspecified. * </pre> * * <code>FIELD_TYPE_UNSPECIFIED = 0;</code> */ FIELD_TYPE_UNSPECIFIED(0), /** * * * <pre> * Arbitrary content field type. * </pre> * * <code>CONTENT = 1;</code> */ CONTENT(1), /** * * * <pre> * Text field type. * </pre> * * <code>TEXT = 2;</code> */ TEXT(2), /** * * * <pre> * Image field type. * </pre> * * <code>IMAGE = 3;</code> */ IMAGE(3), /** * * * <pre> * Audio field type. * </pre> * * <code>AUDIO = 4;</code> */ AUDIO(4), UNRECOGNIZED(-1), ; /** * * * <pre> * Field type is unspecified. * </pre> * * <code>FIELD_TYPE_UNSPECIFIED = 0;</code> */ public static final int FIELD_TYPE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Arbitrary content field type. * </pre> * * <code>CONTENT = 1;</code> */ public static final int CONTENT_VALUE = 1; /** * * * <pre> * Text field type. * </pre> * * <code>TEXT = 2;</code> */ public static final int TEXT_VALUE = 2; /** * * * <pre> * Image field type. * </pre> * * <code>IMAGE = 3;</code> */ public static final int IMAGE_VALUE = 3; /** * * * <pre> * Audio field type. * </pre> * * <code>AUDIO = 4;</code> */ public static final int AUDIO_VALUE = 4; 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 FieldType 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 FieldType forNumber(int value) { switch (value) { case 0: return FIELD_TYPE_UNSPECIFIED; case 1: return CONTENT; case 2: return TEXT; case 3: return IMAGE; case 4: return AUDIO; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<FieldType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<FieldType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<FieldType>() { public FieldType findValueByNumber(int number) { return FieldType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.cloud.aiplatform.v1.OutputFieldSpec.getDescriptor().getEnumTypes().get(0); } private static final FieldType[] VALUES = values(); public static FieldType 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 FieldType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.aiplatform.v1.OutputFieldSpec.FieldType) } public static final int FIELD_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object fieldName_ = ""; /** * * * <pre> * Required. The name of the output field. * </pre> * * <code>string field_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The fieldName. */ @java.lang.Override public java.lang.String getFieldName() { java.lang.Object ref = fieldName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); fieldName_ = s; return s; } } /** * * * <pre> * Required. The name of the output field. * </pre> * * <code>string field_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for fieldName. */ @java.lang.Override public com.google.protobuf.ByteString getFieldNameBytes() { java.lang.Object ref = fieldName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); fieldName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int GUIDANCE_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object guidance_ = ""; /** * * * <pre> * Optional. Optional, but recommended. Additional guidance specific to this * field to provide targeted instructions for the LLM to generate the content * of a single output field. While the LLM can sometimes infer content from * the field name, providing explicit guidance is preferred. * </pre> * * <code>string guidance = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The guidance. */ @java.lang.Override public java.lang.String getGuidance() { java.lang.Object ref = guidance_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); guidance_ = s; return s; } } /** * * * <pre> * Optional. Optional, but recommended. Additional guidance specific to this * field to provide targeted instructions for the LLM to generate the content * of a single output field. While the LLM can sometimes infer content from * the field name, providing explicit guidance is preferred. * </pre> * * <code>string guidance = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for guidance. */ @java.lang.Override public com.google.protobuf.ByteString getGuidanceBytes() { java.lang.Object ref = guidance_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); guidance_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FIELD_TYPE_FIELD_NUMBER = 3; private int fieldType_ = 0; /** * * * <pre> * Optional. The data type of the field. Defaults to CONTENT if not set. * </pre> * * <code> * .google.cloud.aiplatform.v1.OutputFieldSpec.FieldType field_type = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The enum numeric value on the wire for fieldType. */ @java.lang.Override public int getFieldTypeValue() { return fieldType_; } /** * * * <pre> * Optional. The data type of the field. Defaults to CONTENT if not set. * </pre> * * <code> * .google.cloud.aiplatform.v1.OutputFieldSpec.FieldType field_type = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The fieldType. */ @java.lang.Override public com.google.cloud.aiplatform.v1.OutputFieldSpec.FieldType getFieldType() { com.google.cloud.aiplatform.v1.OutputFieldSpec.FieldType result = com.google.cloud.aiplatform.v1.OutputFieldSpec.FieldType.forNumber(fieldType_); return result == null ? com.google.cloud.aiplatform.v1.OutputFieldSpec.FieldType.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(fieldName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, fieldName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(guidance_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, guidance_); } if (fieldType_ != com.google.cloud.aiplatform.v1.OutputFieldSpec.FieldType.FIELD_TYPE_UNSPECIFIED .getNumber()) { output.writeEnum(3, fieldType_); } 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(fieldName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, fieldName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(guidance_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, guidance_); } if (fieldType_ != com.google.cloud.aiplatform.v1.OutputFieldSpec.FieldType.FIELD_TYPE_UNSPECIFIED .getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(3, fieldType_); } 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.OutputFieldSpec)) { return super.equals(obj); } com.google.cloud.aiplatform.v1.OutputFieldSpec other = (com.google.cloud.aiplatform.v1.OutputFieldSpec) obj; if (!getFieldName().equals(other.getFieldName())) return false; if (!getGuidance().equals(other.getGuidance())) return false; if (fieldType_ != other.fieldType_) 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) + FIELD_NAME_FIELD_NUMBER; hash = (53 * hash) + getFieldName().hashCode(); hash = (37 * hash) + GUIDANCE_FIELD_NUMBER; hash = (53 * hash) + getGuidance().hashCode(); hash = (37 * hash) + FIELD_TYPE_FIELD_NUMBER; hash = (53 * hash) + fieldType_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1.OutputFieldSpec parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.OutputFieldSpec 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.OutputFieldSpec parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.OutputFieldSpec 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.OutputFieldSpec parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.OutputFieldSpec 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.OutputFieldSpec parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.OutputFieldSpec 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.OutputFieldSpec parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.OutputFieldSpec 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.OutputFieldSpec 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.OutputFieldSpec 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.OutputFieldSpec 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> * Defines a specification for a single output field. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.OutputFieldSpec} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.OutputFieldSpec) com.google.cloud.aiplatform.v1.OutputFieldSpecOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.DataFoundryServiceProto .internal_static_google_cloud_aiplatform_v1_OutputFieldSpec_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.DataFoundryServiceProto .internal_static_google_cloud_aiplatform_v1_OutputFieldSpec_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.OutputFieldSpec.class, com.google.cloud.aiplatform.v1.OutputFieldSpec.Builder.class); } // Construct using com.google.cloud.aiplatform.v1.OutputFieldSpec.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; fieldName_ = ""; guidance_ = ""; fieldType_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1.DataFoundryServiceProto .internal_static_google_cloud_aiplatform_v1_OutputFieldSpec_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1.OutputFieldSpec getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1.OutputFieldSpec.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1.OutputFieldSpec build() { com.google.cloud.aiplatform.v1.OutputFieldSpec result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1.OutputFieldSpec buildPartial() { com.google.cloud.aiplatform.v1.OutputFieldSpec result = new com.google.cloud.aiplatform.v1.OutputFieldSpec(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.aiplatform.v1.OutputFieldSpec result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.fieldName_ = fieldName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.guidance_ = guidance_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.fieldType_ = fieldType_; } } @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.OutputFieldSpec) { return mergeFrom((com.google.cloud.aiplatform.v1.OutputFieldSpec) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1.OutputFieldSpec other) { if (other == com.google.cloud.aiplatform.v1.OutputFieldSpec.getDefaultInstance()) return this; if (!other.getFieldName().isEmpty()) { fieldName_ = other.fieldName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getGuidance().isEmpty()) { guidance_ = other.guidance_; bitField0_ |= 0x00000002; onChanged(); } if (other.fieldType_ != 0) { setFieldTypeValue(other.getFieldTypeValue()); } 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: { fieldName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { guidance_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { fieldType_ = input.readEnum(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object fieldName_ = ""; /** * * * <pre> * Required. The name of the output field. * </pre> * * <code>string field_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The fieldName. */ public java.lang.String getFieldName() { java.lang.Object ref = fieldName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); fieldName_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of the output field. * </pre> * * <code>string field_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for fieldName. */ public com.google.protobuf.ByteString getFieldNameBytes() { java.lang.Object ref = fieldName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); fieldName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of the output field. * </pre> * * <code>string field_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The fieldName to set. * @return This builder for chaining. */ public Builder setFieldName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } fieldName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The name of the output field. * </pre> * * <code>string field_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearFieldName() { fieldName_ = getDefaultInstance().getFieldName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The name of the output field. * </pre> * * <code>string field_name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for fieldName to set. * @return This builder for chaining. */ public Builder setFieldNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); fieldName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object guidance_ = ""; /** * * * <pre> * Optional. Optional, but recommended. Additional guidance specific to this * field to provide targeted instructions for the LLM to generate the content * of a single output field. While the LLM can sometimes infer content from * the field name, providing explicit guidance is preferred. * </pre> * * <code>string guidance = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The guidance. */ public java.lang.String getGuidance() { java.lang.Object ref = guidance_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); guidance_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Optional, but recommended. Additional guidance specific to this * field to provide targeted instructions for the LLM to generate the content * of a single output field. While the LLM can sometimes infer content from * the field name, providing explicit guidance is preferred. * </pre> * * <code>string guidance = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for guidance. */ public com.google.protobuf.ByteString getGuidanceBytes() { java.lang.Object ref = guidance_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); guidance_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Optional, but recommended. Additional guidance specific to this * field to provide targeted instructions for the LLM to generate the content * of a single output field. While the LLM can sometimes infer content from * the field name, providing explicit guidance is preferred. * </pre> * * <code>string guidance = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The guidance to set. * @return This builder for chaining. */ public Builder setGuidance(java.lang.String value) { if (value == null) { throw new NullPointerException(); } guidance_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Optional, but recommended. Additional guidance specific to this * field to provide targeted instructions for the LLM to generate the content * of a single output field. While the LLM can sometimes infer content from * the field name, providing explicit guidance is preferred. * </pre> * * <code>string guidance = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearGuidance() { guidance_ = getDefaultInstance().getGuidance(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Optional. Optional, but recommended. Additional guidance specific to this * field to provide targeted instructions for the LLM to generate the content * of a single output field. While the LLM can sometimes infer content from * the field name, providing explicit guidance is preferred. * </pre> * * <code>string guidance = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for guidance to set. * @return This builder for chaining. */ public Builder setGuidanceBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); guidance_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int fieldType_ = 0; /** * * * <pre> * Optional. The data type of the field. Defaults to CONTENT if not set. * </pre> * * <code> * .google.cloud.aiplatform.v1.OutputFieldSpec.FieldType field_type = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The enum numeric value on the wire for fieldType. */ @java.lang.Override public int getFieldTypeValue() { return fieldType_; } /** * * * <pre> * Optional. The data type of the field. Defaults to CONTENT if not set. * </pre> * * <code> * .google.cloud.aiplatform.v1.OutputFieldSpec.FieldType field_type = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The enum numeric value on the wire for fieldType to set. * @return This builder for chaining. */ public Builder setFieldTypeValue(int value) { fieldType_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. The data type of the field. Defaults to CONTENT if not set. * </pre> * * <code> * .google.cloud.aiplatform.v1.OutputFieldSpec.FieldType field_type = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The fieldType. */ @java.lang.Override public com.google.cloud.aiplatform.v1.OutputFieldSpec.FieldType getFieldType() { com.google.cloud.aiplatform.v1.OutputFieldSpec.FieldType result = com.google.cloud.aiplatform.v1.OutputFieldSpec.FieldType.forNumber(fieldType_); return result == null ? com.google.cloud.aiplatform.v1.OutputFieldSpec.FieldType.UNRECOGNIZED : result; } /** * * * <pre> * Optional. The data type of the field. Defaults to CONTENT if not set. * </pre> * * <code> * .google.cloud.aiplatform.v1.OutputFieldSpec.FieldType field_type = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The fieldType to set. * @return This builder for chaining. */ public Builder setFieldType(com.google.cloud.aiplatform.v1.OutputFieldSpec.FieldType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; fieldType_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Optional. The data type of the field. Defaults to CONTENT if not set. * </pre> * * <code> * .google.cloud.aiplatform.v1.OutputFieldSpec.FieldType field_type = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return This builder for chaining. */ public Builder clearFieldType() { bitField0_ = (bitField0_ & ~0x00000004); fieldType_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.OutputFieldSpec) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.OutputFieldSpec) private static final com.google.cloud.aiplatform.v1.OutputFieldSpec DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.OutputFieldSpec(); } public static com.google.cloud.aiplatform.v1.OutputFieldSpec getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<OutputFieldSpec> PARSER = new com.google.protobuf.AbstractParser<OutputFieldSpec>() { @java.lang.Override public OutputFieldSpec 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<OutputFieldSpec> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<OutputFieldSpec> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1.OutputFieldSpec getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/helix
37,069
helix-core/src/test/java/org/apache/helix/manager/zk/TestZkBaseDataAccessor.java
package org.apache.helix.manager.zk; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.google.common.collect.ImmutableList; import org.apache.helix.AccessOption; import org.apache.helix.BaseDataAccessor; import org.apache.helix.PropertyPathBuilder; import org.apache.helix.TestHelper; import org.apache.helix.zookeeper.api.client.HelixZkClient; import org.apache.helix.zookeeper.api.client.RealmAwareZkClient; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.datamodel.ZNRecordUpdater; import org.apache.helix.ZkUnitTestBase; import org.apache.helix.manager.zk.ZkBaseDataAccessor.AccessResult; import org.apache.helix.manager.zk.ZkBaseDataAccessor.RetCode; import org.apache.helix.zookeeper.exception.ZkClientException; import org.apache.helix.zookeeper.zkclient.DataUpdater; import org.apache.helix.zookeeper.zkclient.exception.ZkBadVersionException; import org.apache.helix.zookeeper.zkclient.exception.ZkException; import org.apache.helix.zookeeper.zkclient.exception.ZkMarshallingError; import org.apache.helix.zookeeper.zkclient.serialize.ZkSerializer; import org.apache.zookeeper.data.Stat; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; public class TestZkBaseDataAccessor extends ZkUnitTestBase { // serialize/deserialize integer list to byte array private static final ZkSerializer LIST_SERIALIZER = new ZkSerializer() { @Override public byte[] serialize(Object o) throws ZkMarshallingError { List<Integer> list = (List<Integer>) o; return list.stream().map(String::valueOf).collect(Collectors.joining(",")) .getBytes(); } @Override public Object deserialize(byte[] bytes) throws ZkMarshallingError { String string = new String(bytes); return Arrays.stream(string.split(",")).map(Integer::valueOf) .collect(Collectors.toList()); } }; String _rootPath = TestHelper.getTestClassName(); @AfterMethod public void afterMethod() { String path = "/" + _rootPath; if (_gZkClient.exists(path)) { _gZkClient.deleteRecursively(path); } } @Test public void testSyncSet() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZNRecord record = new ZNRecord("msg_0"); BaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); boolean success = accessor.set(path, record, AccessOption.PERSISTENT); Assert.assertTrue(success); ZNRecord getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "msg_0"); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testSyncSetWithVersion() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZNRecord record = new ZNRecord("msg_0"); BaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); // set persistent boolean success = accessor.set(path, record, 0, AccessOption.PERSISTENT); Assert.assertFalse(success, "Should fail since version not match"); try { _gZkClient.readData(path, false); Assert.fail("Should get no node exception"); } catch (Exception e) { // OK } success = accessor.set(path, record, -1, AccessOption.PERSISTENT); Assert.assertTrue(success); ZNRecord getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "msg_0"); // set ephemeral path = String.format("/%s/%s", _rootPath, "msg_1"); record = new ZNRecord("msg_1"); success = accessor.set(path, record, 0, AccessOption.EPHEMERAL); Assert.assertFalse(success); try { _gZkClient.readData(path, false); Assert.fail("Should get no node exception"); } catch (Exception e) { // OK } success = accessor.set(path, record, -1, AccessOption.EPHEMERAL); Assert.assertTrue(success); getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "msg_1"); record.setSimpleField("key0", "value0"); success = accessor.set(path, record, 0, AccessOption.PERSISTENT); Assert.assertTrue(success, "Should pass. AccessOption.PERSISTENT is ignored"); getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getSimpleFields().size(), 1); Assert.assertNotNull(getRecord.getSimpleField("key0")); Assert.assertEquals(getRecord.getSimpleField("key0"), "value0"); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testSyncDoSet() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s/%s", _rootPath, "msg_0", "submsg_0"); ZNRecord record = new ZNRecord("submsg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); AccessResult result = accessor.doSet(path, record, -1, AccessOption.PERSISTENT); Assert.assertEquals(result._retCode, RetCode.OK); Assert.assertEquals(result._pathCreated.size(), 3); Assert.assertTrue(result._pathCreated.contains(String.format("/%s/%s", _rootPath, "msg_0"))); Assert.assertTrue(result._pathCreated.contains(path)); Assert.assertTrue(_gZkClient.exists(String.format("/%s/%s", _rootPath, "msg_0"))); ZNRecord getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "submsg_0"); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testDoSetWithException() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s/%s", _rootPath, "msg_0", "submsg_0"); ZNRecord record = new ZNRecord("submsg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); AccessResult result = accessor.doSet(path, record, -1, AccessOption.PERSISTENT); ZNRecord getRecord = _gZkClient.readData(path); // create mock spy for _gZkClient HelixZkClient mockZkClient = Mockito.spy(_gZkClient); // mock so that _gZkClient throws ZkBadVersionException Mockito.doThrow(new ZkBadVersionException("")) .when(mockZkClient).writeDataGetStat(Mockito.anyString(), Mockito.any(), Mockito.anyInt()); try { accessor.doSet(path, record, getRecord.getVersion(), AccessOption.PERSISTENT); } catch (ZkBadVersionException e) { // OK } System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testSyncCreate() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZNRecord record = new ZNRecord("msg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<>(_gZkClient); boolean success = accessor.create(path, record, AccessOption.PERSISTENT); Assert.assertTrue(success); ZNRecord getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "msg_0"); record.setSimpleField("key0", "value0"); success = accessor.create(path, record, AccessOption.PERSISTENT); Assert.assertFalse(success, "Should fail since node already exists"); getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getSimpleFields().size(), 0); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testSyncCreateWithTTL() { System.setProperty("zookeeper.extendedTypesEnabled", "true"); String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZNRecord record = new ZNRecord("msg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<>(_gZkClient); boolean success = accessor.create(path, record, AccessOption.PERSISTENT_WITH_TTL); Assert.assertFalse(success); long ttl = 1L; success = accessor.create(path, record, AccessOption.PERSISTENT_WITH_TTL, ttl); Assert.assertTrue(success); ZNRecord getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "msg_0"); record.setSimpleField("key0", "value0"); success = accessor.create(path, record, AccessOption.PERSISTENT_WITH_TTL, ttl); Assert.assertFalse(success, "Should fail since node already exists"); getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getSimpleFields().size(), 0); System.clearProperty("zookeeper.extendedTypesEnabled"); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testSyncCreateContainer() { System.setProperty("zookeeper.extendedTypesEnabled", "true"); String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZNRecord record = new ZNRecord("msg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<>(_gZkClient); boolean success = accessor.create(path, record, AccessOption.CONTAINER); Assert.assertTrue(success); ZNRecord getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "msg_0"); record.setSimpleField("key0", "value0"); success = accessor.create(path, record, AccessOption.CONTAINER); Assert.assertFalse(success, "Should fail since node already exists"); getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getSimpleFields().size(), 0); System.clearProperty("zookeeper.extendedTypesEnabled"); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testDefaultAccessorCreateCustomData() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZkBaseDataAccessor defaultAccessor = new ZkBaseDataAccessor(ZK_ADDR); List<Integer> l0 = ImmutableList.of(1, 2, 3); boolean createResult = defaultAccessor.create(path, l0, AccessOption.PERSISTENT); // The result is expected to be false because the list is not ZNRecord Assert.assertFalse(createResult); createResult = defaultAccessor.create(path, new ZNRecord("test"), AccessOption.PERSISTENT); // The result is expected to be true Assert.assertTrue(createResult); defaultAccessor.close(); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testCustomAccessorCreateZnRecord() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZkBaseDataAccessor customDataAccessor = new ZkBaseDataAccessor(ZK_ADDR, LIST_SERIALIZER); boolean createResult = customDataAccessor.create(path, new ZNRecord("test"), AccessOption.PERSISTENT); // The result is expected to be false because the ZnRecord is not List Assert.assertFalse(createResult); createResult = customDataAccessor.create(path, ImmutableList.of(1, 2, 3), AccessOption.PERSISTENT); // The result is expected to be true Assert.assertTrue(createResult); customDataAccessor.close(); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testSyncCreateWithCustomSerializer() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZkBaseDataAccessor<List<Integer>> accessor = new ZkBaseDataAccessor<>(ZK_ADDR, LIST_SERIALIZER); List<Integer> l0 = ImmutableList.of(1, 2, 3); List<Integer> l1 = ImmutableList.of(4, 5, 6); boolean createResult = accessor.create(path, l0, AccessOption.PERSISTENT); Assert.assertTrue(createResult); List<Integer> data = (List<Integer>) accessor.get(path, null, AccessOption.PERSISTENT); Assert.assertEquals(data, l0); boolean setResult = accessor.set(path, l1, 0, AccessOption.PERSISTENT); Assert.assertTrue(setResult); data = (List<Integer>) accessor.get(path, null, AccessOption.PERSISTENT); Assert.assertEquals(data, l1); accessor.close(); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testSyncUpdate() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZNRecord record = new ZNRecord("msg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); boolean success = accessor.update(path, new ZNRecordUpdater(record), AccessOption.PERSISTENT); Assert.assertTrue(success); ZNRecord getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "msg_0"); record.setSimpleField("key0", "value0"); success = accessor.update(path, new ZNRecordUpdater(record), AccessOption.PERSISTENT); Assert.assertTrue(success); getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getSimpleFields().size(), 1); Assert.assertNotNull(getRecord.getSimpleField("key0")); Assert.assertEquals(getRecord.getSimpleField("key0"), "value0"); // test throw exception from updater success = accessor.update(path, new DataUpdater<ZNRecord>() { @Override public ZNRecord update(ZNRecord currentData) { throw new RuntimeException("IGNORABLE: test throw exception from updater"); } }, AccessOption.PERSISTENT); Assert.assertFalse(success); getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getSimpleFields().size(), 1); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testSyncMultiSet() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path1 = String.format("/%s/%s", _rootPath, "foo"); String path2 = String.format("/%s/%s", _rootPath, "bar"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); accessor.create(path1, new ZNRecord("foo"), AccessOption.PERSISTENT); accessor.create(path2, new ZNRecord("bar"), AccessOption.PERSISTENT); boolean success = accessor.multiSet(Map.of(path1, new DataUpdater<ZNRecord>() { @Override public ZNRecord update(ZNRecord currentData) { currentData.setMapField("key", Map.of("key1", "value1")); return currentData; } }, path2, new DataUpdater<ZNRecord>() { @Override public ZNRecord update(ZNRecord currentData) { currentData.setSimpleField("key", "value"); return currentData; } })); Assert.assertTrue(success); ZNRecord getRecord1 = _gZkClient.readData(path1); ZNRecord getRecord2 = _gZkClient.readData(path2); Assert.assertNotNull(getRecord1); Assert.assertEquals(getRecord1.getId(), "foo"); Assert.assertEquals(getRecord1.getMapField("key"), Map.of("key1", "value1")); Assert.assertNotNull(getRecord2); Assert.assertEquals(getRecord2.getId(), "bar"); Assert.assertEquals(getRecord2.getSimpleField("key"), "value"); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testSyncMultiSetOneRecordNoExist() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path1 = String.format("/%s/%s", _rootPath, "foo"); String path2 = String.format("/%s/%s", _rootPath, "bar"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); accessor.create(path1, new ZNRecord("foo"), AccessOption.PERSISTENT); boolean success = accessor.multiSet(Map.of(path1, new DataUpdater<ZNRecord>() { @Override public ZNRecord update(ZNRecord currentData) { currentData.setMapField("key", Map.of("key1", "value1")); return currentData; } }, path2, new DataUpdater<ZNRecord>() { @Override public ZNRecord update(ZNRecord currentData) { currentData.setSimpleField("key", "value"); return currentData; } })); Assert.assertFalse(success); ZNRecord getRecord1 = _gZkClient.readData(path1); Assert.assertNotNull(getRecord1); Assert.assertEquals(getRecord1.getId(), "foo"); Assert.assertNotSame(getRecord1.getMapField("key"), Map.of("key1", "value1")); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testSyncRemove() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZNRecord record = new ZNRecord("msg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); // Base data accessor shall not fail when remove a non-exist path boolean success = accessor.remove(path, 0); Assert.assertTrue(success); success = accessor.create(path, record, AccessOption.PERSISTENT); Assert.assertTrue(success); ZNRecord getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "msg_0"); // Tests that ZkClientException thrown from ZkClient should be caught // and remove() should return false. RealmAwareZkClient mockZkClient = Mockito.mock(RealmAwareZkClient.class); Mockito.doThrow(new ZkException("Failed to delete " + path)).when(mockZkClient) .delete(path); Mockito.doThrow(new ZkClientException("Failed to recursively delete " + path)).when(mockZkClient) .deleteRecursively(path); ZkBaseDataAccessor<ZNRecord> accessorMock = new ZkBaseDataAccessor<>(mockZkClient); try { Assert.assertFalse(accessorMock.remove(path, AccessOption.PERSISTENT), "Should return false because ZkClientException is thrown"); } catch (ZkClientException e) { Assert.fail("Should not throw ZkClientException because it should be caught."); } success = accessor.remove(path, 0); Assert.assertTrue(success); Assert.assertFalse(_gZkClient.exists(path)); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } /** * Test that remove with expected version will fail on version mismatch. Succeed on version match. */ @Test public void testRemoveWithExpectedVersion() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZNRecord record = new ZNRecord("msg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); // Create node Assert.assertTrue(accessor.create(path, record, AccessOption.PERSISTENT)); // Create child node String childPath = path + "/child"; Assert.assertTrue(accessor.create(childPath, record, AccessOption.PERSISTENT)); // Delete parent with correct expected version. Should fail due to having a child int currentVersion = accessor.getStat(path, 0).getVersion(); Assert.assertFalse(accessor.removeWithExpectedVersion(path, 0, currentVersion)); // Remove Child Assert.assertTrue(accessor.removeWithExpectedVersion(childPath, 0, -1)); // Delete childless node with wrong expected version. Should fail due to version mismatch Assert.assertFalse(accessor.removeWithExpectedVersion(path, 0, currentVersion+100)); // Delete childless node with correct expected version. Shoudl succeed Assert.assertTrue(accessor.removeWithExpectedVersion(path, 0, currentVersion)); } @Test public void testDeleteNodeWithChildren() { String root = _rootPath; ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<>(_gZkClient); // CreateChildren List<ZNRecord> records = new ArrayList<>(); List<String> paths = new ArrayList<>(); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; paths.add(PropertyPathBuilder.instanceMessage(root, "host_1", msgId)); records.add(new ZNRecord(msgId)); } boolean[] success = accessor.createChildren(paths, records, AccessOption.PERSISTENT); // Attempt to remove parent. Shouldn't throw an error or warning log. // Should return True if recursive deletion succeeds. Assert.assertTrue(accessor.remove(PropertyPathBuilder.instanceMessage(root, "host_1"), 0), "Should return True despite log errors."); // Assert child message nodes were removed when calling remove on parent for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; String path = PropertyPathBuilder.instanceMessage(root, "host_1", msgId); boolean pathExists = _gZkClient.exists(path); Assert.assertFalse(pathExists, "Message znode should have been removed by accessor msgId=" + msgId); } } @Test public void testSyncGet() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZNRecord record = new ZNRecord("msg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); Stat stat = new Stat(); ZNRecord getRecord = accessor.get(path, stat, 0); Assert.assertNull(getRecord); try { accessor.get(path, stat, AccessOption.THROW_EXCEPTION_IFNOTEXIST); Assert.fail("Should throw exception if not exist"); } catch (Exception e) { // OK } boolean success = accessor.create(path, record, AccessOption.PERSISTENT); Assert.assertTrue(success); getRecord = accessor.get(path, stat, 0); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "msg_0"); Assert.assertEquals(stat.getVersion(), 0); record.setSimpleField("key0", "value0"); success = accessor.set(path, record, AccessOption.PERSISTENT); Assert.assertTrue(success); getRecord = accessor.get(path, stat, 0); Assert.assertNotNull(getRecord); Assert.assertEquals(record.getSimpleFields().size(), 1); Assert.assertNotNull(getRecord.getSimpleField("key0")); Assert.assertEquals(getRecord.getSimpleField("key0"), "value0"); Assert.assertEquals(stat.getVersion(), 1); ZNRecord newRecord = new ZNRecord("msg_0"); newRecord.setSimpleField("key1", "value1"); success = accessor.update(path, new ZNRecordUpdater(newRecord), AccessOption.PERSISTENT); Assert.assertTrue(success); getRecord = accessor.get(path, stat, 0); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getSimpleFields().size(), 2); Assert.assertNotNull(getRecord.getSimpleField("key0")); Assert.assertEquals(getRecord.getSimpleField("key0"), "value0"); Assert.assertNotNull(getRecord.getSimpleField("key1")); Assert.assertEquals(getRecord.getSimpleField("key1"), "value1"); Assert.assertEquals(stat.getVersion(), 2); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testSyncExist() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZNRecord record = new ZNRecord("msg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); boolean success = accessor.exists(path, 0); Assert.assertFalse(success); success = accessor.create(path, record, AccessOption.EPHEMERAL); Assert.assertTrue(success); success = accessor.exists(path, 0); Assert.assertTrue(success); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testSyncGetStat() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZNRecord record = new ZNRecord("msg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); Stat stat = accessor.getStat(path, 0); Assert.assertNull(stat); boolean success = accessor.create(path, record, AccessOption.EPHEMERAL); Assert.assertTrue(success); stat = accessor.getStat(path, 0); Assert.assertNotNull(stat); Assert.assertEquals(stat.getVersion(), 0); Assert.assertNotSame(stat.getEphemeralOwner(), 0); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); } @Test public void testAsyncZkBaseDataAccessor() { System.out.println( "START TestZkBaseDataAccessor.async at " + new Date(System.currentTimeMillis())); String root = _rootPath; _gZkClient.deleteRecursively("/" + root); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<>(_gZkClient); // test async createChildren List<ZNRecord> records = new ArrayList<>(); List<String> paths = new ArrayList<>(); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; paths.add(PropertyPathBuilder.instanceMessage(root, "host_1", msgId)); records.add(new ZNRecord(msgId)); } boolean[] success = accessor.createChildren(paths, records, AccessOption.PERSISTENT); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; Assert.assertTrue(success[i], "Should succeed in create " + msgId); } // test get what we created for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; String path = PropertyPathBuilder.instanceMessage(root, "host_1", msgId); ZNRecord record = _gZkClient.readData(path); Assert.assertEquals(record.getId(), msgId, "Should get what we created"); } // test async createChildren with TTL System.setProperty("zookeeper.extendedTypesEnabled", "true"); records = new ArrayList<>(); paths = new ArrayList<>(); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; paths.add(PropertyPathBuilder.instanceMessage(root, "host_2", msgId)); records.add(new ZNRecord(msgId)); } success = accessor.createChildren(paths, records, AccessOption.PERSISTENT_WITH_TTL, 1L); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; Assert.assertTrue(success[i], "Should succeed in create " + msgId); } // test get what we created for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; String path = PropertyPathBuilder.instanceMessage(root, "host_2", msgId); ZNRecord record = _gZkClient.readData(path); Assert.assertEquals(record.getId(), msgId, "Should get what we created"); } // test async createChildren with Container mode records = new ArrayList<>(); paths = new ArrayList<>(); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; paths.add(PropertyPathBuilder.instanceMessage(root, "host_3", msgId)); records.add(new ZNRecord(msgId)); } success = accessor.createChildren(paths, records, AccessOption.CONTAINER); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; Assert.assertTrue(success[i], "Should succeed in create " + msgId); } // test get what we created for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; String path = PropertyPathBuilder.instanceMessage(root, "host_3", msgId); ZNRecord record = _gZkClient.readData(path); Assert.assertEquals(record.getId(), msgId, "Should get what we created"); } System.clearProperty("zookeeper.extendedTypesEnabled"); // test async setChildren records = new ArrayList<>(); paths = new ArrayList<>(); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; paths.add(PropertyPathBuilder.instanceMessage(root, "host_1", msgId)); ZNRecord newRecord = new ZNRecord(msgId); newRecord.setSimpleField("key1", "value1"); records.add(newRecord); } success = accessor.setChildren(paths, records, AccessOption.PERSISTENT); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; Assert.assertTrue(success[i], "Should succeed in set " + msgId); } // test get what we set for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; String path = PropertyPathBuilder.instanceMessage(root, "host_1", msgId); ZNRecord record = _gZkClient.readData(path); Assert.assertEquals(record.getSimpleFields().size(), 1, "Should have 1 simple field set"); Assert.assertEquals(record.getSimpleField("key1"), "value1", "Should have value1 set"); } // test async updateChildren // records = new ArrayList<ZNRecord>(); List<DataUpdater<ZNRecord>> znrecordUpdaters = new ArrayList<DataUpdater<ZNRecord>>(); paths = new ArrayList<>(); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; paths.add(PropertyPathBuilder.instanceMessage(root, "host_1", msgId)); ZNRecord newRecord = new ZNRecord(msgId); newRecord.setSimpleField("key2", "value2"); // records.add(newRecord); znrecordUpdaters.add(new ZNRecordUpdater(newRecord)); } success = accessor.updateChildren(paths, znrecordUpdaters, AccessOption.PERSISTENT); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; Assert.assertTrue(success[i], "Should succeed in update " + msgId); } // test get what we updated for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; String path = PropertyPathBuilder.instanceMessage(root, "host_1", msgId); ZNRecord record = _gZkClient.readData(path); Assert.assertEquals(record.getSimpleFields().size(), 2, "Should have 2 simple fields set"); Assert.assertEquals(record.getSimpleField("key2"), "value2", "Should have value2 set"); } // test async getChildren String parentPath = PropertyPathBuilder.instanceMessage(root, "host_1"); records = accessor.getChildren(parentPath, null, 0, 0, 0); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; ZNRecord record = records.get(i); Assert.assertEquals(record.getId(), msgId, "Should get what we updated"); Assert.assertEquals(record.getSimpleFields().size(), 2, "Should have 2 simple fields set"); Assert.assertEquals(record.getSimpleField("key2"), "value2", "Should have value2 set"); } // test async exists paths = new ArrayList<>(); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; paths.add(PropertyPathBuilder.instanceMessage(root, "host_1", msgId)); } boolean[] exists = accessor.exists(paths, 0); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; Assert.assertTrue(exists[i], "Should exist " + msgId); } // test async getStats paths = new ArrayList<>(); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; paths.add(PropertyPathBuilder.instanceMessage(root, "host_1", msgId)); } Stat[] stats = accessor.getStats(paths, 0); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; Assert.assertNotNull(stats[i], "Stat should exist for " + msgId); Assert.assertEquals(stats[i].getVersion(), 2, "DataVersion should be 2, since we set 1 and update 1 for " + msgId); } // test async remove paths = new ArrayList<>(); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; paths.add(PropertyPathBuilder.instanceMessage(root, "host_1", msgId)); } success = accessor.remove(paths, 0); for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; Assert.assertTrue(success[i], "Should succeed in remove " + msgId); } // test get what we removed for (int i = 0; i < 10; i++) { String msgId = "msg_" + i; String path = PropertyPathBuilder.instanceMessage(root, "host_1", msgId); boolean pathExists = _gZkClient.exists(path); Assert.assertFalse(pathExists, "Should be removed " + msgId); } System.out.println("END TestZkBaseDataAccessor.async at " + new Date(System.currentTimeMillis())); } }
googleapis/google-api-java-client-services
37,547
clients/google-api-services-tagmanager/v2/1.30.1/com/google/api/services/tagmanager/model/Trigger.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.tagmanager.model; /** * Represents a Google Tag Manager Trigger * * <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 Tag Manager 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 Trigger extends com.google.api.client.json.GenericJson { /** * GTM Account ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String accountId; /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> autoEventFilter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter checkValidation; /** * GTM Container ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String containerId; /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter continuousTimeMinMilliseconds; /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> customEventFilter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter eventName; /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> filter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String fingerprint; /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter horizontalScrollPercentageList; /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter interval; /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter intervalSeconds; /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter limit; /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter maxTimerLengthSeconds; /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String notes; /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Parameter> parameter; static { // hack to force ProGuard to consider Parameter 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(Parameter.class); } /** * Parent folder id. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String parentFolderId; /** * GTM Trigger's API relative path. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String path; /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter selector; /** * Auto generated link to the tag manager UI * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String tagManagerUrl; /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter totalTimeMinMilliseconds; /** * The Trigger ID uniquely identifies the GTM Trigger. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String triggerId; /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String type; /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter uniqueTriggerId; /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter verticalScrollPercentageList; /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visibilitySelector; /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visiblePercentageMax; /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visiblePercentageMin; /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter waitForTags; /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter waitForTagsTimeout; /** * GTM Workspace ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String workspaceId; /** * GTM Account ID. * @return value or {@code null} for none */ public java.lang.String getAccountId() { return accountId; } /** * GTM Account ID. * @param accountId accountId or {@code null} for none */ public Trigger setAccountId(java.lang.String accountId) { this.accountId = accountId; return this; } /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getAutoEventFilter() { return autoEventFilter; } /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param autoEventFilter autoEventFilter or {@code null} for none */ public Trigger setAutoEventFilter(java.util.List<Condition> autoEventFilter) { this.autoEventFilter = autoEventFilter; return this; } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getCheckValidation() { return checkValidation; } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param checkValidation checkValidation or {@code null} for none */ public Trigger setCheckValidation(Parameter checkValidation) { this.checkValidation = checkValidation; return this; } /** * GTM Container ID. * @return value or {@code null} for none */ public java.lang.String getContainerId() { return containerId; } /** * GTM Container ID. * @param containerId containerId or {@code null} for none */ public Trigger setContainerId(java.lang.String containerId) { this.containerId = containerId; return this; } /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getContinuousTimeMinMilliseconds() { return continuousTimeMinMilliseconds; } /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param continuousTimeMinMilliseconds continuousTimeMinMilliseconds or {@code null} for none */ public Trigger setContinuousTimeMinMilliseconds(Parameter continuousTimeMinMilliseconds) { this.continuousTimeMinMilliseconds = continuousTimeMinMilliseconds; return this; } /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getCustomEventFilter() { return customEventFilter; } /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param customEventFilter customEventFilter or {@code null} for none */ public Trigger setCustomEventFilter(java.util.List<Condition> customEventFilter) { this.customEventFilter = customEventFilter; return this; } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getEventName() { return eventName; } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param eventName eventName or {@code null} for none */ public Trigger setEventName(Parameter eventName) { this.eventName = eventName; return this; } /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getFilter() { return filter; } /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param filter filter or {@code null} for none */ public Trigger setFilter(java.util.List<Condition> filter) { this.filter = filter; return this; } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * @return value or {@code null} for none */ public java.lang.String getFingerprint() { return fingerprint; } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * @param fingerprint fingerprint or {@code null} for none */ public Trigger setFingerprint(java.lang.String fingerprint) { this.fingerprint = fingerprint; return this; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getHorizontalScrollPercentageList() { return horizontalScrollPercentageList; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param horizontalScrollPercentageList horizontalScrollPercentageList or {@code null} for none */ public Trigger setHorizontalScrollPercentageList(Parameter horizontalScrollPercentageList) { this.horizontalScrollPercentageList = horizontalScrollPercentageList; return this; } /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getInterval() { return interval; } /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param interval interval or {@code null} for none */ public Trigger setInterval(Parameter interval) { this.interval = interval; return this; } /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getIntervalSeconds() { return intervalSeconds; } /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param intervalSeconds intervalSeconds or {@code null} for none */ public Trigger setIntervalSeconds(Parameter intervalSeconds) { this.intervalSeconds = intervalSeconds; return this; } /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getLimit() { return limit; } /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param limit limit or {@code null} for none */ public Trigger setLimit(Parameter limit) { this.limit = limit; return this; } /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getMaxTimerLengthSeconds() { return maxTimerLengthSeconds; } /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param maxTimerLengthSeconds maxTimerLengthSeconds or {@code null} for none */ public Trigger setMaxTimerLengthSeconds(Parameter maxTimerLengthSeconds) { this.maxTimerLengthSeconds = maxTimerLengthSeconds; return this; } /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param name name or {@code null} for none */ public Trigger setName(java.lang.String name) { this.name = name; return this; } /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getNotes() { return notes; } /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param notes notes or {@code null} for none */ public Trigger setNotes(java.lang.String notes) { this.notes = notes; return this; } /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Parameter> getParameter() { return parameter; } /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param parameter parameter or {@code null} for none */ public Trigger setParameter(java.util.List<Parameter> parameter) { this.parameter = parameter; return this; } /** * Parent folder id. * @return value or {@code null} for none */ public java.lang.String getParentFolderId() { return parentFolderId; } /** * Parent folder id. * @param parentFolderId parentFolderId or {@code null} for none */ public Trigger setParentFolderId(java.lang.String parentFolderId) { this.parentFolderId = parentFolderId; return this; } /** * GTM Trigger's API relative path. * @return value or {@code null} for none */ public java.lang.String getPath() { return path; } /** * GTM Trigger's API relative path. * @param path path or {@code null} for none */ public Trigger setPath(java.lang.String path) { this.path = path; return this; } /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getSelector() { return selector; } /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param selector selector or {@code null} for none */ public Trigger setSelector(Parameter selector) { this.selector = selector; return this; } /** * Auto generated link to the tag manager UI * @return value or {@code null} for none */ public java.lang.String getTagManagerUrl() { return tagManagerUrl; } /** * Auto generated link to the tag manager UI * @param tagManagerUrl tagManagerUrl or {@code null} for none */ public Trigger setTagManagerUrl(java.lang.String tagManagerUrl) { this.tagManagerUrl = tagManagerUrl; return this; } /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getTotalTimeMinMilliseconds() { return totalTimeMinMilliseconds; } /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param totalTimeMinMilliseconds totalTimeMinMilliseconds or {@code null} for none */ public Trigger setTotalTimeMinMilliseconds(Parameter totalTimeMinMilliseconds) { this.totalTimeMinMilliseconds = totalTimeMinMilliseconds; return this; } /** * The Trigger ID uniquely identifies the GTM Trigger. * @return value or {@code null} for none */ public java.lang.String getTriggerId() { return triggerId; } /** * The Trigger ID uniquely identifies the GTM Trigger. * @param triggerId triggerId or {@code null} for none */ public Trigger setTriggerId(java.lang.String triggerId) { this.triggerId = triggerId; return this; } /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getType() { return type; } /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param type type or {@code null} for none */ public Trigger setType(java.lang.String type) { this.type = type; return this; } /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getUniqueTriggerId() { return uniqueTriggerId; } /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param uniqueTriggerId uniqueTriggerId or {@code null} for none */ public Trigger setUniqueTriggerId(Parameter uniqueTriggerId) { this.uniqueTriggerId = uniqueTriggerId; return this; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVerticalScrollPercentageList() { return verticalScrollPercentageList; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param verticalScrollPercentageList verticalScrollPercentageList or {@code null} for none */ public Trigger setVerticalScrollPercentageList(Parameter verticalScrollPercentageList) { this.verticalScrollPercentageList = verticalScrollPercentageList; return this; } /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisibilitySelector() { return visibilitySelector; } /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visibilitySelector visibilitySelector or {@code null} for none */ public Trigger setVisibilitySelector(Parameter visibilitySelector) { this.visibilitySelector = visibilitySelector; return this; } /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisiblePercentageMax() { return visiblePercentageMax; } /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visiblePercentageMax visiblePercentageMax or {@code null} for none */ public Trigger setVisiblePercentageMax(Parameter visiblePercentageMax) { this.visiblePercentageMax = visiblePercentageMax; return this; } /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisiblePercentageMin() { return visiblePercentageMin; } /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visiblePercentageMin visiblePercentageMin or {@code null} for none */ public Trigger setVisiblePercentageMin(Parameter visiblePercentageMin) { this.visiblePercentageMin = visiblePercentageMin; return this; } /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getWaitForTags() { return waitForTags; } /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param waitForTags waitForTags or {@code null} for none */ public Trigger setWaitForTags(Parameter waitForTags) { this.waitForTags = waitForTags; return this; } /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getWaitForTagsTimeout() { return waitForTagsTimeout; } /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param waitForTagsTimeout waitForTagsTimeout or {@code null} for none */ public Trigger setWaitForTagsTimeout(Parameter waitForTagsTimeout) { this.waitForTagsTimeout = waitForTagsTimeout; return this; } /** * GTM Workspace ID. * @return value or {@code null} for none */ public java.lang.String getWorkspaceId() { return workspaceId; } /** * GTM Workspace ID. * @param workspaceId workspaceId or {@code null} for none */ public Trigger setWorkspaceId(java.lang.String workspaceId) { this.workspaceId = workspaceId; return this; } @Override public Trigger set(String fieldName, Object value) { return (Trigger) super.set(fieldName, value); } @Override public Trigger clone() { return (Trigger) super.clone(); } }
googleapis/google-api-java-client-services
37,547
clients/google-api-services-tagmanager/v2/1.31.0/com/google/api/services/tagmanager/model/Trigger.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.tagmanager.model; /** * Represents a Google Tag Manager Trigger * * <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 Tag Manager 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 Trigger extends com.google.api.client.json.GenericJson { /** * GTM Account ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String accountId; /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> autoEventFilter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter checkValidation; /** * GTM Container ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String containerId; /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter continuousTimeMinMilliseconds; /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> customEventFilter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter eventName; /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> filter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String fingerprint; /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter horizontalScrollPercentageList; /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter interval; /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter intervalSeconds; /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter limit; /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter maxTimerLengthSeconds; /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String notes; /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Parameter> parameter; static { // hack to force ProGuard to consider Parameter 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(Parameter.class); } /** * Parent folder id. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String parentFolderId; /** * GTM Trigger's API relative path. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String path; /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter selector; /** * Auto generated link to the tag manager UI * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String tagManagerUrl; /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter totalTimeMinMilliseconds; /** * The Trigger ID uniquely identifies the GTM Trigger. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String triggerId; /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String type; /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter uniqueTriggerId; /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter verticalScrollPercentageList; /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visibilitySelector; /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visiblePercentageMax; /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visiblePercentageMin; /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter waitForTags; /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter waitForTagsTimeout; /** * GTM Workspace ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String workspaceId; /** * GTM Account ID. * @return value or {@code null} for none */ public java.lang.String getAccountId() { return accountId; } /** * GTM Account ID. * @param accountId accountId or {@code null} for none */ public Trigger setAccountId(java.lang.String accountId) { this.accountId = accountId; return this; } /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getAutoEventFilter() { return autoEventFilter; } /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param autoEventFilter autoEventFilter or {@code null} for none */ public Trigger setAutoEventFilter(java.util.List<Condition> autoEventFilter) { this.autoEventFilter = autoEventFilter; return this; } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getCheckValidation() { return checkValidation; } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param checkValidation checkValidation or {@code null} for none */ public Trigger setCheckValidation(Parameter checkValidation) { this.checkValidation = checkValidation; return this; } /** * GTM Container ID. * @return value or {@code null} for none */ public java.lang.String getContainerId() { return containerId; } /** * GTM Container ID. * @param containerId containerId or {@code null} for none */ public Trigger setContainerId(java.lang.String containerId) { this.containerId = containerId; return this; } /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getContinuousTimeMinMilliseconds() { return continuousTimeMinMilliseconds; } /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param continuousTimeMinMilliseconds continuousTimeMinMilliseconds or {@code null} for none */ public Trigger setContinuousTimeMinMilliseconds(Parameter continuousTimeMinMilliseconds) { this.continuousTimeMinMilliseconds = continuousTimeMinMilliseconds; return this; } /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getCustomEventFilter() { return customEventFilter; } /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param customEventFilter customEventFilter or {@code null} for none */ public Trigger setCustomEventFilter(java.util.List<Condition> customEventFilter) { this.customEventFilter = customEventFilter; return this; } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getEventName() { return eventName; } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param eventName eventName or {@code null} for none */ public Trigger setEventName(Parameter eventName) { this.eventName = eventName; return this; } /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getFilter() { return filter; } /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param filter filter or {@code null} for none */ public Trigger setFilter(java.util.List<Condition> filter) { this.filter = filter; return this; } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * @return value or {@code null} for none */ public java.lang.String getFingerprint() { return fingerprint; } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * @param fingerprint fingerprint or {@code null} for none */ public Trigger setFingerprint(java.lang.String fingerprint) { this.fingerprint = fingerprint; return this; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getHorizontalScrollPercentageList() { return horizontalScrollPercentageList; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param horizontalScrollPercentageList horizontalScrollPercentageList or {@code null} for none */ public Trigger setHorizontalScrollPercentageList(Parameter horizontalScrollPercentageList) { this.horizontalScrollPercentageList = horizontalScrollPercentageList; return this; } /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getInterval() { return interval; } /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param interval interval or {@code null} for none */ public Trigger setInterval(Parameter interval) { this.interval = interval; return this; } /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getIntervalSeconds() { return intervalSeconds; } /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param intervalSeconds intervalSeconds or {@code null} for none */ public Trigger setIntervalSeconds(Parameter intervalSeconds) { this.intervalSeconds = intervalSeconds; return this; } /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getLimit() { return limit; } /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param limit limit or {@code null} for none */ public Trigger setLimit(Parameter limit) { this.limit = limit; return this; } /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getMaxTimerLengthSeconds() { return maxTimerLengthSeconds; } /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param maxTimerLengthSeconds maxTimerLengthSeconds or {@code null} for none */ public Trigger setMaxTimerLengthSeconds(Parameter maxTimerLengthSeconds) { this.maxTimerLengthSeconds = maxTimerLengthSeconds; return this; } /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param name name or {@code null} for none */ public Trigger setName(java.lang.String name) { this.name = name; return this; } /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getNotes() { return notes; } /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param notes notes or {@code null} for none */ public Trigger setNotes(java.lang.String notes) { this.notes = notes; return this; } /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Parameter> getParameter() { return parameter; } /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param parameter parameter or {@code null} for none */ public Trigger setParameter(java.util.List<Parameter> parameter) { this.parameter = parameter; return this; } /** * Parent folder id. * @return value or {@code null} for none */ public java.lang.String getParentFolderId() { return parentFolderId; } /** * Parent folder id. * @param parentFolderId parentFolderId or {@code null} for none */ public Trigger setParentFolderId(java.lang.String parentFolderId) { this.parentFolderId = parentFolderId; return this; } /** * GTM Trigger's API relative path. * @return value or {@code null} for none */ public java.lang.String getPath() { return path; } /** * GTM Trigger's API relative path. * @param path path or {@code null} for none */ public Trigger setPath(java.lang.String path) { this.path = path; return this; } /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getSelector() { return selector; } /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param selector selector or {@code null} for none */ public Trigger setSelector(Parameter selector) { this.selector = selector; return this; } /** * Auto generated link to the tag manager UI * @return value or {@code null} for none */ public java.lang.String getTagManagerUrl() { return tagManagerUrl; } /** * Auto generated link to the tag manager UI * @param tagManagerUrl tagManagerUrl or {@code null} for none */ public Trigger setTagManagerUrl(java.lang.String tagManagerUrl) { this.tagManagerUrl = tagManagerUrl; return this; } /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getTotalTimeMinMilliseconds() { return totalTimeMinMilliseconds; } /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param totalTimeMinMilliseconds totalTimeMinMilliseconds or {@code null} for none */ public Trigger setTotalTimeMinMilliseconds(Parameter totalTimeMinMilliseconds) { this.totalTimeMinMilliseconds = totalTimeMinMilliseconds; return this; } /** * The Trigger ID uniquely identifies the GTM Trigger. * @return value or {@code null} for none */ public java.lang.String getTriggerId() { return triggerId; } /** * The Trigger ID uniquely identifies the GTM Trigger. * @param triggerId triggerId or {@code null} for none */ public Trigger setTriggerId(java.lang.String triggerId) { this.triggerId = triggerId; return this; } /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getType() { return type; } /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param type type or {@code null} for none */ public Trigger setType(java.lang.String type) { this.type = type; return this; } /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getUniqueTriggerId() { return uniqueTriggerId; } /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param uniqueTriggerId uniqueTriggerId or {@code null} for none */ public Trigger setUniqueTriggerId(Parameter uniqueTriggerId) { this.uniqueTriggerId = uniqueTriggerId; return this; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVerticalScrollPercentageList() { return verticalScrollPercentageList; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param verticalScrollPercentageList verticalScrollPercentageList or {@code null} for none */ public Trigger setVerticalScrollPercentageList(Parameter verticalScrollPercentageList) { this.verticalScrollPercentageList = verticalScrollPercentageList; return this; } /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisibilitySelector() { return visibilitySelector; } /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visibilitySelector visibilitySelector or {@code null} for none */ public Trigger setVisibilitySelector(Parameter visibilitySelector) { this.visibilitySelector = visibilitySelector; return this; } /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisiblePercentageMax() { return visiblePercentageMax; } /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visiblePercentageMax visiblePercentageMax or {@code null} for none */ public Trigger setVisiblePercentageMax(Parameter visiblePercentageMax) { this.visiblePercentageMax = visiblePercentageMax; return this; } /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisiblePercentageMin() { return visiblePercentageMin; } /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visiblePercentageMin visiblePercentageMin or {@code null} for none */ public Trigger setVisiblePercentageMin(Parameter visiblePercentageMin) { this.visiblePercentageMin = visiblePercentageMin; return this; } /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getWaitForTags() { return waitForTags; } /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param waitForTags waitForTags or {@code null} for none */ public Trigger setWaitForTags(Parameter waitForTags) { this.waitForTags = waitForTags; return this; } /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getWaitForTagsTimeout() { return waitForTagsTimeout; } /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param waitForTagsTimeout waitForTagsTimeout or {@code null} for none */ public Trigger setWaitForTagsTimeout(Parameter waitForTagsTimeout) { this.waitForTagsTimeout = waitForTagsTimeout; return this; } /** * GTM Workspace ID. * @return value or {@code null} for none */ public java.lang.String getWorkspaceId() { return workspaceId; } /** * GTM Workspace ID. * @param workspaceId workspaceId or {@code null} for none */ public Trigger setWorkspaceId(java.lang.String workspaceId) { this.workspaceId = workspaceId; return this; } @Override public Trigger set(String fieldName, Object value) { return (Trigger) super.set(fieldName, value); } @Override public Trigger clone() { return (Trigger) super.clone(); } }
googleapis/google-cloud-java
37,298
java-channel/proto-google-cloud-channel-v1/src/main/java/com/google/cloud/channel/v1/Price.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/channel/v1/offers.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.channel.v1; /** * * * <pre> * Represents the price of the Offer. * </pre> * * Protobuf type {@code google.cloud.channel.v1.Price} */ public final class Price extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.channel.v1.Price) PriceOrBuilder { private static final long serialVersionUID = 0L; // Use Price.newBuilder() to construct. private Price(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Price() { externalPriceUri_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new Price(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.channel.v1.OffersProto .internal_static_google_cloud_channel_v1_Price_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.channel.v1.OffersProto .internal_static_google_cloud_channel_v1_Price_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.channel.v1.Price.class, com.google.cloud.channel.v1.Price.Builder.class); } private int bitField0_; public static final int BASE_PRICE_FIELD_NUMBER = 1; private com.google.type.Money basePrice_; /** * * * <pre> * Base price. * </pre> * * <code>.google.type.Money base_price = 1;</code> * * @return Whether the basePrice field is set. */ @java.lang.Override public boolean hasBasePrice() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Base price. * </pre> * * <code>.google.type.Money base_price = 1;</code> * * @return The basePrice. */ @java.lang.Override public com.google.type.Money getBasePrice() { return basePrice_ == null ? com.google.type.Money.getDefaultInstance() : basePrice_; } /** * * * <pre> * Base price. * </pre> * * <code>.google.type.Money base_price = 1;</code> */ @java.lang.Override public com.google.type.MoneyOrBuilder getBasePriceOrBuilder() { return basePrice_ == null ? com.google.type.Money.getDefaultInstance() : basePrice_; } public static final int DISCOUNT_FIELD_NUMBER = 2; private double discount_ = 0D; /** * * * <pre> * Discount percentage, represented as decimal. * For example, a 20% discount will be represent as 0.2. * </pre> * * <code>double discount = 2;</code> * * @return The discount. */ @java.lang.Override public double getDiscount() { return discount_; } public static final int EFFECTIVE_PRICE_FIELD_NUMBER = 3; private com.google.type.Money effectivePrice_; /** * * * <pre> * Effective Price after applying the discounts. * </pre> * * <code>.google.type.Money effective_price = 3;</code> * * @return Whether the effectivePrice field is set. */ @java.lang.Override public boolean hasEffectivePrice() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Effective Price after applying the discounts. * </pre> * * <code>.google.type.Money effective_price = 3;</code> * * @return The effectivePrice. */ @java.lang.Override public com.google.type.Money getEffectivePrice() { return effectivePrice_ == null ? com.google.type.Money.getDefaultInstance() : effectivePrice_; } /** * * * <pre> * Effective Price after applying the discounts. * </pre> * * <code>.google.type.Money effective_price = 3;</code> */ @java.lang.Override public com.google.type.MoneyOrBuilder getEffectivePriceOrBuilder() { return effectivePrice_ == null ? com.google.type.Money.getDefaultInstance() : effectivePrice_; } public static final int EXTERNAL_PRICE_URI_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object externalPriceUri_ = ""; /** * * * <pre> * Link to external price list, such as link to Google Voice rate card. * </pre> * * <code>string external_price_uri = 4;</code> * * @return The externalPriceUri. */ @java.lang.Override public java.lang.String getExternalPriceUri() { java.lang.Object ref = externalPriceUri_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); externalPriceUri_ = s; return s; } } /** * * * <pre> * Link to external price list, such as link to Google Voice rate card. * </pre> * * <code>string external_price_uri = 4;</code> * * @return The bytes for externalPriceUri. */ @java.lang.Override public com.google.protobuf.ByteString getExternalPriceUriBytes() { java.lang.Object ref = externalPriceUri_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); externalPriceUri_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getBasePrice()); } if (java.lang.Double.doubleToRawLongBits(discount_) != 0) { output.writeDouble(2, discount_); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(3, getEffectivePrice()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(externalPriceUri_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, externalPriceUri_); } 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, getBasePrice()); } if (java.lang.Double.doubleToRawLongBits(discount_) != 0) { size += com.google.protobuf.CodedOutputStream.computeDoubleSize(2, discount_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getEffectivePrice()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(externalPriceUri_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, externalPriceUri_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.channel.v1.Price)) { return super.equals(obj); } com.google.cloud.channel.v1.Price other = (com.google.cloud.channel.v1.Price) obj; if (hasBasePrice() != other.hasBasePrice()) return false; if (hasBasePrice()) { if (!getBasePrice().equals(other.getBasePrice())) return false; } if (java.lang.Double.doubleToLongBits(getDiscount()) != java.lang.Double.doubleToLongBits(other.getDiscount())) return false; if (hasEffectivePrice() != other.hasEffectivePrice()) return false; if (hasEffectivePrice()) { if (!getEffectivePrice().equals(other.getEffectivePrice())) return false; } if (!getExternalPriceUri().equals(other.getExternalPriceUri())) 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 (hasBasePrice()) { hash = (37 * hash) + BASE_PRICE_FIELD_NUMBER; hash = (53 * hash) + getBasePrice().hashCode(); } hash = (37 * hash) + DISCOUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( java.lang.Double.doubleToLongBits(getDiscount())); if (hasEffectivePrice()) { hash = (37 * hash) + EFFECTIVE_PRICE_FIELD_NUMBER; hash = (53 * hash) + getEffectivePrice().hashCode(); } hash = (37 * hash) + EXTERNAL_PRICE_URI_FIELD_NUMBER; hash = (53 * hash) + getExternalPriceUri().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.channel.v1.Price parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.channel.v1.Price parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.channel.v1.Price parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.channel.v1.Price parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.channel.v1.Price parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.channel.v1.Price parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.channel.v1.Price parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.channel.v1.Price parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.channel.v1.Price parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.channel.v1.Price parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.channel.v1.Price parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.channel.v1.Price parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.channel.v1.Price prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Represents the price of the Offer. * </pre> * * Protobuf type {@code google.cloud.channel.v1.Price} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.channel.v1.Price) com.google.cloud.channel.v1.PriceOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.channel.v1.OffersProto .internal_static_google_cloud_channel_v1_Price_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.channel.v1.OffersProto .internal_static_google_cloud_channel_v1_Price_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.channel.v1.Price.class, com.google.cloud.channel.v1.Price.Builder.class); } // Construct using com.google.cloud.channel.v1.Price.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getBasePriceFieldBuilder(); getEffectivePriceFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; basePrice_ = null; if (basePriceBuilder_ != null) { basePriceBuilder_.dispose(); basePriceBuilder_ = null; } discount_ = 0D; effectivePrice_ = null; if (effectivePriceBuilder_ != null) { effectivePriceBuilder_.dispose(); effectivePriceBuilder_ = null; } externalPriceUri_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.channel.v1.OffersProto .internal_static_google_cloud_channel_v1_Price_descriptor; } @java.lang.Override public com.google.cloud.channel.v1.Price getDefaultInstanceForType() { return com.google.cloud.channel.v1.Price.getDefaultInstance(); } @java.lang.Override public com.google.cloud.channel.v1.Price build() { com.google.cloud.channel.v1.Price result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.channel.v1.Price buildPartial() { com.google.cloud.channel.v1.Price result = new com.google.cloud.channel.v1.Price(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.channel.v1.Price result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.basePrice_ = basePriceBuilder_ == null ? basePrice_ : basePriceBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.discount_ = discount_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.effectivePrice_ = effectivePriceBuilder_ == null ? effectivePrice_ : effectivePriceBuilder_.build(); to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000008) != 0)) { result.externalPriceUri_ = externalPriceUri_; } 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.channel.v1.Price) { return mergeFrom((com.google.cloud.channel.v1.Price) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.channel.v1.Price other) { if (other == com.google.cloud.channel.v1.Price.getDefaultInstance()) return this; if (other.hasBasePrice()) { mergeBasePrice(other.getBasePrice()); } if (other.getDiscount() != 0D) { setDiscount(other.getDiscount()); } if (other.hasEffectivePrice()) { mergeEffectivePrice(other.getEffectivePrice()); } if (!other.getExternalPriceUri().isEmpty()) { externalPriceUri_ = other.externalPriceUri_; 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: { input.readMessage(getBasePriceFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 17: { discount_ = input.readDouble(); bitField0_ |= 0x00000002; break; } // case 17 case 26: { input.readMessage(getEffectivePriceFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 case 34: { externalPriceUri_ = 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 com.google.type.Money basePrice_; private com.google.protobuf.SingleFieldBuilderV3< com.google.type.Money, com.google.type.Money.Builder, com.google.type.MoneyOrBuilder> basePriceBuilder_; /** * * * <pre> * Base price. * </pre> * * <code>.google.type.Money base_price = 1;</code> * * @return Whether the basePrice field is set. */ public boolean hasBasePrice() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Base price. * </pre> * * <code>.google.type.Money base_price = 1;</code> * * @return The basePrice. */ public com.google.type.Money getBasePrice() { if (basePriceBuilder_ == null) { return basePrice_ == null ? com.google.type.Money.getDefaultInstance() : basePrice_; } else { return basePriceBuilder_.getMessage(); } } /** * * * <pre> * Base price. * </pre> * * <code>.google.type.Money base_price = 1;</code> */ public Builder setBasePrice(com.google.type.Money value) { if (basePriceBuilder_ == null) { if (value == null) { throw new NullPointerException(); } basePrice_ = value; } else { basePriceBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Base price. * </pre> * * <code>.google.type.Money base_price = 1;</code> */ public Builder setBasePrice(com.google.type.Money.Builder builderForValue) { if (basePriceBuilder_ == null) { basePrice_ = builderForValue.build(); } else { basePriceBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Base price. * </pre> * * <code>.google.type.Money base_price = 1;</code> */ public Builder mergeBasePrice(com.google.type.Money value) { if (basePriceBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && basePrice_ != null && basePrice_ != com.google.type.Money.getDefaultInstance()) { getBasePriceBuilder().mergeFrom(value); } else { basePrice_ = value; } } else { basePriceBuilder_.mergeFrom(value); } if (basePrice_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Base price. * </pre> * * <code>.google.type.Money base_price = 1;</code> */ public Builder clearBasePrice() { bitField0_ = (bitField0_ & ~0x00000001); basePrice_ = null; if (basePriceBuilder_ != null) { basePriceBuilder_.dispose(); basePriceBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Base price. * </pre> * * <code>.google.type.Money base_price = 1;</code> */ public com.google.type.Money.Builder getBasePriceBuilder() { bitField0_ |= 0x00000001; onChanged(); return getBasePriceFieldBuilder().getBuilder(); } /** * * * <pre> * Base price. * </pre> * * <code>.google.type.Money base_price = 1;</code> */ public com.google.type.MoneyOrBuilder getBasePriceOrBuilder() { if (basePriceBuilder_ != null) { return basePriceBuilder_.getMessageOrBuilder(); } else { return basePrice_ == null ? com.google.type.Money.getDefaultInstance() : basePrice_; } } /** * * * <pre> * Base price. * </pre> * * <code>.google.type.Money base_price = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.type.Money, com.google.type.Money.Builder, com.google.type.MoneyOrBuilder> getBasePriceFieldBuilder() { if (basePriceBuilder_ == null) { basePriceBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.type.Money, com.google.type.Money.Builder, com.google.type.MoneyOrBuilder>(getBasePrice(), getParentForChildren(), isClean()); basePrice_ = null; } return basePriceBuilder_; } private double discount_; /** * * * <pre> * Discount percentage, represented as decimal. * For example, a 20% discount will be represent as 0.2. * </pre> * * <code>double discount = 2;</code> * * @return The discount. */ @java.lang.Override public double getDiscount() { return discount_; } /** * * * <pre> * Discount percentage, represented as decimal. * For example, a 20% discount will be represent as 0.2. * </pre> * * <code>double discount = 2;</code> * * @param value The discount to set. * @return This builder for chaining. */ public Builder setDiscount(double value) { discount_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Discount percentage, represented as decimal. * For example, a 20% discount will be represent as 0.2. * </pre> * * <code>double discount = 2;</code> * * @return This builder for chaining. */ public Builder clearDiscount() { bitField0_ = (bitField0_ & ~0x00000002); discount_ = 0D; onChanged(); return this; } private com.google.type.Money effectivePrice_; private com.google.protobuf.SingleFieldBuilderV3< com.google.type.Money, com.google.type.Money.Builder, com.google.type.MoneyOrBuilder> effectivePriceBuilder_; /** * * * <pre> * Effective Price after applying the discounts. * </pre> * * <code>.google.type.Money effective_price = 3;</code> * * @return Whether the effectivePrice field is set. */ public boolean hasEffectivePrice() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Effective Price after applying the discounts. * </pre> * * <code>.google.type.Money effective_price = 3;</code> * * @return The effectivePrice. */ public com.google.type.Money getEffectivePrice() { if (effectivePriceBuilder_ == null) { return effectivePrice_ == null ? com.google.type.Money.getDefaultInstance() : effectivePrice_; } else { return effectivePriceBuilder_.getMessage(); } } /** * * * <pre> * Effective Price after applying the discounts. * </pre> * * <code>.google.type.Money effective_price = 3;</code> */ public Builder setEffectivePrice(com.google.type.Money value) { if (effectivePriceBuilder_ == null) { if (value == null) { throw new NullPointerException(); } effectivePrice_ = value; } else { effectivePriceBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Effective Price after applying the discounts. * </pre> * * <code>.google.type.Money effective_price = 3;</code> */ public Builder setEffectivePrice(com.google.type.Money.Builder builderForValue) { if (effectivePriceBuilder_ == null) { effectivePrice_ = builderForValue.build(); } else { effectivePriceBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Effective Price after applying the discounts. * </pre> * * <code>.google.type.Money effective_price = 3;</code> */ public Builder mergeEffectivePrice(com.google.type.Money value) { if (effectivePriceBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && effectivePrice_ != null && effectivePrice_ != com.google.type.Money.getDefaultInstance()) { getEffectivePriceBuilder().mergeFrom(value); } else { effectivePrice_ = value; } } else { effectivePriceBuilder_.mergeFrom(value); } if (effectivePrice_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Effective Price after applying the discounts. * </pre> * * <code>.google.type.Money effective_price = 3;</code> */ public Builder clearEffectivePrice() { bitField0_ = (bitField0_ & ~0x00000004); effectivePrice_ = null; if (effectivePriceBuilder_ != null) { effectivePriceBuilder_.dispose(); effectivePriceBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Effective Price after applying the discounts. * </pre> * * <code>.google.type.Money effective_price = 3;</code> */ public com.google.type.Money.Builder getEffectivePriceBuilder() { bitField0_ |= 0x00000004; onChanged(); return getEffectivePriceFieldBuilder().getBuilder(); } /** * * * <pre> * Effective Price after applying the discounts. * </pre> * * <code>.google.type.Money effective_price = 3;</code> */ public com.google.type.MoneyOrBuilder getEffectivePriceOrBuilder() { if (effectivePriceBuilder_ != null) { return effectivePriceBuilder_.getMessageOrBuilder(); } else { return effectivePrice_ == null ? com.google.type.Money.getDefaultInstance() : effectivePrice_; } } /** * * * <pre> * Effective Price after applying the discounts. * </pre> * * <code>.google.type.Money effective_price = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.type.Money, com.google.type.Money.Builder, com.google.type.MoneyOrBuilder> getEffectivePriceFieldBuilder() { if (effectivePriceBuilder_ == null) { effectivePriceBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.type.Money, com.google.type.Money.Builder, com.google.type.MoneyOrBuilder>( getEffectivePrice(), getParentForChildren(), isClean()); effectivePrice_ = null; } return effectivePriceBuilder_; } private java.lang.Object externalPriceUri_ = ""; /** * * * <pre> * Link to external price list, such as link to Google Voice rate card. * </pre> * * <code>string external_price_uri = 4;</code> * * @return The externalPriceUri. */ public java.lang.String getExternalPriceUri() { java.lang.Object ref = externalPriceUri_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); externalPriceUri_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Link to external price list, such as link to Google Voice rate card. * </pre> * * <code>string external_price_uri = 4;</code> * * @return The bytes for externalPriceUri. */ public com.google.protobuf.ByteString getExternalPriceUriBytes() { java.lang.Object ref = externalPriceUri_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); externalPriceUri_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Link to external price list, such as link to Google Voice rate card. * </pre> * * <code>string external_price_uri = 4;</code> * * @param value The externalPriceUri to set. * @return This builder for chaining. */ public Builder setExternalPriceUri(java.lang.String value) { if (value == null) { throw new NullPointerException(); } externalPriceUri_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Link to external price list, such as link to Google Voice rate card. * </pre> * * <code>string external_price_uri = 4;</code> * * @return This builder for chaining. */ public Builder clearExternalPriceUri() { externalPriceUri_ = getDefaultInstance().getExternalPriceUri(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Link to external price list, such as link to Google Voice rate card. * </pre> * * <code>string external_price_uri = 4;</code> * * @param value The bytes for externalPriceUri to set. * @return This builder for chaining. */ public Builder setExternalPriceUriBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); externalPriceUri_ = 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.channel.v1.Price) } // @@protoc_insertion_point(class_scope:google.cloud.channel.v1.Price) private static final com.google.cloud.channel.v1.Price DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.channel.v1.Price(); } public static com.google.cloud.channel.v1.Price getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Price> PARSER = new com.google.protobuf.AbstractParser<Price>() { @java.lang.Override public Price 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<Price> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Price> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.channel.v1.Price getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
36,401
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/services/KeywordPlanIdeaServiceProto.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v19/services/keyword_plan_idea_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v19.services; public final class KeywordPlanIdeaServiceProto { private KeywordPlanIdeaServiceProto() {} 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_ads_googleads_v19_services_GenerateKeywordIdeasRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeasRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_KeywordAndUrlSeed_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_KeywordAndUrlSeed_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_KeywordSeed_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_KeywordSeed_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_SiteSeed_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_SiteSeed_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_UrlSeed_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_UrlSeed_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeaResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeaResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeaResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeaResult_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsResult_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_GenerateAdGroupThemesRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_GenerateAdGroupThemesRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_GenerateAdGroupThemesResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_GenerateAdGroupThemesResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_AdGroupKeywordSuggestion_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_AdGroupKeywordSuggestion_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_UnusableAdGroup_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_UnusableAdGroup_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_GenerateKeywordForecastMetricsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_GenerateKeywordForecastMetricsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_CampaignToForecast_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_CampaignToForecast_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_CampaignToForecast_CampaignBiddingStrategy_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_CampaignToForecast_CampaignBiddingStrategy_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_ForecastAdGroup_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_ForecastAdGroup_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_BiddableKeyword_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_BiddableKeyword_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_CriterionBidModifier_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_CriterionBidModifier_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_ManualCpcBiddingStrategy_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_ManualCpcBiddingStrategy_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_MaximizeClicksBiddingStrategy_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_MaximizeClicksBiddingStrategy_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_MaximizeConversionsBiddingStrategy_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_MaximizeConversionsBiddingStrategy_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_GenerateKeywordForecastMetricsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_GenerateKeywordForecastMetricsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v19_services_KeywordForecastMetrics_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v19_services_KeywordForecastMetrics_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\nAgoogle/ads/googleads/v19/services/keyw" + "ord_plan_idea_service.proto\022!google.ads." + "googleads.v19.services\032.google/ads/googl" + "eads/v19/common/criteria.proto\032+google/a" + "ds/googleads/v19/common/dates.proto\0329goo" + "gle/ads/googleads/v19/common/keyword_pla" + "n_common.proto\0327google/ads/googleads/v19" + "/enums/keyword_match_type.proto\032Dgoogle/" + "ads/googleads/v19/enums/keyword_plan_key" + "word_annotation.proto\0329google/ads/google" + "ads/v19/enums/keyword_plan_network.proto" + "\032\034google/api/annotations.proto\032\027google/a" + "pi/client.proto\032\037google/api/field_behavi" + "or.proto\"\377\006\n\033GenerateKeywordIdeasRequest" + "\022\023\n\013customer_id\030\001 \001(\t\022\025\n\010language\030\016 \001(\tH" + "\001\210\001\001\022\034\n\024geo_target_constants\030\017 \003(\t\022\036\n\026in" + "clude_adult_keywords\030\n \001(\010\022\022\n\npage_token" + "\030\014 \001(\t\022\021\n\tpage_size\030\r \001(\005\022g\n\024keyword_pla" + "n_network\030\t \001(\0162I.google.ads.googleads.v" + "19.enums.KeywordPlanNetworkEnum.KeywordP" + "lanNetwork\022y\n\022keyword_annotation\030\021 \003(\0162]" + ".google.ads.googleads.v19.enums.KeywordP" + "lanKeywordAnnotationEnum.KeywordPlanKeyw" + "ordAnnotation\022W\n\021aggregate_metrics\030\020 \001(\013" + "2<.google.ads.googleads.v19.common.Keywo" + "rdPlanAggregateMetrics\022]\n\032historical_met" + "rics_options\030\022 \001(\01329.google.ads.googlead" + "s.v19.common.HistoricalMetricsOptions\022T\n" + "\024keyword_and_url_seed\030\002 \001(\01324.google.ads" + ".googleads.v19.services.KeywordAndUrlSee" + "dH\000\022F\n\014keyword_seed\030\003 \001(\0132..google.ads.g" + "oogleads.v19.services.KeywordSeedH\000\022>\n\010u" + "rl_seed\030\005 \001(\0132*.google.ads.googleads.v19" + ".services.UrlSeedH\000\022@\n\tsite_seed\030\013 \001(\0132+" + ".google.ads.googleads.v19.services.SiteS" + "eedH\000B\006\n\004seedB\013\n\t_language\"?\n\021KeywordAnd" + "UrlSeed\022\020\n\003url\030\003 \001(\tH\000\210\001\001\022\020\n\010keywords\030\004 " + "\003(\tB\006\n\004_url\"\037\n\013KeywordSeed\022\020\n\010keywords\030\002" + " \003(\t\"&\n\010SiteSeed\022\021\n\004site\030\002 \001(\tH\000\210\001\001B\007\n\005_" + "site\"#\n\007UrlSeed\022\020\n\003url\030\002 \001(\tH\000\210\001\001B\006\n\004_ur" + "l\"\377\001\n\033GenerateKeywordIdeaResponse\022M\n\007res" + "ults\030\001 \003(\0132<.google.ads.googleads.v19.se" + "rvices.GenerateKeywordIdeaResult\022d\n\030aggr" + "egate_metric_results\030\004 \001(\0132B.google.ads." + "googleads.v19.common.KeywordPlanAggregat" + "eMetricResults\022\027\n\017next_page_token\030\002 \001(\t\022" + "\022\n\ntotal_size\030\003 \001(\003\"\376\001\n\031GenerateKeywordI" + "deaResult\022\021\n\004text\030\005 \001(\tH\000\210\001\001\022[\n\024keyword_" + "idea_metrics\030\003 \001(\0132=.google.ads.googlead" + "s.v19.common.KeywordPlanHistoricalMetric" + "s\022P\n\023keyword_annotations\030\006 \001(\01323.google." + "ads.googleads.v19.common.KeywordAnnotati" + "ons\022\026\n\016close_variants\030\007 \003(\tB\007\n\005_text\"\323\003\n" + "\'GenerateKeywordHistoricalMetricsRequest" + "\022\023\n\013customer_id\030\001 \001(\t\022\020\n\010keywords\030\002 \003(\t\022" + "\025\n\010language\030\004 \001(\tH\000\210\001\001\022\036\n\026include_adult_" + "keywords\030\005 \001(\010\022\034\n\024geo_target_constants\030\006" + " \003(\t\022g\n\024keyword_plan_network\030\007 \001(\0162I.goo" + "gle.ads.googleads.v19.enums.KeywordPlanN" + "etworkEnum.KeywordPlanNetwork\022W\n\021aggrega" + "te_metrics\030\010 \001(\0132<.google.ads.googleads." + "v19.common.KeywordPlanAggregateMetrics\022]" + "\n\032historical_metrics_options\030\003 \001(\01329.goo" + "gle.ads.googleads.v19.common.HistoricalM" + "etricsOptionsB\013\n\t_language\"\354\001\n(GenerateK" + "eywordHistoricalMetricsResponse\022Z\n\007resul" + "ts\030\001 \003(\0132I.google.ads.googleads.v19.serv" + "ices.GenerateKeywordHistoricalMetricsRes" + "ult\022d\n\030aggregate_metric_results\030\002 \001(\0132B." + "google.ads.googleads.v19.common.KeywordP" + "lanAggregateMetricResults\"\264\001\n&GenerateKe" + "ywordHistoricalMetricsResult\022\021\n\004text\030\001 \001" + "(\tH\000\210\001\001\022\026\n\016close_variants\030\003 \003(\t\022V\n\017keywo" + "rd_metrics\030\002 \001(\0132=.google.ads.googleads." + "v19.common.KeywordPlanHistoricalMetricsB" + "\007\n\005_text\"g\n\034GenerateAdGroupThemesRequest" + "\022\030\n\013customer_id\030\001 \001(\tB\003\340A\002\022\025\n\010keywords\030\002" + " \003(\tB\003\340A\002\022\026\n\tad_groups\030\003 \003(\tB\003\340A\002\"\322\001\n\035Ge" + "nerateAdGroupThemesResponse\022a\n\034ad_group_" + "keyword_suggestions\030\001 \003(\0132;.google.ads.g" + "oogleads.v19.services.AdGroupKeywordSugg" + "estion\022N\n\022unusable_ad_groups\030\002 \003(\01322.goo" + "gle.ads.googleads.v19.services.UnusableA" + "dGroup\"\355\001\n\030AdGroupKeywordSuggestion\022\024\n\014k" + "eyword_text\030\001 \001(\t\022\036\n\026suggested_keyword_t" + "ext\030\002 \001(\t\022c\n\024suggested_match_type\030\003 \001(\0162" + "E.google.ads.googleads.v19.enums.Keyword" + "MatchTypeEnum.KeywordMatchType\022\032\n\022sugges" + "ted_ad_group\030\004 \001(\t\022\032\n\022suggested_campaign" + "\030\005 \001(\t\"5\n\017UnusableAdGroup\022\020\n\010ad_group\030\001 " + "\001(\t\022\020\n\010campaign\030\002 \001(\t\"\375\001\n%GenerateKeywor" + "dForecastMetricsRequest\022\023\n\013customer_id\030\001" + " \001(\t\022\032\n\rcurrency_code\030\002 \001(\tH\000\210\001\001\022C\n\017fore" + "cast_period\030\003 \001(\0132*.google.ads.googleads" + ".v19.common.DateRange\022L\n\010campaign\030\004 \001(\0132" + "5.google.ads.googleads.v19.services.Camp" + "aignToForecastB\003\340A\002B\020\n\016_currency_code\"\230\007" + "\n\022CampaignToForecast\022\032\n\022language_constan" + "ts\030\001 \003(\t\022N\n\rgeo_modifiers\030\002 \003(\01327.google" + ".ads.googleads.v19.services.CriterionBid" + "Modifier\022l\n\024keyword_plan_network\030\003 \001(\0162I" + ".google.ads.googleads.v19.enums.KeywordP" + "lanNetworkEnum.KeywordPlanNetworkB\003\340A\002\022G" + "\n\021negative_keywords\030\004 \003(\0132,.google.ads.g" + "oogleads.v19.common.KeywordInfo\022l\n\020biddi" + "ng_strategy\030\005 \001(\0132M.google.ads.googleads" + ".v19.services.CampaignToForecast.Campaig" + "nBiddingStrategyB\003\340A\002\022\034\n\017conversion_rate" + "\030\006 \001(\001H\000\210\001\001\022E\n\tad_groups\030\007 \003(\01322.google." + "ads.googleads.v19.services.ForecastAdGro" + "up\032\367\002\n\027CampaignBiddingStrategy\022b\n\033manual" + "_cpc_bidding_strategy\030\001 \001(\0132;.google.ads" + ".googleads.v19.services.ManualCpcBidding" + "StrategyH\000\022l\n maximize_clicks_bidding_st" + "rategy\030\002 \001(\0132@.google.ads.googleads.v19." + "services.MaximizeClicksBiddingStrategyH\000" + "\022v\n%maximize_conversions_bidding_strateg" + "y\030\003 \001(\0132E.google.ads.googleads.v19.servi" + "ces.MaximizeConversionsBiddingStrategyH\000" + "B\022\n\020bidding_strategyB\022\n\020_conversion_rate" + "\"\346\001\n\017ForecastAdGroup\022\037\n\022max_cpc_bid_micr" + "os\030\001 \001(\003H\000\210\001\001\022R\n\021biddable_keywords\030\002 \003(\013" + "22.google.ads.googleads.v19.services.Bid" + "dableKeywordB\003\340A\002\022G\n\021negative_keywords\030\003" + " \003(\0132,.google.ads.googleads.v19.common.K" + "eywordInfoB\025\n\023_max_cpc_bid_micros\"\215\001\n\017Bi" + "ddableKeyword\022B\n\007keyword\030\001 \001(\0132,.google." + "ads.googleads.v19.common.KeywordInfoB\003\340A" + "\002\022\037\n\022max_cpc_bid_micros\030\002 \001(\003H\000\210\001\001B\025\n\023_m" + "ax_cpc_bid_micros\"_\n\024CriterionBidModifie" + "r\022\033\n\023geo_target_constant\030\001 \001(\t\022\031\n\014bid_mo" + "difier\030\002 \001(\001H\000\210\001\001B\017\n\r_bid_modifier\"u\n\030Ma" + "nualCpcBiddingStrategy\022 \n\023daily_budget_m" + "icros\030\001 \001(\003H\000\210\001\001\022\037\n\022max_cpc_bid_micros\030\002" + " \001(\003B\003\340A\002B\026\n\024_daily_budget_micros\"\217\001\n\035Ma" + "ximizeClicksBiddingStrategy\022&\n\031daily_tar" + "get_spend_micros\030\001 \001(\003B\003\340A\002\022\'\n\032max_cpc_b" + "id_ceiling_micros\030\002 \001(\003H\000\210\001\001B\035\n\033_max_cpc" + "_bid_ceiling_micros\"L\n\"MaximizeConversio" + "nsBiddingStrategy\022&\n\031daily_target_spend_" + "micros\030\001 \001(\003B\003\340A\002\"\251\001\n&GenerateKeywordFor" + "ecastMetricsResponse\022a\n\031campaign_forecas" + "t_metrics\030\001 \001(\01329.google.ads.googleads.v" + "19.services.KeywordForecastMetricsH\000\210\001\001B" + "\034\n\032_campaign_forecast_metrics\"\220\003\n\026Keywor" + "dForecastMetrics\022\030\n\013impressions\030\001 \001(\001H\000\210" + "\001\001\022\037\n\022click_through_rate\030\002 \001(\001H\001\210\001\001\022\037\n\022a" + "verage_cpc_micros\030\003 \001(\003H\002\210\001\001\022\023\n\006clicks\030\004" + " \001(\001H\003\210\001\001\022\030\n\013cost_micros\030\005 \001(\003H\004\210\001\001\022\030\n\013c" + "onversions\030\006 \001(\001H\005\210\001\001\022\034\n\017conversion_rate" + "\030\007 \001(\001H\006\210\001\001\022\037\n\022average_cpa_micros\030\010 \001(\003H" + "\007\210\001\001B\016\n\014_impressionsB\025\n\023_click_through_r" + "ateB\025\n\023_average_cpc_microsB\t\n\007_clicksB\016\n" + "\014_cost_microsB\016\n\014_conversionsB\022\n\020_conver" + "sion_rateB\025\n\023_average_cpa_micros2\316\010\n\026Key" + "wordPlanIdeaService\022\326\001\n\024GenerateKeywordI" + "deas\022>.google.ads.googleads.v19.services" + ".GenerateKeywordIdeasRequest\032>.google.ad" + "s.googleads.v19.services.GenerateKeyword" + "IdeaResponse\">\202\323\344\223\0028\"3/v19/customers/{cu" + "stomer_id=*}:generateKeywordIdeas:\001*\022\207\002\n" + " GenerateKeywordHistoricalMetrics\022J.goog" + "le.ads.googleads.v19.services.GenerateKe" + "ywordHistoricalMetricsRequest\032K.google.a" + "ds.googleads.v19.services.GenerateKeywor" + "dHistoricalMetricsResponse\"J\202\323\344\223\002D\"?/v19" + "/customers/{customer_id=*}:generateKeywo" + "rdHistoricalMetrics:\001*\022\374\001\n\025GenerateAdGro" + "upThemes\022?.google.ads.googleads.v19.serv" + "ices.GenerateAdGroupThemesRequest\032@.goog" + "le.ads.googleads.v19.services.GenerateAd" + "GroupThemesResponse\"`\332A\036customer_id,keyw" + "ords,ad_groups\202\323\344\223\0029\"4/v19/customers/{cu" + "stomer_id=*}:generateAdGroupThemes:\001*\022\212\002" + "\n\036GenerateKeywordForecastMetrics\022H.googl" + "e.ads.googleads.v19.services.GenerateKey" + "wordForecastMetricsRequest\032I.google.ads." + "googleads.v19.services.GenerateKeywordFo" + "recastMetricsResponse\"S\332A\010campaign\202\323\344\223\002B" + "\"=/v19/customers/{customer_id=*}:generat" + "eKeywordForecastMetrics:\001*\032E\312A\030googleads" + ".googleapis.com\322A\'https://www.googleapis" + ".com/auth/adwordsB\207\002\n%com.google.ads.goo" + "gleads.v19.servicesB\033KeywordPlanIdeaServ" + "iceProtoP\001ZIgoogle.golang.org/genproto/g" + "oogleapis/ads/googleads/v19/services;ser" + "vices\242\002\003GAA\252\002!Google.Ads.GoogleAds.V19.S" + "ervices\312\002!Google\\Ads\\GoogleAds\\V19\\Servi" + "ces\352\002%Google::Ads::GoogleAds::V19::Servi" + "cesb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.ads.googleads.v19.common.CriteriaProto.getDescriptor(), com.google.ads.googleads.v19.common.DatesProto.getDescriptor(), com.google.ads.googleads.v19.common.KeywordPlanCommonProto.getDescriptor(), com.google.ads.googleads.v19.enums.KeywordMatchTypeProto.getDescriptor(), com.google.ads.googleads.v19.enums.KeywordPlanKeywordAnnotationProto.getDescriptor(), com.google.ads.googleads.v19.enums.KeywordPlanNetworkProto.getDescriptor(), com.google.api.AnnotationsProto.getDescriptor(), com.google.api.ClientProto.getDescriptor(), com.google.api.FieldBehaviorProto.getDescriptor(), }); internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeasRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeasRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeasRequest_descriptor, new java.lang.String[] { "CustomerId", "Language", "GeoTargetConstants", "IncludeAdultKeywords", "PageToken", "PageSize", "KeywordPlanNetwork", "KeywordAnnotation", "AggregateMetrics", "HistoricalMetricsOptions", "KeywordAndUrlSeed", "KeywordSeed", "UrlSeed", "SiteSeed", "Seed", }); internal_static_google_ads_googleads_v19_services_KeywordAndUrlSeed_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_ads_googleads_v19_services_KeywordAndUrlSeed_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_KeywordAndUrlSeed_descriptor, new java.lang.String[] { "Url", "Keywords", }); internal_static_google_ads_googleads_v19_services_KeywordSeed_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_ads_googleads_v19_services_KeywordSeed_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_KeywordSeed_descriptor, new java.lang.String[] { "Keywords", }); internal_static_google_ads_googleads_v19_services_SiteSeed_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_ads_googleads_v19_services_SiteSeed_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_SiteSeed_descriptor, new java.lang.String[] { "Site", }); internal_static_google_ads_googleads_v19_services_UrlSeed_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_google_ads_googleads_v19_services_UrlSeed_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_UrlSeed_descriptor, new java.lang.String[] { "Url", }); internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeaResponse_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeaResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeaResponse_descriptor, new java.lang.String[] { "Results", "AggregateMetricResults", "NextPageToken", "TotalSize", }); internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeaResult_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeaResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_GenerateKeywordIdeaResult_descriptor, new java.lang.String[] { "Text", "KeywordIdeaMetrics", "KeywordAnnotations", "CloseVariants", }); internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsRequest_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsRequest_descriptor, new java.lang.String[] { "CustomerId", "Keywords", "Language", "IncludeAdultKeywords", "GeoTargetConstants", "KeywordPlanNetwork", "AggregateMetrics", "HistoricalMetricsOptions", }); internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsResponse_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsResponse_descriptor, new java.lang.String[] { "Results", "AggregateMetricResults", }); internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsResult_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_GenerateKeywordHistoricalMetricsResult_descriptor, new java.lang.String[] { "Text", "CloseVariants", "KeywordMetrics", }); internal_static_google_ads_googleads_v19_services_GenerateAdGroupThemesRequest_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_google_ads_googleads_v19_services_GenerateAdGroupThemesRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_GenerateAdGroupThemesRequest_descriptor, new java.lang.String[] { "CustomerId", "Keywords", "AdGroups", }); internal_static_google_ads_googleads_v19_services_GenerateAdGroupThemesResponse_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_google_ads_googleads_v19_services_GenerateAdGroupThemesResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_GenerateAdGroupThemesResponse_descriptor, new java.lang.String[] { "AdGroupKeywordSuggestions", "UnusableAdGroups", }); internal_static_google_ads_googleads_v19_services_AdGroupKeywordSuggestion_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_google_ads_googleads_v19_services_AdGroupKeywordSuggestion_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_AdGroupKeywordSuggestion_descriptor, new java.lang.String[] { "KeywordText", "SuggestedKeywordText", "SuggestedMatchType", "SuggestedAdGroup", "SuggestedCampaign", }); internal_static_google_ads_googleads_v19_services_UnusableAdGroup_descriptor = getDescriptor().getMessageTypes().get(13); internal_static_google_ads_googleads_v19_services_UnusableAdGroup_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_UnusableAdGroup_descriptor, new java.lang.String[] { "AdGroup", "Campaign", }); internal_static_google_ads_googleads_v19_services_GenerateKeywordForecastMetricsRequest_descriptor = getDescriptor().getMessageTypes().get(14); internal_static_google_ads_googleads_v19_services_GenerateKeywordForecastMetricsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_GenerateKeywordForecastMetricsRequest_descriptor, new java.lang.String[] { "CustomerId", "CurrencyCode", "ForecastPeriod", "Campaign", }); internal_static_google_ads_googleads_v19_services_CampaignToForecast_descriptor = getDescriptor().getMessageTypes().get(15); internal_static_google_ads_googleads_v19_services_CampaignToForecast_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_CampaignToForecast_descriptor, new java.lang.String[] { "LanguageConstants", "GeoModifiers", "KeywordPlanNetwork", "NegativeKeywords", "BiddingStrategy", "ConversionRate", "AdGroups", }); internal_static_google_ads_googleads_v19_services_CampaignToForecast_CampaignBiddingStrategy_descriptor = internal_static_google_ads_googleads_v19_services_CampaignToForecast_descriptor.getNestedTypes().get(0); internal_static_google_ads_googleads_v19_services_CampaignToForecast_CampaignBiddingStrategy_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_CampaignToForecast_CampaignBiddingStrategy_descriptor, new java.lang.String[] { "ManualCpcBiddingStrategy", "MaximizeClicksBiddingStrategy", "MaximizeConversionsBiddingStrategy", "BiddingStrategy", }); internal_static_google_ads_googleads_v19_services_ForecastAdGroup_descriptor = getDescriptor().getMessageTypes().get(16); internal_static_google_ads_googleads_v19_services_ForecastAdGroup_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_ForecastAdGroup_descriptor, new java.lang.String[] { "MaxCpcBidMicros", "BiddableKeywords", "NegativeKeywords", }); internal_static_google_ads_googleads_v19_services_BiddableKeyword_descriptor = getDescriptor().getMessageTypes().get(17); internal_static_google_ads_googleads_v19_services_BiddableKeyword_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_BiddableKeyword_descriptor, new java.lang.String[] { "Keyword", "MaxCpcBidMicros", }); internal_static_google_ads_googleads_v19_services_CriterionBidModifier_descriptor = getDescriptor().getMessageTypes().get(18); internal_static_google_ads_googleads_v19_services_CriterionBidModifier_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_CriterionBidModifier_descriptor, new java.lang.String[] { "GeoTargetConstant", "BidModifier", }); internal_static_google_ads_googleads_v19_services_ManualCpcBiddingStrategy_descriptor = getDescriptor().getMessageTypes().get(19); internal_static_google_ads_googleads_v19_services_ManualCpcBiddingStrategy_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_ManualCpcBiddingStrategy_descriptor, new java.lang.String[] { "DailyBudgetMicros", "MaxCpcBidMicros", }); internal_static_google_ads_googleads_v19_services_MaximizeClicksBiddingStrategy_descriptor = getDescriptor().getMessageTypes().get(20); internal_static_google_ads_googleads_v19_services_MaximizeClicksBiddingStrategy_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_MaximizeClicksBiddingStrategy_descriptor, new java.lang.String[] { "DailyTargetSpendMicros", "MaxCpcBidCeilingMicros", }); internal_static_google_ads_googleads_v19_services_MaximizeConversionsBiddingStrategy_descriptor = getDescriptor().getMessageTypes().get(21); internal_static_google_ads_googleads_v19_services_MaximizeConversionsBiddingStrategy_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_MaximizeConversionsBiddingStrategy_descriptor, new java.lang.String[] { "DailyTargetSpendMicros", }); internal_static_google_ads_googleads_v19_services_GenerateKeywordForecastMetricsResponse_descriptor = getDescriptor().getMessageTypes().get(22); internal_static_google_ads_googleads_v19_services_GenerateKeywordForecastMetricsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_GenerateKeywordForecastMetricsResponse_descriptor, new java.lang.String[] { "CampaignForecastMetrics", }); internal_static_google_ads_googleads_v19_services_KeywordForecastMetrics_descriptor = getDescriptor().getMessageTypes().get(23); internal_static_google_ads_googleads_v19_services_KeywordForecastMetrics_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v19_services_KeywordForecastMetrics_descriptor, new java.lang.String[] { "Impressions", "ClickThroughRate", "AverageCpcMicros", "Clicks", "CostMicros", "Conversions", "ConversionRate", "AverageCpaMicros", }); 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.ads.googleads.v19.common.CriteriaProto.getDescriptor(); com.google.ads.googleads.v19.common.DatesProto.getDescriptor(); com.google.ads.googleads.v19.common.KeywordPlanCommonProto.getDescriptor(); com.google.ads.googleads.v19.enums.KeywordMatchTypeProto.getDescriptor(); com.google.ads.googleads.v19.enums.KeywordPlanKeywordAnnotationProto.getDescriptor(); com.google.ads.googleads.v19.enums.KeywordPlanNetworkProto.getDescriptor(); com.google.api.AnnotationsProto.getDescriptor(); com.google.api.ClientProto.getDescriptor(); com.google.api.FieldBehaviorProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
googleads/google-ads-java
36,401
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/services/KeywordPlanIdeaServiceProto.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v20/services/keyword_plan_idea_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v20.services; public final class KeywordPlanIdeaServiceProto { private KeywordPlanIdeaServiceProto() {} 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_ads_googleads_v20_services_GenerateKeywordIdeasRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeasRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_KeywordAndUrlSeed_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_KeywordAndUrlSeed_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_KeywordSeed_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_KeywordSeed_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_SiteSeed_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_SiteSeed_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_UrlSeed_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_UrlSeed_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeaResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeaResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeaResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeaResult_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsResult_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_GenerateAdGroupThemesRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_GenerateAdGroupThemesRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_GenerateAdGroupThemesResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_GenerateAdGroupThemesResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_AdGroupKeywordSuggestion_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_AdGroupKeywordSuggestion_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_UnusableAdGroup_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_UnusableAdGroup_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_GenerateKeywordForecastMetricsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_GenerateKeywordForecastMetricsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_CampaignToForecast_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_CampaignToForecast_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_CampaignToForecast_CampaignBiddingStrategy_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_CampaignToForecast_CampaignBiddingStrategy_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_ForecastAdGroup_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_ForecastAdGroup_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_BiddableKeyword_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_BiddableKeyword_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_CriterionBidModifier_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_CriterionBidModifier_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_ManualCpcBiddingStrategy_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_ManualCpcBiddingStrategy_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_MaximizeClicksBiddingStrategy_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_MaximizeClicksBiddingStrategy_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_MaximizeConversionsBiddingStrategy_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_MaximizeConversionsBiddingStrategy_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_GenerateKeywordForecastMetricsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_GenerateKeywordForecastMetricsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v20_services_KeywordForecastMetrics_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v20_services_KeywordForecastMetrics_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\nAgoogle/ads/googleads/v20/services/keyw" + "ord_plan_idea_service.proto\022!google.ads." + "googleads.v20.services\032.google/ads/googl" + "eads/v20/common/criteria.proto\032+google/a" + "ds/googleads/v20/common/dates.proto\0329goo" + "gle/ads/googleads/v20/common/keyword_pla" + "n_common.proto\0327google/ads/googleads/v20" + "/enums/keyword_match_type.proto\032Dgoogle/" + "ads/googleads/v20/enums/keyword_plan_key" + "word_annotation.proto\0329google/ads/google" + "ads/v20/enums/keyword_plan_network.proto" + "\032\034google/api/annotations.proto\032\027google/a" + "pi/client.proto\032\037google/api/field_behavi" + "or.proto\"\377\006\n\033GenerateKeywordIdeasRequest" + "\022\023\n\013customer_id\030\001 \001(\t\022\025\n\010language\030\016 \001(\tH" + "\001\210\001\001\022\034\n\024geo_target_constants\030\017 \003(\t\022\036\n\026in" + "clude_adult_keywords\030\n \001(\010\022\022\n\npage_token" + "\030\014 \001(\t\022\021\n\tpage_size\030\r \001(\005\022g\n\024keyword_pla" + "n_network\030\t \001(\0162I.google.ads.googleads.v" + "20.enums.KeywordPlanNetworkEnum.KeywordP" + "lanNetwork\022y\n\022keyword_annotation\030\021 \003(\0162]" + ".google.ads.googleads.v20.enums.KeywordP" + "lanKeywordAnnotationEnum.KeywordPlanKeyw" + "ordAnnotation\022W\n\021aggregate_metrics\030\020 \001(\013" + "2<.google.ads.googleads.v20.common.Keywo" + "rdPlanAggregateMetrics\022]\n\032historical_met" + "rics_options\030\022 \001(\01329.google.ads.googlead" + "s.v20.common.HistoricalMetricsOptions\022T\n" + "\024keyword_and_url_seed\030\002 \001(\01324.google.ads" + ".googleads.v20.services.KeywordAndUrlSee" + "dH\000\022F\n\014keyword_seed\030\003 \001(\0132..google.ads.g" + "oogleads.v20.services.KeywordSeedH\000\022>\n\010u" + "rl_seed\030\005 \001(\0132*.google.ads.googleads.v20" + ".services.UrlSeedH\000\022@\n\tsite_seed\030\013 \001(\0132+" + ".google.ads.googleads.v20.services.SiteS" + "eedH\000B\006\n\004seedB\013\n\t_language\"?\n\021KeywordAnd" + "UrlSeed\022\020\n\003url\030\003 \001(\tH\000\210\001\001\022\020\n\010keywords\030\004 " + "\003(\tB\006\n\004_url\"\037\n\013KeywordSeed\022\020\n\010keywords\030\002" + " \003(\t\"&\n\010SiteSeed\022\021\n\004site\030\002 \001(\tH\000\210\001\001B\007\n\005_" + "site\"#\n\007UrlSeed\022\020\n\003url\030\002 \001(\tH\000\210\001\001B\006\n\004_ur" + "l\"\377\001\n\033GenerateKeywordIdeaResponse\022M\n\007res" + "ults\030\001 \003(\0132<.google.ads.googleads.v20.se" + "rvices.GenerateKeywordIdeaResult\022d\n\030aggr" + "egate_metric_results\030\004 \001(\0132B.google.ads." + "googleads.v20.common.KeywordPlanAggregat" + "eMetricResults\022\027\n\017next_page_token\030\002 \001(\t\022" + "\022\n\ntotal_size\030\003 \001(\003\"\376\001\n\031GenerateKeywordI" + "deaResult\022\021\n\004text\030\005 \001(\tH\000\210\001\001\022[\n\024keyword_" + "idea_metrics\030\003 \001(\0132=.google.ads.googlead" + "s.v20.common.KeywordPlanHistoricalMetric" + "s\022P\n\023keyword_annotations\030\006 \001(\01323.google." + "ads.googleads.v20.common.KeywordAnnotati" + "ons\022\026\n\016close_variants\030\007 \003(\tB\007\n\005_text\"\323\003\n" + "\'GenerateKeywordHistoricalMetricsRequest" + "\022\023\n\013customer_id\030\001 \001(\t\022\020\n\010keywords\030\002 \003(\t\022" + "\025\n\010language\030\004 \001(\tH\000\210\001\001\022\036\n\026include_adult_" + "keywords\030\005 \001(\010\022\034\n\024geo_target_constants\030\006" + " \003(\t\022g\n\024keyword_plan_network\030\007 \001(\0162I.goo" + "gle.ads.googleads.v20.enums.KeywordPlanN" + "etworkEnum.KeywordPlanNetwork\022W\n\021aggrega" + "te_metrics\030\010 \001(\0132<.google.ads.googleads." + "v20.common.KeywordPlanAggregateMetrics\022]" + "\n\032historical_metrics_options\030\003 \001(\01329.goo" + "gle.ads.googleads.v20.common.HistoricalM" + "etricsOptionsB\013\n\t_language\"\354\001\n(GenerateK" + "eywordHistoricalMetricsResponse\022Z\n\007resul" + "ts\030\001 \003(\0132I.google.ads.googleads.v20.serv" + "ices.GenerateKeywordHistoricalMetricsRes" + "ult\022d\n\030aggregate_metric_results\030\002 \001(\0132B." + "google.ads.googleads.v20.common.KeywordP" + "lanAggregateMetricResults\"\264\001\n&GenerateKe" + "ywordHistoricalMetricsResult\022\021\n\004text\030\001 \001" + "(\tH\000\210\001\001\022\026\n\016close_variants\030\003 \003(\t\022V\n\017keywo" + "rd_metrics\030\002 \001(\0132=.google.ads.googleads." + "v20.common.KeywordPlanHistoricalMetricsB" + "\007\n\005_text\"g\n\034GenerateAdGroupThemesRequest" + "\022\030\n\013customer_id\030\001 \001(\tB\003\340A\002\022\025\n\010keywords\030\002" + " \003(\tB\003\340A\002\022\026\n\tad_groups\030\003 \003(\tB\003\340A\002\"\322\001\n\035Ge" + "nerateAdGroupThemesResponse\022a\n\034ad_group_" + "keyword_suggestions\030\001 \003(\0132;.google.ads.g" + "oogleads.v20.services.AdGroupKeywordSugg" + "estion\022N\n\022unusable_ad_groups\030\002 \003(\01322.goo" + "gle.ads.googleads.v20.services.UnusableA" + "dGroup\"\355\001\n\030AdGroupKeywordSuggestion\022\024\n\014k" + "eyword_text\030\001 \001(\t\022\036\n\026suggested_keyword_t" + "ext\030\002 \001(\t\022c\n\024suggested_match_type\030\003 \001(\0162" + "E.google.ads.googleads.v20.enums.Keyword" + "MatchTypeEnum.KeywordMatchType\022\032\n\022sugges" + "ted_ad_group\030\004 \001(\t\022\032\n\022suggested_campaign" + "\030\005 \001(\t\"5\n\017UnusableAdGroup\022\020\n\010ad_group\030\001 " + "\001(\t\022\020\n\010campaign\030\002 \001(\t\"\375\001\n%GenerateKeywor" + "dForecastMetricsRequest\022\023\n\013customer_id\030\001" + " \001(\t\022\032\n\rcurrency_code\030\002 \001(\tH\000\210\001\001\022C\n\017fore" + "cast_period\030\003 \001(\0132*.google.ads.googleads" + ".v20.common.DateRange\022L\n\010campaign\030\004 \001(\0132" + "5.google.ads.googleads.v20.services.Camp" + "aignToForecastB\003\340A\002B\020\n\016_currency_code\"\230\007" + "\n\022CampaignToForecast\022\032\n\022language_constan" + "ts\030\001 \003(\t\022N\n\rgeo_modifiers\030\002 \003(\01327.google" + ".ads.googleads.v20.services.CriterionBid" + "Modifier\022l\n\024keyword_plan_network\030\003 \001(\0162I" + ".google.ads.googleads.v20.enums.KeywordP" + "lanNetworkEnum.KeywordPlanNetworkB\003\340A\002\022G" + "\n\021negative_keywords\030\004 \003(\0132,.google.ads.g" + "oogleads.v20.common.KeywordInfo\022l\n\020biddi" + "ng_strategy\030\005 \001(\0132M.google.ads.googleads" + ".v20.services.CampaignToForecast.Campaig" + "nBiddingStrategyB\003\340A\002\022\034\n\017conversion_rate" + "\030\006 \001(\001H\000\210\001\001\022E\n\tad_groups\030\007 \003(\01322.google." + "ads.googleads.v20.services.ForecastAdGro" + "up\032\367\002\n\027CampaignBiddingStrategy\022b\n\033manual" + "_cpc_bidding_strategy\030\001 \001(\0132;.google.ads" + ".googleads.v20.services.ManualCpcBidding" + "StrategyH\000\022l\n maximize_clicks_bidding_st" + "rategy\030\002 \001(\0132@.google.ads.googleads.v20." + "services.MaximizeClicksBiddingStrategyH\000" + "\022v\n%maximize_conversions_bidding_strateg" + "y\030\003 \001(\0132E.google.ads.googleads.v20.servi" + "ces.MaximizeConversionsBiddingStrategyH\000" + "B\022\n\020bidding_strategyB\022\n\020_conversion_rate" + "\"\346\001\n\017ForecastAdGroup\022\037\n\022max_cpc_bid_micr" + "os\030\001 \001(\003H\000\210\001\001\022R\n\021biddable_keywords\030\002 \003(\013" + "22.google.ads.googleads.v20.services.Bid" + "dableKeywordB\003\340A\002\022G\n\021negative_keywords\030\003" + " \003(\0132,.google.ads.googleads.v20.common.K" + "eywordInfoB\025\n\023_max_cpc_bid_micros\"\215\001\n\017Bi" + "ddableKeyword\022B\n\007keyword\030\001 \001(\0132,.google." + "ads.googleads.v20.common.KeywordInfoB\003\340A" + "\002\022\037\n\022max_cpc_bid_micros\030\002 \001(\003H\000\210\001\001B\025\n\023_m" + "ax_cpc_bid_micros\"_\n\024CriterionBidModifie" + "r\022\033\n\023geo_target_constant\030\001 \001(\t\022\031\n\014bid_mo" + "difier\030\002 \001(\001H\000\210\001\001B\017\n\r_bid_modifier\"u\n\030Ma" + "nualCpcBiddingStrategy\022 \n\023daily_budget_m" + "icros\030\001 \001(\003H\000\210\001\001\022\037\n\022max_cpc_bid_micros\030\002" + " \001(\003B\003\340A\002B\026\n\024_daily_budget_micros\"\217\001\n\035Ma" + "ximizeClicksBiddingStrategy\022&\n\031daily_tar" + "get_spend_micros\030\001 \001(\003B\003\340A\002\022\'\n\032max_cpc_b" + "id_ceiling_micros\030\002 \001(\003H\000\210\001\001B\035\n\033_max_cpc" + "_bid_ceiling_micros\"L\n\"MaximizeConversio" + "nsBiddingStrategy\022&\n\031daily_target_spend_" + "micros\030\001 \001(\003B\003\340A\002\"\251\001\n&GenerateKeywordFor" + "ecastMetricsResponse\022a\n\031campaign_forecas" + "t_metrics\030\001 \001(\01329.google.ads.googleads.v" + "20.services.KeywordForecastMetricsH\000\210\001\001B" + "\034\n\032_campaign_forecast_metrics\"\220\003\n\026Keywor" + "dForecastMetrics\022\030\n\013impressions\030\001 \001(\001H\000\210" + "\001\001\022\037\n\022click_through_rate\030\002 \001(\001H\001\210\001\001\022\037\n\022a" + "verage_cpc_micros\030\003 \001(\003H\002\210\001\001\022\023\n\006clicks\030\004" + " \001(\001H\003\210\001\001\022\030\n\013cost_micros\030\005 \001(\003H\004\210\001\001\022\030\n\013c" + "onversions\030\006 \001(\001H\005\210\001\001\022\034\n\017conversion_rate" + "\030\007 \001(\001H\006\210\001\001\022\037\n\022average_cpa_micros\030\010 \001(\003H" + "\007\210\001\001B\016\n\014_impressionsB\025\n\023_click_through_r" + "ateB\025\n\023_average_cpc_microsB\t\n\007_clicksB\016\n" + "\014_cost_microsB\016\n\014_conversionsB\022\n\020_conver" + "sion_rateB\025\n\023_average_cpa_micros2\316\010\n\026Key" + "wordPlanIdeaService\022\326\001\n\024GenerateKeywordI" + "deas\022>.google.ads.googleads.v20.services" + ".GenerateKeywordIdeasRequest\032>.google.ad" + "s.googleads.v20.services.GenerateKeyword" + "IdeaResponse\">\202\323\344\223\0028\"3/v20/customers/{cu" + "stomer_id=*}:generateKeywordIdeas:\001*\022\207\002\n" + " GenerateKeywordHistoricalMetrics\022J.goog" + "le.ads.googleads.v20.services.GenerateKe" + "ywordHistoricalMetricsRequest\032K.google.a" + "ds.googleads.v20.services.GenerateKeywor" + "dHistoricalMetricsResponse\"J\202\323\344\223\002D\"?/v20" + "/customers/{customer_id=*}:generateKeywo" + "rdHistoricalMetrics:\001*\022\374\001\n\025GenerateAdGro" + "upThemes\022?.google.ads.googleads.v20.serv" + "ices.GenerateAdGroupThemesRequest\032@.goog" + "le.ads.googleads.v20.services.GenerateAd" + "GroupThemesResponse\"`\332A\036customer_id,keyw" + "ords,ad_groups\202\323\344\223\0029\"4/v20/customers/{cu" + "stomer_id=*}:generateAdGroupThemes:\001*\022\212\002" + "\n\036GenerateKeywordForecastMetrics\022H.googl" + "e.ads.googleads.v20.services.GenerateKey" + "wordForecastMetricsRequest\032I.google.ads." + "googleads.v20.services.GenerateKeywordFo" + "recastMetricsResponse\"S\332A\010campaign\202\323\344\223\002B" + "\"=/v20/customers/{customer_id=*}:generat" + "eKeywordForecastMetrics:\001*\032E\312A\030googleads" + ".googleapis.com\322A\'https://www.googleapis" + ".com/auth/adwordsB\207\002\n%com.google.ads.goo" + "gleads.v20.servicesB\033KeywordPlanIdeaServ" + "iceProtoP\001ZIgoogle.golang.org/genproto/g" + "oogleapis/ads/googleads/v20/services;ser" + "vices\242\002\003GAA\252\002!Google.Ads.GoogleAds.V20.S" + "ervices\312\002!Google\\Ads\\GoogleAds\\V20\\Servi" + "ces\352\002%Google::Ads::GoogleAds::V20::Servi" + "cesb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.ads.googleads.v20.common.CriteriaProto.getDescriptor(), com.google.ads.googleads.v20.common.DatesProto.getDescriptor(), com.google.ads.googleads.v20.common.KeywordPlanCommonProto.getDescriptor(), com.google.ads.googleads.v20.enums.KeywordMatchTypeProto.getDescriptor(), com.google.ads.googleads.v20.enums.KeywordPlanKeywordAnnotationProto.getDescriptor(), com.google.ads.googleads.v20.enums.KeywordPlanNetworkProto.getDescriptor(), com.google.api.AnnotationsProto.getDescriptor(), com.google.api.ClientProto.getDescriptor(), com.google.api.FieldBehaviorProto.getDescriptor(), }); internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeasRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeasRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeasRequest_descriptor, new java.lang.String[] { "CustomerId", "Language", "GeoTargetConstants", "IncludeAdultKeywords", "PageToken", "PageSize", "KeywordPlanNetwork", "KeywordAnnotation", "AggregateMetrics", "HistoricalMetricsOptions", "KeywordAndUrlSeed", "KeywordSeed", "UrlSeed", "SiteSeed", "Seed", }); internal_static_google_ads_googleads_v20_services_KeywordAndUrlSeed_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_ads_googleads_v20_services_KeywordAndUrlSeed_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_KeywordAndUrlSeed_descriptor, new java.lang.String[] { "Url", "Keywords", }); internal_static_google_ads_googleads_v20_services_KeywordSeed_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_ads_googleads_v20_services_KeywordSeed_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_KeywordSeed_descriptor, new java.lang.String[] { "Keywords", }); internal_static_google_ads_googleads_v20_services_SiteSeed_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_ads_googleads_v20_services_SiteSeed_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_SiteSeed_descriptor, new java.lang.String[] { "Site", }); internal_static_google_ads_googleads_v20_services_UrlSeed_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_google_ads_googleads_v20_services_UrlSeed_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_UrlSeed_descriptor, new java.lang.String[] { "Url", }); internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeaResponse_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeaResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeaResponse_descriptor, new java.lang.String[] { "Results", "AggregateMetricResults", "NextPageToken", "TotalSize", }); internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeaResult_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeaResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_GenerateKeywordIdeaResult_descriptor, new java.lang.String[] { "Text", "KeywordIdeaMetrics", "KeywordAnnotations", "CloseVariants", }); internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsRequest_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsRequest_descriptor, new java.lang.String[] { "CustomerId", "Keywords", "Language", "IncludeAdultKeywords", "GeoTargetConstants", "KeywordPlanNetwork", "AggregateMetrics", "HistoricalMetricsOptions", }); internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsResponse_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsResponse_descriptor, new java.lang.String[] { "Results", "AggregateMetricResults", }); internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsResult_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_GenerateKeywordHistoricalMetricsResult_descriptor, new java.lang.String[] { "Text", "CloseVariants", "KeywordMetrics", }); internal_static_google_ads_googleads_v20_services_GenerateAdGroupThemesRequest_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_google_ads_googleads_v20_services_GenerateAdGroupThemesRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_GenerateAdGroupThemesRequest_descriptor, new java.lang.String[] { "CustomerId", "Keywords", "AdGroups", }); internal_static_google_ads_googleads_v20_services_GenerateAdGroupThemesResponse_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_google_ads_googleads_v20_services_GenerateAdGroupThemesResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_GenerateAdGroupThemesResponse_descriptor, new java.lang.String[] { "AdGroupKeywordSuggestions", "UnusableAdGroups", }); internal_static_google_ads_googleads_v20_services_AdGroupKeywordSuggestion_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_google_ads_googleads_v20_services_AdGroupKeywordSuggestion_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_AdGroupKeywordSuggestion_descriptor, new java.lang.String[] { "KeywordText", "SuggestedKeywordText", "SuggestedMatchType", "SuggestedAdGroup", "SuggestedCampaign", }); internal_static_google_ads_googleads_v20_services_UnusableAdGroup_descriptor = getDescriptor().getMessageTypes().get(13); internal_static_google_ads_googleads_v20_services_UnusableAdGroup_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_UnusableAdGroup_descriptor, new java.lang.String[] { "AdGroup", "Campaign", }); internal_static_google_ads_googleads_v20_services_GenerateKeywordForecastMetricsRequest_descriptor = getDescriptor().getMessageTypes().get(14); internal_static_google_ads_googleads_v20_services_GenerateKeywordForecastMetricsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_GenerateKeywordForecastMetricsRequest_descriptor, new java.lang.String[] { "CustomerId", "CurrencyCode", "ForecastPeriod", "Campaign", }); internal_static_google_ads_googleads_v20_services_CampaignToForecast_descriptor = getDescriptor().getMessageTypes().get(15); internal_static_google_ads_googleads_v20_services_CampaignToForecast_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_CampaignToForecast_descriptor, new java.lang.String[] { "LanguageConstants", "GeoModifiers", "KeywordPlanNetwork", "NegativeKeywords", "BiddingStrategy", "ConversionRate", "AdGroups", }); internal_static_google_ads_googleads_v20_services_CampaignToForecast_CampaignBiddingStrategy_descriptor = internal_static_google_ads_googleads_v20_services_CampaignToForecast_descriptor.getNestedTypes().get(0); internal_static_google_ads_googleads_v20_services_CampaignToForecast_CampaignBiddingStrategy_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_CampaignToForecast_CampaignBiddingStrategy_descriptor, new java.lang.String[] { "ManualCpcBiddingStrategy", "MaximizeClicksBiddingStrategy", "MaximizeConversionsBiddingStrategy", "BiddingStrategy", }); internal_static_google_ads_googleads_v20_services_ForecastAdGroup_descriptor = getDescriptor().getMessageTypes().get(16); internal_static_google_ads_googleads_v20_services_ForecastAdGroup_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_ForecastAdGroup_descriptor, new java.lang.String[] { "MaxCpcBidMicros", "BiddableKeywords", "NegativeKeywords", }); internal_static_google_ads_googleads_v20_services_BiddableKeyword_descriptor = getDescriptor().getMessageTypes().get(17); internal_static_google_ads_googleads_v20_services_BiddableKeyword_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_BiddableKeyword_descriptor, new java.lang.String[] { "Keyword", "MaxCpcBidMicros", }); internal_static_google_ads_googleads_v20_services_CriterionBidModifier_descriptor = getDescriptor().getMessageTypes().get(18); internal_static_google_ads_googleads_v20_services_CriterionBidModifier_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_CriterionBidModifier_descriptor, new java.lang.String[] { "GeoTargetConstant", "BidModifier", }); internal_static_google_ads_googleads_v20_services_ManualCpcBiddingStrategy_descriptor = getDescriptor().getMessageTypes().get(19); internal_static_google_ads_googleads_v20_services_ManualCpcBiddingStrategy_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_ManualCpcBiddingStrategy_descriptor, new java.lang.String[] { "DailyBudgetMicros", "MaxCpcBidMicros", }); internal_static_google_ads_googleads_v20_services_MaximizeClicksBiddingStrategy_descriptor = getDescriptor().getMessageTypes().get(20); internal_static_google_ads_googleads_v20_services_MaximizeClicksBiddingStrategy_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_MaximizeClicksBiddingStrategy_descriptor, new java.lang.String[] { "DailyTargetSpendMicros", "MaxCpcBidCeilingMicros", }); internal_static_google_ads_googleads_v20_services_MaximizeConversionsBiddingStrategy_descriptor = getDescriptor().getMessageTypes().get(21); internal_static_google_ads_googleads_v20_services_MaximizeConversionsBiddingStrategy_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_MaximizeConversionsBiddingStrategy_descriptor, new java.lang.String[] { "DailyTargetSpendMicros", }); internal_static_google_ads_googleads_v20_services_GenerateKeywordForecastMetricsResponse_descriptor = getDescriptor().getMessageTypes().get(22); internal_static_google_ads_googleads_v20_services_GenerateKeywordForecastMetricsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_GenerateKeywordForecastMetricsResponse_descriptor, new java.lang.String[] { "CampaignForecastMetrics", }); internal_static_google_ads_googleads_v20_services_KeywordForecastMetrics_descriptor = getDescriptor().getMessageTypes().get(23); internal_static_google_ads_googleads_v20_services_KeywordForecastMetrics_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v20_services_KeywordForecastMetrics_descriptor, new java.lang.String[] { "Impressions", "ClickThroughRate", "AverageCpcMicros", "Clicks", "CostMicros", "Conversions", "ConversionRate", "AverageCpaMicros", }); 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.ads.googleads.v20.common.CriteriaProto.getDescriptor(); com.google.ads.googleads.v20.common.DatesProto.getDescriptor(); com.google.ads.googleads.v20.common.KeywordPlanCommonProto.getDescriptor(); com.google.ads.googleads.v20.enums.KeywordMatchTypeProto.getDescriptor(); com.google.ads.googleads.v20.enums.KeywordPlanKeywordAnnotationProto.getDescriptor(); com.google.ads.googleads.v20.enums.KeywordPlanNetworkProto.getDescriptor(); com.google.api.AnnotationsProto.getDescriptor(); com.google.api.ClientProto.getDescriptor(); com.google.api.FieldBehaviorProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
googleads/google-ads-java
36,401
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/services/KeywordPlanIdeaServiceProto.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v21/services/keyword_plan_idea_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v21.services; public final class KeywordPlanIdeaServiceProto { private KeywordPlanIdeaServiceProto() {} 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_ads_googleads_v21_services_GenerateKeywordIdeasRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeasRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_KeywordAndUrlSeed_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_KeywordAndUrlSeed_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_KeywordSeed_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_KeywordSeed_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_SiteSeed_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_SiteSeed_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_UrlSeed_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_UrlSeed_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeaResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeaResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeaResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeaResult_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsResult_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_GenerateAdGroupThemesRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_GenerateAdGroupThemesRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_GenerateAdGroupThemesResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_GenerateAdGroupThemesResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_AdGroupKeywordSuggestion_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_AdGroupKeywordSuggestion_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_UnusableAdGroup_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_UnusableAdGroup_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_GenerateKeywordForecastMetricsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_GenerateKeywordForecastMetricsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_CampaignToForecast_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_CampaignToForecast_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_CampaignToForecast_CampaignBiddingStrategy_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_CampaignToForecast_CampaignBiddingStrategy_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_ForecastAdGroup_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_ForecastAdGroup_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_BiddableKeyword_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_BiddableKeyword_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_CriterionBidModifier_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_CriterionBidModifier_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_ManualCpcBiddingStrategy_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_ManualCpcBiddingStrategy_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_MaximizeClicksBiddingStrategy_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_MaximizeClicksBiddingStrategy_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_MaximizeConversionsBiddingStrategy_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_MaximizeConversionsBiddingStrategy_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_GenerateKeywordForecastMetricsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_GenerateKeywordForecastMetricsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v21_services_KeywordForecastMetrics_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v21_services_KeywordForecastMetrics_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\nAgoogle/ads/googleads/v21/services/keyw" + "ord_plan_idea_service.proto\022!google.ads." + "googleads.v21.services\032.google/ads/googl" + "eads/v21/common/criteria.proto\032+google/a" + "ds/googleads/v21/common/dates.proto\0329goo" + "gle/ads/googleads/v21/common/keyword_pla" + "n_common.proto\0327google/ads/googleads/v21" + "/enums/keyword_match_type.proto\032Dgoogle/" + "ads/googleads/v21/enums/keyword_plan_key" + "word_annotation.proto\0329google/ads/google" + "ads/v21/enums/keyword_plan_network.proto" + "\032\034google/api/annotations.proto\032\027google/a" + "pi/client.proto\032\037google/api/field_behavi" + "or.proto\"\377\006\n\033GenerateKeywordIdeasRequest" + "\022\023\n\013customer_id\030\001 \001(\t\022\025\n\010language\030\016 \001(\tH" + "\001\210\001\001\022\034\n\024geo_target_constants\030\017 \003(\t\022\036\n\026in" + "clude_adult_keywords\030\n \001(\010\022\022\n\npage_token" + "\030\014 \001(\t\022\021\n\tpage_size\030\r \001(\005\022g\n\024keyword_pla" + "n_network\030\t \001(\0162I.google.ads.googleads.v" + "21.enums.KeywordPlanNetworkEnum.KeywordP" + "lanNetwork\022y\n\022keyword_annotation\030\021 \003(\0162]" + ".google.ads.googleads.v21.enums.KeywordP" + "lanKeywordAnnotationEnum.KeywordPlanKeyw" + "ordAnnotation\022W\n\021aggregate_metrics\030\020 \001(\013" + "2<.google.ads.googleads.v21.common.Keywo" + "rdPlanAggregateMetrics\022]\n\032historical_met" + "rics_options\030\022 \001(\01329.google.ads.googlead" + "s.v21.common.HistoricalMetricsOptions\022T\n" + "\024keyword_and_url_seed\030\002 \001(\01324.google.ads" + ".googleads.v21.services.KeywordAndUrlSee" + "dH\000\022F\n\014keyword_seed\030\003 \001(\0132..google.ads.g" + "oogleads.v21.services.KeywordSeedH\000\022>\n\010u" + "rl_seed\030\005 \001(\0132*.google.ads.googleads.v21" + ".services.UrlSeedH\000\022@\n\tsite_seed\030\013 \001(\0132+" + ".google.ads.googleads.v21.services.SiteS" + "eedH\000B\006\n\004seedB\013\n\t_language\"?\n\021KeywordAnd" + "UrlSeed\022\020\n\003url\030\003 \001(\tH\000\210\001\001\022\020\n\010keywords\030\004 " + "\003(\tB\006\n\004_url\"\037\n\013KeywordSeed\022\020\n\010keywords\030\002" + " \003(\t\"&\n\010SiteSeed\022\021\n\004site\030\002 \001(\tH\000\210\001\001B\007\n\005_" + "site\"#\n\007UrlSeed\022\020\n\003url\030\002 \001(\tH\000\210\001\001B\006\n\004_ur" + "l\"\377\001\n\033GenerateKeywordIdeaResponse\022M\n\007res" + "ults\030\001 \003(\0132<.google.ads.googleads.v21.se" + "rvices.GenerateKeywordIdeaResult\022d\n\030aggr" + "egate_metric_results\030\004 \001(\0132B.google.ads." + "googleads.v21.common.KeywordPlanAggregat" + "eMetricResults\022\027\n\017next_page_token\030\002 \001(\t\022" + "\022\n\ntotal_size\030\003 \001(\003\"\376\001\n\031GenerateKeywordI" + "deaResult\022\021\n\004text\030\005 \001(\tH\000\210\001\001\022[\n\024keyword_" + "idea_metrics\030\003 \001(\0132=.google.ads.googlead" + "s.v21.common.KeywordPlanHistoricalMetric" + "s\022P\n\023keyword_annotations\030\006 \001(\01323.google." + "ads.googleads.v21.common.KeywordAnnotati" + "ons\022\026\n\016close_variants\030\007 \003(\tB\007\n\005_text\"\323\003\n" + "\'GenerateKeywordHistoricalMetricsRequest" + "\022\023\n\013customer_id\030\001 \001(\t\022\020\n\010keywords\030\002 \003(\t\022" + "\025\n\010language\030\004 \001(\tH\000\210\001\001\022\036\n\026include_adult_" + "keywords\030\005 \001(\010\022\034\n\024geo_target_constants\030\006" + " \003(\t\022g\n\024keyword_plan_network\030\007 \001(\0162I.goo" + "gle.ads.googleads.v21.enums.KeywordPlanN" + "etworkEnum.KeywordPlanNetwork\022W\n\021aggrega" + "te_metrics\030\010 \001(\0132<.google.ads.googleads." + "v21.common.KeywordPlanAggregateMetrics\022]" + "\n\032historical_metrics_options\030\003 \001(\01329.goo" + "gle.ads.googleads.v21.common.HistoricalM" + "etricsOptionsB\013\n\t_language\"\354\001\n(GenerateK" + "eywordHistoricalMetricsResponse\022Z\n\007resul" + "ts\030\001 \003(\0132I.google.ads.googleads.v21.serv" + "ices.GenerateKeywordHistoricalMetricsRes" + "ult\022d\n\030aggregate_metric_results\030\002 \001(\0132B." + "google.ads.googleads.v21.common.KeywordP" + "lanAggregateMetricResults\"\264\001\n&GenerateKe" + "ywordHistoricalMetricsResult\022\021\n\004text\030\001 \001" + "(\tH\000\210\001\001\022\026\n\016close_variants\030\003 \003(\t\022V\n\017keywo" + "rd_metrics\030\002 \001(\0132=.google.ads.googleads." + "v21.common.KeywordPlanHistoricalMetricsB" + "\007\n\005_text\"g\n\034GenerateAdGroupThemesRequest" + "\022\030\n\013customer_id\030\001 \001(\tB\003\340A\002\022\025\n\010keywords\030\002" + " \003(\tB\003\340A\002\022\026\n\tad_groups\030\003 \003(\tB\003\340A\002\"\322\001\n\035Ge" + "nerateAdGroupThemesResponse\022a\n\034ad_group_" + "keyword_suggestions\030\001 \003(\0132;.google.ads.g" + "oogleads.v21.services.AdGroupKeywordSugg" + "estion\022N\n\022unusable_ad_groups\030\002 \003(\01322.goo" + "gle.ads.googleads.v21.services.UnusableA" + "dGroup\"\355\001\n\030AdGroupKeywordSuggestion\022\024\n\014k" + "eyword_text\030\001 \001(\t\022\036\n\026suggested_keyword_t" + "ext\030\002 \001(\t\022c\n\024suggested_match_type\030\003 \001(\0162" + "E.google.ads.googleads.v21.enums.Keyword" + "MatchTypeEnum.KeywordMatchType\022\032\n\022sugges" + "ted_ad_group\030\004 \001(\t\022\032\n\022suggested_campaign" + "\030\005 \001(\t\"5\n\017UnusableAdGroup\022\020\n\010ad_group\030\001 " + "\001(\t\022\020\n\010campaign\030\002 \001(\t\"\375\001\n%GenerateKeywor" + "dForecastMetricsRequest\022\023\n\013customer_id\030\001" + " \001(\t\022\032\n\rcurrency_code\030\002 \001(\tH\000\210\001\001\022C\n\017fore" + "cast_period\030\003 \001(\0132*.google.ads.googleads" + ".v21.common.DateRange\022L\n\010campaign\030\004 \001(\0132" + "5.google.ads.googleads.v21.services.Camp" + "aignToForecastB\003\340A\002B\020\n\016_currency_code\"\230\007" + "\n\022CampaignToForecast\022\032\n\022language_constan" + "ts\030\001 \003(\t\022N\n\rgeo_modifiers\030\002 \003(\01327.google" + ".ads.googleads.v21.services.CriterionBid" + "Modifier\022l\n\024keyword_plan_network\030\003 \001(\0162I" + ".google.ads.googleads.v21.enums.KeywordP" + "lanNetworkEnum.KeywordPlanNetworkB\003\340A\002\022G" + "\n\021negative_keywords\030\004 \003(\0132,.google.ads.g" + "oogleads.v21.common.KeywordInfo\022l\n\020biddi" + "ng_strategy\030\005 \001(\0132M.google.ads.googleads" + ".v21.services.CampaignToForecast.Campaig" + "nBiddingStrategyB\003\340A\002\022\034\n\017conversion_rate" + "\030\006 \001(\001H\000\210\001\001\022E\n\tad_groups\030\007 \003(\01322.google." + "ads.googleads.v21.services.ForecastAdGro" + "up\032\367\002\n\027CampaignBiddingStrategy\022b\n\033manual" + "_cpc_bidding_strategy\030\001 \001(\0132;.google.ads" + ".googleads.v21.services.ManualCpcBidding" + "StrategyH\000\022l\n maximize_clicks_bidding_st" + "rategy\030\002 \001(\0132@.google.ads.googleads.v21." + "services.MaximizeClicksBiddingStrategyH\000" + "\022v\n%maximize_conversions_bidding_strateg" + "y\030\003 \001(\0132E.google.ads.googleads.v21.servi" + "ces.MaximizeConversionsBiddingStrategyH\000" + "B\022\n\020bidding_strategyB\022\n\020_conversion_rate" + "\"\346\001\n\017ForecastAdGroup\022\037\n\022max_cpc_bid_micr" + "os\030\001 \001(\003H\000\210\001\001\022R\n\021biddable_keywords\030\002 \003(\013" + "22.google.ads.googleads.v21.services.Bid" + "dableKeywordB\003\340A\002\022G\n\021negative_keywords\030\003" + " \003(\0132,.google.ads.googleads.v21.common.K" + "eywordInfoB\025\n\023_max_cpc_bid_micros\"\215\001\n\017Bi" + "ddableKeyword\022B\n\007keyword\030\001 \001(\0132,.google." + "ads.googleads.v21.common.KeywordInfoB\003\340A" + "\002\022\037\n\022max_cpc_bid_micros\030\002 \001(\003H\000\210\001\001B\025\n\023_m" + "ax_cpc_bid_micros\"_\n\024CriterionBidModifie" + "r\022\033\n\023geo_target_constant\030\001 \001(\t\022\031\n\014bid_mo" + "difier\030\002 \001(\001H\000\210\001\001B\017\n\r_bid_modifier\"u\n\030Ma" + "nualCpcBiddingStrategy\022 \n\023daily_budget_m" + "icros\030\001 \001(\003H\000\210\001\001\022\037\n\022max_cpc_bid_micros\030\002" + " \001(\003B\003\340A\002B\026\n\024_daily_budget_micros\"\217\001\n\035Ma" + "ximizeClicksBiddingStrategy\022&\n\031daily_tar" + "get_spend_micros\030\001 \001(\003B\003\340A\002\022\'\n\032max_cpc_b" + "id_ceiling_micros\030\002 \001(\003H\000\210\001\001B\035\n\033_max_cpc" + "_bid_ceiling_micros\"L\n\"MaximizeConversio" + "nsBiddingStrategy\022&\n\031daily_target_spend_" + "micros\030\001 \001(\003B\003\340A\002\"\251\001\n&GenerateKeywordFor" + "ecastMetricsResponse\022a\n\031campaign_forecas" + "t_metrics\030\001 \001(\01329.google.ads.googleads.v" + "21.services.KeywordForecastMetricsH\000\210\001\001B" + "\034\n\032_campaign_forecast_metrics\"\220\003\n\026Keywor" + "dForecastMetrics\022\030\n\013impressions\030\001 \001(\001H\000\210" + "\001\001\022\037\n\022click_through_rate\030\002 \001(\001H\001\210\001\001\022\037\n\022a" + "verage_cpc_micros\030\003 \001(\003H\002\210\001\001\022\023\n\006clicks\030\004" + " \001(\001H\003\210\001\001\022\030\n\013cost_micros\030\005 \001(\003H\004\210\001\001\022\030\n\013c" + "onversions\030\006 \001(\001H\005\210\001\001\022\034\n\017conversion_rate" + "\030\007 \001(\001H\006\210\001\001\022\037\n\022average_cpa_micros\030\010 \001(\003H" + "\007\210\001\001B\016\n\014_impressionsB\025\n\023_click_through_r" + "ateB\025\n\023_average_cpc_microsB\t\n\007_clicksB\016\n" + "\014_cost_microsB\016\n\014_conversionsB\022\n\020_conver" + "sion_rateB\025\n\023_average_cpa_micros2\316\010\n\026Key" + "wordPlanIdeaService\022\326\001\n\024GenerateKeywordI" + "deas\022>.google.ads.googleads.v21.services" + ".GenerateKeywordIdeasRequest\032>.google.ad" + "s.googleads.v21.services.GenerateKeyword" + "IdeaResponse\">\202\323\344\223\0028\"3/v21/customers/{cu" + "stomer_id=*}:generateKeywordIdeas:\001*\022\207\002\n" + " GenerateKeywordHistoricalMetrics\022J.goog" + "le.ads.googleads.v21.services.GenerateKe" + "ywordHistoricalMetricsRequest\032K.google.a" + "ds.googleads.v21.services.GenerateKeywor" + "dHistoricalMetricsResponse\"J\202\323\344\223\002D\"?/v21" + "/customers/{customer_id=*}:generateKeywo" + "rdHistoricalMetrics:\001*\022\374\001\n\025GenerateAdGro" + "upThemes\022?.google.ads.googleads.v21.serv" + "ices.GenerateAdGroupThemesRequest\032@.goog" + "le.ads.googleads.v21.services.GenerateAd" + "GroupThemesResponse\"`\332A\036customer_id,keyw" + "ords,ad_groups\202\323\344\223\0029\"4/v21/customers/{cu" + "stomer_id=*}:generateAdGroupThemes:\001*\022\212\002" + "\n\036GenerateKeywordForecastMetrics\022H.googl" + "e.ads.googleads.v21.services.GenerateKey" + "wordForecastMetricsRequest\032I.google.ads." + "googleads.v21.services.GenerateKeywordFo" + "recastMetricsResponse\"S\332A\010campaign\202\323\344\223\002B" + "\"=/v21/customers/{customer_id=*}:generat" + "eKeywordForecastMetrics:\001*\032E\312A\030googleads" + ".googleapis.com\322A\'https://www.googleapis" + ".com/auth/adwordsB\207\002\n%com.google.ads.goo" + "gleads.v21.servicesB\033KeywordPlanIdeaServ" + "iceProtoP\001ZIgoogle.golang.org/genproto/g" + "oogleapis/ads/googleads/v21/services;ser" + "vices\242\002\003GAA\252\002!Google.Ads.GoogleAds.V21.S" + "ervices\312\002!Google\\Ads\\GoogleAds\\V21\\Servi" + "ces\352\002%Google::Ads::GoogleAds::V21::Servi" + "cesb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.ads.googleads.v21.common.CriteriaProto.getDescriptor(), com.google.ads.googleads.v21.common.DatesProto.getDescriptor(), com.google.ads.googleads.v21.common.KeywordPlanCommonProto.getDescriptor(), com.google.ads.googleads.v21.enums.KeywordMatchTypeProto.getDescriptor(), com.google.ads.googleads.v21.enums.KeywordPlanKeywordAnnotationProto.getDescriptor(), com.google.ads.googleads.v21.enums.KeywordPlanNetworkProto.getDescriptor(), com.google.api.AnnotationsProto.getDescriptor(), com.google.api.ClientProto.getDescriptor(), com.google.api.FieldBehaviorProto.getDescriptor(), }); internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeasRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeasRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeasRequest_descriptor, new java.lang.String[] { "CustomerId", "Language", "GeoTargetConstants", "IncludeAdultKeywords", "PageToken", "PageSize", "KeywordPlanNetwork", "KeywordAnnotation", "AggregateMetrics", "HistoricalMetricsOptions", "KeywordAndUrlSeed", "KeywordSeed", "UrlSeed", "SiteSeed", "Seed", }); internal_static_google_ads_googleads_v21_services_KeywordAndUrlSeed_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_ads_googleads_v21_services_KeywordAndUrlSeed_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_KeywordAndUrlSeed_descriptor, new java.lang.String[] { "Url", "Keywords", }); internal_static_google_ads_googleads_v21_services_KeywordSeed_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_ads_googleads_v21_services_KeywordSeed_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_KeywordSeed_descriptor, new java.lang.String[] { "Keywords", }); internal_static_google_ads_googleads_v21_services_SiteSeed_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_ads_googleads_v21_services_SiteSeed_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_SiteSeed_descriptor, new java.lang.String[] { "Site", }); internal_static_google_ads_googleads_v21_services_UrlSeed_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_google_ads_googleads_v21_services_UrlSeed_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_UrlSeed_descriptor, new java.lang.String[] { "Url", }); internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeaResponse_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeaResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeaResponse_descriptor, new java.lang.String[] { "Results", "AggregateMetricResults", "NextPageToken", "TotalSize", }); internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeaResult_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeaResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_GenerateKeywordIdeaResult_descriptor, new java.lang.String[] { "Text", "KeywordIdeaMetrics", "KeywordAnnotations", "CloseVariants", }); internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsRequest_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsRequest_descriptor, new java.lang.String[] { "CustomerId", "Keywords", "Language", "IncludeAdultKeywords", "GeoTargetConstants", "KeywordPlanNetwork", "AggregateMetrics", "HistoricalMetricsOptions", }); internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsResponse_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsResponse_descriptor, new java.lang.String[] { "Results", "AggregateMetricResults", }); internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsResult_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_GenerateKeywordHistoricalMetricsResult_descriptor, new java.lang.String[] { "Text", "CloseVariants", "KeywordMetrics", }); internal_static_google_ads_googleads_v21_services_GenerateAdGroupThemesRequest_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_google_ads_googleads_v21_services_GenerateAdGroupThemesRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_GenerateAdGroupThemesRequest_descriptor, new java.lang.String[] { "CustomerId", "Keywords", "AdGroups", }); internal_static_google_ads_googleads_v21_services_GenerateAdGroupThemesResponse_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_google_ads_googleads_v21_services_GenerateAdGroupThemesResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_GenerateAdGroupThemesResponse_descriptor, new java.lang.String[] { "AdGroupKeywordSuggestions", "UnusableAdGroups", }); internal_static_google_ads_googleads_v21_services_AdGroupKeywordSuggestion_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_google_ads_googleads_v21_services_AdGroupKeywordSuggestion_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_AdGroupKeywordSuggestion_descriptor, new java.lang.String[] { "KeywordText", "SuggestedKeywordText", "SuggestedMatchType", "SuggestedAdGroup", "SuggestedCampaign", }); internal_static_google_ads_googleads_v21_services_UnusableAdGroup_descriptor = getDescriptor().getMessageTypes().get(13); internal_static_google_ads_googleads_v21_services_UnusableAdGroup_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_UnusableAdGroup_descriptor, new java.lang.String[] { "AdGroup", "Campaign", }); internal_static_google_ads_googleads_v21_services_GenerateKeywordForecastMetricsRequest_descriptor = getDescriptor().getMessageTypes().get(14); internal_static_google_ads_googleads_v21_services_GenerateKeywordForecastMetricsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_GenerateKeywordForecastMetricsRequest_descriptor, new java.lang.String[] { "CustomerId", "CurrencyCode", "ForecastPeriod", "Campaign", }); internal_static_google_ads_googleads_v21_services_CampaignToForecast_descriptor = getDescriptor().getMessageTypes().get(15); internal_static_google_ads_googleads_v21_services_CampaignToForecast_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_CampaignToForecast_descriptor, new java.lang.String[] { "LanguageConstants", "GeoModifiers", "KeywordPlanNetwork", "NegativeKeywords", "BiddingStrategy", "ConversionRate", "AdGroups", }); internal_static_google_ads_googleads_v21_services_CampaignToForecast_CampaignBiddingStrategy_descriptor = internal_static_google_ads_googleads_v21_services_CampaignToForecast_descriptor.getNestedTypes().get(0); internal_static_google_ads_googleads_v21_services_CampaignToForecast_CampaignBiddingStrategy_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_CampaignToForecast_CampaignBiddingStrategy_descriptor, new java.lang.String[] { "ManualCpcBiddingStrategy", "MaximizeClicksBiddingStrategy", "MaximizeConversionsBiddingStrategy", "BiddingStrategy", }); internal_static_google_ads_googleads_v21_services_ForecastAdGroup_descriptor = getDescriptor().getMessageTypes().get(16); internal_static_google_ads_googleads_v21_services_ForecastAdGroup_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_ForecastAdGroup_descriptor, new java.lang.String[] { "MaxCpcBidMicros", "BiddableKeywords", "NegativeKeywords", }); internal_static_google_ads_googleads_v21_services_BiddableKeyword_descriptor = getDescriptor().getMessageTypes().get(17); internal_static_google_ads_googleads_v21_services_BiddableKeyword_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_BiddableKeyword_descriptor, new java.lang.String[] { "Keyword", "MaxCpcBidMicros", }); internal_static_google_ads_googleads_v21_services_CriterionBidModifier_descriptor = getDescriptor().getMessageTypes().get(18); internal_static_google_ads_googleads_v21_services_CriterionBidModifier_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_CriterionBidModifier_descriptor, new java.lang.String[] { "GeoTargetConstant", "BidModifier", }); internal_static_google_ads_googleads_v21_services_ManualCpcBiddingStrategy_descriptor = getDescriptor().getMessageTypes().get(19); internal_static_google_ads_googleads_v21_services_ManualCpcBiddingStrategy_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_ManualCpcBiddingStrategy_descriptor, new java.lang.String[] { "DailyBudgetMicros", "MaxCpcBidMicros", }); internal_static_google_ads_googleads_v21_services_MaximizeClicksBiddingStrategy_descriptor = getDescriptor().getMessageTypes().get(20); internal_static_google_ads_googleads_v21_services_MaximizeClicksBiddingStrategy_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_MaximizeClicksBiddingStrategy_descriptor, new java.lang.String[] { "DailyTargetSpendMicros", "MaxCpcBidCeilingMicros", }); internal_static_google_ads_googleads_v21_services_MaximizeConversionsBiddingStrategy_descriptor = getDescriptor().getMessageTypes().get(21); internal_static_google_ads_googleads_v21_services_MaximizeConversionsBiddingStrategy_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_MaximizeConversionsBiddingStrategy_descriptor, new java.lang.String[] { "DailyTargetSpendMicros", }); internal_static_google_ads_googleads_v21_services_GenerateKeywordForecastMetricsResponse_descriptor = getDescriptor().getMessageTypes().get(22); internal_static_google_ads_googleads_v21_services_GenerateKeywordForecastMetricsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_GenerateKeywordForecastMetricsResponse_descriptor, new java.lang.String[] { "CampaignForecastMetrics", }); internal_static_google_ads_googleads_v21_services_KeywordForecastMetrics_descriptor = getDescriptor().getMessageTypes().get(23); internal_static_google_ads_googleads_v21_services_KeywordForecastMetrics_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v21_services_KeywordForecastMetrics_descriptor, new java.lang.String[] { "Impressions", "ClickThroughRate", "AverageCpcMicros", "Clicks", "CostMicros", "Conversions", "ConversionRate", "AverageCpaMicros", }); 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.ads.googleads.v21.common.CriteriaProto.getDescriptor(); com.google.ads.googleads.v21.common.DatesProto.getDescriptor(); com.google.ads.googleads.v21.common.KeywordPlanCommonProto.getDescriptor(); com.google.ads.googleads.v21.enums.KeywordMatchTypeProto.getDescriptor(); com.google.ads.googleads.v21.enums.KeywordPlanKeywordAnnotationProto.getDescriptor(); com.google.ads.googleads.v21.enums.KeywordPlanNetworkProto.getDescriptor(); com.google.api.AnnotationsProto.getDescriptor(); com.google.api.ClientProto.getDescriptor(); com.google.api.FieldBehaviorProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
googleapis/google-api-java-client-services
37,550
clients/google-api-services-tagmanager/v2/1.26.0/com/google/api/services/tagmanager/model/Trigger.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.tagmanager.model; /** * Represents a Google Tag Manager Trigger * * <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 Tag Manager 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 Trigger extends com.google.api.client.json.GenericJson { /** * GTM Account ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String accountId; /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> autoEventFilter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter checkValidation; /** * GTM Container ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String containerId; /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter continuousTimeMinMilliseconds; /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> customEventFilter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter eventName; /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> filter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String fingerprint; /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter horizontalScrollPercentageList; /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter interval; /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter intervalSeconds; /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter limit; /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter maxTimerLengthSeconds; /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String notes; /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Parameter> parameter; static { // hack to force ProGuard to consider Parameter 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(Parameter.class); } /** * Parent folder id. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String parentFolderId; /** * GTM Trigger's API relative path. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String path; /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter selector; /** * Auto generated link to the tag manager UI * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String tagManagerUrl; /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter totalTimeMinMilliseconds; /** * The Trigger ID uniquely identifies the GTM Trigger. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String triggerId; /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String type; /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter uniqueTriggerId; /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter verticalScrollPercentageList; /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visibilitySelector; /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visiblePercentageMax; /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visiblePercentageMin; /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter waitForTags; /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter waitForTagsTimeout; /** * GTM Workspace ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String workspaceId; /** * GTM Account ID. * @return value or {@code null} for none */ public java.lang.String getAccountId() { return accountId; } /** * GTM Account ID. * @param accountId accountId or {@code null} for none */ public Trigger setAccountId(java.lang.String accountId) { this.accountId = accountId; return this; } /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getAutoEventFilter() { return autoEventFilter; } /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param autoEventFilter autoEventFilter or {@code null} for none */ public Trigger setAutoEventFilter(java.util.List<Condition> autoEventFilter) { this.autoEventFilter = autoEventFilter; return this; } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getCheckValidation() { return checkValidation; } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param checkValidation checkValidation or {@code null} for none */ public Trigger setCheckValidation(Parameter checkValidation) { this.checkValidation = checkValidation; return this; } /** * GTM Container ID. * @return value or {@code null} for none */ public java.lang.String getContainerId() { return containerId; } /** * GTM Container ID. * @param containerId containerId or {@code null} for none */ public Trigger setContainerId(java.lang.String containerId) { this.containerId = containerId; return this; } /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getContinuousTimeMinMilliseconds() { return continuousTimeMinMilliseconds; } /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param continuousTimeMinMilliseconds continuousTimeMinMilliseconds or {@code null} for none */ public Trigger setContinuousTimeMinMilliseconds(Parameter continuousTimeMinMilliseconds) { this.continuousTimeMinMilliseconds = continuousTimeMinMilliseconds; return this; } /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getCustomEventFilter() { return customEventFilter; } /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param customEventFilter customEventFilter or {@code null} for none */ public Trigger setCustomEventFilter(java.util.List<Condition> customEventFilter) { this.customEventFilter = customEventFilter; return this; } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getEventName() { return eventName; } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param eventName eventName or {@code null} for none */ public Trigger setEventName(Parameter eventName) { this.eventName = eventName; return this; } /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getFilter() { return filter; } /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param filter filter or {@code null} for none */ public Trigger setFilter(java.util.List<Condition> filter) { this.filter = filter; return this; } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * @return value or {@code null} for none */ public java.lang.String getFingerprint() { return fingerprint; } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * @param fingerprint fingerprint or {@code null} for none */ public Trigger setFingerprint(java.lang.String fingerprint) { this.fingerprint = fingerprint; return this; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getHorizontalScrollPercentageList() { return horizontalScrollPercentageList; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param horizontalScrollPercentageList horizontalScrollPercentageList or {@code null} for none */ public Trigger setHorizontalScrollPercentageList(Parameter horizontalScrollPercentageList) { this.horizontalScrollPercentageList = horizontalScrollPercentageList; return this; } /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getInterval() { return interval; } /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param interval interval or {@code null} for none */ public Trigger setInterval(Parameter interval) { this.interval = interval; return this; } /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getIntervalSeconds() { return intervalSeconds; } /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param intervalSeconds intervalSeconds or {@code null} for none */ public Trigger setIntervalSeconds(Parameter intervalSeconds) { this.intervalSeconds = intervalSeconds; return this; } /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getLimit() { return limit; } /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param limit limit or {@code null} for none */ public Trigger setLimit(Parameter limit) { this.limit = limit; return this; } /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getMaxTimerLengthSeconds() { return maxTimerLengthSeconds; } /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param maxTimerLengthSeconds maxTimerLengthSeconds or {@code null} for none */ public Trigger setMaxTimerLengthSeconds(Parameter maxTimerLengthSeconds) { this.maxTimerLengthSeconds = maxTimerLengthSeconds; return this; } /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param name name or {@code null} for none */ public Trigger setName(java.lang.String name) { this.name = name; return this; } /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getNotes() { return notes; } /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param notes notes or {@code null} for none */ public Trigger setNotes(java.lang.String notes) { this.notes = notes; return this; } /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Parameter> getParameter() { return parameter; } /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param parameter parameter or {@code null} for none */ public Trigger setParameter(java.util.List<Parameter> parameter) { this.parameter = parameter; return this; } /** * Parent folder id. * @return value or {@code null} for none */ public java.lang.String getParentFolderId() { return parentFolderId; } /** * Parent folder id. * @param parentFolderId parentFolderId or {@code null} for none */ public Trigger setParentFolderId(java.lang.String parentFolderId) { this.parentFolderId = parentFolderId; return this; } /** * GTM Trigger's API relative path. * @return value or {@code null} for none */ public java.lang.String getPath() { return path; } /** * GTM Trigger's API relative path. * @param path path or {@code null} for none */ public Trigger setPath(java.lang.String path) { this.path = path; return this; } /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getSelector() { return selector; } /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param selector selector or {@code null} for none */ public Trigger setSelector(Parameter selector) { this.selector = selector; return this; } /** * Auto generated link to the tag manager UI * @return value or {@code null} for none */ public java.lang.String getTagManagerUrl() { return tagManagerUrl; } /** * Auto generated link to the tag manager UI * @param tagManagerUrl tagManagerUrl or {@code null} for none */ public Trigger setTagManagerUrl(java.lang.String tagManagerUrl) { this.tagManagerUrl = tagManagerUrl; return this; } /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getTotalTimeMinMilliseconds() { return totalTimeMinMilliseconds; } /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param totalTimeMinMilliseconds totalTimeMinMilliseconds or {@code null} for none */ public Trigger setTotalTimeMinMilliseconds(Parameter totalTimeMinMilliseconds) { this.totalTimeMinMilliseconds = totalTimeMinMilliseconds; return this; } /** * The Trigger ID uniquely identifies the GTM Trigger. * @return value or {@code null} for none */ public java.lang.String getTriggerId() { return triggerId; } /** * The Trigger ID uniquely identifies the GTM Trigger. * @param triggerId triggerId or {@code null} for none */ public Trigger setTriggerId(java.lang.String triggerId) { this.triggerId = triggerId; return this; } /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getType() { return type; } /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param type type or {@code null} for none */ public Trigger setType(java.lang.String type) { this.type = type; return this; } /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getUniqueTriggerId() { return uniqueTriggerId; } /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param uniqueTriggerId uniqueTriggerId or {@code null} for none */ public Trigger setUniqueTriggerId(Parameter uniqueTriggerId) { this.uniqueTriggerId = uniqueTriggerId; return this; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVerticalScrollPercentageList() { return verticalScrollPercentageList; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param verticalScrollPercentageList verticalScrollPercentageList or {@code null} for none */ public Trigger setVerticalScrollPercentageList(Parameter verticalScrollPercentageList) { this.verticalScrollPercentageList = verticalScrollPercentageList; return this; } /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisibilitySelector() { return visibilitySelector; } /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visibilitySelector visibilitySelector or {@code null} for none */ public Trigger setVisibilitySelector(Parameter visibilitySelector) { this.visibilitySelector = visibilitySelector; return this; } /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisiblePercentageMax() { return visiblePercentageMax; } /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visiblePercentageMax visiblePercentageMax or {@code null} for none */ public Trigger setVisiblePercentageMax(Parameter visiblePercentageMax) { this.visiblePercentageMax = visiblePercentageMax; return this; } /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisiblePercentageMin() { return visiblePercentageMin; } /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visiblePercentageMin visiblePercentageMin or {@code null} for none */ public Trigger setVisiblePercentageMin(Parameter visiblePercentageMin) { this.visiblePercentageMin = visiblePercentageMin; return this; } /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getWaitForTags() { return waitForTags; } /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param waitForTags waitForTags or {@code null} for none */ public Trigger setWaitForTags(Parameter waitForTags) { this.waitForTags = waitForTags; return this; } /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getWaitForTagsTimeout() { return waitForTagsTimeout; } /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param waitForTagsTimeout waitForTagsTimeout or {@code null} for none */ public Trigger setWaitForTagsTimeout(Parameter waitForTagsTimeout) { this.waitForTagsTimeout = waitForTagsTimeout; return this; } /** * GTM Workspace ID. * @return value or {@code null} for none */ public java.lang.String getWorkspaceId() { return workspaceId; } /** * GTM Workspace ID. * @param workspaceId workspaceId or {@code null} for none */ public Trigger setWorkspaceId(java.lang.String workspaceId) { this.workspaceId = workspaceId; return this; } @Override public Trigger set(String fieldName, Object value) { return (Trigger) super.set(fieldName, value); } @Override public Trigger clone() { return (Trigger) super.clone(); } }
googleapis/google-api-java-client-services
37,550
clients/google-api-services-tagmanager/v2/1.27.0/com/google/api/services/tagmanager/model/Trigger.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.tagmanager.model; /** * Represents a Google Tag Manager Trigger * * <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 Tag Manager 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 Trigger extends com.google.api.client.json.GenericJson { /** * GTM Account ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String accountId; /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> autoEventFilter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter checkValidation; /** * GTM Container ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String containerId; /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter continuousTimeMinMilliseconds; /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> customEventFilter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter eventName; /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> filter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String fingerprint; /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter horizontalScrollPercentageList; /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter interval; /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter intervalSeconds; /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter limit; /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter maxTimerLengthSeconds; /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String notes; /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Parameter> parameter; static { // hack to force ProGuard to consider Parameter 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(Parameter.class); } /** * Parent folder id. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String parentFolderId; /** * GTM Trigger's API relative path. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String path; /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter selector; /** * Auto generated link to the tag manager UI * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String tagManagerUrl; /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter totalTimeMinMilliseconds; /** * The Trigger ID uniquely identifies the GTM Trigger. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String triggerId; /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String type; /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter uniqueTriggerId; /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter verticalScrollPercentageList; /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visibilitySelector; /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visiblePercentageMax; /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visiblePercentageMin; /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter waitForTags; /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter waitForTagsTimeout; /** * GTM Workspace ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String workspaceId; /** * GTM Account ID. * @return value or {@code null} for none */ public java.lang.String getAccountId() { return accountId; } /** * GTM Account ID. * @param accountId accountId or {@code null} for none */ public Trigger setAccountId(java.lang.String accountId) { this.accountId = accountId; return this; } /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getAutoEventFilter() { return autoEventFilter; } /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param autoEventFilter autoEventFilter or {@code null} for none */ public Trigger setAutoEventFilter(java.util.List<Condition> autoEventFilter) { this.autoEventFilter = autoEventFilter; return this; } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getCheckValidation() { return checkValidation; } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param checkValidation checkValidation or {@code null} for none */ public Trigger setCheckValidation(Parameter checkValidation) { this.checkValidation = checkValidation; return this; } /** * GTM Container ID. * @return value or {@code null} for none */ public java.lang.String getContainerId() { return containerId; } /** * GTM Container ID. * @param containerId containerId or {@code null} for none */ public Trigger setContainerId(java.lang.String containerId) { this.containerId = containerId; return this; } /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getContinuousTimeMinMilliseconds() { return continuousTimeMinMilliseconds; } /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param continuousTimeMinMilliseconds continuousTimeMinMilliseconds or {@code null} for none */ public Trigger setContinuousTimeMinMilliseconds(Parameter continuousTimeMinMilliseconds) { this.continuousTimeMinMilliseconds = continuousTimeMinMilliseconds; return this; } /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getCustomEventFilter() { return customEventFilter; } /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param customEventFilter customEventFilter or {@code null} for none */ public Trigger setCustomEventFilter(java.util.List<Condition> customEventFilter) { this.customEventFilter = customEventFilter; return this; } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getEventName() { return eventName; } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param eventName eventName or {@code null} for none */ public Trigger setEventName(Parameter eventName) { this.eventName = eventName; return this; } /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getFilter() { return filter; } /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param filter filter or {@code null} for none */ public Trigger setFilter(java.util.List<Condition> filter) { this.filter = filter; return this; } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * @return value or {@code null} for none */ public java.lang.String getFingerprint() { return fingerprint; } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * @param fingerprint fingerprint or {@code null} for none */ public Trigger setFingerprint(java.lang.String fingerprint) { this.fingerprint = fingerprint; return this; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getHorizontalScrollPercentageList() { return horizontalScrollPercentageList; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param horizontalScrollPercentageList horizontalScrollPercentageList or {@code null} for none */ public Trigger setHorizontalScrollPercentageList(Parameter horizontalScrollPercentageList) { this.horizontalScrollPercentageList = horizontalScrollPercentageList; return this; } /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getInterval() { return interval; } /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param interval interval or {@code null} for none */ public Trigger setInterval(Parameter interval) { this.interval = interval; return this; } /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getIntervalSeconds() { return intervalSeconds; } /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param intervalSeconds intervalSeconds or {@code null} for none */ public Trigger setIntervalSeconds(Parameter intervalSeconds) { this.intervalSeconds = intervalSeconds; return this; } /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getLimit() { return limit; } /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param limit limit or {@code null} for none */ public Trigger setLimit(Parameter limit) { this.limit = limit; return this; } /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getMaxTimerLengthSeconds() { return maxTimerLengthSeconds; } /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param maxTimerLengthSeconds maxTimerLengthSeconds or {@code null} for none */ public Trigger setMaxTimerLengthSeconds(Parameter maxTimerLengthSeconds) { this.maxTimerLengthSeconds = maxTimerLengthSeconds; return this; } /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param name name or {@code null} for none */ public Trigger setName(java.lang.String name) { this.name = name; return this; } /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getNotes() { return notes; } /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param notes notes or {@code null} for none */ public Trigger setNotes(java.lang.String notes) { this.notes = notes; return this; } /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Parameter> getParameter() { return parameter; } /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param parameter parameter or {@code null} for none */ public Trigger setParameter(java.util.List<Parameter> parameter) { this.parameter = parameter; return this; } /** * Parent folder id. * @return value or {@code null} for none */ public java.lang.String getParentFolderId() { return parentFolderId; } /** * Parent folder id. * @param parentFolderId parentFolderId or {@code null} for none */ public Trigger setParentFolderId(java.lang.String parentFolderId) { this.parentFolderId = parentFolderId; return this; } /** * GTM Trigger's API relative path. * @return value or {@code null} for none */ public java.lang.String getPath() { return path; } /** * GTM Trigger's API relative path. * @param path path or {@code null} for none */ public Trigger setPath(java.lang.String path) { this.path = path; return this; } /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getSelector() { return selector; } /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param selector selector or {@code null} for none */ public Trigger setSelector(Parameter selector) { this.selector = selector; return this; } /** * Auto generated link to the tag manager UI * @return value or {@code null} for none */ public java.lang.String getTagManagerUrl() { return tagManagerUrl; } /** * Auto generated link to the tag manager UI * @param tagManagerUrl tagManagerUrl or {@code null} for none */ public Trigger setTagManagerUrl(java.lang.String tagManagerUrl) { this.tagManagerUrl = tagManagerUrl; return this; } /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getTotalTimeMinMilliseconds() { return totalTimeMinMilliseconds; } /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param totalTimeMinMilliseconds totalTimeMinMilliseconds or {@code null} for none */ public Trigger setTotalTimeMinMilliseconds(Parameter totalTimeMinMilliseconds) { this.totalTimeMinMilliseconds = totalTimeMinMilliseconds; return this; } /** * The Trigger ID uniquely identifies the GTM Trigger. * @return value or {@code null} for none */ public java.lang.String getTriggerId() { return triggerId; } /** * The Trigger ID uniquely identifies the GTM Trigger. * @param triggerId triggerId or {@code null} for none */ public Trigger setTriggerId(java.lang.String triggerId) { this.triggerId = triggerId; return this; } /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getType() { return type; } /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param type type or {@code null} for none */ public Trigger setType(java.lang.String type) { this.type = type; return this; } /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getUniqueTriggerId() { return uniqueTriggerId; } /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param uniqueTriggerId uniqueTriggerId or {@code null} for none */ public Trigger setUniqueTriggerId(Parameter uniqueTriggerId) { this.uniqueTriggerId = uniqueTriggerId; return this; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVerticalScrollPercentageList() { return verticalScrollPercentageList; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param verticalScrollPercentageList verticalScrollPercentageList or {@code null} for none */ public Trigger setVerticalScrollPercentageList(Parameter verticalScrollPercentageList) { this.verticalScrollPercentageList = verticalScrollPercentageList; return this; } /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisibilitySelector() { return visibilitySelector; } /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visibilitySelector visibilitySelector or {@code null} for none */ public Trigger setVisibilitySelector(Parameter visibilitySelector) { this.visibilitySelector = visibilitySelector; return this; } /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisiblePercentageMax() { return visiblePercentageMax; } /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visiblePercentageMax visiblePercentageMax or {@code null} for none */ public Trigger setVisiblePercentageMax(Parameter visiblePercentageMax) { this.visiblePercentageMax = visiblePercentageMax; return this; } /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisiblePercentageMin() { return visiblePercentageMin; } /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visiblePercentageMin visiblePercentageMin or {@code null} for none */ public Trigger setVisiblePercentageMin(Parameter visiblePercentageMin) { this.visiblePercentageMin = visiblePercentageMin; return this; } /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getWaitForTags() { return waitForTags; } /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param waitForTags waitForTags or {@code null} for none */ public Trigger setWaitForTags(Parameter waitForTags) { this.waitForTags = waitForTags; return this; } /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getWaitForTagsTimeout() { return waitForTagsTimeout; } /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param waitForTagsTimeout waitForTagsTimeout or {@code null} for none */ public Trigger setWaitForTagsTimeout(Parameter waitForTagsTimeout) { this.waitForTagsTimeout = waitForTagsTimeout; return this; } /** * GTM Workspace ID. * @return value or {@code null} for none */ public java.lang.String getWorkspaceId() { return workspaceId; } /** * GTM Workspace ID. * @param workspaceId workspaceId or {@code null} for none */ public Trigger setWorkspaceId(java.lang.String workspaceId) { this.workspaceId = workspaceId; return this; } @Override public Trigger set(String fieldName, Object value) { return (Trigger) super.set(fieldName, value); } @Override public Trigger clone() { return (Trigger) super.clone(); } }
googleapis/google-api-java-client-services
37,550
clients/google-api-services-tagmanager/v2/1.28.0/com/google/api/services/tagmanager/model/Trigger.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.tagmanager.model; /** * Represents a Google Tag Manager Trigger * * <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 Tag Manager 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 Trigger extends com.google.api.client.json.GenericJson { /** * GTM Account ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String accountId; /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> autoEventFilter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter checkValidation; /** * GTM Container ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String containerId; /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter continuousTimeMinMilliseconds; /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> customEventFilter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter eventName; /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> filter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String fingerprint; /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter horizontalScrollPercentageList; /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter interval; /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter intervalSeconds; /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter limit; /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter maxTimerLengthSeconds; /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String notes; /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Parameter> parameter; static { // hack to force ProGuard to consider Parameter 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(Parameter.class); } /** * Parent folder id. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String parentFolderId; /** * GTM Trigger's API relative path. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String path; /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter selector; /** * Auto generated link to the tag manager UI * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String tagManagerUrl; /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter totalTimeMinMilliseconds; /** * The Trigger ID uniquely identifies the GTM Trigger. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String triggerId; /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String type; /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter uniqueTriggerId; /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter verticalScrollPercentageList; /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visibilitySelector; /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visiblePercentageMax; /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visiblePercentageMin; /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter waitForTags; /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter waitForTagsTimeout; /** * GTM Workspace ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String workspaceId; /** * GTM Account ID. * @return value or {@code null} for none */ public java.lang.String getAccountId() { return accountId; } /** * GTM Account ID. * @param accountId accountId or {@code null} for none */ public Trigger setAccountId(java.lang.String accountId) { this.accountId = accountId; return this; } /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getAutoEventFilter() { return autoEventFilter; } /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param autoEventFilter autoEventFilter or {@code null} for none */ public Trigger setAutoEventFilter(java.util.List<Condition> autoEventFilter) { this.autoEventFilter = autoEventFilter; return this; } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getCheckValidation() { return checkValidation; } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param checkValidation checkValidation or {@code null} for none */ public Trigger setCheckValidation(Parameter checkValidation) { this.checkValidation = checkValidation; return this; } /** * GTM Container ID. * @return value or {@code null} for none */ public java.lang.String getContainerId() { return containerId; } /** * GTM Container ID. * @param containerId containerId or {@code null} for none */ public Trigger setContainerId(java.lang.String containerId) { this.containerId = containerId; return this; } /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getContinuousTimeMinMilliseconds() { return continuousTimeMinMilliseconds; } /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param continuousTimeMinMilliseconds continuousTimeMinMilliseconds or {@code null} for none */ public Trigger setContinuousTimeMinMilliseconds(Parameter continuousTimeMinMilliseconds) { this.continuousTimeMinMilliseconds = continuousTimeMinMilliseconds; return this; } /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getCustomEventFilter() { return customEventFilter; } /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param customEventFilter customEventFilter or {@code null} for none */ public Trigger setCustomEventFilter(java.util.List<Condition> customEventFilter) { this.customEventFilter = customEventFilter; return this; } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getEventName() { return eventName; } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param eventName eventName or {@code null} for none */ public Trigger setEventName(Parameter eventName) { this.eventName = eventName; return this; } /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getFilter() { return filter; } /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param filter filter or {@code null} for none */ public Trigger setFilter(java.util.List<Condition> filter) { this.filter = filter; return this; } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * @return value or {@code null} for none */ public java.lang.String getFingerprint() { return fingerprint; } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * @param fingerprint fingerprint or {@code null} for none */ public Trigger setFingerprint(java.lang.String fingerprint) { this.fingerprint = fingerprint; return this; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getHorizontalScrollPercentageList() { return horizontalScrollPercentageList; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param horizontalScrollPercentageList horizontalScrollPercentageList or {@code null} for none */ public Trigger setHorizontalScrollPercentageList(Parameter horizontalScrollPercentageList) { this.horizontalScrollPercentageList = horizontalScrollPercentageList; return this; } /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getInterval() { return interval; } /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param interval interval or {@code null} for none */ public Trigger setInterval(Parameter interval) { this.interval = interval; return this; } /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getIntervalSeconds() { return intervalSeconds; } /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param intervalSeconds intervalSeconds or {@code null} for none */ public Trigger setIntervalSeconds(Parameter intervalSeconds) { this.intervalSeconds = intervalSeconds; return this; } /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getLimit() { return limit; } /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param limit limit or {@code null} for none */ public Trigger setLimit(Parameter limit) { this.limit = limit; return this; } /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getMaxTimerLengthSeconds() { return maxTimerLengthSeconds; } /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param maxTimerLengthSeconds maxTimerLengthSeconds or {@code null} for none */ public Trigger setMaxTimerLengthSeconds(Parameter maxTimerLengthSeconds) { this.maxTimerLengthSeconds = maxTimerLengthSeconds; return this; } /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param name name or {@code null} for none */ public Trigger setName(java.lang.String name) { this.name = name; return this; } /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getNotes() { return notes; } /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param notes notes or {@code null} for none */ public Trigger setNotes(java.lang.String notes) { this.notes = notes; return this; } /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Parameter> getParameter() { return parameter; } /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param parameter parameter or {@code null} for none */ public Trigger setParameter(java.util.List<Parameter> parameter) { this.parameter = parameter; return this; } /** * Parent folder id. * @return value or {@code null} for none */ public java.lang.String getParentFolderId() { return parentFolderId; } /** * Parent folder id. * @param parentFolderId parentFolderId or {@code null} for none */ public Trigger setParentFolderId(java.lang.String parentFolderId) { this.parentFolderId = parentFolderId; return this; } /** * GTM Trigger's API relative path. * @return value or {@code null} for none */ public java.lang.String getPath() { return path; } /** * GTM Trigger's API relative path. * @param path path or {@code null} for none */ public Trigger setPath(java.lang.String path) { this.path = path; return this; } /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getSelector() { return selector; } /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param selector selector or {@code null} for none */ public Trigger setSelector(Parameter selector) { this.selector = selector; return this; } /** * Auto generated link to the tag manager UI * @return value or {@code null} for none */ public java.lang.String getTagManagerUrl() { return tagManagerUrl; } /** * Auto generated link to the tag manager UI * @param tagManagerUrl tagManagerUrl or {@code null} for none */ public Trigger setTagManagerUrl(java.lang.String tagManagerUrl) { this.tagManagerUrl = tagManagerUrl; return this; } /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getTotalTimeMinMilliseconds() { return totalTimeMinMilliseconds; } /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param totalTimeMinMilliseconds totalTimeMinMilliseconds or {@code null} for none */ public Trigger setTotalTimeMinMilliseconds(Parameter totalTimeMinMilliseconds) { this.totalTimeMinMilliseconds = totalTimeMinMilliseconds; return this; } /** * The Trigger ID uniquely identifies the GTM Trigger. * @return value or {@code null} for none */ public java.lang.String getTriggerId() { return triggerId; } /** * The Trigger ID uniquely identifies the GTM Trigger. * @param triggerId triggerId or {@code null} for none */ public Trigger setTriggerId(java.lang.String triggerId) { this.triggerId = triggerId; return this; } /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getType() { return type; } /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param type type or {@code null} for none */ public Trigger setType(java.lang.String type) { this.type = type; return this; } /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getUniqueTriggerId() { return uniqueTriggerId; } /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param uniqueTriggerId uniqueTriggerId or {@code null} for none */ public Trigger setUniqueTriggerId(Parameter uniqueTriggerId) { this.uniqueTriggerId = uniqueTriggerId; return this; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVerticalScrollPercentageList() { return verticalScrollPercentageList; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param verticalScrollPercentageList verticalScrollPercentageList or {@code null} for none */ public Trigger setVerticalScrollPercentageList(Parameter verticalScrollPercentageList) { this.verticalScrollPercentageList = verticalScrollPercentageList; return this; } /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisibilitySelector() { return visibilitySelector; } /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visibilitySelector visibilitySelector or {@code null} for none */ public Trigger setVisibilitySelector(Parameter visibilitySelector) { this.visibilitySelector = visibilitySelector; return this; } /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisiblePercentageMax() { return visiblePercentageMax; } /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visiblePercentageMax visiblePercentageMax or {@code null} for none */ public Trigger setVisiblePercentageMax(Parameter visiblePercentageMax) { this.visiblePercentageMax = visiblePercentageMax; return this; } /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisiblePercentageMin() { return visiblePercentageMin; } /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visiblePercentageMin visiblePercentageMin or {@code null} for none */ public Trigger setVisiblePercentageMin(Parameter visiblePercentageMin) { this.visiblePercentageMin = visiblePercentageMin; return this; } /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getWaitForTags() { return waitForTags; } /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param waitForTags waitForTags or {@code null} for none */ public Trigger setWaitForTags(Parameter waitForTags) { this.waitForTags = waitForTags; return this; } /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getWaitForTagsTimeout() { return waitForTagsTimeout; } /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param waitForTagsTimeout waitForTagsTimeout or {@code null} for none */ public Trigger setWaitForTagsTimeout(Parameter waitForTagsTimeout) { this.waitForTagsTimeout = waitForTagsTimeout; return this; } /** * GTM Workspace ID. * @return value or {@code null} for none */ public java.lang.String getWorkspaceId() { return workspaceId; } /** * GTM Workspace ID. * @param workspaceId workspaceId or {@code null} for none */ public Trigger setWorkspaceId(java.lang.String workspaceId) { this.workspaceId = workspaceId; return this; } @Override public Trigger set(String fieldName, Object value) { return (Trigger) super.set(fieldName, value); } @Override public Trigger clone() { return (Trigger) super.clone(); } }
googleapis/google-api-java-client-services
37,550
clients/google-api-services-tagmanager/v2/1.29.2/com/google/api/services/tagmanager/model/Trigger.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.tagmanager.model; /** * Represents a Google Tag Manager Trigger * * <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 Tag Manager 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 Trigger extends com.google.api.client.json.GenericJson { /** * GTM Account ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String accountId; /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> autoEventFilter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter checkValidation; /** * GTM Container ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String containerId; /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter continuousTimeMinMilliseconds; /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> customEventFilter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter eventName; /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Condition> filter; static { // hack to force ProGuard to consider Condition 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(Condition.class); } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String fingerprint; /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter horizontalScrollPercentageList; /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter interval; /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter intervalSeconds; /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter limit; /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter maxTimerLengthSeconds; /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String notes; /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Parameter> parameter; static { // hack to force ProGuard to consider Parameter 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(Parameter.class); } /** * Parent folder id. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String parentFolderId; /** * GTM Trigger's API relative path. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String path; /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter selector; /** * Auto generated link to the tag manager UI * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String tagManagerUrl; /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter totalTimeMinMilliseconds; /** * The Trigger ID uniquely identifies the GTM Trigger. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String triggerId; /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String type; /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter uniqueTriggerId; /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter verticalScrollPercentageList; /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visibilitySelector; /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visiblePercentageMax; /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter visiblePercentageMin; /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter waitForTags; /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * The value may be {@code null}. */ @com.google.api.client.util.Key private Parameter waitForTagsTimeout; /** * GTM Workspace ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String workspaceId; /** * GTM Account ID. * @return value or {@code null} for none */ public java.lang.String getAccountId() { return accountId; } /** * GTM Account ID. * @param accountId accountId or {@code null} for none */ public Trigger setAccountId(java.lang.String accountId) { this.accountId = accountId; return this; } /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getAutoEventFilter() { return autoEventFilter; } /** * Used in the case of auto event tracking. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param autoEventFilter autoEventFilter or {@code null} for none */ public Trigger setAutoEventFilter(java.util.List<Condition> autoEventFilter) { this.autoEventFilter = autoEventFilter; return this; } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getCheckValidation() { return checkValidation; } /** * Whether or not we should only fire tags if the form submit or link click event is not cancelled * by some other event handler (e.g. because of validation). Only valid for Form Submission and * Link Click triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param checkValidation checkValidation or {@code null} for none */ public Trigger setCheckValidation(Parameter checkValidation) { this.checkValidation = checkValidation; return this; } /** * GTM Container ID. * @return value or {@code null} for none */ public java.lang.String getContainerId() { return containerId; } /** * GTM Container ID. * @param containerId containerId or {@code null} for none */ public Trigger setContainerId(java.lang.String containerId) { this.containerId = containerId; return this; } /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getContinuousTimeMinMilliseconds() { return continuousTimeMinMilliseconds; } /** * A visibility trigger minimum continuous visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param continuousTimeMinMilliseconds continuousTimeMinMilliseconds or {@code null} for none */ public Trigger setContinuousTimeMinMilliseconds(Parameter continuousTimeMinMilliseconds) { this.continuousTimeMinMilliseconds = continuousTimeMinMilliseconds; return this; } /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getCustomEventFilter() { return customEventFilter; } /** * Used in the case of custom event, which is fired iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param customEventFilter customEventFilter or {@code null} for none */ public Trigger setCustomEventFilter(java.util.List<Condition> customEventFilter) { this.customEventFilter = customEventFilter; return this; } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getEventName() { return eventName; } /** * Name of the GTM event that is fired. Only valid for Timer triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param eventName eventName or {@code null} for none */ public Trigger setEventName(Parameter eventName) { this.eventName = eventName; return this; } /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Condition> getFilter() { return filter; } /** * The trigger will only fire iff all Conditions are true. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param filter filter or {@code null} for none */ public Trigger setFilter(java.util.List<Condition> filter) { this.filter = filter; return this; } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * @return value or {@code null} for none */ public java.lang.String getFingerprint() { return fingerprint; } /** * The fingerprint of the GTM Trigger as computed at storage time. This value is recomputed * whenever the trigger is modified. * @param fingerprint fingerprint or {@code null} for none */ public Trigger setFingerprint(java.lang.String fingerprint) { this.fingerprint = fingerprint; return this; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getHorizontalScrollPercentageList() { return horizontalScrollPercentageList; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled horizontally. Only valid for AMP scroll * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param horizontalScrollPercentageList horizontalScrollPercentageList or {@code null} for none */ public Trigger setHorizontalScrollPercentageList(Parameter horizontalScrollPercentageList) { this.horizontalScrollPercentageList = horizontalScrollPercentageList; return this; } /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getInterval() { return interval; } /** * Time between triggering recurring Timer Events (in milliseconds). Only valid for Timer * triggers. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param interval interval or {@code null} for none */ public Trigger setInterval(Parameter interval) { this.interval = interval; return this; } /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getIntervalSeconds() { return intervalSeconds; } /** * Time between Timer Events to fire (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param intervalSeconds intervalSeconds or {@code null} for none */ public Trigger setIntervalSeconds(Parameter intervalSeconds) { this.intervalSeconds = intervalSeconds; return this; } /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getLimit() { return limit; } /** * Limit of the number of GTM events this Timer Trigger will fire. If no limit is set, we will * continue to fire GTM events until the user leaves the page. Only valid for Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param limit limit or {@code null} for none */ public Trigger setLimit(Parameter limit) { this.limit = limit; return this; } /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getMaxTimerLengthSeconds() { return maxTimerLengthSeconds; } /** * Max time to fire Timer Events (in seconds). Only valid for AMP Timer trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param maxTimerLengthSeconds maxTimerLengthSeconds or {@code null} for none */ public Trigger setMaxTimerLengthSeconds(Parameter maxTimerLengthSeconds) { this.maxTimerLengthSeconds = maxTimerLengthSeconds; return this; } /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Trigger display name. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param name name or {@code null} for none */ public Trigger setName(java.lang.String name) { this.name = name; return this; } /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getNotes() { return notes; } /** * User notes on how to apply this trigger in the container. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param notes notes or {@code null} for none */ public Trigger setNotes(java.lang.String notes) { this.notes = notes; return this; } /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.util.List<Parameter> getParameter() { return parameter; } /** * Additional parameters. @mutable tagmanager.accounts.containers.workspaces.triggers.create * @mutable tagmanager.accounts.containers.workspaces.triggers.update * @param parameter parameter or {@code null} for none */ public Trigger setParameter(java.util.List<Parameter> parameter) { this.parameter = parameter; return this; } /** * Parent folder id. * @return value or {@code null} for none */ public java.lang.String getParentFolderId() { return parentFolderId; } /** * Parent folder id. * @param parentFolderId parentFolderId or {@code null} for none */ public Trigger setParentFolderId(java.lang.String parentFolderId) { this.parentFolderId = parentFolderId; return this; } /** * GTM Trigger's API relative path. * @return value or {@code null} for none */ public java.lang.String getPath() { return path; } /** * GTM Trigger's API relative path. * @param path path or {@code null} for none */ public Trigger setPath(java.lang.String path) { this.path = path; return this; } /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getSelector() { return selector; } /** * A click trigger CSS selector (i.e. "a", "button" etc.). Only valid for AMP Click trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param selector selector or {@code null} for none */ public Trigger setSelector(Parameter selector) { this.selector = selector; return this; } /** * Auto generated link to the tag manager UI * @return value or {@code null} for none */ public java.lang.String getTagManagerUrl() { return tagManagerUrl; } /** * Auto generated link to the tag manager UI * @param tagManagerUrl tagManagerUrl or {@code null} for none */ public Trigger setTagManagerUrl(java.lang.String tagManagerUrl) { this.tagManagerUrl = tagManagerUrl; return this; } /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getTotalTimeMinMilliseconds() { return totalTimeMinMilliseconds; } /** * A visibility trigger minimum total visible time (in milliseconds). Only valid for AMP * Visibility trigger. @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param totalTimeMinMilliseconds totalTimeMinMilliseconds or {@code null} for none */ public Trigger setTotalTimeMinMilliseconds(Parameter totalTimeMinMilliseconds) { this.totalTimeMinMilliseconds = totalTimeMinMilliseconds; return this; } /** * The Trigger ID uniquely identifies the GTM Trigger. * @return value or {@code null} for none */ public java.lang.String getTriggerId() { return triggerId; } /** * The Trigger ID uniquely identifies the GTM Trigger. * @param triggerId triggerId or {@code null} for none */ public Trigger setTriggerId(java.lang.String triggerId) { this.triggerId = triggerId; return this; } /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public java.lang.String getType() { return type; } /** * Defines the data layer event that causes this trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param type type or {@code null} for none */ public Trigger setType(java.lang.String type) { this.type = type; return this; } /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getUniqueTriggerId() { return uniqueTriggerId; } /** * Globally unique id of the trigger that auto-generates this (a Form Submit, Link Click or Timer * listener) if any. Used to make incompatible auto-events work together with trigger filtering * based on trigger ids. This value is populated during output generation since the tags implied * by triggers don't exist until then. Only valid for Form Submit, Link Click and Timer triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param uniqueTriggerId uniqueTriggerId or {@code null} for none */ public Trigger setUniqueTriggerId(Parameter uniqueTriggerId) { this.uniqueTriggerId = uniqueTriggerId; return this; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVerticalScrollPercentageList() { return verticalScrollPercentageList; } /** * List of integer percentage values for scroll triggers. The trigger will fire when each * percentage is reached when the view is scrolled vertically. Only valid for AMP scroll triggers. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param verticalScrollPercentageList verticalScrollPercentageList or {@code null} for none */ public Trigger setVerticalScrollPercentageList(Parameter verticalScrollPercentageList) { this.verticalScrollPercentageList = verticalScrollPercentageList; return this; } /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisibilitySelector() { return visibilitySelector; } /** * A visibility trigger CSS selector (i.e. "#id"). Only valid for AMP Visibility trigger. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visibilitySelector visibilitySelector or {@code null} for none */ public Trigger setVisibilitySelector(Parameter visibilitySelector) { this.visibilitySelector = visibilitySelector; return this; } /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisiblePercentageMax() { return visiblePercentageMax; } /** * A visibility trigger maximum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visiblePercentageMax visiblePercentageMax or {@code null} for none */ public Trigger setVisiblePercentageMax(Parameter visiblePercentageMax) { this.visiblePercentageMax = visiblePercentageMax; return this; } /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getVisiblePercentageMin() { return visiblePercentageMin; } /** * A visibility trigger minimum percent visibility. Only valid for AMP Visibility trigger. * @mutable tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param visiblePercentageMin visiblePercentageMin or {@code null} for none */ public Trigger setVisiblePercentageMin(Parameter visiblePercentageMin) { this.visiblePercentageMin = visiblePercentageMin; return this; } /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getWaitForTags() { return waitForTags; } /** * Whether or not we should delay the form submissions or link opening until all of the tags have * fired (by preventing the default action and later simulating the default action). Only valid * for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param waitForTags waitForTags or {@code null} for none */ public Trigger setWaitForTags(Parameter waitForTags) { this.waitForTags = waitForTags; return this; } /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @return value or {@code null} for none */ public Parameter getWaitForTagsTimeout() { return waitForTagsTimeout; } /** * How long to wait (in milliseconds) for tags to fire when 'waits_for_tags' above evaluates to * true. Only valid for Form Submission and Link Click triggers. @mutable * tagmanager.accounts.containers.workspaces.triggers.create @mutable * tagmanager.accounts.containers.workspaces.triggers.update * @param waitForTagsTimeout waitForTagsTimeout or {@code null} for none */ public Trigger setWaitForTagsTimeout(Parameter waitForTagsTimeout) { this.waitForTagsTimeout = waitForTagsTimeout; return this; } /** * GTM Workspace ID. * @return value or {@code null} for none */ public java.lang.String getWorkspaceId() { return workspaceId; } /** * GTM Workspace ID. * @param workspaceId workspaceId or {@code null} for none */ public Trigger setWorkspaceId(java.lang.String workspaceId) { this.workspaceId = workspaceId; return this; } @Override public Trigger set(String fieldName, Object value) { return (Trigger) super.set(fieldName, value); } @Override public Trigger clone() { return (Trigger) super.clone(); } }