repo_id stringclasses 875
values | size int64 974 38.9k | file_path stringlengths 10 308 | content stringlengths 974 38.9k |
|---|---|---|---|
apache/flink-kubernetes-operator | 36,076 | flink-autoscaler/src/test/java/org/apache/flink/autoscaler/DelayedScaleDownEndToEndTest.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.autoscaler;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.JobStatus;
import org.apache.flink.autoscaler.config.AutoScalerOptions;
import org.apache.flink.autoscaler.event.TestingEventCollector;
import org.apache.flink.autoscaler.metrics.ScalingMetric;
import org.apache.flink.autoscaler.metrics.TestMetrics;
import org.apache.flink.autoscaler.realizer.TestingScalingRealizer;
import org.apache.flink.autoscaler.state.AutoScalerStateStore;
import org.apache.flink.autoscaler.state.InMemoryAutoScalerStateStore;
import org.apache.flink.autoscaler.topology.JobTopology;
import org.apache.flink.autoscaler.topology.VertexInfo;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static org.apache.flink.autoscaler.TestingAutoscalerUtils.createDefaultJobAutoScalerContext;
import static org.apache.flink.autoscaler.TestingAutoscalerUtils.getRestClusterClientSupplier;
import static org.apache.flink.autoscaler.metrics.ScalingMetric.RECOMMENDED_PARALLELISM;
import static org.apache.flink.autoscaler.topology.ShipStrategy.REBALANCE;
import static org.assertj.core.api.Assertions.assertThat;
/** End-to-end test for {@link DelayedScaleDown}. */
public class DelayedScaleDownEndToEndTest {
private static final int INITIAL_SOURCE_PARALLELISM = 200;
private static final int INITIAL_SINK_PARALLELISM = 1000;
private static final double UTILIZATION_TARGET = 0.8;
private JobAutoScalerContext<JobID> context;
private AutoScalerStateStore<JobID, JobAutoScalerContext<JobID>> stateStore;
TestingScalingRealizer<JobID, JobAutoScalerContext<JobID>> scalingRealizer;
private TestingMetricsCollector<JobID, JobAutoScalerContext<JobID>> metricsCollector;
private JobVertexID source, sink;
private JobAutoScalerImpl<JobID, JobAutoScalerContext<JobID>> autoscaler;
private Instant now;
private int expectedMetricSize;
@BeforeEach
public void setup() throws Exception {
context = createDefaultJobAutoScalerContext();
TestingEventCollector<JobID, JobAutoScalerContext<JobID>> eventCollector =
new TestingEventCollector<>();
stateStore = new InMemoryAutoScalerStateStore<>();
source = new JobVertexID();
sink = new JobVertexID();
metricsCollector =
new TestingMetricsCollector<>(
new JobTopology(
new VertexInfo(source, Map.of(), INITIAL_SOURCE_PARALLELISM, 4000),
new VertexInfo(
sink,
Map.of(source, REBALANCE),
INITIAL_SINK_PARALLELISM,
4000)));
var scaleDownInterval = Duration.ofMinutes(60).minus(Duration.ofSeconds(1));
// The metric window size is 9:59 to avoid other metrics are mixed.
var metricWindow = Duration.ofMinutes(10).minus(Duration.ofSeconds(1));
var defaultConf = context.getConfiguration();
defaultConf.set(AutoScalerOptions.AUTOSCALER_ENABLED, true);
defaultConf.set(AutoScalerOptions.SCALING_ENABLED, true);
defaultConf.set(AutoScalerOptions.STABILIZATION_INTERVAL, Duration.ZERO);
defaultConf.set(AutoScalerOptions.RESTART_TIME, Duration.ofSeconds(0));
defaultConf.set(AutoScalerOptions.CATCH_UP_DURATION, Duration.ofSeconds(0));
defaultConf.set(AutoScalerOptions.VERTEX_MAX_PARALLELISM, 10000);
defaultConf.set(AutoScalerOptions.SCALING_ENABLED, true);
defaultConf.set(AutoScalerOptions.MAX_SCALE_DOWN_FACTOR, 1.);
defaultConf.set(AutoScalerOptions.MAX_SCALE_UP_FACTOR, (double) Integer.MAX_VALUE);
defaultConf.set(AutoScalerOptions.UTILIZATION_TARGET, UTILIZATION_TARGET);
defaultConf.set(AutoScalerOptions.UTILIZATION_MAX, UTILIZATION_TARGET + 0.1);
defaultConf.set(AutoScalerOptions.UTILIZATION_MIN, UTILIZATION_TARGET - 0.1);
defaultConf.set(AutoScalerOptions.SCALE_DOWN_INTERVAL, scaleDownInterval);
defaultConf.set(AutoScalerOptions.METRICS_WINDOW, metricWindow);
scalingRealizer = new TestingScalingRealizer<>();
autoscaler =
new JobAutoScalerImpl<>(
metricsCollector,
new ScalingMetricEvaluator(),
new ScalingExecutor<>(eventCollector, stateStore),
eventCollector,
scalingRealizer,
stateStore);
// initially the last evaluated metrics are empty
assertThat(autoscaler.lastEvaluatedMetrics.get(context.getJobKey())).isNull();
now = Instant.ofEpochMilli(0);
setClocksTo(now);
running(now);
metricsCollector.updateMetrics(source, buildMetric(0, 800));
metricsCollector.updateMetrics(sink, buildMetric(0, 800));
// the recommended parallelism values are empty initially
autoscaler.scale(context);
expectedMetricSize = 1;
assertCollectedMetricsSize(expectedMetricSize);
}
/**
* The scale down won't be executed before scale down interval window is full, and it will use
* the max recommended parallelism in the past scale down interval window size when scale down
* is executed.
*/
@Test
void testDelayedScaleDownHappenInLastMetricWindow() throws Exception {
var sourceBusyList = List.of(800, 800, 800, 800, 800, 800, 800);
var sinkBusyList = List.of(350, 300, 150, 200, 400, 250, 100);
var metricWindowSize = sourceBusyList.size();
assertThat(metricWindowSize).isGreaterThan(6);
var totalRecords = 0L;
int recordsPerMinutes = 4800000;
for (int windowIndex = 0; windowIndex < metricWindowSize; windowIndex++) {
for (int i = 1; i <= 10; i++) {
now = now.plus(Duration.ofMinutes(1));
setClocksTo(now);
metricsCollector.updateMetrics(
source, buildMetric(totalRecords, sourceBusyList.get(windowIndex)));
metricsCollector.updateMetrics(
sink, buildMetric(totalRecords, sinkBusyList.get(windowIndex)));
autoscaler.scale(context);
// Metric window is 10 minutes, so 10 is the maximal metric size.
expectedMetricSize = Math.min(expectedMetricSize + 1, 10);
assertCollectedMetricsSize(expectedMetricSize);
// Assert the recommended parallelism.
if (windowIndex == metricWindowSize - 1 && i == 10) {
// Last metric, we expect scale down is executed, and max recommended
// parallelism in the past window should be used.
// The max busy time needs more parallelism than others, so we could compute
// parallelism based on the max busy time.
var expectedSourceParallelism =
getExpectedParallelism(sourceBusyList, INITIAL_SOURCE_PARALLELISM);
var expectedSinkParallelism =
getExpectedParallelism(sinkBusyList, INITIAL_SINK_PARALLELISM);
pollAndAssertScalingRealizer(
expectedSourceParallelism, expectedSinkParallelism);
} else {
// Otherwise, scale down cannot be executed.
if (windowIndex == 0 && i <= 9) {
// Metric window is not full, so don't have recommended parallelism.
assertThat(getCurrentMetricValue(source, RECOMMENDED_PARALLELISM)).isNull();
assertThat(getCurrentMetricValue(sink, RECOMMENDED_PARALLELISM)).isNull();
} else {
// Scale down won't be executed before scale down interval window is full.
assertThat(getCurrentMetricValue(source, RECOMMENDED_PARALLELISM))
.isEqualTo(INITIAL_SOURCE_PARALLELISM);
assertThat(getCurrentMetricValue(sink, RECOMMENDED_PARALLELISM))
.isEqualTo(INITIAL_SINK_PARALLELISM);
}
assertThat(scalingRealizer.events).isEmpty();
}
totalRecords += recordsPerMinutes;
}
}
}
private static List<List<Integer>>
sinkParallelismMaxRecommendedParallelismWithinUtilizationBoundaryProvider() {
return List.of(
List.of(
700, 690, 690, 690, 690, 690, 700, 690, 690, 690, 690, 690, 700, 690, 690,
690, 690, 690, 700, 690, 690, 690, 690, 690, 700, 690, 690, 690, 690, 690,
700),
List.of(700, 690, 700, 690, 700, 690, 700, 690, 700, 690, 700, 690, 700, 690, 700),
List.of(
790, 200, 200, 200, 200, 200, 790, 200, 200, 200, 200, 200, 790, 200, 200,
200, 200, 200, 790, 200, 200, 200, 200, 200, 790, 200, 200, 200, 200, 200,
790),
List.of(790, 200, 790, 200, 790, 200, 790, 200, 790, 200, 790, 200, 790, 200, 790));
}
/**
* Job never scale down when the max recommended parallelism in the past scale down interval
* window is inside the utilization boundary.
*/
@ParameterizedTest
@MethodSource("sinkParallelismMaxRecommendedParallelismWithinUtilizationBoundaryProvider")
void testScaleDownNeverHappenWhenMaxRecommendedParallelismWithinUtilizationBoundary(
List<Integer> sinkBusyList) throws Exception {
var metricWindowSize = sinkBusyList.size();
var sourceBusyList = Collections.nCopies(metricWindowSize, 800);
assertThat(sourceBusyList).hasSameSizeAs(sinkBusyList);
var totalRecords = 0L;
int recordsPerMinutes = 4800000;
for (int windowIndex = 0; windowIndex < metricWindowSize; windowIndex++) {
for (int i = 1; i <= 10; i++) {
now = now.plus(Duration.ofMinutes(1));
setClocksTo(now);
metricsCollector.updateMetrics(
source, buildMetric(totalRecords, sourceBusyList.get(windowIndex)));
metricsCollector.updateMetrics(
sink, buildMetric(totalRecords, sinkBusyList.get(windowIndex)));
autoscaler.scale(context);
// Metric window is 10 minutes, so 10 is the maximal metric size.
expectedMetricSize = Math.min(expectedMetricSize + 1, 10);
assertCollectedMetricsSize(expectedMetricSize);
// Assert the recommended parallelism.
if (windowIndex == 0 && i <= 9) {
// Metric window is not full, so don't have recommended parallelism.
assertThat(getCurrentMetricValue(source, RECOMMENDED_PARALLELISM)).isNull();
assertThat(getCurrentMetricValue(sink, RECOMMENDED_PARALLELISM)).isNull();
} else {
// Scale down won't be executed before scale down interval window is full.
assertThat(getCurrentMetricValue(source, RECOMMENDED_PARALLELISM))
.isEqualTo(INITIAL_SOURCE_PARALLELISM);
assertThat(getCurrentMetricValue(sink, RECOMMENDED_PARALLELISM))
.isEqualTo(INITIAL_SINK_PARALLELISM);
}
assertThat(scalingRealizer.events).isEmpty();
totalRecords += recordsPerMinutes;
}
}
}
private static Stream<Arguments> scaleDownUtilizationBoundaryFromWithinToOutsideProvider() {
return Stream.of(
Arguments.of(
List.of(
780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780,
780, 780, 780, 780),
List.of(
800, 790, 780, 770, 760, 750, 740, 730, 720, 710, 700, 690, 680,
670, 660, 660, 660)),
Arguments.of(
List.of(
780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780,
780, 780, 780, 780),
List.of(
700, 700, 700, 700, 700, 700, 700, 700, 700, 700, 700, 690, 680,
670, 660, 660, 660)),
Arguments.of(
List.of(
780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780,
780, 780, 780, 780, 780),
List.of(
800, 790, 790, 790, 790, 790, 790, 790, 790, 790, 790, 690, 680,
670, 660, 660, 660, 660)),
Arguments.of(
List.of(
780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780,
780, 780, 780, 780),
List.of(
800, 790, 780, 770, 760, 750, 740, 730, 720, 710, 700, 100, 100,
100, 100, 100, 100)),
Arguments.of(
List.of(
780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780, 780,
780, 780, 780, 780, 780, 780, 780, 780, 780, 780),
// only 50 minutes are outside of bound in the first time
List.of(
800, 790, 780, 770, 760, 750, 740, 730, 720, 710, 700, 200, 200,
200, 200, 200, 700, 100, 100, 100, 100, 100, 100)));
}
/**
* Initially, all tasks are scaled down within the utilization bound, and scaling down is only
* executed when the max recommended parallelism in the past scale down interval for any task is
* outside the utilization bound.
*/
@ParameterizedTest
@MethodSource("scaleDownUtilizationBoundaryFromWithinToOutsideProvider")
void testScaleDownUtilizationBoundaryFromWithinToOutside(
List<Integer> sourceBusyList, List<Integer> sinkBusyList) throws Exception {
assertThat(sourceBusyList).hasSameSizeAs(sinkBusyList);
var metricWindowSize = sourceBusyList.size();
assertThat(metricWindowSize).isGreaterThan(6);
var totalRecords = 0L;
int recordsPerMinutes = 4800000;
var sinkBusyWindow = new LinkedList<Integer>();
var sinkRecommendationOutsideBound = new LinkedList<Integer>();
var sourceBusyWindow = new LinkedList<Integer>();
var sourceRecommendation = new LinkedList<Integer>();
for (int windowIndex = 0; windowIndex < metricWindowSize; windowIndex++) {
for (int i = 1; i <= 10; i++) {
now = now.plus(Duration.ofMinutes(1));
setClocksTo(now);
var sourceBusyTimePerSec = sourceBusyList.get(windowIndex);
var sinkBusyTimePerSec = sinkBusyList.get(windowIndex);
sourceBusyWindow.add(sourceBusyTimePerSec);
sinkBusyWindow.add(sinkBusyTimePerSec);
// Poll the oldest metric.
if (sinkBusyWindow.size() > 10) {
sinkBusyWindow.pollFirst();
sourceBusyWindow.pollFirst();
}
metricsCollector.updateMetrics(
source, buildMetric(totalRecords, sourceBusyList.get(windowIndex)));
metricsCollector.updateMetrics(
sink, buildMetric(totalRecords, sinkBusyList.get(windowIndex)));
autoscaler.scale(context);
// Metric window is 10 minutes, so 10 is the maximal metric size.
expectedMetricSize = Math.min(expectedMetricSize + 1, 10);
assertCollectedMetricsSize(expectedMetricSize);
if (windowIndex == 0 && i <= 9) {
// Metric window is not full, so don't have recommended parallelism.
assertThat(getCurrentMetricValue(source, RECOMMENDED_PARALLELISM)).isNull();
assertThat(getCurrentMetricValue(sink, RECOMMENDED_PARALLELISM)).isNull();
assertThat(scalingRealizer.events).isEmpty();
} else {
double sourceBusyAvg =
sourceBusyWindow.stream().mapToInt(e -> e).average().getAsDouble();
double sinkBusyAvg =
sinkBusyWindow.stream().mapToInt(e -> e).average().getAsDouble();
if (sinkBusyAvg < 700) {
var expectedSourceParallelism =
getExpectedParallelism(sourceBusyAvg, INITIAL_SOURCE_PARALLELISM);
var expectedSinkParallelism =
getExpectedParallelism(sinkBusyAvg, INITIAL_SINK_PARALLELISM);
sourceRecommendation.add(expectedSourceParallelism);
sinkRecommendationOutsideBound.add(expectedSinkParallelism);
} else {
sourceRecommendation.clear();
sinkRecommendationOutsideBound.clear();
}
// Assert the recommended parallelism.
// why it's 60 instead of 59
if (sinkRecommendationOutsideBound.size() >= 60) {
// Last metric, we expect scale down is executed, and max recommended
// parallelism in the past window should be used.
// The max busy time needs more parallelism than others, so we could compute
// parallelism based on the max busy time.
var expectedSourceParallelism =
sourceRecommendation.stream().mapToInt(e -> e).max().getAsInt();
var expectedSinkParallelism =
sinkRecommendationOutsideBound.stream()
.mapToInt(e -> e)
.max()
.getAsInt();
pollAndAssertScalingRealizer(
expectedSourceParallelism, expectedSinkParallelism);
break;
} else {
// Otherwise, scale down cannot be executed.
// Scale down won't be executed before scale down interval window is full.
assertThat(getCurrentMetricValue(source, RECOMMENDED_PARALLELISM))
.isEqualTo(INITIAL_SOURCE_PARALLELISM);
assertThat(getCurrentMetricValue(sink, RECOMMENDED_PARALLELISM))
.isEqualTo(INITIAL_SINK_PARALLELISM);
assertThat(scalingRealizer.events).isEmpty();
}
}
totalRecords += recordsPerMinutes;
}
}
}
/** The scale down trigger time will be reset, when other tasks scale up. */
@Test
void testDelayedScaleDownIsResetWhenAnotherTaskScaleUp() throws Exception {
// It expects delayed scale down of sink is reset when scale up is executed for source.
var sourceBusyList = List.of(800, 800, 800, 800, 950);
var sinkBusyList = List.of(200, 200, 200, 200, 200);
var sourceBusyWindow = new LinkedList<Integer>();
var metricWindowSize = sourceBusyList.size();
var totalRecords = 0L;
int recordsPerMinutes = 4800000;
for (int windowIndex = 0; windowIndex < metricWindowSize; windowIndex++) {
for (int i = 1; i <= 10; i++) {
now = now.plus(Duration.ofMinutes(1));
setClocksTo(now);
var busyTimePerSec = sourceBusyList.get(windowIndex);
sourceBusyWindow.add(busyTimePerSec);
// Poll the oldest metric.
if (sourceBusyWindow.size() > 10) {
sourceBusyWindow.pollFirst();
}
metricsCollector.updateMetrics(source, buildMetric(totalRecords, busyTimePerSec));
metricsCollector.updateMetrics(
sink, buildMetric(totalRecords, sinkBusyList.get(windowIndex)));
autoscaler.scale(context);
// Metric window is 10 minutes, so 10 is the maximal metric size.
expectedMetricSize = Math.min(expectedMetricSize + 1, 10);
assertCollectedMetricsSize(expectedMetricSize);
// Assert the recommended parallelism.
if (windowIndex == 0 && i <= 9) {
// Metric window is not full, so don't have recommended parallelism.
assertThat(getCurrentMetricValue(source, RECOMMENDED_PARALLELISM)).isNull();
assertThat(getCurrentMetricValue(sink, RECOMMENDED_PARALLELISM)).isNull();
assertThat(scalingRealizer.events).isEmpty();
} else {
double busyAvg =
sourceBusyWindow.stream().mapToInt(e -> e).average().getAsDouble();
if (busyAvg > 900) {
// Scaling up happens for source, and the scale down of sink cannot be
// executed since the scale down interval window is not full.
var sourceMaxBusyRatio = busyAvg / 1000;
var expectedSourceParallelism =
(int)
Math.ceil(
INITIAL_SOURCE_PARALLELISM
* sourceMaxBusyRatio
/ UTILIZATION_TARGET);
pollAndAssertScalingRealizer(
expectedSourceParallelism, INITIAL_SINK_PARALLELISM);
// The delayed scale down should be cleaned up after source scales up.
assertThat(stateStore.getDelayedScaleDown(context).getDelayedVertices())
.isEmpty();
break;
} else {
// Scale down won't be executed before source utilization within the
// utilization bound.
assertThat(getCurrentMetricValue(source, RECOMMENDED_PARALLELISM))
.isEqualTo(INITIAL_SOURCE_PARALLELISM);
assertThat(getCurrentMetricValue(sink, RECOMMENDED_PARALLELISM))
.isEqualTo(INITIAL_SINK_PARALLELISM);
assertThat(scalingRealizer.events).isEmpty();
// Delayed scale down is triggered
assertThat(stateStore.getDelayedScaleDown(context).getDelayedVertices())
.isNotEmpty();
}
}
totalRecords += recordsPerMinutes;
}
}
}
/** The scale down trigger time will be reset, when other tasks scale down. */
@Test
void testDelayedScaleDownIsResetWhenAnotherTaskScaleDown() throws Exception {
// It expects delayed scale down of sink is reset when scale down is executed for source.
var sourceBusyList = List.of(200, 200, 200, 200, 200, 200, 200);
var sinkBusyList = List.of(800, 800, 200, 200, 200, 200, 200);
var metricWindowSize = sourceBusyList.size();
var totalRecords = 0L;
int recordsPerMinutes = 4800000;
for (int windowIndex = 0; windowIndex < metricWindowSize; windowIndex++) {
for (int i = 1; i <= 10; i++) {
now = now.plus(Duration.ofMinutes(1));
setClocksTo(now);
metricsCollector.updateMetrics(
source, buildMetric(totalRecords, sourceBusyList.get(windowIndex)));
metricsCollector.updateMetrics(
sink, buildMetric(totalRecords, sinkBusyList.get(windowIndex)));
autoscaler.scale(context);
// Metric window is 10 minutes, so 10 is the maximal metric size.
expectedMetricSize = Math.min(expectedMetricSize + 1, 10);
assertCollectedMetricsSize(expectedMetricSize);
// Assert the recommended parallelism.
if (windowIndex == 0 && i <= 9) {
// Metric window is not full, so don't have recommended parallelism.
assertThat(getCurrentMetricValue(source, RECOMMENDED_PARALLELISM)).isNull();
assertThat(getCurrentMetricValue(sink, RECOMMENDED_PARALLELISM)).isNull();
assertThat(scalingRealizer.events).isEmpty();
} else {
if (windowIndex == metricWindowSize - 1 && i == 10) {
// Scaling up happens for source, and the scale down of sink cannot be
// executed since the scale down interval window is not full.
var expectedSourceParallelism =
getExpectedParallelism(sourceBusyList, INITIAL_SOURCE_PARALLELISM);
pollAndAssertScalingRealizer(
expectedSourceParallelism, INITIAL_SINK_PARALLELISM);
// The delayed scale down should be cleaned up after source scales down.
assertThat(stateStore.getDelayedScaleDown(context).getDelayedVertices())
.isEmpty();
} else {
// Scale down won't be executed when scale down interval window of source is
// not full.
assertThat(getCurrentMetricValue(source, RECOMMENDED_PARALLELISM))
.isEqualTo(INITIAL_SOURCE_PARALLELISM);
assertThat(getCurrentMetricValue(sink, RECOMMENDED_PARALLELISM))
.isEqualTo(INITIAL_SINK_PARALLELISM);
assertThat(scalingRealizer.events).isEmpty();
// Delayed scale down is triggered
assertThat(stateStore.getDelayedScaleDown(context).getDelayedVertices())
.isNotEmpty();
}
}
totalRecords += recordsPerMinutes;
}
}
}
private static List<List<Integer>> sinkParallelismIsGreaterOrEqualProvider() {
return List.of(
// test for the recommended parallelism is equal to the current parallelism.
List.of(200, 200, 200, 200, 800),
List.of(700, 700, 700, 700, 800),
List.of(780, 780, 780, 780, 800),
List.of(790, 800),
List.of(760, 800),
List.of(750, 800),
List.of(350, 800),
// test for the recommended parallelism is greater than current parallelism.
List.of(200, 200, 200, 200, 850),
List.of(700, 700, 700, 700, 850),
List.of(780, 780, 780, 780, 850),
List.of(790, 850),
List.of(760, 850),
List.of(750, 850),
List.of(350, 850),
List.of(200, 200, 200, 200, 900),
List.of(700, 700, 700, 700, 900),
List.of(780, 780, 780, 780, 900),
List.of(790, 900),
List.of(760, 900),
List.of(750, 900),
List.of(350, 900));
}
/**
* The triggered scale down of sink will be canceled when the recommended parallelism is greater
* than or equal to the current parallelism.
*/
@ParameterizedTest
@MethodSource("sinkParallelismIsGreaterOrEqualProvider")
void testDelayedScaleDownIsCanceledWhenRecommendedParallelismIsGreaterOrEqual(
List<Integer> sinkBusyList) throws Exception {
var metricWindowSize = sinkBusyList.size();
var sourceBusyList = Collections.nCopies(metricWindowSize, 800);
var sinkBusyWindow = new LinkedList<Integer>();
var totalRecords = 0L;
int recordsPerMinutes = 480000000;
for (int windowIndex = 0; windowIndex < metricWindowSize; windowIndex++) {
for (int i = 1; i <= 10; i++) {
now = now.plus(Duration.ofMinutes(1));
setClocksTo(now);
var busyTimePerSec = sinkBusyList.get(windowIndex);
sinkBusyWindow.add(busyTimePerSec);
// Poll the oldest metric.
if (sinkBusyWindow.size() > 10) {
sinkBusyWindow.pollFirst();
}
metricsCollector.updateMetrics(
source, buildMetric(totalRecords, sourceBusyList.get(windowIndex)));
metricsCollector.updateMetrics(sink, buildMetric(totalRecords, busyTimePerSec));
autoscaler.scale(context);
// Metric window is 10 minutes, so 10 is the maximal metric size.
expectedMetricSize = Math.min(expectedMetricSize + 1, 10);
assertCollectedMetricsSize(expectedMetricSize);
assertThat(scalingRealizer.events).isEmpty();
// Assert the recommended parallelism.
if (windowIndex == 0 && i <= 9) {
// Metric window is not full, so don't have recommended parallelism.
assertThat(getCurrentMetricValue(source, RECOMMENDED_PARALLELISM)).isNull();
assertThat(getCurrentMetricValue(sink, RECOMMENDED_PARALLELISM)).isNull();
} else {
// Scale down won't be executed before scale down interval window is full.
assertThat(getCurrentMetricValue(source, RECOMMENDED_PARALLELISM))
.isEqualTo(INITIAL_SOURCE_PARALLELISM);
assertThat(getCurrentMetricValue(sink, RECOMMENDED_PARALLELISM))
.isEqualTo(INITIAL_SINK_PARALLELISM);
double sinkBusyAvg =
sinkBusyWindow.stream().mapToInt(e -> e).average().getAsDouble();
if (sinkBusyAvg >= 800) {
// The delayed scale down should be cleaned up after the expected
// recommended parallelism is greater than or equal to the current
// parallelism.
assertThat(stateStore.getDelayedScaleDown(context).getDelayedVertices())
.isEmpty();
break;
} else {
// Delayed scale down is triggered
assertThat(stateStore.getDelayedScaleDown(context).getDelayedVertices())
.isNotEmpty();
}
}
totalRecords += recordsPerMinutes;
}
}
}
private static int getExpectedParallelism(List<Integer> taskBusyList, int currentParallelism) {
var maxBusyTime =
taskBusyList.stream()
.skip(taskBusyList.size() - 6)
.max(Comparator.naturalOrder())
.get();
return getExpectedParallelism(maxBusyTime, currentParallelism);
}
private static int getExpectedParallelism(double busyTime, int currentParallelism) {
var maxBusyRatio = busyTime / 1000;
return (int) Math.ceil(currentParallelism * maxBusyRatio / UTILIZATION_TARGET);
}
private void pollAndAssertScalingRealizer(
int expectedSourceParallelism, int expectedSinkParallelism) {
// Assert metric
assertThat(getCurrentMetricValue(source, RECOMMENDED_PARALLELISM))
.isEqualTo(expectedSourceParallelism);
assertThat(getCurrentMetricValue(sink, RECOMMENDED_PARALLELISM))
.isEqualTo(expectedSinkParallelism);
// Check scaling realizer.
assertThat(scalingRealizer.events).hasSize(1);
var parallelismOverrides = scalingRealizer.events.poll().getParallelismOverrides();
assertThat(parallelismOverrides)
.containsEntry(source.toHexString(), Integer.toString(expectedSourceParallelism));
assertThat(parallelismOverrides)
.containsEntry(sink.toHexString(), Integer.toString(expectedSinkParallelism));
}
private void assertCollectedMetricsSize(int expectedSize) throws Exception {
assertThat(stateStore.getCollectedMetrics(context)).hasSize(expectedSize);
}
private Double getCurrentMetricValue(JobVertexID jobVertexID, ScalingMetric scalingMetric) {
var metric =
autoscaler
.lastEvaluatedMetrics
.get(context.getJobKey())
.getVertexMetrics()
.get(jobVertexID)
.get(scalingMetric);
return metric == null ? null : metric.getCurrent();
}
private void running(Instant now) {
metricsCollector.setJobUpdateTs(now);
context =
new JobAutoScalerContext<>(
context.getJobKey(),
context.getJobID(),
JobStatus.RUNNING,
context.getConfiguration(),
context.getMetricGroup(),
getRestClusterClientSupplier());
}
private void setClocksTo(Instant time) {
var clock = Clock.fixed(time, ZoneId.systemDefault());
metricsCollector.setClock(clock);
autoscaler.setClock(clock);
}
private TestMetrics buildMetric(long totalRecords, int busyTimePerSec) {
return TestMetrics.builder()
.numRecordsIn(totalRecords)
.numRecordsOut(totalRecords)
.maxBusyTimePerSec(busyTimePerSec)
.build();
}
}
|
apache/hadoop-common | 35,030 | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/util/TestProcfsBasedProcessTree.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.util;
import static org.apache.hadoop.yarn.util.ProcfsBasedProcessTree.KB_TO_BYTES;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.util.Shell.ExitCodeException;
import org.apache.hadoop.util.Shell.ShellCommandExecutor;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.util.ProcfsBasedProcessTree.MemInfo;
import org.apache.hadoop.yarn.util.ProcfsBasedProcessTree.ProcessSmapMemoryInfo;
import org.apache.hadoop.yarn.util.ProcfsBasedProcessTree.ProcessTreeSmapMemInfo;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* A JUnit test to test ProcfsBasedProcessTree.
*/
public class TestProcfsBasedProcessTree {
private static final Log LOG = LogFactory
.getLog(TestProcfsBasedProcessTree.class);
protected static File TEST_ROOT_DIR = new File("target",
TestProcfsBasedProcessTree.class.getName() + "-localDir");
private ShellCommandExecutor shexec = null;
private String pidFile, lowestDescendant;
private String shellScript;
private static final int N = 6; // Controls the RogueTask
private class RogueTaskThread extends Thread {
public void run() {
try {
Vector<String> args = new Vector<String>();
if (isSetsidAvailable()) {
args.add("setsid");
}
args.add("bash");
args.add("-c");
args.add(" echo $$ > " + pidFile + "; sh " + shellScript + " " + N
+ ";");
shexec = new ShellCommandExecutor(args.toArray(new String[0]));
shexec.execute();
} catch (ExitCodeException ee) {
LOG.info("Shell Command exit with a non-zero exit code. This is"
+ " expected as we are killing the subprocesses of the"
+ " task intentionally. " + ee);
} catch (IOException ioe) {
LOG.info("Error executing shell command " + ioe);
} finally {
LOG.info("Exit code: " + shexec.getExitCode());
}
}
}
private String getRogueTaskPID() {
File f = new File(pidFile);
while (!f.exists()) {
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
break;
}
}
// read from pidFile
return getPidFromPidFile(pidFile);
}
@Before
public void setup() throws IOException {
assumeTrue(Shell.LINUX);
FileContext.getLocalFSFileContext().delete(
new Path(TEST_ROOT_DIR.getAbsolutePath()), true);
}
@Test(timeout = 30000)
public void testProcessTree() throws Exception {
try {
Assert.assertTrue(ProcfsBasedProcessTree.isAvailable());
} catch (Exception e) {
LOG.info(StringUtils.stringifyException(e));
Assert.assertTrue("ProcfsBaseProcessTree should be available on Linux",
false);
return;
}
// create shell script
Random rm = new Random();
File tempFile =
new File(TEST_ROOT_DIR, getClass().getName() + "_shellScript_"
+ rm.nextInt() + ".sh");
tempFile.deleteOnExit();
shellScript = TEST_ROOT_DIR + File.separator + tempFile.getName();
// create pid file
tempFile =
new File(TEST_ROOT_DIR, getClass().getName() + "_pidFile_"
+ rm.nextInt() + ".pid");
tempFile.deleteOnExit();
pidFile = TEST_ROOT_DIR + File.separator + tempFile.getName();
lowestDescendant =
TEST_ROOT_DIR + File.separator + "lowestDescendantPidFile";
// write to shell-script
try {
FileWriter fWriter = new FileWriter(shellScript);
fWriter.write("# rogue task\n" + "sleep 1\n" + "echo hello\n"
+ "if [ $1 -ne 0 ]\n" + "then\n" + " sh " + shellScript
+ " $(($1-1))\n" + "else\n" + " echo $$ > " + lowestDescendant + "\n"
+ " while true\n do\n" + " sleep 5\n" + " done\n" + "fi");
fWriter.close();
} catch (IOException ioe) {
LOG.info("Error: " + ioe);
return;
}
Thread t = new RogueTaskThread();
t.start();
String pid = getRogueTaskPID();
LOG.info("Root process pid: " + pid);
ProcfsBasedProcessTree p = createProcessTree(pid);
p.updateProcessTree(); // initialize
LOG.info("ProcessTree: " + p.toString());
File leaf = new File(lowestDescendant);
// wait till lowest descendant process of Rougue Task starts execution
while (!leaf.exists()) {
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
break;
}
}
p.updateProcessTree(); // reconstruct
LOG.info("ProcessTree: " + p.toString());
// Get the process-tree dump
String processTreeDump = p.getProcessTreeDump();
// destroy the process and all its subprocesses
destroyProcessTree(pid);
boolean isAlive = true;
for (int tries = 100; tries > 0; tries--) {
if (isSetsidAvailable()) {// whole processtree
isAlive = isAnyProcessInTreeAlive(p);
} else {// process
isAlive = isAlive(pid);
}
if (!isAlive) {
break;
}
Thread.sleep(100);
}
if (isAlive) {
fail("ProcessTree shouldn't be alive");
}
LOG.info("Process-tree dump follows: \n" + processTreeDump);
Assert.assertTrue("Process-tree dump doesn't start with a proper header",
processTreeDump.startsWith("\t|- PID PPID PGRPID SESSID CMD_NAME "
+ "USER_MODE_TIME(MILLIS) SYSTEM_TIME(MILLIS) VMEM_USAGE(BYTES) "
+ "RSSMEM_USAGE(PAGES) FULL_CMD_LINE\n"));
for (int i = N; i >= 0; i--) {
String cmdLineDump =
"\\|- [0-9]+ [0-9]+ [0-9]+ [0-9]+ \\(sh\\)"
+ " [0-9]+ [0-9]+ [0-9]+ [0-9]+ sh " + shellScript + " " + i;
Pattern pat = Pattern.compile(cmdLineDump);
Matcher mat = pat.matcher(processTreeDump);
Assert.assertTrue("Process-tree dump doesn't contain the cmdLineDump of "
+ i + "th process!", mat.find());
}
// Not able to join thread sometimes when forking with large N.
try {
t.join(2000);
LOG.info("RogueTaskThread successfully joined.");
} catch (InterruptedException ie) {
LOG.info("Interrupted while joining RogueTaskThread.");
}
// ProcessTree is gone now. Any further calls should be sane.
p.updateProcessTree();
Assert.assertFalse("ProcessTree must have been gone", isAlive(pid));
Assert.assertTrue(
"Cumulative vmem for the gone-process is " + p.getCumulativeVmem()
+ " . It should be zero.", p.getCumulativeVmem() == 0);
Assert.assertTrue(p.toString().equals("[ ]"));
}
protected ProcfsBasedProcessTree createProcessTree(String pid) {
return new ProcfsBasedProcessTree(pid);
}
protected ProcfsBasedProcessTree createProcessTree(String pid,
String procfsRootDir) {
return new ProcfsBasedProcessTree(pid, procfsRootDir);
}
protected void destroyProcessTree(String pid) throws IOException {
sendSignal(pid, 9);
}
/**
* Get PID from a pid-file.
*
* @param pidFileName
* Name of the pid-file.
* @return the PID string read from the pid-file. Returns null if the
* pidFileName points to a non-existing file or if read fails from the
* file.
*/
public static String getPidFromPidFile(String pidFileName) {
BufferedReader pidFile = null;
FileReader fReader = null;
String pid = null;
try {
fReader = new FileReader(pidFileName);
pidFile = new BufferedReader(fReader);
} catch (FileNotFoundException f) {
LOG.debug("PidFile doesn't exist : " + pidFileName);
return pid;
}
try {
pid = pidFile.readLine();
} catch (IOException i) {
LOG.error("Failed to read from " + pidFileName);
} finally {
try {
if (fReader != null) {
fReader.close();
}
try {
if (pidFile != null) {
pidFile.close();
}
} catch (IOException i) {
LOG.warn("Error closing the stream " + pidFile);
}
} catch (IOException i) {
LOG.warn("Error closing the stream " + fReader);
}
}
return pid;
}
public static class ProcessStatInfo {
// sample stat in a single line : 3910 (gpm) S 1 3910 3910 0 -1 4194624
// 83 0 0 0 0 0 0 0 16 0 1 0 7852 2408448 88 4294967295 134512640
// 134590050 3220521392 3220520036 10975138 0 0 4096 134234626
// 4294967295 0 0 17 1 0 0
String pid;
String name;
String ppid;
String pgrpId;
String session;
String vmem = "0";
String rssmemPage = "0";
String utime = "0";
String stime = "0";
public ProcessStatInfo(String[] statEntries) {
pid = statEntries[0];
name = statEntries[1];
ppid = statEntries[2];
pgrpId = statEntries[3];
session = statEntries[4];
vmem = statEntries[5];
if (statEntries.length > 6) {
rssmemPage = statEntries[6];
}
if (statEntries.length > 7) {
utime = statEntries[7];
stime = statEntries[8];
}
}
// construct a line that mimics the procfs stat file.
// all unused numerical entries are set to 0.
public String getStatLine() {
return String.format("%s (%s) S %s %s %s 0 0 0"
+ " 0 0 0 0 %s %s 0 0 0 0 0 0 0 %s %s 0 0" + " 0 0 0 0 0 0 0 0"
+ " 0 0 0 0 0", pid, name, ppid, pgrpId, session, utime, stime, vmem,
rssmemPage);
}
}
public ProcessSmapMemoryInfo constructMemoryMappingInfo(String address,
String[] entries) {
ProcessSmapMemoryInfo info = new ProcessSmapMemoryInfo(address);
info.setMemInfo(MemInfo.SIZE.name(), entries[0]);
info.setMemInfo(MemInfo.RSS.name(), entries[1]);
info.setMemInfo(MemInfo.PSS.name(), entries[2]);
info.setMemInfo(MemInfo.SHARED_CLEAN.name(), entries[3]);
info.setMemInfo(MemInfo.SHARED_DIRTY.name(), entries[4]);
info.setMemInfo(MemInfo.PRIVATE_CLEAN.name(), entries[5]);
info.setMemInfo(MemInfo.PRIVATE_DIRTY.name(), entries[6]);
info.setMemInfo(MemInfo.REFERENCED.name(), entries[7]);
info.setMemInfo(MemInfo.ANONYMOUS.name(), entries[8]);
info.setMemInfo(MemInfo.ANON_HUGE_PAGES.name(), entries[9]);
info.setMemInfo(MemInfo.SWAP.name(), entries[10]);
info.setMemInfo(MemInfo.KERNEL_PAGE_SIZE.name(), entries[11]);
info.setMemInfo(MemInfo.MMU_PAGE_SIZE.name(), entries[12]);
return info;
}
public void createMemoryMappingInfo(ProcessTreeSmapMemInfo[] procMemInfo) {
for (int i = 0; i < procMemInfo.length; i++) {
// Construct 4 memory mappings per process.
// As per min(Shared_Dirty, Pss) + Private_Clean + Private_Dirty
// and not including r--s, r-xs, we should get 100 KB per process
List<ProcessSmapMemoryInfo> memoryMappingList =
procMemInfo[i].getMemoryInfoList();
memoryMappingList.add(constructMemoryMappingInfo(
"7f56c177c000-7f56c177d000 "
+ "rw-p 00010000 08:02 40371558 "
+ "/grid/0/jdk1.7.0_25/jre/lib/amd64/libnio.so",
new String[] { "4", "4", "25", "4", "25", "15", "10", "4", "0", "0",
"0", "4", "4" }));
memoryMappingList.add(constructMemoryMappingInfo(
"7fb09382e000-7fb09382f000 r--s 00003000 " + "08:02 25953545",
new String[] { "4", "4", "25", "4", "0", "15", "10", "4", "0", "0",
"0", "4", "4" }));
memoryMappingList.add(constructMemoryMappingInfo(
"7e8790000-7e8b80000 r-xs 00000000 00:00 0", new String[] { "4", "4",
"25", "4", "0", "15", "10", "4", "0", "0", "0", "4", "4" }));
memoryMappingList.add(constructMemoryMappingInfo(
"7da677000-7e0dcf000 rw-p 00000000 00:00 0", new String[] { "4", "4",
"25", "4", "50", "15", "10", "4", "0", "0", "0", "4", "4" }));
}
}
/**
* A basic test that creates a few process directories and writes stat files.
* Verifies that the cpu time and memory is correctly computed.
*
* @throws IOException
* if there was a problem setting up the fake procfs directories or
* files.
*/
@Test(timeout = 30000)
public void testCpuAndMemoryForProcessTree() throws IOException {
// test processes
String[] pids = { "100", "200", "300", "400" };
// create the fake procfs root directory.
File procfsRootDir = new File(TEST_ROOT_DIR, "proc");
try {
setupProcfsRootDir(procfsRootDir);
setupPidDirs(procfsRootDir, pids);
// create stat objects.
// assuming processes 100, 200, 300 are in tree and 400 is not.
ProcessStatInfo[] procInfos = new ProcessStatInfo[4];
procInfos[0] =
new ProcessStatInfo(new String[] { "100", "proc1", "1", "100", "100",
"100000", "100", "1000", "200" });
procInfos[1] =
new ProcessStatInfo(new String[] { "200", "proc2", "100", "100",
"100", "200000", "200", "2000", "400" });
procInfos[2] =
new ProcessStatInfo(new String[] { "300", "proc3", "200", "100",
"100", "300000", "300", "3000", "600" });
procInfos[3] =
new ProcessStatInfo(new String[] { "400", "proc4", "1", "400", "400",
"400000", "400", "4000", "800" });
ProcessTreeSmapMemInfo[] memInfo = new ProcessTreeSmapMemInfo[4];
memInfo[0] = new ProcessTreeSmapMemInfo("100");
memInfo[1] = new ProcessTreeSmapMemInfo("200");
memInfo[2] = new ProcessTreeSmapMemInfo("300");
memInfo[3] = new ProcessTreeSmapMemInfo("400");
createMemoryMappingInfo(memInfo);
writeStatFiles(procfsRootDir, pids, procInfos, memInfo);
// crank up the process tree class.
Configuration conf = new Configuration();
ProcfsBasedProcessTree processTree =
createProcessTree("100", procfsRootDir.getAbsolutePath());
processTree.setConf(conf);
// build the process tree.
processTree.updateProcessTree();
// verify cumulative memory
Assert.assertEquals("Cumulative virtual memory does not match", 600000L,
processTree.getCumulativeVmem());
// verify rss memory
long cumuRssMem =
ProcfsBasedProcessTree.PAGE_SIZE > 0
? 600L * ProcfsBasedProcessTree.PAGE_SIZE : 0L;
Assert.assertEquals("Cumulative rss memory does not match", cumuRssMem,
processTree.getCumulativeRssmem());
// verify cumulative cpu time
long cumuCpuTime =
ProcfsBasedProcessTree.JIFFY_LENGTH_IN_MILLIS > 0
? 7200L * ProcfsBasedProcessTree.JIFFY_LENGTH_IN_MILLIS : 0L;
Assert.assertEquals("Cumulative cpu time does not match", cumuCpuTime,
processTree.getCumulativeCpuTime());
// Check by enabling smaps
setSmapsInProceTree(processTree, true);
// RSS=Min(shared_dirty,PSS)+PrivateClean+PrivateDirty (exclude r-xs,
// r--s)
Assert.assertEquals("Cumulative rss memory does not match",
(100 * KB_TO_BYTES * 3), processTree.getCumulativeRssmem());
// test the cpu time again to see if it cumulates
procInfos[0] =
new ProcessStatInfo(new String[] { "100", "proc1", "1", "100", "100",
"100000", "100", "2000", "300" });
procInfos[1] =
new ProcessStatInfo(new String[] { "200", "proc2", "100", "100",
"100", "200000", "200", "3000", "500" });
writeStatFiles(procfsRootDir, pids, procInfos, memInfo);
// build the process tree.
processTree.updateProcessTree();
// verify cumulative cpu time again
cumuCpuTime =
ProcfsBasedProcessTree.JIFFY_LENGTH_IN_MILLIS > 0
? 9400L * ProcfsBasedProcessTree.JIFFY_LENGTH_IN_MILLIS : 0L;
Assert.assertEquals("Cumulative cpu time does not match", cumuCpuTime,
processTree.getCumulativeCpuTime());
} finally {
FileUtil.fullyDelete(procfsRootDir);
}
}
private void setSmapsInProceTree(ProcfsBasedProcessTree processTree,
boolean enableFlag) {
Configuration conf = processTree.getConf();
if (conf == null) {
conf = new Configuration();
}
conf.setBoolean(YarnConfiguration.PROCFS_USE_SMAPS_BASED_RSS_ENABLED, enableFlag);
processTree.setConf(conf);
processTree.updateProcessTree();
}
/**
* Tests that cumulative memory is computed only for processes older than a
* given age.
*
* @throws IOException
* if there was a problem setting up the fake procfs directories or
* files.
*/
@Test(timeout = 30000)
public void testMemForOlderProcesses() throws IOException {
testMemForOlderProcesses(false);
testMemForOlderProcesses(true);
}
private void testMemForOlderProcesses(boolean smapEnabled) throws IOException {
// initial list of processes
String[] pids = { "100", "200", "300", "400" };
// create the fake procfs root directory.
File procfsRootDir = new File(TEST_ROOT_DIR, "proc");
try {
setupProcfsRootDir(procfsRootDir);
setupPidDirs(procfsRootDir, pids);
// create stat objects.
// assuming 100, 200 and 400 are in tree, 300 is not.
ProcessStatInfo[] procInfos = new ProcessStatInfo[4];
procInfos[0] =
new ProcessStatInfo(new String[] { "100", "proc1", "1", "100", "100",
"100000", "100" });
procInfos[1] =
new ProcessStatInfo(new String[] { "200", "proc2", "100", "100",
"100", "200000", "200" });
procInfos[2] =
new ProcessStatInfo(new String[] { "300", "proc3", "1", "300", "300",
"300000", "300" });
procInfos[3] =
new ProcessStatInfo(new String[] { "400", "proc4", "100", "100",
"100", "400000", "400" });
// write smap information invariably for testing
ProcessTreeSmapMemInfo[] memInfo = new ProcessTreeSmapMemInfo[4];
memInfo[0] = new ProcessTreeSmapMemInfo("100");
memInfo[1] = new ProcessTreeSmapMemInfo("200");
memInfo[2] = new ProcessTreeSmapMemInfo("300");
memInfo[3] = new ProcessTreeSmapMemInfo("400");
createMemoryMappingInfo(memInfo);
writeStatFiles(procfsRootDir, pids, procInfos, memInfo);
// crank up the process tree class.
ProcfsBasedProcessTree processTree =
createProcessTree("100", procfsRootDir.getAbsolutePath());
setSmapsInProceTree(processTree, smapEnabled);
// verify cumulative memory
Assert.assertEquals("Cumulative memory does not match", 700000L,
processTree.getCumulativeVmem());
// write one more process as child of 100.
String[] newPids = { "500" };
setupPidDirs(procfsRootDir, newPids);
ProcessStatInfo[] newProcInfos = new ProcessStatInfo[1];
newProcInfos[0] =
new ProcessStatInfo(new String[] { "500", "proc5", "100", "100",
"100", "500000", "500" });
ProcessTreeSmapMemInfo[] newMemInfos = new ProcessTreeSmapMemInfo[1];
newMemInfos[0] = new ProcessTreeSmapMemInfo("500");
createMemoryMappingInfo(newMemInfos);
writeStatFiles(procfsRootDir, newPids, newProcInfos, newMemInfos);
// check memory includes the new process.
processTree.updateProcessTree();
Assert.assertEquals("Cumulative vmem does not include new process",
1200000L, processTree.getCumulativeVmem());
if (!smapEnabled) {
long cumuRssMem =
ProcfsBasedProcessTree.PAGE_SIZE > 0
? 1200L * ProcfsBasedProcessTree.PAGE_SIZE : 0L;
Assert.assertEquals("Cumulative rssmem does not include new process",
cumuRssMem, processTree.getCumulativeRssmem());
} else {
Assert.assertEquals("Cumulative rssmem does not include new process",
100 * KB_TO_BYTES * 4, processTree.getCumulativeRssmem());
}
// however processes older than 1 iteration will retain the older value
Assert.assertEquals(
"Cumulative vmem shouldn't have included new process", 700000L,
processTree.getCumulativeVmem(1));
if (!smapEnabled) {
long cumuRssMem =
ProcfsBasedProcessTree.PAGE_SIZE > 0
? 700L * ProcfsBasedProcessTree.PAGE_SIZE : 0L;
Assert.assertEquals(
"Cumulative rssmem shouldn't have included new process", cumuRssMem,
processTree.getCumulativeRssmem(1));
} else {
Assert.assertEquals(
"Cumulative rssmem shouldn't have included new process",
100 * KB_TO_BYTES * 3, processTree.getCumulativeRssmem(1));
}
// one more process
newPids = new String[] { "600" };
setupPidDirs(procfsRootDir, newPids);
newProcInfos = new ProcessStatInfo[1];
newProcInfos[0] =
new ProcessStatInfo(new String[] { "600", "proc6", "100", "100",
"100", "600000", "600" });
newMemInfos = new ProcessTreeSmapMemInfo[1];
newMemInfos[0] = new ProcessTreeSmapMemInfo("600");
createMemoryMappingInfo(newMemInfos);
writeStatFiles(procfsRootDir, newPids, newProcInfos, newMemInfos);
// refresh process tree
processTree.updateProcessTree();
// processes older than 2 iterations should be same as before.
Assert.assertEquals(
"Cumulative vmem shouldn't have included new processes", 700000L,
processTree.getCumulativeVmem(2));
if (!smapEnabled) {
long cumuRssMem =
ProcfsBasedProcessTree.PAGE_SIZE > 0
? 700L * ProcfsBasedProcessTree.PAGE_SIZE : 0L;
Assert.assertEquals(
"Cumulative rssmem shouldn't have included new processes",
cumuRssMem, processTree.getCumulativeRssmem(2));
} else {
Assert.assertEquals(
"Cumulative rssmem shouldn't have included new processes",
100 * KB_TO_BYTES * 3, processTree.getCumulativeRssmem(2));
}
// processes older than 1 iteration should not include new process,
// but include process 500
Assert.assertEquals(
"Cumulative vmem shouldn't have included new processes", 1200000L,
processTree.getCumulativeVmem(1));
if (!smapEnabled) {
long cumuRssMem =
ProcfsBasedProcessTree.PAGE_SIZE > 0
? 1200L * ProcfsBasedProcessTree.PAGE_SIZE : 0L;
Assert.assertEquals(
"Cumulative rssmem shouldn't have included new processes",
cumuRssMem, processTree.getCumulativeRssmem(1));
} else {
Assert.assertEquals(
"Cumulative rssmem shouldn't have included new processes",
100 * KB_TO_BYTES * 4, processTree.getCumulativeRssmem(1));
}
// no processes older than 3 iterations, this should be 0
Assert.assertEquals(
"Getting non-zero vmem for processes older than 3 iterations", 0L,
processTree.getCumulativeVmem(3));
Assert.assertEquals(
"Getting non-zero rssmem for processes older than 3 iterations", 0L,
processTree.getCumulativeRssmem(3));
Assert.assertEquals(
"Getting non-zero rssmem for processes older than 3 iterations", 0L,
processTree.getCumulativeRssmem(3));
} finally {
FileUtil.fullyDelete(procfsRootDir);
}
}
/**
* Verifies ProcfsBasedProcessTree.checkPidPgrpidForMatch() in case of
* 'constructProcessInfo() returning null' by not writing stat file for the
* mock process
*
* @throws IOException
* if there was a problem setting up the fake procfs directories or
* files.
*/
@Test(timeout = 30000)
public void testDestroyProcessTree() throws IOException {
// test process
String pid = "100";
// create the fake procfs root directory.
File procfsRootDir = new File(TEST_ROOT_DIR, "proc");
try {
setupProcfsRootDir(procfsRootDir);
// crank up the process tree class.
createProcessTree(pid, procfsRootDir.getAbsolutePath());
// Let us not create stat file for pid 100.
Assert.assertTrue(ProcfsBasedProcessTree.checkPidPgrpidForMatch(pid,
procfsRootDir.getAbsolutePath()));
} finally {
FileUtil.fullyDelete(procfsRootDir);
}
}
/**
* Test the correctness of process-tree dump.
*
* @throws IOException
*/
@Test(timeout = 30000)
public void testProcessTreeDump() throws IOException {
String[] pids = { "100", "200", "300", "400", "500", "600" };
File procfsRootDir = new File(TEST_ROOT_DIR, "proc");
try {
setupProcfsRootDir(procfsRootDir);
setupPidDirs(procfsRootDir, pids);
int numProcesses = pids.length;
// Processes 200, 300, 400 and 500 are descendants of 100. 600 is not.
ProcessStatInfo[] procInfos = new ProcessStatInfo[numProcesses];
procInfos[0] =
new ProcessStatInfo(new String[] { "100", "proc1", "1", "100", "100",
"100000", "100", "1000", "200" });
procInfos[1] =
new ProcessStatInfo(new String[] { "200", "proc2", "100", "100",
"100", "200000", "200", "2000", "400" });
procInfos[2] =
new ProcessStatInfo(new String[] { "300", "proc3", "200", "100",
"100", "300000", "300", "3000", "600" });
procInfos[3] =
new ProcessStatInfo(new String[] { "400", "proc4", "200", "100",
"100", "400000", "400", "4000", "800" });
procInfos[4] =
new ProcessStatInfo(new String[] { "500", "proc5", "400", "100",
"100", "400000", "400", "4000", "800" });
procInfos[5] =
new ProcessStatInfo(new String[] { "600", "proc6", "1", "1", "1",
"400000", "400", "4000", "800" });
ProcessTreeSmapMemInfo[] memInfos = new ProcessTreeSmapMemInfo[6];
memInfos[0] = new ProcessTreeSmapMemInfo("100");
memInfos[1] = new ProcessTreeSmapMemInfo("200");
memInfos[2] = new ProcessTreeSmapMemInfo("300");
memInfos[3] = new ProcessTreeSmapMemInfo("400");
memInfos[4] = new ProcessTreeSmapMemInfo("500");
memInfos[5] = new ProcessTreeSmapMemInfo("600");
String[] cmdLines = new String[numProcesses];
cmdLines[0] = "proc1 arg1 arg2";
cmdLines[1] = "proc2 arg3 arg4";
cmdLines[2] = "proc3 arg5 arg6";
cmdLines[3] = "proc4 arg7 arg8";
cmdLines[4] = "proc5 arg9 arg10";
cmdLines[5] = "proc6 arg11 arg12";
createMemoryMappingInfo(memInfos);
writeStatFiles(procfsRootDir, pids, procInfos, memInfos);
writeCmdLineFiles(procfsRootDir, pids, cmdLines);
ProcfsBasedProcessTree processTree =
createProcessTree("100", procfsRootDir.getAbsolutePath());
// build the process tree.
processTree.updateProcessTree();
// Get the process-tree dump
String processTreeDump = processTree.getProcessTreeDump();
LOG.info("Process-tree dump follows: \n" + processTreeDump);
Assert.assertTrue("Process-tree dump doesn't start with a proper header",
processTreeDump.startsWith("\t|- PID PPID PGRPID SESSID CMD_NAME "
+ "USER_MODE_TIME(MILLIS) SYSTEM_TIME(MILLIS) VMEM_USAGE(BYTES) "
+ "RSSMEM_USAGE(PAGES) FULL_CMD_LINE\n"));
for (int i = 0; i < 5; i++) {
ProcessStatInfo p = procInfos[i];
Assert.assertTrue(
"Process-tree dump doesn't contain the cmdLineDump of process "
+ p.pid,
processTreeDump.contains("\t|- " + p.pid + " " + p.ppid + " "
+ p.pgrpId + " " + p.session + " (" + p.name + ") " + p.utime
+ " " + p.stime + " " + p.vmem + " " + p.rssmemPage + " "
+ cmdLines[i]));
}
// 600 should not be in the dump
ProcessStatInfo p = procInfos[5];
Assert.assertFalse(
"Process-tree dump shouldn't contain the cmdLineDump of process "
+ p.pid,
processTreeDump.contains("\t|- " + p.pid + " " + p.ppid + " "
+ p.pgrpId + " " + p.session + " (" + p.name + ") " + p.utime + " "
+ p.stime + " " + p.vmem + " " + cmdLines[5]));
} finally {
FileUtil.fullyDelete(procfsRootDir);
}
}
protected static boolean isSetsidAvailable() {
ShellCommandExecutor shexec = null;
boolean setsidSupported = true;
try {
String[] args = { "setsid", "bash", "-c", "echo $$" };
shexec = new ShellCommandExecutor(args);
shexec.execute();
} catch (IOException ioe) {
LOG.warn("setsid is not available on this machine. So not using it.");
setsidSupported = false;
} finally { // handle the exit code
LOG.info("setsid exited with exit code " + shexec.getExitCode());
}
return setsidSupported;
}
/**
* Is the root-process alive? Used only in tests.
*
* @return true if the root-process is alive, false otherwise.
*/
private static boolean isAlive(String pid) {
try {
final String sigpid = isSetsidAvailable() ? "-" + pid : pid;
try {
sendSignal(sigpid, 0);
} catch (ExitCodeException e) {
return false;
}
return true;
} catch (IOException ignored) {
}
return false;
}
private static void sendSignal(String pid, int signal) throws IOException {
ShellCommandExecutor shexec = null;
String[] arg = { "kill", "-" + signal, pid };
shexec = new ShellCommandExecutor(arg);
shexec.execute();
}
/**
* Is any of the subprocesses in the process-tree alive? Used only in tests.
*
* @return true if any of the processes in the process-tree is alive, false
* otherwise.
*/
private static boolean isAnyProcessInTreeAlive(
ProcfsBasedProcessTree processTree) {
for (String pId : processTree.getCurrentProcessIDs()) {
if (isAlive(pId)) {
return true;
}
}
return false;
}
/**
* Create a directory to mimic the procfs file system's root.
*
* @param procfsRootDir
* root directory to create.
* @throws IOException
* if could not delete the procfs root directory
*/
public static void setupProcfsRootDir(File procfsRootDir) throws IOException {
// cleanup any existing process root dir.
if (procfsRootDir.exists()) {
Assert.assertTrue(FileUtil.fullyDelete(procfsRootDir));
}
// create afresh
Assert.assertTrue(procfsRootDir.mkdirs());
}
/**
* Create PID directories under the specified procfs root directory
*
* @param procfsRootDir
* root directory of procfs file system
* @param pids
* the PID directories to create.
* @throws IOException
* If PID dirs could not be created
*/
public static void setupPidDirs(File procfsRootDir, String[] pids)
throws IOException {
for (String pid : pids) {
File pidDir = new File(procfsRootDir, pid);
pidDir.mkdir();
if (!pidDir.exists()) {
throw new IOException("couldn't make process directory under "
+ "fake procfs");
} else {
LOG.info("created pid dir");
}
}
}
/**
* Write stat files under the specified pid directories with data setup in the
* corresponding ProcessStatInfo objects
*
* @param procfsRootDir
* root directory of procfs file system
* @param pids
* the PID directories under which to create the stat file
* @param procs
* corresponding ProcessStatInfo objects whose data should be written
* to the stat files.
* @throws IOException
* if stat files could not be written
*/
public static void writeStatFiles(File procfsRootDir, String[] pids,
ProcessStatInfo[] procs, ProcessTreeSmapMemInfo[] smaps)
throws IOException {
for (int i = 0; i < pids.length; i++) {
File statFile =
new File(new File(procfsRootDir, pids[i]),
ProcfsBasedProcessTree.PROCFS_STAT_FILE);
BufferedWriter bw = null;
try {
FileWriter fw = new FileWriter(statFile);
bw = new BufferedWriter(fw);
bw.write(procs[i].getStatLine());
LOG.info("wrote stat file for " + pids[i] + " with contents: "
+ procs[i].getStatLine());
} finally {
// not handling exception - will throw an error and fail the test.
if (bw != null) {
bw.close();
}
}
if (smaps != null) {
File smapFile =
new File(new File(procfsRootDir, pids[i]),
ProcfsBasedProcessTree.SMAPS);
bw = null;
try {
FileWriter fw = new FileWriter(smapFile);
bw = new BufferedWriter(fw);
bw.write(smaps[i].toString());
bw.flush();
LOG.info("wrote smap file for " + pids[i] + " with contents: "
+ smaps[i].toString());
} finally {
// not handling exception - will throw an error and fail the test.
if (bw != null) {
bw.close();
}
}
}
}
}
private static void writeCmdLineFiles(File procfsRootDir, String[] pids,
String[] cmdLines) throws IOException {
for (int i = 0; i < pids.length; i++) {
File statFile =
new File(new File(procfsRootDir, pids[i]),
ProcfsBasedProcessTree.PROCFS_CMDLINE_FILE);
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(statFile));
bw.write(cmdLines[i]);
LOG.info("wrote command-line file for " + pids[i] + " with contents: "
+ cmdLines[i]);
} finally {
// not handling exception - will throw an error and fail the test.
if (bw != null) {
bw.close();
}
}
}
}
}
|
apache/tomcat | 35,271 | test/org/apache/catalina/connector/TestRequest.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.catalina.connector;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.authenticator.BasicAuthenticator;
import org.apache.catalina.startup.SimpleHttpClient;
import org.apache.catalina.startup.TesterMapRealm;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.unittest.TesterRequest;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.EncodedSolidusHandling;
import org.apache.tomcat.util.buf.StringUtils;
import org.apache.tomcat.util.descriptor.web.LoginConfig;
import org.apache.tomcat.util.http.Method;
/**
* Test case for {@link Request}.
*/
public class TestRequest extends TomcatBaseTest {
/**
* Test case for https://bz.apache.org/bugzilla/show_bug.cgi?id=37794 POST parameters are not returned from a call
* to any of the {@link HttpServletRequest} getParameterXXX() methods if the request is chunked.
*/
@Test
public void testBug37794() {
Bug37794Client client = new Bug37794Client();
// Edge cases around zero
client.doRequest(-1, false); // Unlimited
Assert.assertTrue(client.isResponse200());
Assert.assertTrue(client.isResponseBodyOK());
client.reset();
client.doRequest(0, false); // 0 bytes - too small should fail
Assert.assertTrue(client.isResponse413());
client.reset();
client.doRequest(1, false); // 1 byte - too small should fail
Assert.assertTrue(client.isResponse413());
// Edge cases around actual content length
client.reset();
client.doRequest(6, false); // Too small should fail
Assert.assertTrue(client.isResponse413());
client.reset();
client.doRequest(7, false); // Just enough should pass
Assert.assertTrue(client.isResponse200());
Assert.assertTrue(client.isResponseBodyOK());
client.reset();
client.doRequest(8, false); // 1 extra - should pass
Assert.assertTrue(client.isResponse200());
Assert.assertTrue(client.isResponseBodyOK());
// Much larger
client.reset();
client.doRequest(8096, false); // Plenty of space - should pass
Assert.assertTrue(client.isResponse200());
Assert.assertTrue(client.isResponseBodyOK());
// Check for case insensitivity
client.reset();
client.doRequest(8096, true); // Plenty of space - should pass
Assert.assertTrue(client.isResponse200());
Assert.assertTrue(client.isResponseBodyOK());
}
private static class Bug37794Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Only interested in the parameters and values for POST requests.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Just echo the parameters and values back as plain text
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
// Assume one value per attribute
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
out.println(name + "=" + req.getParameter(name));
}
}
}
/**
* Bug 37794 test client.
*/
private class Bug37794Client extends SimpleHttpClient {
private boolean init;
private synchronized void init() throws Exception {
if (init) {
return;
}
Tomcat tomcat = getTomcatInstance();
Context root = tomcat.addContext("", TEMP_DIR);
Tomcat.addServlet(root, "Bug37794", new Bug37794Servlet());
root.addServletMappingDecoded("/test", "Bug37794");
tomcat.start();
setPort(tomcat.getConnector().getLocalPort());
init = true;
}
private Exception doRequest(int postLimit, boolean ucChunkedHead) {
Tomcat tomcat = getTomcatInstance();
try {
init();
tomcat.getConnector().setMaxPostSize(postLimit);
// Open connection
connect();
// Send request in two parts
String[] request = new String[2];
if (ucChunkedHead) {
// @formatter:off
request[0] =
"POST http://localhost:8080/test HTTP/1.1" + CRLF +
"Host: localhost:8080" + CRLF +
SimpleHttpClient.HTTP_HEADER_CONTENT_TYPE_FORM_URL_ENCODING +
"Transfer-Encoding: CHUNKED" + CRLF +
"Connection: close" + CRLF +
CRLF +
"3" + CRLF +
"a=1" + CRLF;
// @formatter:on
} else {
// @formatter:off
request[0] =
"POST http://localhost:8080/test HTTP/1.1" + CRLF +
"Host: localhost:8080" + CRLF +
SimpleHttpClient.HTTP_HEADER_CONTENT_TYPE_FORM_URL_ENCODING +
"Transfer-Encoding: chunked" + CRLF +
"Connection: close" + CRLF +
CRLF +
"3" + CRLF +
"a=1" + CRLF;
// @formatter:on
}
// @formatter:off
request[1] =
"4" + CRLF +
"&b=2" + CRLF +
"0" + CRLF +
CRLF;
// @formatter:on
setRequest(request);
processRequest(); // blocks until response has been read
// Close the connection
disconnect();
} catch (Exception e) {
return e;
}
return null;
}
@Override
public boolean isResponseBodyOK() {
if (getResponseBody() == null) {
return false;
}
if (!getResponseBody().contains("a=1")) {
return false;
}
if (!getResponseBody().contains("b=2")) {
return false;
}
return true;
}
}
/*
* Test case for <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=38113">bug 38118</a>.
*/
@Test
public void testBug38113() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = getProgrammaticRootContext();
// Add the Servlet
Tomcat.addServlet(ctx, "servlet", new EchoQueryStringServlet());
ctx.addServletMappingDecoded("/", "servlet");
tomcat.start();
// No query string
ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
Assert.assertEquals("QueryString=null", res.toString());
// Query string
res = getUrl("http://localhost:" + getPort() + "/?a=b");
Assert.assertEquals("QueryString=a=b", res.toString());
// Empty string
res = getUrl("http://localhost:" + getPort() + "/?");
Assert.assertEquals("QueryString=", res.toString());
}
private static final class EchoQueryStringServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
PrintWriter pw = resp.getWriter();
pw.print("QueryString=" + req.getQueryString());
}
}
/*
* Test case for {@link Request#login(String, String)} and {@link Request#logout()}.
*/
@Test
public void testLoginLogout() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = getProgrammaticRootContext();
LoginConfig config = new LoginConfig();
config.setAuthMethod("BASIC");
ctx.setLoginConfig(config);
ctx.getPipeline().addValve(new BasicAuthenticator());
Tomcat.addServlet(ctx, "servlet", new LoginLogoutServlet());
ctx.addServletMappingDecoded("/", "servlet");
TesterMapRealm realm = new TesterMapRealm();
realm.addUser(LoginLogoutServlet.USER, LoginLogoutServlet.PWD);
ctx.setRealm(realm);
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
Assert.assertEquals(LoginLogoutServlet.OK, res.toString());
}
private static final class LoginLogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String USER = "user";
private static final String PWD = "pwd";
private static final String OK = "OK";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.login(USER, PWD);
if (!req.getRemoteUser().equals(USER)) {
throw new ServletException();
}
if (!req.getUserPrincipal().getName().equals(USER)) {
throw new ServletException();
}
req.logout();
if (req.getRemoteUser() != null) {
throw new ServletException();
}
if (req.getUserPrincipal() != null) {
throw new ServletException();
}
resp.getWriter().write(OK);
}
}
@Test
public void testBug49424NoChunking() throws Exception {
Tomcat tomcat = getTomcatInstance();
Context root = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
Tomcat.addServlet(root, "Bug37794", new Bug37794Servlet());
root.addServletMappingDecoded("/", "Bug37794");
tomcat.start();
HttpURLConnection conn = getConnection("http://localhost:" + getPort() + "/");
InputStream is = conn.getInputStream();
Assert.assertNotNull(is);
}
@Test
public void testBug49424WithChunking() throws Exception {
Tomcat tomcat = getTomcatInstance();
Context root = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
Tomcat.addServlet(root, "Bug37794", new Bug37794Servlet());
root.addServletMappingDecoded("/", "Bug37794");
tomcat.start();
HttpURLConnection conn = getConnection("http://localhost:" + getPort() + "/");
conn.setChunkedStreamingMode(8 * 1024);
InputStream is = conn.getInputStream();
Assert.assertNotNull(is);
}
/**
* Test case for https://bz.apache.org/bugzilla/show_bug.cgi?id=48692 PUT requests should be able to fetch request
* parameters coming from the request body (when properly configured using the new parseBodyMethod setting).
*/
@Test
public void testBug48692() {
Bug48692Client client = new Bug48692Client();
// Make sure GET works properly
client.doRequest(Method.GET, "foo=bar", null, null, false);
Assert.assertTrue("Non-200 response for GET request", client.isResponse200());
Assert.assertEquals("Incorrect response for GET request", "foo=bar", client.getResponseBody());
client.reset();
//
// Make sure POST works properly
//
// POST with separate GET and POST parameters
client.doRequest(Method.POST, "foo=bar", Globals.CONTENT_TYPE_FORM_URL_ENCODING, "bar=baz", true);
Assert.assertTrue("Non-200 response for POST request", client.isResponse200());
Assert.assertEquals("Incorrect response for POST request", "bar=baz,foo=bar", client.getResponseBody());
client.reset();
// POST with overlapping GET and POST parameters
client.doRequest(Method.POST, "foo=bar&bar=foo", Globals.CONTENT_TYPE_FORM_URL_ENCODING, "bar=baz&foo=baz", true);
Assert.assertTrue("Non-200 response for POST request", client.isResponse200());
Assert.assertEquals("Incorrect response for POST request", "bar=baz,bar=foo,foo=bar,foo=baz",
client.getResponseBody());
client.reset();
// PUT without POST-style parsing
client.doRequest(Method.PUT, "foo=bar&bar=foo", Globals.CONTENT_TYPE_FORM_URL_ENCODING, "bar=baz&foo=baz", false);
Assert.assertTrue("Non-200 response for PUT/noparse request", client.isResponse200());
Assert.assertEquals("Incorrect response for PUT request", "bar=foo,foo=bar", client.getResponseBody());
client.reset();
// PUT with POST-style parsing
client.doRequest(Method.PUT, "foo=bar&bar=foo", Globals.CONTENT_TYPE_FORM_URL_ENCODING, "bar=baz&foo=baz", true);
Assert.assertTrue("Non-200 response for PUT request", client.isResponse200());
Assert.assertEquals("Incorrect response for PUT/parse request", "bar=baz,bar=foo,foo=bar,foo=baz",
client.getResponseBody());
client.reset();
}
@Test
public void testBug54984() throws Exception {
Tomcat tomcat = getTomcatInstance();
Context root = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
root.setAllowCasualMultipartParsing(true);
Tomcat.addServlet(root, "Bug54984", new Bug54984Servlet());
root.addServletMappingDecoded("/", "Bug54984");
tomcat.start();
HttpURLConnection conn = getConnection("http://localhost:" + getPort() + "/parseParametersBeforeParseParts");
prepareMultiPartRequest(conn);
checkResponseBug54984(conn);
conn.disconnect();
conn = getConnection("http://localhost:" + getPort() + "/");
prepareMultiPartRequest(conn);
checkResponseBug54984(conn);
conn.disconnect();
}
/**
*
*/
private static class EchoParametersServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Only interested in the parameters and values for requests. Note: echos parameters in alphabetical order.
*/
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Just echo the parameters and values back as plain text
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
TreeMap<String,String[]> parameters = new TreeMap<>(req.getParameterMap());
boolean first = true;
for (String name : parameters.keySet()) {
String[] values = req.getParameterValues(name);
Arrays.sort(values);
for (String value : values) {
if (first) {
first = false;
} else {
out.print(",");
}
out.print(name + "=" + value);
}
}
}
}
/**
* Bug 48692 test client: test for allowing PUT request bodies.
*/
private class Bug48692Client extends SimpleHttpClient {
private boolean init;
private synchronized void init() throws Exception {
if (init) {
return;
}
Tomcat tomcat = getTomcatInstance();
Context root = tomcat.addContext("", TEMP_DIR);
Tomcat.addServlet(root, "EchoParameters", new EchoParametersServlet());
root.addServletMappingDecoded("/echo", "EchoParameters");
tomcat.start();
setPort(tomcat.getConnector().getLocalPort());
init = true;
}
private Exception doRequest(String method, String queryString, String contentType, String requestBody,
boolean allowBody) {
Tomcat tomcat = getTomcatInstance();
try {
init();
if (allowBody) {
tomcat.getConnector().setParseBodyMethods(method);
} else {
tomcat.getConnector().setParseBodyMethods(""); // never parse
}
// Open connection
connect();
// Re-encode the request body so that bytes = characters
if (null != requestBody) {
requestBody = new String(requestBody.getBytes("UTF-8"), "ASCII");
}
// Send specified request body using method
// @formatter:off
String[] request = {
method + " http://localhost:" + getPort() + "/echo" +
(null == queryString ? "" : ("?" + queryString)) + " HTTP/1.1" + CRLF +
"Host: localhost:" + getPort() + CRLF +
(null == contentType ? "" : ("Content-Type: " + contentType + CRLF)) +
"Connection: close" + CRLF +
(null == requestBody ? "" : "Content-Length: " + requestBody.length() + CRLF) +
CRLF +
(null == requestBody ? "" : requestBody)
};
// @formatter:on
setRequest(request);
processRequest(); // blocks until response has been read
// Close the connection
disconnect();
} catch (Exception e) {
return e;
}
return null;
}
@Override
public boolean isResponseBodyOK() {
return false; // Don't care
}
}
private HttpURLConnection getConnection(String query) throws IOException {
URL postURL;
postURL = URI.create(query).toURL();
HttpURLConnection conn = (HttpURLConnection) postURL.openConnection();
conn.setRequestMethod(Method.POST);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
return conn;
}
private static class Bug54984Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
if (req.getRequestURI().endsWith("parseParametersBeforeParseParts")) {
req.getParameterNames();
}
req.getPart("part");
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().println("Part " + req.getParameter("part"));
}
}
private void prepareMultiPartRequest(HttpURLConnection conn) throws Exception {
String boundary = "-----" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
PrintWriter writer = new PrintWriter(osw, true)) {
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"part\"\r\n");
writer.append("Content-Type: text/plain; charset=UTF-8\r\n");
writer.append("\r\n");
writer.append("äö").append("\r\n");
writer.flush();
writer.append("\r\n");
writer.flush();
writer.append("--" + boundary + "--").append("\r\n");
}
}
private void checkResponseBug54984(HttpURLConnection conn) throws Exception {
List<String> response = new ArrayList<>();
int status = conn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
try (InputStreamReader isr = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(isr)) {
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
Assert.assertTrue(response.contains("Part äö"));
}
} else {
Assert.fail("OK status was expected: " + status);
}
}
@Test
public void testBug56501a() throws Exception {
doBug56501("/path", "/path", "/path");
}
@Test
public void testBug56501b() throws Exception {
doBug56501("/path", "/path/", "/path");
}
@Test
public void testBug56501c() throws Exception {
doBug56501("/path", "/path/xxx", "/path");
}
@Test
public void testBug56501d() throws Exception {
doBug56501("", "", "");
}
@Test
public void testBug56501e() throws Exception {
doBug56501("", "/", "");
}
@Test
public void testBug56501f() throws Exception {
doBug56501("", "/xxx", "");
}
@Test
public void testBug56501g() throws Exception {
doBug56501("/path/abc", "/path/abc", "/path/abc");
}
@Test
public void testBug56501h() throws Exception {
doBug56501("/path/abc", "/path/abc/", "/path/abc");
}
@Test
public void testBug56501i() throws Exception {
doBug56501("/path/abc", "/path/abc/xxx", "/path/abc");
}
@Test
public void testBug56501j() throws Exception {
doBug56501("/pa_th/abc", "/pa%5Fth/abc", "/pa_th/abc");
}
@Test
public void testBug56501k() throws Exception {
doBug56501("/pa_th/abc", "/pa%5Fth/abc/", "/pa_th/abc");
}
@Test
public void testBug56501l() throws Exception {
doBug56501("/pa_th/abc", "/pa%5Fth/abc/xxx", "/pa_th/abc");
}
@Test
public void testBug56501m() throws Exception {
doBug56501("/pa_th/abc", "/pa_th/abc", "/pa_th/abc");
}
@Test
public void testBug56501n() throws Exception {
doBug56501("/pa_th/abc", "/pa_th/abc/", "/pa_th/abc");
}
@Test
public void testBug56501o() throws Exception {
doBug56501("/pa_th/abc", "/pa_th/abc/xxx", "/pa_th/abc");
}
@Test
public void testBug56501p() throws Exception {
doBug56501("/path/abc", "/path;a=b/abc/xxx", "/path/abc");
}
@Test
public void testBug56501q() throws Exception {
doBug56501("/path/abc", "/path/abc;a=b/xxx", "/path/abc");
}
@Test
public void testBug56501r() throws Exception {
doBug56501("/path/abc", "/path/abc/xxx;a=b", "/path/abc");
}
@Test
public void testBug56501s() throws Exception {
doBug56501("/path/abc", "/.;a=b/path/abc/xxx", "/path/abc");
}
@Test
public void testBug57215a() throws Exception {
doBug56501("/path", "//path", "/path");
}
@Test
public void testBug57215b() throws Exception {
doBug56501("/path", "//path/", "/path");
}
@Test
public void testBug57215c() throws Exception {
doBug56501("/path", "/%2Fpath", "/path", EncodedSolidusHandling.DECODE);
}
@Test
public void testBug57215d() throws Exception {
doBug56501("/path", "/%2Fpath%2F", "/path", EncodedSolidusHandling.DECODE);
}
@Test
public void testBug57215e() throws Exception {
doBug56501("/path", "/foo/../path", "/path");
}
@Test
public void testBug57215f() throws Exception {
doBug56501("/path", "/foo/..%2fpath", "/path", EncodedSolidusHandling.DECODE);
}
private void doBug56501(String deployPath, String requestPath, String expected) throws Exception {
doBug56501(deployPath, requestPath, expected, EncodedSolidusHandling.REJECT);
}
private void doBug56501(String deployPath, String requestPath, String expected,
EncodedSolidusHandling encodedSolidusHandling) throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
tomcat.getConnector().setEncodedSolidusHandling(encodedSolidusHandling.getValue());
// No file system docBase required
Context ctx = tomcat.addContext(deployPath, null);
ctx.setAllowMultipleLeadingForwardSlashInPath(true);
Tomcat.addServlet(ctx, "servlet", new Bug56501Servlet());
ctx.addServletMappingDecoded("/*", "servlet");
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() + requestPath);
String resultPath = res.toString();
if (resultPath == null) {
resultPath = "";
}
Assert.assertEquals(expected, resultPath);
}
private static class Bug56501Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
resp.getWriter().print(req.getContextPath());
}
}
@Test
public void getLocaleMultipleHeaders01() throws Exception {
TesterRequest req = new TesterRequest();
req.addHeader("accept-language", "en;q=0.5");
req.addHeader("accept-language", "en-gb");
Locale actual = req.getLocale();
Locale expected = Locale.forLanguageTag("en-gb");
Assert.assertEquals(expected, actual);
}
/*
* Reverse header order of getLocaleMultipleHeaders01() and make sure the result is the same.
*/
@Test
public void getLocaleMultipleHeaders02() throws Exception {
TesterRequest req = new TesterRequest();
req.addHeader("accept-language", "en-gb");
req.addHeader("accept-language", "en;q=0.5");
Locale actual = req.getLocale();
Locale expected = Locale.forLanguageTag("en-gb");
Assert.assertEquals(expected, actual);
}
@Test
public void testGetReaderValidEncoding() throws Exception {
doTestGetReader("ISO-8859-1", true);
}
@Test
public void testGetReaderInvalidEncoding() throws Exception {
doTestGetReader("X-Invalid", false);
}
private void doTestGetReader(String userAgentCharacterEncoding, boolean expect200) throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = getProgrammaticRootContext();
Tomcat.addServlet(ctx, "servlet", new Bug61264GetReaderServlet());
ctx.addServletMappingDecoded("/", "servlet");
tomcat.start();
Charset charset = StandardCharsets.ISO_8859_1;
try {
charset = Charset.forName(userAgentCharacterEncoding);
} catch (UnsupportedCharsetException e) {
// Ignore - use default set above
}
byte[] body = "Test".getBytes(charset);
ByteChunk bc = new ByteChunk();
Map<String,List<String>> reqHeaders = new HashMap<>();
reqHeaders.put("Content-Type",
Arrays.asList(new String[] { "text/plain;charset=" + userAgentCharacterEncoding }));
int rc = postUrl(body, "http://localhost:" + getPort() + "/", bc, reqHeaders, null);
if (expect200) {
Assert.assertEquals(200, rc);
} else {
Assert.assertEquals(500, rc);
}
}
private static class Bug61264GetReaderServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// This is intended for POST requests
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Container will handle any errors
req.getReader();
}
}
/*
* https://bz.apache.org/bugzilla/show_bug.cgi?id=69442
*/
@Test
public void testTestParameterMediaTypeLowerCase() throws Exception {
// toLowerCase() is unnecessary but keep it in case the constant is changed in the future
doTestParameterMediaTypeCase(Globals.CONTENT_TYPE_FORM_URL_ENCODING.toLowerCase(Locale.ENGLISH));
}
/*
* https://bz.apache.org/bugzilla/show_bug.cgi?id=69442
*/
@Test
public void testTestParameterMediaTypeUpperCase() throws Exception {
doTestParameterMediaTypeCase(Globals.CONTENT_TYPE_FORM_URL_ENCODING.toUpperCase(Locale.ENGLISH));
}
private void doTestParameterMediaTypeCase(String contentType) throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = getProgrammaticRootContext();
Tomcat.addServlet(ctx, "servlet", new Bug69442Servlet());
ctx.addServletMappingDecoded("/", "servlet");
tomcat.start();
ByteChunk bc = new ByteChunk();
Map<String,List<String>> reqHeaders = new HashMap<>();
reqHeaders.put("Content-Type", Arrays.asList(contentType));
postUrl("a=b&c=d".getBytes(), "http://localhost:" + getPort() + "/", bc, reqHeaders, null);
String responseBody = bc.toString();
Assert.assertTrue(responseBody, responseBody.contains("a=b"));
Assert.assertTrue(responseBody, responseBody.contains("c=d"));
}
private static class Bug69442Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
resp.setCharacterEncoding(StandardCharsets.UTF_8);
PrintWriter pw = resp.getWriter();
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String[] values = req.getParameterValues(name);
pw.println(name + "=" + StringUtils.join(values));
}
}
}
/*
* getParameter should work with a multipart/form-data request if there is no multipart config.
*/
@Test
public void testBug69690a() throws Exception {
Tomcat tomcat = getTomcatInstance();
Context ctx = getProgrammaticRootContext();
Tomcat.addServlet(ctx, "Bug69690", new Bug69690Servlet());
ctx.addServletMappingDecoded("/", "Bug69690");
tomcat.start();
HttpURLConnection conn = getConnection("http://localhost:" + getPort() + "/parameter?a=b");
prepareMultiPartRequest(conn);
List<String> response = new ArrayList<>();
int status = conn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
try (InputStreamReader isr = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(isr)) {
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
Assert.assertTrue(response.contains("OK"));
}
} else {
Assert.fail("OK status was expected: " + status);
}
conn.disconnect();
}
/*
* getPart should not work with a multipart/form-data request if there is no multipart config.
*/
@Test
public void testBug69690b() throws Exception {
Tomcat tomcat = getTomcatInstance();
Context ctx = getProgrammaticRootContext();
Tomcat.addServlet(ctx, "Bug69690", new Bug69690Servlet());
ctx.addServletMappingDecoded("/", "Bug69690");
tomcat.start();
HttpURLConnection conn = getConnection("http://localhost:" + getPort() + "/part?a=b");
prepareMultiPartRequest(conn);
Assert.assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, conn.getResponseCode());
conn.disconnect();
}
private class Bug69690Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding(StandardCharsets.UTF_8);
resp.setContentType("text/plain");
PrintWriter pw = resp.getWriter();
if (req.getRequestURI().endsWith("/parameter")) {
if ("b".equals(req.getParameter("a"))) {
pw.print("OK");
} else {
pw.print("FAIL - Parameter 'a' not set to 'b'");
}
} else {
// This should trigger an error since the servlet does not have a multi-part configuration.
req.getPart("any");
}
}
}
}
|
apache/ofbiz | 35,435 | applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayServices.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.accounting.thirdparty.sagepay;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.UtilProperties;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.service.DispatchContext;
import org.apache.ofbiz.service.ModelService;
import org.apache.ofbiz.service.ServiceUtil;
public class SagePayServices
{
public static final String module = SagePayServices.class.getName();
public static final String resource = "AccountingUiLabels";
private static Map<String, String> buildSagePayProperties(Map<String, Object> context, Delegator delegator) {
Map<String, String> sagePayConfig = new HashMap<String, String>();
String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId");
if (UtilValidate.isNotEmpty(paymentGatewayConfigId)) {
try {
GenericValue sagePay = EntityQuery.use(delegator).from("PaymentGatewaySagePay").where("paymentGatewayConfigId", paymentGatewayConfigId).queryOne();
if (sagePay != null) {
Map<String, Object> tmp = sagePay.getAllFields();
Set<String> keys = tmp.keySet();
for (String key : keys) {
String value = tmp.get(key).toString();
sagePayConfig.put(key, value);
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
Debug.logInfo("SagePay Configuration : " + sagePayConfig.toString(), module);
return sagePayConfig;
}
public static Map<String, Object> paymentAuthentication(DispatchContext ctx, Map<String, Object> context) {
Debug.logInfo("SagePay - Entered paymentAuthentication", module);
Debug.logInfo("SagePay paymentAuthentication context : " + context, module);
Delegator delegator = ctx.getDelegator();
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, String> props = buildSagePayProperties(context, delegator);
String vendorTxCode = (String)context.get("vendorTxCode");
String cardHolder = (String) context.get("cardHolder");
String cardNumber = (String) context.get("cardNumber");
String expiryDate = (String) context.get("expiryDate");
String cardType = (String) context.get("cardType");
String cv2 = (String) context.get("cv2");
String amount = (String) context.get("amount");
String currency = (String) context.get("currency");
String description = (String) context.get("description");
String billingSurname = (String) context.get("billingSurname");
String billingFirstnames = (String) context.get("billingFirstnames");
String billingAddress = (String) context.get("billingAddress");
String billingAddress2 = (String) context.get("billingAddress2");
String billingCity = (String) context.get("billingCity");
String billingPostCode = (String) context.get("billingPostCode");
String billingCountry = (String) context.get("billingCountry");
String billingState = (String) context.get("billingState");
String billingPhone = (String) context.get("billingPhone");
Boolean isBillingSameAsDelivery = (Boolean) context.get("isBillingSameAsDelivery");
String deliverySurname = (String) context.get("deliverySurname");
String deliveryFirstnames = (String) context.get("deliveryFirstnames");
String deliveryAddress = (String) context.get("deliveryAddress");
String deliveryAddress2 = (String) context.get("deliveryAddress2");
String deliveryCity = (String) context.get("deliveryCity");
String deliveryPostCode = (String) context.get("deliveryPostCode");
String deliveryCountry = (String) context.get("deliveryCountry");
String deliveryState = (String) context.get("deliveryState");
String deliveryPhone = (String) context.get("deliveryPhone");
String startDate = (String) context.get("startDate");
String issueNumber = (String) context.get("issueNumber");
String basket = (String) context.get("basket");
String clientIPAddress = (String) context.get("clientIPAddress");
Locale locale = (Locale) context.get("locale");
HttpHost host = SagePayUtil.getHost(props);
//start - authentication parameters
Map<String, String> parameters = new HashMap<String, String>();
String vpsProtocol = props.get("protocolVersion");
String vendor = props.get("vendor");
String txType = props.get("authenticationTransType");
//start - required parameters
parameters.put("VPSProtocol", vpsProtocol);
parameters.put("TxType", txType);
parameters.put("Vendor", vendor);
if (vendorTxCode != null) { parameters.put("VendorTxCode", vendorTxCode); }
if (amount != null) { parameters.put("Amount", amount); }
if (currency != null) { parameters.put("Currency", currency); } //GBP/USD
if (description != null) { parameters.put("Description", description); }
if (cardHolder != null) { parameters.put("CardHolder", cardHolder); }
if (cardNumber != null) { parameters.put("CardNumber", cardNumber); }
if (expiryDate != null) { parameters.put("ExpiryDate", expiryDate); }
if (cardType != null) { parameters.put("CardType", cardType); }
//start - billing details
if (billingSurname != null) { parameters.put("BillingSurname", billingSurname); }
if (billingFirstnames != null) { parameters.put("BillingFirstnames", billingFirstnames); }
if (billingAddress != null) { parameters.put("BillingAddress", billingAddress); }
if (billingAddress2 != null) { parameters.put("BillingAddress2", billingAddress2); }
if (billingCity != null) { parameters.put("BillingCity", billingCity); }
if (billingPostCode != null) { parameters.put("BillingPostCode", billingPostCode); }
if (billingCountry != null) { parameters.put("BillingCountry", billingCountry); }
if (billingState != null) { parameters.put("BillingState", billingState); }
if (billingPhone != null) { parameters.put("BillingPhone", billingPhone); }
//end - billing details
//start - delivery details
if (isBillingSameAsDelivery != null && isBillingSameAsDelivery) {
if (billingSurname != null) { parameters.put("DeliverySurname", billingSurname); }
if (billingFirstnames != null) { parameters.put("DeliveryFirstnames", billingFirstnames); }
if (billingAddress != null) { parameters.put("DeliveryAddress", billingAddress); }
if (billingAddress2 != null) { parameters.put("DeliveryAddress2", billingAddress2); }
if (billingCity != null) { parameters.put("DeliveryCity", billingCity); }
if (billingPostCode != null) { parameters.put("DeliveryPostCode", billingPostCode); }
if (billingCountry != null) { parameters.put("DeliveryCountry", billingCountry); }
if (billingState != null) { parameters.put("DeliveryState", billingState); }
if (billingPhone != null) { parameters.put("DeliveryPhone", billingPhone); }
} else {
if (deliverySurname != null) { parameters.put("DeliverySurname", deliverySurname); }
if (deliveryFirstnames != null) { parameters.put("DeliveryFirstnames", deliveryFirstnames); }
if (deliveryAddress != null) { parameters.put("DeliveryAddress", deliveryAddress); }
if (deliveryAddress2 != null) { parameters.put("DeliveryAddress2", deliveryAddress2); }
if (deliveryCity != null) { parameters.put("DeliveryCity", deliveryCity); }
if (deliveryPostCode != null) { parameters.put("DeliveryPostCode", deliveryPostCode); }
if (deliveryCountry != null) { parameters.put("DeliveryCountry", deliveryCountry); }
if (deliveryState != null) { parameters.put("DeliveryState", deliveryState); }
if (deliveryPhone != null) {parameters.put("DeliveryPhone", deliveryPhone); }
}
//end - delivery details
//end - required parameters
//start - optional parameters
if (cv2 != null) { parameters.put("CV2", cv2); }
if (startDate != null) { parameters.put("StartDate", startDate); }
if (issueNumber != null) { parameters.put("IssueNumber", issueNumber); }
if (basket != null) { parameters.put("Basket", basket); }
if (clientIPAddress != null) { parameters.put("ClientIPAddress", clientIPAddress); }
//end - optional parameters
//end - authentication parameters
try (CloseableHttpClient httpClient = SagePayUtil.getHttpClient()) {
String successMessage = null;
HttpPost httpPost = SagePayUtil.getHttpPost(props.get("authenticationUrl"), parameters);
HttpResponse response = httpClient.execute(host, httpPost);
Map<String, String> responseData = SagePayUtil.getResponseData(response);
String status = responseData.get("Status");
String statusDetail = responseData.get("StatusDetail");
resultMap.put("status", status);
resultMap.put("statusDetail", statusDetail);
//returning the below details back to the calling code, as it not returned back by the payment gateway
resultMap.put("vendorTxCode", vendorTxCode);
resultMap.put("amount", amount);
resultMap.put("transactionType", txType);
//start - transaction authorized
if ("OK".equals(status)) {
resultMap.put("vpsTxId", responseData.get("VPSTxId"));
resultMap.put("securityKey", responseData.get("SecurityKey"));
resultMap.put("txAuthNo", responseData.get("TxAuthNo"));
resultMap.put("avsCv2", responseData.get("AVSCV2"));
resultMap.put("addressResult", responseData.get("AddressResult"));
resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
resultMap.put("cv2Result", responseData.get("CV2Result"));
successMessage = "Payment authorized";
}
//end - transaction authorized
if ("NOTAUTHED".equals(status)) {
resultMap.put("vpsTxId", responseData.get("VPSTxId"));
resultMap.put("securityKey", responseData.get("SecurityKey"));
resultMap.put("avsCv2", responseData.get("AVSCV2"));
resultMap.put("addressResult", responseData.get("AddressResult"));
resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
resultMap.put("cv2Result", responseData.get("CV2Result"));
successMessage = "Payment not authorized";
}
if ("MALFORMED".equals(status)) {
//request not formed properly or parameters missing
resultMap.put("vpsTxId", responseData.get("VPSTxId"));
resultMap.put("securityKey", responseData.get("SecurityKey"));
resultMap.put("avsCv2", responseData.get("AVSCV2"));
resultMap.put("addressResult", responseData.get("AddressResult"));
resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
resultMap.put("cv2Result", responseData.get("CV2Result"));
}
if ("INVALID".equals(status)) {
//invalid information in request
resultMap.put("vpsTxId", responseData.get("VPSTxId"));
resultMap.put("securityKey", responseData.get("SecurityKey"));
resultMap.put("avsCv2", responseData.get("AVSCV2"));
resultMap.put("addressResult", responseData.get("AddressResult"));
resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
resultMap.put("cv2Result", responseData.get("CV2Result"));
}
if ("REJECTED".equals(status)) {
//invalid information in request
resultMap.put("vpsTxId", responseData.get("VPSTxId"));
resultMap.put("securityKey", responseData.get("SecurityKey"));
resultMap.put("avsCv2", responseData.get("AVSCV2"));
resultMap.put("addressResult", responseData.get("AddressResult"));
resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
resultMap.put("cv2Result", responseData.get("CV2Result"));
}
resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage);
} catch(UnsupportedEncodingException uee) {
//exception in encoding parameters in httpPost
Debug.logError(uee, "Error occurred in encoding parameters for HttpPost (" + uee.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorEncodingParameters", UtilMisc.toMap("errorString", uee.getMessage()), locale));
} catch(ClientProtocolException cpe) {
//from httpClient execute
Debug.logError(cpe, "Error occurred in HttpClient execute(" + cpe.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorHttpClientExecute", UtilMisc.toMap("errorString", cpe.getMessage()), locale));
} catch(IOException ioe) {
//from httpClient execute or getResponsedata
Debug.logError(ioe, "Error occurred in HttpClient execute or getting response (" + ioe.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorHttpClientExecuteOrGettingResponse", UtilMisc.toMap("errorString", ioe.getMessage()), locale));
}
return resultMap;
}
public static Map<String, Object> paymentAuthorisation(DispatchContext ctx, Map<String, Object> context) {
Debug.logInfo("SagePay - Entered paymentAuthorisation", module);
Debug.logInfo("SagePay paymentAuthorisation context : " + context, module);
Delegator delegator = ctx.getDelegator();
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, String> props = buildSagePayProperties(context, delegator);
String vendorTxCode = (String)context.get("vendorTxCode");
String vpsTxId = (String) context.get("vpsTxId");
String securityKey = (String) context.get("securityKey");
String txAuthNo = (String) context.get("txAuthNo");
String amount = (String) context.get("amount");
Locale locale = (Locale) context.get("locale");
HttpHost host = SagePayUtil.getHost(props);
//start - authorization parameters
Map<String, String> parameters = new HashMap<String, String>();
String vpsProtocol = props.get("protocolVersion");
String vendor = props.get("vendor");
String txType = props.get("authoriseTransType");
parameters.put("VPSProtocol", vpsProtocol);
parameters.put("TxType", txType);
parameters.put("Vendor", vendor);
parameters.put("VendorTxCode", vendorTxCode);
parameters.put("VPSTxId", vpsTxId);
parameters.put("SecurityKey", securityKey);
parameters.put("TxAuthNo", txAuthNo);
parameters.put("ReleaseAmount", amount);
Debug.logInfo("authorization parameters -> " + parameters, module);
//end - authorization parameters
try (CloseableHttpClient httpClient = SagePayUtil.getHttpClient()) {
String successMessage = null;
HttpPost httpPost = SagePayUtil.getHttpPost(props.get("authoriseUrl"), parameters);
HttpResponse response = httpClient.execute(host, httpPost);
Map<String, String> responseData = SagePayUtil.getResponseData(response);
String status = responseData.get("Status");
String statusDetail = responseData.get("StatusDetail");
resultMap.put("status", status);
resultMap.put("statusDetail", statusDetail);
//start - payment refunded
if ("OK".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentReleased", locale);
}
//end - payment refunded
//start - refund request not formed properly or parameters missing
if ("MALFORMED".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentReleaseRequestMalformed", locale);
}
//end - refund request not formed properly or parameters missing
//start - invalid information passed in parameters
if ("INVALID".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentInvalidInformationPassed", locale);
}
//end - invalid information passed in parameters
//start - problem at Sagepay
if ("ERROR".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentError", locale);
}
//end - problem at Sagepay
resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage);
} catch(UnsupportedEncodingException uee) {
//exception in encoding parameters in httpPost
Debug.logError(uee, "Error occurred in encoding parameters for HttpPost (" + uee.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorEncodingParameters", UtilMisc.toMap("errorString", uee.getMessage()), locale));
} catch(ClientProtocolException cpe) {
//from httpClient execute
Debug.logError(cpe, "Error occurred in HttpClient execute(" + cpe.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorHttpClientExecute", UtilMisc.toMap("errorString", cpe.getMessage()), locale));
} catch(IOException ioe) {
//from httpClient execute or getResponsedata
Debug.logError(ioe, "Error occurred in HttpClient execute or getting response (" + ioe.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorHttpClientExecuteOrGettingResponse", UtilMisc.toMap("errorString", ioe.getMessage()), locale));
}
return resultMap;
}
public static Map<String, Object> paymentRelease(DispatchContext ctx, Map<String, Object> context) {
Debug.logInfo("SagePay - Entered paymentRelease", module);
Debug.logInfo("SagePay paymentRelease context : " + context, module);
Delegator delegator = ctx.getDelegator();
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, String> props = buildSagePayProperties(context, delegator);
String vendorTxCode = (String)context.get("vendorTxCode");
String vpsTxId = (String) context.get("vpsTxId");
String securityKey = (String) context.get("securityKey");
String txAuthNo = (String) context.get("txAuthNo");
Locale locale = (Locale) context.get("locale");
HttpHost host = SagePayUtil.getHost(props);
//start - release parameters
Map<String, String> parameters = new HashMap<String, String>();
String vpsProtocol = props.get("protocolVersion");
String vendor = props.get("vendor");
String txType = props.get("releaseTransType");
parameters.put("VPSProtocol", vpsProtocol);
parameters.put("TxType", txType);
parameters.put("Vendor", vendor);
parameters.put("VendorTxCode", vendorTxCode);
parameters.put("VPSTxId", vpsTxId);
parameters.put("SecurityKey", securityKey);
parameters.put("TxAuthNo", txAuthNo);
//end - release parameters
try (CloseableHttpClient httpClient = SagePayUtil.getHttpClient()) {
String successMessage = null;
HttpPost httpPost = SagePayUtil.getHttpPost(props.get("releaseUrl"), parameters);
HttpResponse response = httpClient.execute(host, httpPost);
Map<String, String> responseData = SagePayUtil.getResponseData(response);
String status = responseData.get("Status");
String statusDetail = responseData.get("StatusDetail");
resultMap.put("status", status);
resultMap.put("statusDetail", statusDetail);
//start - payment released
if ("OK".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentReleased", locale);
}
//end - payment released
//start - release request not formed properly or parameters missing
if ("MALFORMED".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentReleaseRequestMalformed", locale);
}
//end - release request not formed properly or parameters missing
//start - invalid information passed in parameters
if ("INVALID".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentInvalidInformationPassed", locale);
}
//end - invalid information passed in parameters
//start - problem at Sagepay
if ("ERROR".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentError", locale);
}
//end - problem at Sagepay
resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage);
} catch(UnsupportedEncodingException uee) {
//exception in encoding parameters in httpPost
Debug.logError(uee, "Error occurred in encoding parameters for HttpPost (" + uee.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorEncodingParameters", UtilMisc.toMap("errorString", uee.getMessage()), locale));
} catch(ClientProtocolException cpe) {
//from httpClient execute
Debug.logError(cpe, "Error occurred in HttpClient execute(" + cpe.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorHttpClientExecute", UtilMisc.toMap("errorString", cpe.getMessage()), locale));
} catch(IOException ioe) {
//from httpClient execute or getResponsedata
Debug.logError(ioe, "Error occurred in HttpClient execute or getting response (" + ioe.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorHttpClientExecuteOrGettingResponse", UtilMisc.toMap("errorString", ioe.getMessage()), locale));
}
return resultMap;
}
public static Map<String, Object> paymentVoid(DispatchContext ctx, Map<String, Object> context) {
Debug.logInfo("SagePay - Entered paymentVoid", module);
Debug.logInfo("SagePay paymentVoid context : " + context, module);
Delegator delegator = ctx.getDelegator();
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, String> props = buildSagePayProperties(context, delegator);
String vendorTxCode = (String)context.get("vendorTxCode");
String vpsTxId = (String) context.get("vpsTxId");
String securityKey = (String) context.get("securityKey");
String txAuthNo = (String) context.get("txAuthNo");
Locale locale = (Locale) context.get("locale");
HttpHost host = SagePayUtil.getHost(props);
//start - void parameters
Map<String, String> parameters = new HashMap<String, String>();
String vpsProtocol = props.get("protocolVersion");
String vendor = props.get("vendor");
parameters.put("VPSProtocol", vpsProtocol);
parameters.put("TxType", "VOID");
parameters.put("Vendor", vendor);
parameters.put("VendorTxCode", vendorTxCode);
parameters.put("VPSTxId", vpsTxId);
parameters.put("SecurityKey", securityKey);
parameters.put("TxAuthNo", txAuthNo);
//end - void parameters
try (CloseableHttpClient httpClient = SagePayUtil.getHttpClient()) {
String successMessage = null;
HttpPost httpPost = SagePayUtil.getHttpPost(props.get("voidUrl"), parameters);
HttpResponse response = httpClient.execute(host, httpPost);
Map<String, String> responseData = SagePayUtil.getResponseData(response);
String status = responseData.get("Status");
String statusDetail = responseData.get("StatusDetail");
resultMap.put("status", status);
resultMap.put("statusDetail", statusDetail);
//start - payment void
if ("OK".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentVoided", locale);
}
//end - payment void
//start - void request not formed properly or parameters missing
if ("MALFORMED".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentVoidRequestMalformed", locale);
}
//end - void request not formed properly or parameters missing
//start - invalid information passed in parameters
if ("INVALID".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentInvalidInformationPassed", locale);
}
//end - invalid information passed in parameters
//start - problem at Sagepay
if ("ERROR".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentError", locale);
}
//end - problem at Sagepay
resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage);
} catch(UnsupportedEncodingException uee) {
//exception in encoding parameters in httpPost
Debug.logError(uee, "Error occurred in encoding parameters for HttpPost (" + uee.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorEncodingParameters", UtilMisc.toMap("errorString", uee.getMessage()), locale));
} catch(ClientProtocolException cpe) {
//from httpClient execute
Debug.logError(cpe, "Error occurred in HttpClient execute(" + cpe.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorHttpClientExecute", UtilMisc.toMap("errorString", cpe.getMessage()), locale));
} catch(IOException ioe) {
//from httpClient execute or getResponsedata
Debug.logError(ioe, "Error occurred in HttpClient execute or getting response (" + ioe.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorHttpClientExecuteOrGettingResponse", UtilMisc.toMap("errorString", ioe.getMessage()), locale));
}
return resultMap;
}
public static Map<String, Object> paymentRefund(DispatchContext ctx, Map<String, Object> context) {
Debug.logInfo("SagePay - Entered paymentRefund", module);
Debug.logInfo("SagePay paymentRefund context : " + context, module);
Delegator delegator = ctx.getDelegator();
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, String> props = buildSagePayProperties(context, delegator);
String vendorTxCode = (String)context.get("vendorTxCode");
String amount = (String)context.get("amount");
String currency = (String)context.get("currency");
String description = (String)context.get("description");
String relatedVPSTxId = (String) context.get("relatedVPSTxId");
String relatedVendorTxCode = (String) context.get("relatedVendorTxCode");
String relatedSecurityKey = (String) context.get("relatedSecurityKey");
String relatedTxAuthNo = (String) context.get("relatedTxAuthNo");
Locale locale = (Locale) context.get("locale");
HttpHost host = SagePayUtil.getHost(props);
//start - refund parameters
Map<String, String> parameters = new HashMap<String, String>();
String vpsProtocol = props.get("protocolVersion");
String vendor = props.get("vendor");
parameters.put("VPSProtocol", vpsProtocol);
parameters.put("TxType", "REFUND");
parameters.put("Vendor", vendor);
parameters.put("VendorTxCode", vendorTxCode);
parameters.put("Amount", amount);
parameters.put("Currency", currency);
parameters.put("Description", description);
parameters.put("RelatedVPSTxId", relatedVPSTxId);
parameters.put("RelatedVendorTxCode", relatedVendorTxCode);
parameters.put("RelatedSecurityKey", relatedSecurityKey);
parameters.put("RelatedTxAuthNo", relatedTxAuthNo);
//end - refund parameters
try (CloseableHttpClient httpClient = SagePayUtil.getHttpClient()) {
String successMessage = null;
HttpPost httpPost = SagePayUtil.getHttpPost(props.get("refundUrl"), parameters);
HttpResponse response = httpClient.execute(host, httpPost);
Map<String, String> responseData = SagePayUtil.getResponseData(response);
Debug.logInfo("response data -> " + responseData, module);
String status = responseData.get("Status");
String statusDetail = responseData.get("StatusDetail");
resultMap.put("status", status);
resultMap.put("statusDetail", statusDetail);
//start - payment refunded
if ("OK".equals(status)) {
resultMap.put("vpsTxId", responseData.get("VPSTxId"));
resultMap.put("txAuthNo", responseData.get("TxAuthNo"));
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentRefunded", locale);
}
//end - payment refunded
//start - refund not authorized by the acquiring bank
if ("NOTAUTHED".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentRefundNotAuthorized", locale);
}
//end - refund not authorized by the acquiring bank
//start - refund request not formed properly or parameters missing
if ("MALFORMED".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentRefundRequestMalformed", locale);
}
//end - refund request not formed properly or parameters missing
//start - invalid information passed in parameters
if ("INVALID".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentInvalidInformationPassed", locale);
}
//end - invalid information passed in parameters
//start - problem at Sagepay
if ("ERROR".equals(status)) {
successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentError", locale);
}
//end - problem at Sagepay
resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage);
} catch(UnsupportedEncodingException uee) {
//exception in encoding parameters in httpPost
Debug.logError(uee, "Error occurred in encoding parameters for HttpPost (" + uee.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorEncodingParameters", UtilMisc.toMap("errorString", uee.getMessage()), locale));
} catch(ClientProtocolException cpe) {
//from httpClient execute
Debug.logError(cpe, "Error occurred in HttpClient execute(" + cpe.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorHttpClientExecute", UtilMisc.toMap("errorString", cpe.getMessage()), locale));
} catch(IOException ioe) {
//from httpClient execute or getResponsedata
Debug.logError(ioe, "Error occurred in HttpClient execute or getting response (" + ioe.getMessage() + ")", module);
resultMap = ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorHttpClientExecuteOrGettingResponse", UtilMisc.toMap("errorString", ioe.getMessage()), locale));
}
return resultMap;
}
}
|
apache/flink | 35,900 | flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/typeutils/FieldInfoUtils.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.table.typeutils;
import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.typeinfo.SqlTimeTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.CompositeType;
import org.apache.flink.api.java.typeutils.GenericTypeInfo;
import org.apache.flink.api.java.typeutils.PojoTypeInfo;
import org.apache.flink.api.java.typeutils.TupleTypeInfoBase;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.catalog.ResolvedSchema;
import org.apache.flink.table.expressions.ApiExpressionUtils;
import org.apache.flink.table.expressions.Expression;
import org.apache.flink.table.expressions.ExpressionUtils;
import org.apache.flink.table.expressions.UnresolvedCallExpression;
import org.apache.flink.table.expressions.UnresolvedReferenceExpression;
import org.apache.flink.table.expressions.utils.ApiExpressionDefaultVisitor;
import org.apache.flink.table.functions.BuiltInFunctionDefinitions;
import org.apache.flink.table.legacy.api.TableSchema;
import org.apache.flink.table.legacy.api.Types;
import org.apache.flink.table.types.AtomicDataType;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.DataTypeQueryable;
import org.apache.flink.table.types.logical.LocalZonedTimestampType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.TimestampKind;
import org.apache.flink.table.types.logical.TimestampType;
import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
import org.apache.flink.table.types.utils.TypeConversions;
import org.apache.flink.types.Row;
import javax.annotation.Nullable;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.lang.String.format;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE;
import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.isCompositeType;
import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.isProctimeAttribute;
import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.isRowtimeAttribute;
import static org.apache.flink.table.types.logical.utils.LogicalTypeUtils.getAtomicName;
import static org.apache.flink.table.types.utils.TypeConversions.fromDataTypeToLegacyInfo;
import static org.apache.flink.table.types.utils.TypeConversions.fromLegacyInfoToDataType;
/**
* Utility methods for extracting names and indices of fields from different {@link
* TypeInformation}s.
*/
@Internal
public class FieldInfoUtils {
private static final String ATOMIC_FIELD_NAME = "f0";
/**
* Describes fields' names, indices and {@link DataType}s extracted from a {@link
* TypeInformation} and possibly transformed via {@link Expression} application. It is in fact a
* mapping between {@link TypeInformation} of an input and {@link TableSchema} of a {@link
* Table} that can be created out of it.
*
* @see FieldInfoUtils#getFieldsInfo(TypeInformation)
* @see FieldInfoUtils#getFieldsInfo(TypeInformation, Expression[])
*/
@Internal
public static class TypeInfoSchema {
private final String[] fieldNames;
private final int[] indices;
private final DataType[] fieldTypes;
private final boolean isRowtimeDefined;
TypeInfoSchema(
String[] fieldNames,
int[] indices,
DataType[] fieldTypes,
boolean isRowtimeDefined) {
validateEqualLength(fieldNames, indices, fieldTypes);
validateNamesUniqueness(fieldNames);
this.isRowtimeDefined = isRowtimeDefined;
this.fieldNames = fieldNames;
this.indices = indices;
this.fieldTypes = fieldTypes;
}
private void validateEqualLength(
String[] fieldNames, int[] indices, DataType[] fieldTypes) {
if (fieldNames.length != indices.length || indices.length != fieldTypes.length) {
throw new TableException(
String.format(
"Mismatched number of indices, names and types:\n"
+ "Names: %s\n"
+ "Indices: %s\n"
+ "Types: %s",
Arrays.toString(fieldNames),
Arrays.toString(indices),
Arrays.toString(fieldTypes)));
}
}
private void validateNamesUniqueness(String[] fieldNames) {
// check uniqueness of field names
Set<String> duplicatedNames = findDuplicates(fieldNames);
if (duplicatedNames.size() != 0) {
throw new ValidationException(
String.format(
"Field names must be unique.\n"
+ "List of duplicate fields: [%s].\n"
+ "List of all fields: [%s].",
String.join(", ", duplicatedNames), String.join(", ", fieldNames)));
}
}
public String[] getFieldNames() {
return fieldNames;
}
public int[] getIndices() {
return indices;
}
public DataType[] getFieldTypes() {
return fieldTypes;
}
public boolean isRowtimeDefined() {
return isRowtimeDefined;
}
public ResolvedSchema toResolvedSchema() {
return ResolvedSchema.physical(fieldNames, fieldTypes);
}
}
/**
* Reference input fields by name: All fields in the schema definition are referenced by name
* (and possibly renamed using an alias (as). In this mode, fields can be reordered and
* projected out. Moreover, we can define proctime and rowtime attributes at arbitrary positions
* using arbitrary names (except those that exist in the result schema). This mode can be used
* for any input type, including POJOs.
*
* <p>Reference input fields by position: In this mode, fields are simply renamed. Event-time
* attributes can replace the field on their position in the input data (if it is of correct
* type) or be appended at the end. Proctime attributes must be appended at the end. This mode
* can only be used if the input type has a defined field order (tuple, case class, Row) and no
* of fields references a field of the input type.
*/
private static boolean isReferenceByPosition(
TypeInformation<?> inputType, Expression[] fields) {
if (!isIndexedComposite(inputType)) {
return false;
}
List<String> inputNames = Arrays.asList(getFieldNames(inputType));
// Use the by-position mode if no of the fields exists in the input.
// This prevents confusing cases like ('f2, 'f0, 'myName) for a Tuple3 where fields are
// renamed
// by position but the user might assume reordering instead of renaming.
return Arrays.stream(fields)
.allMatch(
f -> {
if (f instanceof UnresolvedCallExpression
&& ((UnresolvedCallExpression) f).getFunctionDefinition()
== BuiltInFunctionDefinitions.AS
&& f.getChildren().get(0)
instanceof UnresolvedReferenceExpression) {
return false;
}
if (f instanceof UnresolvedReferenceExpression) {
return !inputNames.contains(
((UnresolvedReferenceExpression) f).getName());
}
return true;
});
}
/**
* Returns a {@link TypeInfoSchema} for a given {@link TypeInformation}.
*
* @param inputType The TypeInformation to extract the mapping from.
* @param <A> The type of the TypeInformation.
* @return A description of the input that enables creation of a {@link TableSchema}.
* @see TypeInfoSchema
*/
public static <A> TypeInfoSchema getFieldsInfo(TypeInformation<A> inputType) {
if (inputType instanceof GenericTypeInfo && inputType.getTypeClass() == Row.class) {
throw new ValidationException(
"An input of GenericTypeInfo<Row> cannot be converted to Table. "
+ "Please specify the type of the input with a RowTypeInfo.");
} else {
return new TypeInfoSchema(
getFieldNames(inputType),
getFieldIndices(inputType),
fromLegacyInfoToDataType(getFieldTypes(inputType)),
false);
}
}
/**
* Returns a {@link TypeInfoSchema} for a given {@link TypeInformation}. It gives control of the
* process of mapping {@link TypeInformation} to {@link TableSchema} (via {@link
* TypeInfoSchema}).
*
* <p>Possible operations via the expressions include:
*
* <ul>
* <li>specifying rowtime & proctime attributes via .proctime, .rowtime
* <ul>
* <li>There can be only a single rowtime and/or a single proctime attribute
* <li>Proctime attribute can only be appended to the end of the expression list
* <li>Rowtime attribute can replace an input field if the input field has a compatible
* type. See {@link TimestampType}.
* </ul>
* <li>renaming fields by position (this cannot be mixed with referencing by name)
* <li>renaming & projecting fields by name (this cannot be mixed with referencing by
* position)
* </ul>
*
* @param inputType The TypeInformation to extract the mapping from.
* @param expressions Expressions to apply while extracting the mapping.
* @param <A> The type of the TypeInformation.
* @return A description of the input that enables creation of a {@link TableSchema}.
* @see TypeInfoSchema
*/
public static <A> TypeInfoSchema getFieldsInfo(
TypeInformation<A> inputType, Expression[] expressions) {
validateInputTypeInfo(inputType);
final List<FieldInfo> fieldInfos =
extractFieldInformation(
inputType,
Arrays.stream(expressions)
.map(ApiExpressionUtils::unwrapFromApi)
.toArray(Expression[]::new));
validateNoStarReference(fieldInfos);
boolean isRowtimeAttribute = checkIfRowtimeAttribute(fieldInfos);
validateAtMostOneProctimeAttribute(fieldInfos);
String[] fieldNames =
fieldInfos.stream().map(FieldInfo::getFieldName).toArray(String[]::new);
int[] fieldIndices = fieldInfos.stream().mapToInt(FieldInfo::getIndex).toArray();
DataType[] dataTypes = fieldInfos.stream().map(FieldInfo::getType).toArray(DataType[]::new);
return new TypeInfoSchema(fieldNames, fieldIndices, dataTypes, isRowtimeAttribute);
}
private static void validateNoStarReference(List<FieldInfo> fieldInfos) {
if (fieldInfos.stream().anyMatch(info -> info.getFieldName().equals("*"))) {
throw new ValidationException("Field name can not be '*'.");
}
}
private static <A> List<FieldInfo> extractFieldInformation(
TypeInformation<A> inputType, Expression[] exprs) {
final List<FieldInfo> fieldInfos;
if (inputType instanceof GenericTypeInfo && inputType.getTypeClass() == Row.class) {
throw new ValidationException(
"An input of GenericTypeInfo<Row> cannot be converted to Table. "
+ "Please specify the type of the input with a RowTypeInfo.");
} else if (isIndexedComposite(inputType)) {
fieldInfos = extractFieldInfosFromIndexedCompositeType(inputType, exprs);
} else if (isNonIndexedComposite(inputType)) {
fieldInfos = extractFieldInfosByNameReference(inputType, exprs);
} else {
fieldInfos = extractFieldInfoFromAtomicType(inputType, exprs);
}
return fieldInfos;
}
private static boolean isIndexedComposite(TypeInformation<?> inputType) {
// type originated from Table API
if (inputType instanceof DataTypeQueryable) {
final DataType dataType = ((DataTypeQueryable) inputType).getDataType();
final LogicalType type = dataType.getLogicalType();
return isCompositeType(type); // every composite in Table API is indexed
}
// type originated from other API
return inputType instanceof TupleTypeInfoBase;
}
private static boolean isNonIndexedComposite(TypeInformation<?> inputType) {
return inputType instanceof PojoTypeInfo;
}
private static void validateAtMostOneProctimeAttribute(List<FieldInfo> fieldInfos) {
List<FieldInfo> proctimeAttributes =
fieldInfos.stream()
.filter(FieldInfoUtils::isProctimeField)
.collect(Collectors.toList());
if (proctimeAttributes.size() > 1) {
throw new ValidationException(
"The proctime attribute can only be defined once in a table schema. Duplicated proctime attributes: "
+ proctimeAttributes);
}
}
private static boolean checkIfRowtimeAttribute(List<FieldInfo> fieldInfos) {
List<FieldInfo> rowtimeAttributes =
fieldInfos.stream()
.filter(FieldInfoUtils::isRowtimeField)
.collect(Collectors.toList());
if (rowtimeAttributes.size() > 1) {
throw new ValidationException(
"The rowtime attribute can only be defined once in a table schema. Duplicated rowtime attributes: "
+ rowtimeAttributes);
}
return rowtimeAttributes.size() > 0;
}
/**
* Returns field names for a given {@link TypeInformation}.
*
* @param inputType The TypeInformation extract the field names.
* @param <A> The type of the TypeInformation.
* @return An array holding the field names
*/
public static <A> String[] getFieldNames(TypeInformation<A> inputType) {
return getFieldNames(inputType, Collections.emptyList());
}
/**
* Returns field names for a given {@link TypeInformation}. If the input {@link TypeInformation}
* is not a composite type, the result field name should not exist in the existingNames.
*
* @param inputType The TypeInformation extract the field names.
* @param existingNames The existing field names for non-composite types that can not be used.
* @param <A> The type of the TypeInformation.
* @return An array holding the field names
*/
public static <A> String[] getFieldNames(
TypeInformation<A> inputType, List<String> existingNames) {
validateInputTypeInfo(inputType);
List<String> fieldNames = null;
// type originated from Table API
if (inputType instanceof DataTypeQueryable) {
final DataType dataType = ((DataTypeQueryable) inputType).getDataType();
final LogicalType type = dataType.getLogicalType();
if (isCompositeType(type)) {
fieldNames = LogicalTypeChecks.getFieldNames(type);
}
}
// type originated from other API
else if (inputType instanceof CompositeType) {
fieldNames = Arrays.asList(((CompositeType<A>) inputType).getFieldNames());
}
// atomic in any case
if (fieldNames == null) {
fieldNames = Collections.singletonList(getAtomicName(existingNames));
}
if (fieldNames.contains("*")) {
throw new TableException("Field name can not be '*'.");
}
return fieldNames.toArray(new String[0]);
}
/**
* Validate if class represented by the typeInfo is static and globally accessible.
*
* @param typeInfo type to check
* @throws ValidationException if type does not meet these criteria
*/
public static <A> void validateInputTypeInfo(TypeInformation<A> typeInfo) {
Class<A> clazz = typeInfo.getTypeClass();
if ((clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers()))
|| !Modifier.isPublic(clazz.getModifiers())
|| clazz.getCanonicalName() == null) {
throw new ValidationException(
format(
"Class '%s' described in type information '%s' must be "
+ "static and globally accessible.",
clazz, typeInfo));
}
}
/**
* Returns field indexes for a given {@link TypeInformation}.
*
* @param inputType The TypeInformation extract the field positions from.
* @return An array holding the field positions
*/
public static int[] getFieldIndices(TypeInformation<?> inputType) {
return IntStream.range(0, getFieldNames(inputType).length).toArray();
}
/**
* Returns field types for a given {@link TypeInformation}.
*
* @param inputType The TypeInformation to extract field types from.
* @return An array holding the field types.
*/
public static TypeInformation<?>[] getFieldTypes(TypeInformation<?> inputType) {
validateInputTypeInfo(inputType);
final TypeInformation<?>[] fieldTypes;
if (inputType instanceof CompositeType) {
int arity = inputType.getArity();
CompositeType<?> ct = (CompositeType<?>) inputType;
fieldTypes =
IntStream.range(0, arity)
.mapToObj(ct::getTypeAt)
.toArray(TypeInformation[]::new);
} else {
fieldTypes = new TypeInformation[] {inputType};
}
return fieldTypes;
}
/* Utility methods */
private static DataType[] getFieldDataTypes(TypeInformation<?> inputType) {
validateInputTypeInfo(inputType);
// type originated from Table API
if (inputType instanceof DataTypeQueryable) {
final DataType dataType = ((DataTypeQueryable) inputType).getDataType();
return dataType.getChildren().toArray(new DataType[0]);
}
// type originated from other API
else {
final TypeInformation<?>[] fieldTypes = getFieldTypes(inputType);
return Stream.of(fieldTypes)
.map(TypeConversions::fromLegacyInfoToDataType)
.toArray(DataType[]::new);
}
}
private static List<FieldInfo> extractFieldInfoFromAtomicType(
TypeInformation<?> atomicType, Expression[] exprs) {
List<FieldInfo> fields = new ArrayList<>(exprs.length);
boolean alreadyReferenced = false;
for (int i = 0; i < exprs.length; i++) {
Expression expr = exprs[i];
if (expr instanceof UnresolvedReferenceExpression) {
if (alreadyReferenced) {
throw new ValidationException(
"Too many fields referenced from an atomic type.");
}
alreadyReferenced = true;
String name = ((UnresolvedReferenceExpression) expr).getName();
fields.add(new FieldInfo(name, i, fromLegacyInfoToDataType(atomicType)));
} else if (isRowTimeExpression(expr)) {
UnresolvedReferenceExpression reference = getChildAsReference(expr);
fields.add(createTimeAttributeField(reference, TimestampKind.ROWTIME, null));
} else if (isProcTimeExpression(expr)) {
UnresolvedReferenceExpression reference = getChildAsReference(expr);
fields.add(createTimeAttributeField(reference, TimestampKind.PROCTIME, null));
} else {
throw new ValidationException("Field reference expression expected.");
}
}
return fields;
}
private static List<FieldInfo> extractFieldInfosFromIndexedCompositeType(
TypeInformation<?> inputType, Expression[] exprs) {
boolean isRefByPos = isReferenceByPosition(inputType, exprs);
if (isRefByPos) {
return IntStream.range(0, exprs.length)
.mapToObj(idx -> exprs[idx].accept(new IndexedExprToFieldInfo(inputType, idx)))
.collect(Collectors.toList());
} else {
return extractFieldInfosByNameReference(inputType, exprs);
}
}
private static List<FieldInfo> extractFieldInfosByNameReference(
TypeInformation<?> inputType, Expression[] exprs) {
ExprToFieldInfo exprToFieldInfo = new ExprToFieldInfo(inputType);
return Arrays.stream(exprs)
.map(expr -> expr.accept(exprToFieldInfo))
.collect(Collectors.toList());
}
private static class FieldInfo {
private final String fieldName;
private final int index;
private final DataType type;
FieldInfo(String fieldName, int index, DataType type) {
this.fieldName = fieldName;
this.index = index;
this.type = type;
}
public String getFieldName() {
return fieldName;
}
public int getIndex() {
return index;
}
public DataType getType() {
return type;
}
}
private static class IndexedExprToFieldInfo extends ApiExpressionDefaultVisitor<FieldInfo> {
private final String[] fieldNames;
private final DataType[] fieldDataTypes;
private final int index;
private IndexedExprToFieldInfo(TypeInformation<?> inputType, int index) {
this.fieldNames = getFieldNames(inputType);
this.fieldDataTypes = getFieldDataTypes(inputType);
this.index = index;
}
@Override
public FieldInfo visit(UnresolvedReferenceExpression unresolvedReference) {
String fieldName = unresolvedReference.getName();
return new FieldInfo(fieldName, index, getTypeAt(unresolvedReference));
}
@Override
public FieldInfo visit(UnresolvedCallExpression unresolvedCall) {
if (unresolvedCall.getFunctionDefinition() == BuiltInFunctionDefinitions.AS) {
return visitAlias(unresolvedCall);
} else if (isRowTimeExpression(unresolvedCall)) {
validateRowtimeReplacesCompatibleType(unresolvedCall);
return createTimeAttributeField(
getChildAsReference(unresolvedCall), TimestampKind.ROWTIME, null);
} else if (isProcTimeExpression(unresolvedCall)) {
validateProcTimeAttributeAppended(unresolvedCall);
return createTimeAttributeField(
getChildAsReference(unresolvedCall), TimestampKind.PROCTIME, null);
}
return defaultMethod(unresolvedCall);
}
private FieldInfo visitAlias(UnresolvedCallExpression unresolvedCall) {
List<Expression> children = unresolvedCall.getChildren();
String newName = extractAlias(children.get(1));
Expression child = children.get(0);
if (isProcTimeExpression(child)) {
validateProcTimeAttributeAppended(unresolvedCall);
return createTimeAttributeField(
getChildAsReference(child), TimestampKind.PROCTIME, newName);
} else {
throw new ValidationException(
format(
"Alias '%s' is not allowed if other fields are referenced by position.",
newName));
}
}
private void validateRowtimeReplacesCompatibleType(
UnresolvedCallExpression unresolvedCall) {
if (index < fieldDataTypes.length) {
checkRowtimeType(fromDataTypeToLegacyInfo(getTypeAt(unresolvedCall)));
}
}
private void validateProcTimeAttributeAppended(UnresolvedCallExpression unresolvedCall) {
if (index < fieldDataTypes.length) {
throw new ValidationException(
String.format(
"The proctime attribute can only be appended to the"
+ " table schema and not replace an existing field. Please move '%s' to the end of the"
+ " schema.",
unresolvedCall));
}
}
private DataType getTypeAt(Expression expr) {
if (index >= fieldDataTypes.length) {
throw new ValidationException(
String.format(
"Number of expressions does not match number of input fields.\n"
+ "Available fields: %s\n"
+ "Could not map: %s",
Arrays.toString(fieldNames), expr));
}
return fieldDataTypes[index];
}
@Override
protected FieldInfo defaultMethod(Expression expression) {
throw new ValidationException(
"Field reference expression or alias on field expression expected.");
}
}
private static class ExprToFieldInfo extends ApiExpressionDefaultVisitor<FieldInfo> {
private final TypeInformation<?> inputType;
private final DataType[] fieldDataTypes;
private ExprToFieldInfo(TypeInformation<?> inputType) {
this.inputType = inputType;
this.fieldDataTypes = getFieldDataTypes(inputType);
}
private ValidationException fieldNotFound(String name) {
return new ValidationException(
format(
"%s is not a field of type %s. Expected: %s}",
name, inputType, String.join(", ", getFieldNames(inputType))));
}
@Override
public FieldInfo visit(UnresolvedReferenceExpression unresolvedReference) {
return createFieldInfo(unresolvedReference, null);
}
@Override
public FieldInfo visit(UnresolvedCallExpression unresolvedCall) {
if (unresolvedCall.getFunctionDefinition() == BuiltInFunctionDefinitions.AS) {
return visitAlias(unresolvedCall);
} else if (isRowTimeExpression(unresolvedCall)) {
return createRowtimeFieldInfo(unresolvedCall, null);
} else if (isProcTimeExpression(unresolvedCall)) {
return createProctimeFieldInfo(unresolvedCall, null);
}
return defaultMethod(unresolvedCall);
}
private FieldInfo visitAlias(UnresolvedCallExpression unresolvedCall) {
List<Expression> children = unresolvedCall.getChildren();
String newName = extractAlias(children.get(1));
Expression child = children.get(0);
if (child instanceof UnresolvedReferenceExpression) {
return createFieldInfo((UnresolvedReferenceExpression) child, newName);
} else if (isRowTimeExpression(child)) {
return createRowtimeFieldInfo(child, newName);
} else if (isProcTimeExpression(child)) {
return createProctimeFieldInfo(child, newName);
} else {
return defaultMethod(unresolvedCall);
}
}
private FieldInfo createFieldInfo(
UnresolvedReferenceExpression unresolvedReference, @Nullable String alias) {
String fieldName = unresolvedReference.getName();
return referenceByName(fieldName, inputType)
.map(
idx ->
new FieldInfo(
alias != null ? alias : fieldName,
idx,
fieldDataTypes[idx]))
.orElseThrow(() -> fieldNotFound(fieldName));
}
private FieldInfo createProctimeFieldInfo(Expression expression, @Nullable String alias) {
UnresolvedReferenceExpression reference = getChildAsReference(expression);
String originalName = reference.getName();
validateProctimeDoesNotReplaceField(originalName);
return createTimeAttributeField(reference, TimestampKind.PROCTIME, alias);
}
private void validateProctimeDoesNotReplaceField(String originalName) {
if (referenceByName(originalName, inputType).isPresent()) {
throw new ValidationException(
String.format(
"The proctime attribute '%s' must not replace an existing field.",
originalName));
}
}
private FieldInfo createRowtimeFieldInfo(Expression expression, @Nullable String alias) {
UnresolvedReferenceExpression reference = getChildAsReference(expression);
String originalName = reference.getName();
verifyReferencesValidField(originalName, alias);
return createTimeAttributeField(reference, TimestampKind.ROWTIME, alias);
}
private void verifyReferencesValidField(String origName, @Nullable String alias) {
Optional<Integer> refId = referenceByName(origName, inputType);
if (refId.isPresent()) {
checkRowtimeType(fromDataTypeToLegacyInfo(fieldDataTypes[refId.get()]));
} else if (alias != null) {
throw new ValidationException(
String.format("Alias '%s' must reference an existing field.", alias));
}
}
@Override
protected FieldInfo defaultMethod(Expression expression) {
throw new ValidationException(
"Field reference expression or alias on field expression expected.");
}
}
private static String extractAlias(Expression aliasExpr) {
return ExpressionUtils.extractValue(aliasExpr, String.class)
.orElseThrow(
() ->
new TableException(
"Alias expects string literal as new name. Got: "
+ aliasExpr));
}
private static void checkRowtimeType(TypeInformation<?> type) {
if (!(type.equals(Types.LONG()) || type instanceof SqlTimeTypeInfo)) {
throw new ValidationException(
"The rowtime attribute can only replace a field with a valid time type, "
+ "such as Timestamp or Long. But was: "
+ type);
}
}
private static boolean isRowtimeField(FieldInfo field) {
final LogicalType logicalType = field.getType().getLogicalType();
return logicalType.is(TIMESTAMP_WITHOUT_TIME_ZONE) && isRowtimeAttribute(logicalType);
}
private static boolean isProctimeField(FieldInfo field) {
return isProctimeAttribute(field.getType().getLogicalType());
}
private static boolean isRowTimeExpression(Expression origExpr) {
return origExpr instanceof UnresolvedCallExpression
&& ((UnresolvedCallExpression) origExpr).getFunctionDefinition()
== BuiltInFunctionDefinitions.ROWTIME;
}
private static boolean isProcTimeExpression(Expression origExpr) {
return origExpr instanceof UnresolvedCallExpression
&& ((UnresolvedCallExpression) origExpr).getFunctionDefinition()
== BuiltInFunctionDefinitions.PROCTIME;
}
private static Optional<Integer> referenceByName(String name, TypeInformation<?> inputType) {
final String[] fieldNames = getFieldNames(inputType);
int inputIdx = Arrays.asList(fieldNames).indexOf(name);
if (inputIdx < 0) {
return Optional.empty();
} else {
return Optional.of(inputIdx);
}
}
private static <T> Set<T> findDuplicates(T[] array) {
Set<T> duplicates = new HashSet<>();
Set<T> seenElements = new HashSet<>();
for (T t : array) {
if (seenElements.contains(t)) {
duplicates.add(t);
} else {
seenElements.add(t);
}
}
return duplicates;
}
private static FieldInfo createTimeAttributeField(
UnresolvedReferenceExpression reference, TimestampKind kind, @Nullable String alias) {
final int idx;
if (kind == TimestampKind.PROCTIME) {
idx = TimeIndicatorTypeInfo.PROCTIME_STREAM_MARKER;
} else {
idx = TimeIndicatorTypeInfo.ROWTIME_STREAM_MARKER;
}
String originalName = reference.getName();
return new FieldInfo(
alias != null ? alias : originalName, idx, createTimeIndicatorType(kind));
}
private static UnresolvedReferenceExpression getChildAsReference(Expression expression) {
Expression child = expression.getChildren().get(0);
if (child instanceof UnresolvedReferenceExpression) {
return (UnresolvedReferenceExpression) child;
}
throw new ValidationException("Field reference expression expected.");
}
private static DataType createTimeIndicatorType(TimestampKind kind) {
if (kind == TimestampKind.PROCTIME) {
return new AtomicDataType(new LocalZonedTimestampType(true, kind, 3))
.bridgedTo(java.time.Instant.class);
} else {
return new AtomicDataType(new TimestampType(true, kind, 3))
.bridgedTo(java.sql.Timestamp.class);
}
}
private FieldInfoUtils() {}
}
|
googleapis/google-cloud-java | 35,714 | java-dialogflow-cx/proto-google-cloud-dialogflow-cx-v3beta1/src/main/java/com/google/cloud/dialogflow/cx/v3beta1/CreateSessionEntityTypeRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/cx/v3beta1/session_entity_type.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dialogflow.cx.v3beta1;
/**
*
*
* <pre>
* The request message for
* [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.CreateSessionEntityType].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest}
*/
public final class CreateSessionEntityTypeRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest)
CreateSessionEntityTypeRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateSessionEntityTypeRequest.newBuilder() to construct.
private CreateSessionEntityTypeRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateSessionEntityTypeRequest() {
parent_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateSessionEntityTypeRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.cx.v3beta1.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_CreateSessionEntityTypeRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.cx.v3beta1.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_CreateSessionEntityTypeRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest.class,
com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The session to create a session entity type for.
* Format:
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/sessions/<SessionID>`
* or
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/environments/<EnvironmentID>/sessions/<SessionID>`.
* If `Environment ID` is not specified, we assume default 'draft'
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The session to create a session entity type for.
* Format:
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/sessions/<SessionID>`
* or
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/environments/<EnvironmentID>/sessions/<SessionID>`.
* If `Environment ID` is not specified, we assume default 'draft'
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SESSION_ENTITY_TYPE_FIELD_NUMBER = 2;
private com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType sessionEntityType_;
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.cx.v3beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the sessionEntityType field is set.
*/
@java.lang.Override
public boolean hasSessionEntityType() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.cx.v3beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The sessionEntityType.
*/
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType getSessionEntityType() {
return sessionEntityType_ == null
? com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType.getDefaultInstance()
: sessionEntityType_;
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.cx.v3beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.SessionEntityTypeOrBuilder
getSessionEntityTypeOrBuilder() {
return sessionEntityType_ == null
? com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType.getDefaultInstance()
: sessionEntityType_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getSessionEntityType());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getSessionEntityType());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest other =
(com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasSessionEntityType() != other.hasSessionEntityType()) return false;
if (hasSessionEntityType()) {
if (!getSessionEntityType().equals(other.getSessionEntityType())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
if (hasSessionEntityType()) {
hash = (37 * hash) + SESSION_ENTITY_TYPE_FIELD_NUMBER;
hash = (53 * hash) + getSessionEntityType().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest 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.CreateSessionEntityTypeRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest
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.CreateSessionEntityTypeRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The request message for
* [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.CreateSessionEntityType].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest)
com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.cx.v3beta1.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_CreateSessionEntityTypeRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.cx.v3beta1.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_CreateSessionEntityTypeRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest.class,
com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest.Builder.class);
}
// Construct using
// com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getSessionEntityTypeFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
sessionEntityType_ = null;
if (sessionEntityTypeBuilder_ != null) {
sessionEntityTypeBuilder_.dispose();
sessionEntityTypeBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.cx.v3beta1.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_CreateSessionEntityTypeRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest
getDefaultInstanceForType() {
return com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest build() {
com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest buildPartial() {
com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest result =
new com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.sessionEntityType_ =
sessionEntityTypeBuilder_ == null
? sessionEntityType_
: sessionEntityTypeBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest) {
return mergeFrom(
(com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest other) {
if (other
== com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest
.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasSessionEntityType()) {
mergeSessionEntityType(other.getSessionEntityType());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(
getSessionEntityTypeFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The session to create a session entity type for.
* Format:
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/sessions/<SessionID>`
* or
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/environments/<EnvironmentID>/sessions/<SessionID>`.
* If `Environment ID` is not specified, we assume default 'draft'
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The session to create a session entity type for.
* Format:
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/sessions/<SessionID>`
* or
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/environments/<EnvironmentID>/sessions/<SessionID>`.
* If `Environment ID` is not specified, we assume default 'draft'
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The session to create a session entity type for.
* Format:
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/sessions/<SessionID>`
* or
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/environments/<EnvironmentID>/sessions/<SessionID>`.
* If `Environment ID` is not specified, we assume default 'draft'
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The session to create a session entity type for.
* Format:
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/sessions/<SessionID>`
* or
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/environments/<EnvironmentID>/sessions/<SessionID>`.
* If `Environment ID` is not specified, we assume default 'draft'
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The session to create a session entity type for.
* Format:
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/sessions/<SessionID>`
* or
* `projects/<ProjectID>/locations/<LocationID>/agents/<AgentID>/environments/<EnvironmentID>/sessions/<SessionID>`.
* If `Environment ID` is not specified, we assume default 'draft'
* environment.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType sessionEntityType_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType,
com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType.Builder,
com.google.cloud.dialogflow.cx.v3beta1.SessionEntityTypeOrBuilder>
sessionEntityTypeBuilder_;
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.cx.v3beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the sessionEntityType field is set.
*/
public boolean hasSessionEntityType() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.cx.v3beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The sessionEntityType.
*/
public com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType getSessionEntityType() {
if (sessionEntityTypeBuilder_ == null) {
return sessionEntityType_ == null
? com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType.getDefaultInstance()
: sessionEntityType_;
} else {
return sessionEntityTypeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.cx.v3beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setSessionEntityType(
com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType value) {
if (sessionEntityTypeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
sessionEntityType_ = value;
} else {
sessionEntityTypeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.cx.v3beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setSessionEntityType(
com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType.Builder builderForValue) {
if (sessionEntityTypeBuilder_ == null) {
sessionEntityType_ = builderForValue.build();
} else {
sessionEntityTypeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.cx.v3beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeSessionEntityType(
com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType value) {
if (sessionEntityTypeBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& sessionEntityType_ != null
&& sessionEntityType_
!= com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType.getDefaultInstance()) {
getSessionEntityTypeBuilder().mergeFrom(value);
} else {
sessionEntityType_ = value;
}
} else {
sessionEntityTypeBuilder_.mergeFrom(value);
}
if (sessionEntityType_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.cx.v3beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearSessionEntityType() {
bitField0_ = (bitField0_ & ~0x00000002);
sessionEntityType_ = null;
if (sessionEntityTypeBuilder_ != null) {
sessionEntityTypeBuilder_.dispose();
sessionEntityTypeBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.cx.v3beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType.Builder
getSessionEntityTypeBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getSessionEntityTypeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.cx.v3beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.dialogflow.cx.v3beta1.SessionEntityTypeOrBuilder
getSessionEntityTypeOrBuilder() {
if (sessionEntityTypeBuilder_ != null) {
return sessionEntityTypeBuilder_.getMessageOrBuilder();
} else {
return sessionEntityType_ == null
? com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType.getDefaultInstance()
: sessionEntityType_;
}
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.cx.v3beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType,
com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType.Builder,
com.google.cloud.dialogflow.cx.v3beta1.SessionEntityTypeOrBuilder>
getSessionEntityTypeFieldBuilder() {
if (sessionEntityTypeBuilder_ == null) {
sessionEntityTypeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType,
com.google.cloud.dialogflow.cx.v3beta1.SessionEntityType.Builder,
com.google.cloud.dialogflow.cx.v3beta1.SessionEntityTypeOrBuilder>(
getSessionEntityType(), getParentForChildren(), isClean());
sessionEntityType_ = null;
}
return sessionEntityTypeBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest)
private static final com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest();
}
public static com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateSessionEntityTypeRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateSessionEntityTypeRequest>() {
@java.lang.Override
public CreateSessionEntityTypeRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<CreateSessionEntityTypeRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateSessionEntityTypeRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.CreateSessionEntityTypeRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,558 | java-dialogflow-cx/proto-google-cloud-dialogflow-cx-v3/src/main/java/com/google/cloud/dialogflow/cx/v3/ExportAgentResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/cx/v3/agent.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dialogflow.cx.v3;
/**
*
*
* <pre>
* The response message for
* [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.cx.v3.ExportAgentResponse}
*/
public final class ExportAgentResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.cx.v3.ExportAgentResponse)
ExportAgentResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ExportAgentResponse.newBuilder() to construct.
private ExportAgentResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ExportAgentResponse() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ExportAgentResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.cx.v3.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3_ExportAgentResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.cx.v3.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3_ExportAgentResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.cx.v3.ExportAgentResponse.class,
com.google.cloud.dialogflow.cx.v3.ExportAgentResponse.Builder.class);
}
private int agentCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object agent_;
public enum AgentCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
AGENT_URI(1),
AGENT_CONTENT(2),
COMMIT_SHA(3),
AGENT_NOT_SET(0);
private final int value;
private AgentCase(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 AgentCase valueOf(int value) {
return forNumber(value);
}
public static AgentCase forNumber(int value) {
switch (value) {
case 1:
return AGENT_URI;
case 2:
return AGENT_CONTENT;
case 3:
return COMMIT_SHA;
case 0:
return AGENT_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public AgentCase getAgentCase() {
return AgentCase.forNumber(agentCase_);
}
public static final int AGENT_URI_FIELD_NUMBER = 1;
/**
*
*
* <pre>
* The URI to a file containing the exported agent. This field is populated
* if `agent_uri` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string agent_uri = 1;</code>
*
* @return Whether the agentUri field is set.
*/
public boolean hasAgentUri() {
return agentCase_ == 1;
}
/**
*
*
* <pre>
* The URI to a file containing the exported agent. This field is populated
* if `agent_uri` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string agent_uri = 1;</code>
*
* @return The agentUri.
*/
public java.lang.String getAgentUri() {
java.lang.Object ref = "";
if (agentCase_ == 1) {
ref = agent_;
}
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 (agentCase_ == 1) {
agent_ = s;
}
return s;
}
}
/**
*
*
* <pre>
* The URI to a file containing the exported agent. This field is populated
* if `agent_uri` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string agent_uri = 1;</code>
*
* @return The bytes for agentUri.
*/
public com.google.protobuf.ByteString getAgentUriBytes() {
java.lang.Object ref = "";
if (agentCase_ == 1) {
ref = agent_;
}
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (agentCase_ == 1) {
agent_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int AGENT_CONTENT_FIELD_NUMBER = 2;
/**
*
*
* <pre>
* Uncompressed raw byte content for agent. This field is populated
* if none of `agent_uri` and `git_destination` are specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>bytes agent_content = 2;</code>
*
* @return Whether the agentContent field is set.
*/
@java.lang.Override
public boolean hasAgentContent() {
return agentCase_ == 2;
}
/**
*
*
* <pre>
* Uncompressed raw byte content for agent. This field is populated
* if none of `agent_uri` and `git_destination` are specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>bytes agent_content = 2;</code>
*
* @return The agentContent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getAgentContent() {
if (agentCase_ == 2) {
return (com.google.protobuf.ByteString) agent_;
}
return com.google.protobuf.ByteString.EMPTY;
}
public static final int COMMIT_SHA_FIELD_NUMBER = 3;
/**
*
*
* <pre>
* Commit SHA of the git push. This field is populated if
* `git_destination` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string commit_sha = 3;</code>
*
* @return Whether the commitSha field is set.
*/
public boolean hasCommitSha() {
return agentCase_ == 3;
}
/**
*
*
* <pre>
* Commit SHA of the git push. This field is populated if
* `git_destination` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string commit_sha = 3;</code>
*
* @return The commitSha.
*/
public java.lang.String getCommitSha() {
java.lang.Object ref = "";
if (agentCase_ == 3) {
ref = agent_;
}
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 (agentCase_ == 3) {
agent_ = s;
}
return s;
}
}
/**
*
*
* <pre>
* Commit SHA of the git push. This field is populated if
* `git_destination` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string commit_sha = 3;</code>
*
* @return The bytes for commitSha.
*/
public com.google.protobuf.ByteString getCommitShaBytes() {
java.lang.Object ref = "";
if (agentCase_ == 3) {
ref = agent_;
}
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (agentCase_ == 3) {
agent_ = 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 (agentCase_ == 1) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, agent_);
}
if (agentCase_ == 2) {
output.writeBytes(2, (com.google.protobuf.ByteString) agent_);
}
if (agentCase_ == 3) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, agent_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (agentCase_ == 1) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, agent_);
}
if (agentCase_ == 2) {
size +=
com.google.protobuf.CodedOutputStream.computeBytesSize(
2, (com.google.protobuf.ByteString) agent_);
}
if (agentCase_ == 3) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, agent_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dialogflow.cx.v3.ExportAgentResponse)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.cx.v3.ExportAgentResponse other =
(com.google.cloud.dialogflow.cx.v3.ExportAgentResponse) obj;
if (!getAgentCase().equals(other.getAgentCase())) return false;
switch (agentCase_) {
case 1:
if (!getAgentUri().equals(other.getAgentUri())) return false;
break;
case 2:
if (!getAgentContent().equals(other.getAgentContent())) return false;
break;
case 3:
if (!getCommitSha().equals(other.getCommitSha())) 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 (agentCase_) {
case 1:
hash = (37 * hash) + AGENT_URI_FIELD_NUMBER;
hash = (53 * hash) + getAgentUri().hashCode();
break;
case 2:
hash = (37 * hash) + AGENT_CONTENT_FIELD_NUMBER;
hash = (53 * hash) + getAgentContent().hashCode();
break;
case 3:
hash = (37 * hash) + COMMIT_SHA_FIELD_NUMBER;
hash = (53 * hash) + getCommitSha().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.cx.v3.ExportAgentResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3.ExportAgentResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ExportAgentResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3.ExportAgentResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ExportAgentResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3.ExportAgentResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ExportAgentResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3.ExportAgentResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ExportAgentResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3.ExportAgentResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ExportAgentResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3.ExportAgentResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.dialogflow.cx.v3.ExportAgentResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The response message for
* [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.cx.v3.ExportAgentResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.cx.v3.ExportAgentResponse)
com.google.cloud.dialogflow.cx.v3.ExportAgentResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.cx.v3.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3_ExportAgentResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.cx.v3.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3_ExportAgentResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.cx.v3.ExportAgentResponse.class,
com.google.cloud.dialogflow.cx.v3.ExportAgentResponse.Builder.class);
}
// Construct using com.google.cloud.dialogflow.cx.v3.ExportAgentResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
agentCase_ = 0;
agent_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.cx.v3.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3_ExportAgentResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.ExportAgentResponse getDefaultInstanceForType() {
return com.google.cloud.dialogflow.cx.v3.ExportAgentResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.ExportAgentResponse build() {
com.google.cloud.dialogflow.cx.v3.ExportAgentResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.ExportAgentResponse buildPartial() {
com.google.cloud.dialogflow.cx.v3.ExportAgentResponse result =
new com.google.cloud.dialogflow.cx.v3.ExportAgentResponse(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.dialogflow.cx.v3.ExportAgentResponse result) {
int from_bitField0_ = bitField0_;
}
private void buildPartialOneofs(com.google.cloud.dialogflow.cx.v3.ExportAgentResponse result) {
result.agentCase_ = agentCase_;
result.agent_ = this.agent_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dialogflow.cx.v3.ExportAgentResponse) {
return mergeFrom((com.google.cloud.dialogflow.cx.v3.ExportAgentResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.cx.v3.ExportAgentResponse other) {
if (other == com.google.cloud.dialogflow.cx.v3.ExportAgentResponse.getDefaultInstance())
return this;
switch (other.getAgentCase()) {
case AGENT_URI:
{
agentCase_ = 1;
agent_ = other.agent_;
onChanged();
break;
}
case AGENT_CONTENT:
{
setAgentContent(other.getAgentContent());
break;
}
case COMMIT_SHA:
{
agentCase_ = 3;
agent_ = other.agent_;
onChanged();
break;
}
case AGENT_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();
agentCase_ = 1;
agent_ = s;
break;
} // case 10
case 18:
{
agent_ = input.readBytes();
agentCase_ = 2;
break;
} // case 18
case 26:
{
java.lang.String s = input.readStringRequireUtf8();
agentCase_ = 3;
agent_ = 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 agentCase_ = 0;
private java.lang.Object agent_;
public AgentCase getAgentCase() {
return AgentCase.forNumber(agentCase_);
}
public Builder clearAgent() {
agentCase_ = 0;
agent_ = null;
onChanged();
return this;
}
private int bitField0_;
/**
*
*
* <pre>
* The URI to a file containing the exported agent. This field is populated
* if `agent_uri` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string agent_uri = 1;</code>
*
* @return Whether the agentUri field is set.
*/
@java.lang.Override
public boolean hasAgentUri() {
return agentCase_ == 1;
}
/**
*
*
* <pre>
* The URI to a file containing the exported agent. This field is populated
* if `agent_uri` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string agent_uri = 1;</code>
*
* @return The agentUri.
*/
@java.lang.Override
public java.lang.String getAgentUri() {
java.lang.Object ref = "";
if (agentCase_ == 1) {
ref = agent_;
}
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (agentCase_ == 1) {
agent_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The URI to a file containing the exported agent. This field is populated
* if `agent_uri` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string agent_uri = 1;</code>
*
* @return The bytes for agentUri.
*/
@java.lang.Override
public com.google.protobuf.ByteString getAgentUriBytes() {
java.lang.Object ref = "";
if (agentCase_ == 1) {
ref = agent_;
}
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (agentCase_ == 1) {
agent_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The URI to a file containing the exported agent. This field is populated
* if `agent_uri` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string agent_uri = 1;</code>
*
* @param value The agentUri to set.
* @return This builder for chaining.
*/
public Builder setAgentUri(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
agentCase_ = 1;
agent_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The URI to a file containing the exported agent. This field is populated
* if `agent_uri` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string agent_uri = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearAgentUri() {
if (agentCase_ == 1) {
agentCase_ = 0;
agent_ = null;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The URI to a file containing the exported agent. This field is populated
* if `agent_uri` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string agent_uri = 1;</code>
*
* @param value The bytes for agentUri to set.
* @return This builder for chaining.
*/
public Builder setAgentUriBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
agentCase_ = 1;
agent_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Uncompressed raw byte content for agent. This field is populated
* if none of `agent_uri` and `git_destination` are specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>bytes agent_content = 2;</code>
*
* @return Whether the agentContent field is set.
*/
public boolean hasAgentContent() {
return agentCase_ == 2;
}
/**
*
*
* <pre>
* Uncompressed raw byte content for agent. This field is populated
* if none of `agent_uri` and `git_destination` are specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>bytes agent_content = 2;</code>
*
* @return The agentContent.
*/
public com.google.protobuf.ByteString getAgentContent() {
if (agentCase_ == 2) {
return (com.google.protobuf.ByteString) agent_;
}
return com.google.protobuf.ByteString.EMPTY;
}
/**
*
*
* <pre>
* Uncompressed raw byte content for agent. This field is populated
* if none of `agent_uri` and `git_destination` are specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>bytes agent_content = 2;</code>
*
* @param value The agentContent to set.
* @return This builder for chaining.
*/
public Builder setAgentContent(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
agentCase_ = 2;
agent_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Uncompressed raw byte content for agent. This field is populated
* if none of `agent_uri` and `git_destination` are specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>bytes agent_content = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearAgentContent() {
if (agentCase_ == 2) {
agentCase_ = 0;
agent_ = null;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Commit SHA of the git push. This field is populated if
* `git_destination` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string commit_sha = 3;</code>
*
* @return Whether the commitSha field is set.
*/
@java.lang.Override
public boolean hasCommitSha() {
return agentCase_ == 3;
}
/**
*
*
* <pre>
* Commit SHA of the git push. This field is populated if
* `git_destination` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string commit_sha = 3;</code>
*
* @return The commitSha.
*/
@java.lang.Override
public java.lang.String getCommitSha() {
java.lang.Object ref = "";
if (agentCase_ == 3) {
ref = agent_;
}
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (agentCase_ == 3) {
agent_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Commit SHA of the git push. This field is populated if
* `git_destination` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string commit_sha = 3;</code>
*
* @return The bytes for commitSha.
*/
@java.lang.Override
public com.google.protobuf.ByteString getCommitShaBytes() {
java.lang.Object ref = "";
if (agentCase_ == 3) {
ref = agent_;
}
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (agentCase_ == 3) {
agent_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Commit SHA of the git push. This field is populated if
* `git_destination` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string commit_sha = 3;</code>
*
* @param value The commitSha to set.
* @return This builder for chaining.
*/
public Builder setCommitSha(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
agentCase_ = 3;
agent_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Commit SHA of the git push. This field is populated if
* `git_destination` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string commit_sha = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearCommitSha() {
if (agentCase_ == 3) {
agentCase_ = 0;
agent_ = null;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Commit SHA of the git push. This field is populated if
* `git_destination` is specified in
* [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest].
* </pre>
*
* <code>string commit_sha = 3;</code>
*
* @param value The bytes for commitSha to set.
* @return This builder for chaining.
*/
public Builder setCommitShaBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
agentCase_ = 3;
agent_ = 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.dialogflow.cx.v3.ExportAgentResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.cx.v3.ExportAgentResponse)
private static final com.google.cloud.dialogflow.cx.v3.ExportAgentResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.cx.v3.ExportAgentResponse();
}
public static com.google.cloud.dialogflow.cx.v3.ExportAgentResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ExportAgentResponse> PARSER =
new com.google.protobuf.AbstractParser<ExportAgentResponse>() {
@java.lang.Override
public ExportAgentResponse 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<ExportAgentResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ExportAgentResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.ExportAgentResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
google/ExoPlayer | 35,643 | library/extractor/src/main/java/com/google/android/exoplayer2/text/webvtt/WebvttCueParser.java | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.text.webvtt;
import static java.lang.Math.min;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.SOURCE;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.text.style.UnderlineSpan;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.text.Cue;
import com.google.android.exoplayer2.text.span.HorizontalTextInVerticalContextSpan;
import com.google.android.exoplayer2.text.span.RubySpan;
import com.google.android.exoplayer2.text.span.SpanUtil;
import com.google.android.exoplayer2.text.span.TextAnnotation;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.ParsableByteArray;
import com.google.android.exoplayer2.util.Util;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
/**
* Parser for WebVTT cues. (https://w3c.github.io/webvtt/#cues)
*
* @deprecated com.google.android.exoplayer2 is deprecated. Please migrate to androidx.media3 (which
* contains the same ExoPlayer code). See <a
* href="https://developer.android.com/guide/topics/media/media3/getting-started/migration-guide">the
* migration guide</a> for more details, including a script to help with the migration.
*/
@Deprecated
public final class WebvttCueParser {
/**
* Valid values for {@link WebvttCueInfoBuilder#textAlignment}.
*
* <p>We use a custom list (and not {@link Layout.Alignment} directly) in order to include both
* {@code START}/{@code LEFT} and {@code END}/{@code RIGHT}. The distinction is important for
* {@link WebvttCueInfoBuilder#derivePosition(int)}.
*
* <p>These correspond to the valid values for the 'align' cue setting in the <a
* href="https://www.w3.org/TR/webvtt1/#webvtt-cue-text-alignment">WebVTT spec</a>.
*/
@Documented
@Retention(SOURCE)
@Target(TYPE_USE)
@IntDef({
TEXT_ALIGNMENT_START,
TEXT_ALIGNMENT_CENTER,
TEXT_ALIGNMENT_END,
TEXT_ALIGNMENT_LEFT,
TEXT_ALIGNMENT_RIGHT
})
private @interface TextAlignment {}
/**
* See WebVTT's <a
* href="https://www.w3.org/TR/webvtt1/#webvtt-cue-start-alignment">align:start</a>.
*/
private static final int TEXT_ALIGNMENT_START = 1;
/**
* See WebVTT's <a
* href="https://www.w3.org/TR/webvtt1/#webvtt-cue-center-alignment">align:center</a>.
*/
private static final int TEXT_ALIGNMENT_CENTER = 2;
/**
* See WebVTT's <a href="https://www.w3.org/TR/webvtt1/#webvtt-cue-end-alignment">align:end</a>.
*/
private static final int TEXT_ALIGNMENT_END = 3;
/**
* See WebVTT's <a href="https://www.w3.org/TR/webvtt1/#webvtt-cue-left-alignment">align:left</a>.
*/
private static final int TEXT_ALIGNMENT_LEFT = 4;
/**
* See WebVTT's <a
* href="https://www.w3.org/TR/webvtt1/#webvtt-cue-right-alignment">align:right</a>.
*/
private static final int TEXT_ALIGNMENT_RIGHT = 5;
public static final Pattern CUE_HEADER_PATTERN =
Pattern.compile("^(\\S+)\\s+-->\\s+(\\S+)(.*)?$");
private static final Pattern CUE_SETTING_PATTERN = Pattern.compile("(\\S+?):(\\S+)");
private static final char CHAR_LESS_THAN = '<';
private static final char CHAR_GREATER_THAN = '>';
private static final char CHAR_SLASH = '/';
private static final char CHAR_AMPERSAND = '&';
private static final char CHAR_SEMI_COLON = ';';
private static final char CHAR_SPACE = ' ';
private static final String ENTITY_LESS_THAN = "lt";
private static final String ENTITY_GREATER_THAN = "gt";
private static final String ENTITY_AMPERSAND = "amp";
private static final String ENTITY_NON_BREAK_SPACE = "nbsp";
private static final String TAG_BOLD = "b";
private static final String TAG_CLASS = "c";
private static final String TAG_ITALIC = "i";
private static final String TAG_LANG = "lang";
private static final String TAG_RUBY = "ruby";
private static final String TAG_RUBY_TEXT = "rt";
private static final String TAG_UNDERLINE = "u";
private static final String TAG_VOICE = "v";
private static final int STYLE_BOLD = Typeface.BOLD;
private static final int STYLE_ITALIC = Typeface.ITALIC;
/* package */ static final float DEFAULT_POSITION = 0.5f;
private static final String TAG = "WebvttCueParser";
/**
* See WebVTT's <a href="https://www.w3.org/TR/webvtt1/#default-text-color">default text
* colors</a>.
*/
private static final Map<String, Integer> DEFAULT_TEXT_COLORS;
static {
Map<String, Integer> defaultColors = new HashMap<>();
defaultColors.put("white", Color.rgb(255, 255, 255));
defaultColors.put("lime", Color.rgb(0, 255, 0));
defaultColors.put("cyan", Color.rgb(0, 255, 255));
defaultColors.put("red", Color.rgb(255, 0, 0));
defaultColors.put("yellow", Color.rgb(255, 255, 0));
defaultColors.put("magenta", Color.rgb(255, 0, 255));
defaultColors.put("blue", Color.rgb(0, 0, 255));
defaultColors.put("black", Color.rgb(0, 0, 0));
DEFAULT_TEXT_COLORS = Collections.unmodifiableMap(defaultColors);
}
/**
* See WebVTT's <a href="https://www.w3.org/TR/webvtt1/#default-text-background">default text
* background colors</a>.
*/
private static final Map<String, Integer> DEFAULT_BACKGROUND_COLORS;
static {
Map<String, Integer> defaultBackgroundColors = new HashMap<>();
defaultBackgroundColors.put("bg_white", Color.rgb(255, 255, 255));
defaultBackgroundColors.put("bg_lime", Color.rgb(0, 255, 0));
defaultBackgroundColors.put("bg_cyan", Color.rgb(0, 255, 255));
defaultBackgroundColors.put("bg_red", Color.rgb(255, 0, 0));
defaultBackgroundColors.put("bg_yellow", Color.rgb(255, 255, 0));
defaultBackgroundColors.put("bg_magenta", Color.rgb(255, 0, 255));
defaultBackgroundColors.put("bg_blue", Color.rgb(0, 0, 255));
defaultBackgroundColors.put("bg_black", Color.rgb(0, 0, 0));
DEFAULT_BACKGROUND_COLORS = Collections.unmodifiableMap(defaultBackgroundColors);
}
/**
* Parses the next valid WebVTT cue in a parsable array, including timestamps, settings and text.
*
* @param webvttData Parsable WebVTT file data.
* @param styles List of styles defined by the CSS style blocks preceding the cues.
* @return The parsed cue info, or null if no valid cue was found.
*/
@Nullable
public static WebvttCueInfo parseCue(ParsableByteArray webvttData, List<WebvttCssStyle> styles) {
@Nullable String firstLine = webvttData.readLine();
if (firstLine == null) {
return null;
}
Matcher cueHeaderMatcher = WebvttCueParser.CUE_HEADER_PATTERN.matcher(firstLine);
if (cueHeaderMatcher.matches()) {
// We have found the timestamps in the first line. No id present.
return parseCue(null, cueHeaderMatcher, webvttData, styles);
}
// The first line is not the timestamps, but could be the cue id.
@Nullable String secondLine = webvttData.readLine();
if (secondLine == null) {
return null;
}
cueHeaderMatcher = WebvttCueParser.CUE_HEADER_PATTERN.matcher(secondLine);
if (cueHeaderMatcher.matches()) {
// We can do the rest of the parsing, including the id.
return parseCue(firstLine.trim(), cueHeaderMatcher, webvttData, styles);
}
return null;
}
/**
* Parses a string containing a list of cue settings.
*
* @param cueSettingsList String containing the settings for a given cue.
* @return The cue settings parsed into a {@link Cue.Builder}.
*/
/* package */ static Cue.Builder parseCueSettingsList(String cueSettingsList) {
WebvttCueInfoBuilder builder = new WebvttCueInfoBuilder();
parseCueSettingsList(cueSettingsList, builder);
return builder.toCueBuilder();
}
/** Create a new {@link Cue} containing {@code text} and with WebVTT default values. */
/* package */ static Cue newCueForText(CharSequence text) {
WebvttCueInfoBuilder infoBuilder = new WebvttCueInfoBuilder();
infoBuilder.text = text;
return infoBuilder.toCueBuilder().build();
}
/**
* Parses the text payload of a WebVTT Cue and returns it as a styled {@link SpannedString}.
*
* @param id ID of the cue, {@code null} if it is not present.
* @param markup The markup text to be parsed.
* @param styles List of styles defined by the CSS style blocks preceding the cues.
* @return The styled cue text.
*/
/* package */ static SpannedString parseCueText(
@Nullable String id, String markup, List<WebvttCssStyle> styles) {
SpannableStringBuilder spannedText = new SpannableStringBuilder();
ArrayDeque<StartTag> startTagStack = new ArrayDeque<>();
int pos = 0;
List<Element> nestedElements = new ArrayList<>();
while (pos < markup.length()) {
char curr = markup.charAt(pos);
switch (curr) {
case CHAR_LESS_THAN:
if (pos + 1 >= markup.length()) {
pos++;
break; // avoid ArrayOutOfBoundsException
}
int ltPos = pos;
boolean isClosingTag = markup.charAt(ltPos + 1) == CHAR_SLASH;
pos = findEndOfTag(markup, ltPos + 1);
boolean isVoidTag = markup.charAt(pos - 2) == CHAR_SLASH;
String fullTagExpression =
markup.substring(ltPos + (isClosingTag ? 2 : 1), isVoidTag ? pos - 2 : pos - 1);
if (fullTagExpression.trim().isEmpty()) {
continue;
}
String tagName = getTagName(fullTagExpression);
if (!isSupportedTag(tagName)) {
continue;
}
if (isClosingTag) {
StartTag startTag;
do {
if (startTagStack.isEmpty()) {
break;
}
startTag = startTagStack.pop();
applySpansForTag(id, startTag, nestedElements, spannedText, styles);
if (!startTagStack.isEmpty()) {
nestedElements.add(new Element(startTag, spannedText.length()));
} else {
nestedElements.clear();
}
} while (!startTag.name.equals(tagName));
} else if (!isVoidTag) {
startTagStack.push(StartTag.buildStartTag(fullTagExpression, spannedText.length()));
}
break;
case CHAR_AMPERSAND:
int semiColonEndIndex = markup.indexOf(CHAR_SEMI_COLON, pos + 1);
int spaceEndIndex = markup.indexOf(CHAR_SPACE, pos + 1);
int entityEndIndex =
semiColonEndIndex == -1
? spaceEndIndex
: (spaceEndIndex == -1
? semiColonEndIndex
: min(semiColonEndIndex, spaceEndIndex));
if (entityEndIndex != -1) {
applyEntity(markup.substring(pos + 1, entityEndIndex), spannedText);
if (entityEndIndex == spaceEndIndex) {
spannedText.append(" ");
}
pos = entityEndIndex + 1;
} else {
spannedText.append(curr);
pos++;
}
break;
default:
spannedText.append(curr);
pos++;
break;
}
}
// apply unclosed tags
while (!startTagStack.isEmpty()) {
applySpansForTag(id, startTagStack.pop(), nestedElements, spannedText, styles);
}
applySpansForTag(
id,
StartTag.buildWholeCueVirtualTag(),
/* nestedElements= */ Collections.emptyList(),
spannedText,
styles);
return SpannedString.valueOf(spannedText);
}
// Internal methods
@Nullable
private static WebvttCueInfo parseCue(
@Nullable String id,
Matcher cueHeaderMatcher,
ParsableByteArray webvttData,
List<WebvttCssStyle> styles) {
WebvttCueInfoBuilder builder = new WebvttCueInfoBuilder();
try {
// Parse the cue start and end times.
builder.startTimeUs =
WebvttParserUtil.parseTimestampUs(Assertions.checkNotNull(cueHeaderMatcher.group(1)));
builder.endTimeUs =
WebvttParserUtil.parseTimestampUs(Assertions.checkNotNull(cueHeaderMatcher.group(2)));
} catch (NumberFormatException e) {
Log.w(TAG, "Skipping cue with bad header: " + cueHeaderMatcher.group());
return null;
}
parseCueSettingsList(Assertions.checkNotNull(cueHeaderMatcher.group(3)), builder);
// Parse the cue text.
StringBuilder textBuilder = new StringBuilder();
for (String line = webvttData.readLine();
!TextUtils.isEmpty(line);
line = webvttData.readLine()) {
if (textBuilder.length() > 0) {
textBuilder.append("\n");
}
textBuilder.append(line.trim());
}
builder.text = parseCueText(id, textBuilder.toString(), styles);
return builder.build();
}
private static void parseCueSettingsList(String cueSettingsList, WebvttCueInfoBuilder builder) {
// Parse the cue settings list.
Matcher cueSettingMatcher = CUE_SETTING_PATTERN.matcher(cueSettingsList);
while (cueSettingMatcher.find()) {
String name = Assertions.checkNotNull(cueSettingMatcher.group(1));
String value = Assertions.checkNotNull(cueSettingMatcher.group(2));
try {
if ("line".equals(name)) {
parseLineAttribute(value, builder);
} else if ("align".equals(name)) {
builder.textAlignment = parseTextAlignment(value);
} else if ("position".equals(name)) {
parsePositionAttribute(value, builder);
} else if ("size".equals(name)) {
builder.size = WebvttParserUtil.parsePercentage(value);
} else if ("vertical".equals(name)) {
builder.verticalType = parseVerticalAttribute(value);
} else {
Log.w(TAG, "Unknown cue setting " + name + ":" + value);
}
} catch (NumberFormatException e) {
Log.w(TAG, "Skipping bad cue setting: " + cueSettingMatcher.group());
}
}
}
private static void parseLineAttribute(String s, WebvttCueInfoBuilder builder) {
int commaIndex = s.indexOf(',');
if (commaIndex != -1) {
builder.lineAnchor = parseLineAnchor(s.substring(commaIndex + 1));
s = s.substring(0, commaIndex);
}
if (s.endsWith("%")) {
builder.line = WebvttParserUtil.parsePercentage(s);
builder.lineType = Cue.LINE_TYPE_FRACTION;
} else {
builder.line = Integer.parseInt(s);
builder.lineType = Cue.LINE_TYPE_NUMBER;
}
}
private static @Cue.AnchorType int parseLineAnchor(String s) {
switch (s) {
case "start":
return Cue.ANCHOR_TYPE_START;
case "center":
case "middle":
return Cue.ANCHOR_TYPE_MIDDLE;
case "end":
return Cue.ANCHOR_TYPE_END;
default:
Log.w(TAG, "Invalid anchor value: " + s);
return Cue.TYPE_UNSET;
}
}
private static void parsePositionAttribute(String s, WebvttCueInfoBuilder builder) {
int commaIndex = s.indexOf(',');
if (commaIndex != -1) {
builder.positionAnchor = parsePositionAnchor(s.substring(commaIndex + 1));
s = s.substring(0, commaIndex);
}
builder.position = WebvttParserUtil.parsePercentage(s);
}
private static @Cue.AnchorType int parsePositionAnchor(String s) {
switch (s) {
case "line-left":
case "start":
return Cue.ANCHOR_TYPE_START;
case "center":
case "middle":
return Cue.ANCHOR_TYPE_MIDDLE;
case "line-right":
case "end":
return Cue.ANCHOR_TYPE_END;
default:
Log.w(TAG, "Invalid anchor value: " + s);
return Cue.TYPE_UNSET;
}
}
private static @Cue.VerticalType int parseVerticalAttribute(String s) {
switch (s) {
case "rl":
return Cue.VERTICAL_TYPE_RL;
case "lr":
return Cue.VERTICAL_TYPE_LR;
default:
Log.w(TAG, "Invalid 'vertical' value: " + s);
return Cue.TYPE_UNSET;
}
}
private static @TextAlignment int parseTextAlignment(String s) {
switch (s) {
case "start":
return TEXT_ALIGNMENT_START;
case "left":
return TEXT_ALIGNMENT_LEFT;
case "center":
case "middle":
return TEXT_ALIGNMENT_CENTER;
case "end":
return TEXT_ALIGNMENT_END;
case "right":
return TEXT_ALIGNMENT_RIGHT;
default:
Log.w(TAG, "Invalid alignment value: " + s);
// Default value: https://www.w3.org/TR/webvtt1/#webvtt-cue-text-alignment
return TEXT_ALIGNMENT_CENTER;
}
}
/**
* Find end of tag (>). The position returned is the position of the > plus one (exclusive).
*
* @param markup The WebVTT cue markup to be parsed.
* @param startPos The position from where to start searching for the end of tag.
* @return The position of the end of tag plus 1 (one).
*/
private static int findEndOfTag(String markup, int startPos) {
int index = markup.indexOf(CHAR_GREATER_THAN, startPos);
return index == -1 ? markup.length() : index + 1;
}
private static void applyEntity(String entity, SpannableStringBuilder spannedText) {
switch (entity) {
case ENTITY_LESS_THAN:
spannedText.append('<');
break;
case ENTITY_GREATER_THAN:
spannedText.append('>');
break;
case ENTITY_NON_BREAK_SPACE:
spannedText.append(' ');
break;
case ENTITY_AMPERSAND:
spannedText.append('&');
break;
default:
Log.w(TAG, "ignoring unsupported entity: '&" + entity + ";'");
break;
}
}
private static boolean isSupportedTag(String tagName) {
switch (tagName) {
case TAG_BOLD:
case TAG_CLASS:
case TAG_ITALIC:
case TAG_LANG:
case TAG_RUBY:
case TAG_RUBY_TEXT:
case TAG_UNDERLINE:
case TAG_VOICE:
return true;
default:
return false;
}
}
private static void applySpansForTag(
@Nullable String cueId,
StartTag startTag,
List<Element> nestedElements,
SpannableStringBuilder text,
List<WebvttCssStyle> styles) {
int start = startTag.position;
int end = text.length();
switch (startTag.name) {
case TAG_BOLD:
text.setSpan(new StyleSpan(STYLE_BOLD), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case TAG_ITALIC:
text.setSpan(new StyleSpan(STYLE_ITALIC), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case TAG_RUBY:
applyRubySpans(text, cueId, startTag, nestedElements, styles);
break;
case TAG_UNDERLINE:
text.setSpan(new UnderlineSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case TAG_CLASS:
applyDefaultColors(text, startTag.classes, start, end);
break;
case TAG_LANG:
case TAG_VOICE:
case "": // Case of the "whole cue" virtual tag.
break;
default:
return;
}
List<StyleMatch> applicableStyles = getApplicableStyles(styles, cueId, startTag);
for (int i = 0; i < applicableStyles.size(); i++) {
applyStyleToText(text, applicableStyles.get(i).style, start, end);
}
}
private static void applyRubySpans(
SpannableStringBuilder text,
@Nullable String cueId,
StartTag startTag,
List<Element> nestedElements,
List<WebvttCssStyle> styles) {
@TextAnnotation.Position int rubyTagPosition = getRubyPosition(styles, cueId, startTag);
List<Element> sortedNestedElements = new ArrayList<>(nestedElements.size());
sortedNestedElements.addAll(nestedElements);
Collections.sort(sortedNestedElements, Element.BY_START_POSITION_ASC);
int deletedCharCount = 0;
int lastRubyTextEnd = startTag.position;
for (int i = 0; i < sortedNestedElements.size(); i++) {
if (!TAG_RUBY_TEXT.equals(sortedNestedElements.get(i).startTag.name)) {
continue;
}
Element rubyTextElement = sortedNestedElements.get(i);
// Use the <rt> element's ruby-position if set, otherwise the <ruby> element's and otherwise
// default to OVER.
@TextAnnotation.Position
int rubyPosition =
firstKnownRubyPosition(
getRubyPosition(styles, cueId, rubyTextElement.startTag),
rubyTagPosition,
TextAnnotation.POSITION_BEFORE);
// Move the rubyText from spannedText into the RubySpan.
int adjustedRubyTextStart = rubyTextElement.startTag.position - deletedCharCount;
int adjustedRubyTextEnd = rubyTextElement.endPosition - deletedCharCount;
CharSequence rubyText = text.subSequence(adjustedRubyTextStart, adjustedRubyTextEnd);
text.delete(adjustedRubyTextStart, adjustedRubyTextEnd);
text.setSpan(
new RubySpan(rubyText.toString(), rubyPosition),
lastRubyTextEnd,
adjustedRubyTextStart,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
deletedCharCount += rubyText.length();
// The ruby text has been deleted, so new-start == old-end.
lastRubyTextEnd = adjustedRubyTextStart;
}
}
private static @TextAnnotation.Position int getRubyPosition(
List<WebvttCssStyle> styles, @Nullable String cueId, StartTag startTag) {
List<StyleMatch> styleMatches = getApplicableStyles(styles, cueId, startTag);
for (int i = 0; i < styleMatches.size(); i++) {
WebvttCssStyle style = styleMatches.get(i).style;
if (style.getRubyPosition() != TextAnnotation.POSITION_UNKNOWN) {
return style.getRubyPosition();
}
}
return TextAnnotation.POSITION_UNKNOWN;
}
private static @TextAnnotation.Position int firstKnownRubyPosition(
@TextAnnotation.Position int position1,
@TextAnnotation.Position int position2,
@TextAnnotation.Position int position3) {
if (position1 != TextAnnotation.POSITION_UNKNOWN) {
return position1;
}
if (position2 != TextAnnotation.POSITION_UNKNOWN) {
return position2;
}
if (position3 != TextAnnotation.POSITION_UNKNOWN) {
return position3;
}
throw new IllegalArgumentException();
}
/**
* Adds {@link ForegroundColorSpan}s and {@link BackgroundColorSpan}s to {@code text} for entries
* in {@code classes} that match WebVTT's <a
* href="https://www.w3.org/TR/webvtt1/#default-text-color">default text colors</a> or <a
* href="https://www.w3.org/TR/webvtt1/#default-text-background">default text background
* colors</a>.
*/
private static void applyDefaultColors(
SpannableStringBuilder text, Set<String> classes, int start, int end) {
for (String className : classes) {
if (DEFAULT_TEXT_COLORS.containsKey(className)) {
int color = DEFAULT_TEXT_COLORS.get(className);
text.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if (DEFAULT_BACKGROUND_COLORS.containsKey(className)) {
int color = DEFAULT_BACKGROUND_COLORS.get(className);
text.setSpan(new BackgroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
private static void applyStyleToText(
SpannableStringBuilder spannedText, WebvttCssStyle style, int start, int end) {
if (style == null) {
return;
}
if (style.getStyle() != WebvttCssStyle.UNSPECIFIED) {
SpanUtil.addOrReplaceSpan(
spannedText,
new StyleSpan(style.getStyle()),
start,
end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (style.isLinethrough()) {
spannedText.setSpan(new StrikethroughSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (style.isUnderline()) {
spannedText.setSpan(new UnderlineSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (style.hasFontColor()) {
SpanUtil.addOrReplaceSpan(
spannedText,
new ForegroundColorSpan(style.getFontColor()),
start,
end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (style.hasBackgroundColor()) {
SpanUtil.addOrReplaceSpan(
spannedText,
new BackgroundColorSpan(style.getBackgroundColor()),
start,
end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (style.getFontFamily() != null) {
SpanUtil.addOrReplaceSpan(
spannedText,
new TypefaceSpan(style.getFontFamily()),
start,
end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
switch (style.getFontSizeUnit()) {
case WebvttCssStyle.FONT_SIZE_UNIT_PIXEL:
SpanUtil.addOrReplaceSpan(
spannedText,
new AbsoluteSizeSpan((int) style.getFontSize(), true),
start,
end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case WebvttCssStyle.FONT_SIZE_UNIT_EM:
SpanUtil.addOrReplaceSpan(
spannedText,
new RelativeSizeSpan(style.getFontSize()),
start,
end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case WebvttCssStyle.FONT_SIZE_UNIT_PERCENT:
SpanUtil.addOrReplaceSpan(
spannedText,
new RelativeSizeSpan(style.getFontSize() / 100),
start,
end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
break;
case WebvttCssStyle.UNSPECIFIED:
// Do nothing.
break;
}
if (style.getCombineUpright()) {
spannedText.setSpan(
new HorizontalTextInVerticalContextSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
/**
* Returns the tag name for the given tag contents.
*
* @param tagExpression Characters between &lt: and &gt; of a start or end tag.
* @return The name of tag.
*/
private static String getTagName(String tagExpression) {
tagExpression = tagExpression.trim();
Assertions.checkArgument(!tagExpression.isEmpty());
return Util.splitAtFirst(tagExpression, "[ \\.]")[0];
}
private static List<StyleMatch> getApplicableStyles(
List<WebvttCssStyle> declaredStyles, @Nullable String id, StartTag tag) {
List<StyleMatch> applicableStyles = new ArrayList<>();
for (int i = 0; i < declaredStyles.size(); i++) {
WebvttCssStyle style = declaredStyles.get(i);
int score = style.getSpecificityScore(id, tag.name, tag.classes, tag.voice);
if (score > 0) {
applicableStyles.add(new StyleMatch(score, style));
}
}
Collections.sort(applicableStyles);
return applicableStyles;
}
private static final class WebvttCueInfoBuilder {
public long startTimeUs;
public long endTimeUs;
public @MonotonicNonNull CharSequence text;
public @TextAlignment int textAlignment;
public float line;
// Equivalent to WebVTT's snap-to-lines flag:
// https://www.w3.org/TR/webvtt1/#webvtt-cue-snap-to-lines-flag
public @Cue.LineType int lineType;
public @Cue.AnchorType int lineAnchor;
public float position;
public @Cue.AnchorType int positionAnchor;
public float size;
public @Cue.VerticalType int verticalType;
public WebvttCueInfoBuilder() {
startTimeUs = 0;
endTimeUs = 0;
// Default: https://www.w3.org/TR/webvtt1/#webvtt-cue-text-alignment
textAlignment = TEXT_ALIGNMENT_CENTER;
line = Cue.DIMEN_UNSET;
// Defaults to NUMBER (true): https://www.w3.org/TR/webvtt1/#webvtt-cue-snap-to-lines-flag
lineType = Cue.LINE_TYPE_NUMBER;
// Default: https://www.w3.org/TR/webvtt1/#webvtt-cue-line-alignment
lineAnchor = Cue.ANCHOR_TYPE_START;
position = Cue.DIMEN_UNSET;
positionAnchor = Cue.TYPE_UNSET;
// Default: https://www.w3.org/TR/webvtt1/#webvtt-cue-size
size = 1.0f;
verticalType = Cue.TYPE_UNSET;
}
public WebvttCueInfo build() {
return new WebvttCueInfo(toCueBuilder().build(), startTimeUs, endTimeUs);
}
public Cue.Builder toCueBuilder() {
float position =
this.position != Cue.DIMEN_UNSET ? this.position : derivePosition(textAlignment);
@Cue.AnchorType
int positionAnchor =
this.positionAnchor != Cue.TYPE_UNSET
? this.positionAnchor
: derivePositionAnchor(textAlignment);
Cue.Builder cueBuilder =
new Cue.Builder()
.setTextAlignment(convertTextAlignment(textAlignment))
.setLine(computeLine(line, lineType), lineType)
.setLineAnchor(lineAnchor)
.setPosition(position)
.setPositionAnchor(positionAnchor)
.setSize(min(size, deriveMaxSize(positionAnchor, position)))
.setVerticalType(verticalType);
if (text != null) {
cueBuilder.setText(text);
}
return cueBuilder;
}
// https://www.w3.org/TR/webvtt1/#webvtt-cue-line
private static float computeLine(float line, @Cue.LineType int lineType) {
if (line != Cue.DIMEN_UNSET
&& lineType == Cue.LINE_TYPE_FRACTION
&& (line < 0.0f || line > 1.0f)) {
return 1.0f; // Step 1
} else if (line != Cue.DIMEN_UNSET) {
// Step 2: Do nothing, line is already correct.
return line;
} else if (lineType == Cue.LINE_TYPE_FRACTION) {
return 1.0f; // Step 3
} else {
// Steps 4 - 10 (stacking multiple simultaneous cues) are handled by
// WebvttSubtitle.getCues(long) and WebvttSubtitle.isNormal(Cue).
return Cue.DIMEN_UNSET;
}
}
// https://www.w3.org/TR/webvtt1/#webvtt-cue-position
private static float derivePosition(@TextAlignment int textAlignment) {
switch (textAlignment) {
case TEXT_ALIGNMENT_LEFT:
return 0.0f;
case TEXT_ALIGNMENT_RIGHT:
return 1.0f;
case TEXT_ALIGNMENT_START:
case TEXT_ALIGNMENT_CENTER:
case TEXT_ALIGNMENT_END:
default:
return DEFAULT_POSITION;
}
}
// https://www.w3.org/TR/webvtt1/#webvtt-cue-position-alignment
private static @Cue.AnchorType int derivePositionAnchor(@TextAlignment int textAlignment) {
switch (textAlignment) {
case TEXT_ALIGNMENT_LEFT:
case TEXT_ALIGNMENT_START:
return Cue.ANCHOR_TYPE_START;
case TEXT_ALIGNMENT_RIGHT:
case TEXT_ALIGNMENT_END:
return Cue.ANCHOR_TYPE_END;
case TEXT_ALIGNMENT_CENTER:
default:
return Cue.ANCHOR_TYPE_MIDDLE;
}
}
@Nullable
private static Layout.Alignment convertTextAlignment(@TextAlignment int textAlignment) {
switch (textAlignment) {
case TEXT_ALIGNMENT_START:
case TEXT_ALIGNMENT_LEFT:
return Layout.Alignment.ALIGN_NORMAL;
case TEXT_ALIGNMENT_CENTER:
return Layout.Alignment.ALIGN_CENTER;
case TEXT_ALIGNMENT_END:
case TEXT_ALIGNMENT_RIGHT:
return Layout.Alignment.ALIGN_OPPOSITE;
default:
Log.w(TAG, "Unknown textAlignment: " + textAlignment);
return null;
}
}
// Step 2 here: https://www.w3.org/TR/webvtt1/#processing-cue-settings
private static float deriveMaxSize(@Cue.AnchorType int positionAnchor, float position) {
switch (positionAnchor) {
case Cue.ANCHOR_TYPE_START:
return 1.0f - position;
case Cue.ANCHOR_TYPE_END:
return position;
case Cue.ANCHOR_TYPE_MIDDLE:
if (position <= 0.5f) {
return position * 2;
} else {
return (1.0f - position) * 2;
}
case Cue.TYPE_UNSET:
default:
throw new IllegalStateException(String.valueOf(positionAnchor));
}
}
}
private static final class StyleMatch implements Comparable<StyleMatch> {
public final int score;
public final WebvttCssStyle style;
public StyleMatch(int score, WebvttCssStyle style) {
this.score = score;
this.style = style;
}
@Override
public int compareTo(StyleMatch another) {
return Integer.compare(this.score, another.score);
}
}
private static final class StartTag {
public final String name;
public final int position;
public final String voice;
public final Set<String> classes;
private StartTag(String name, int position, String voice, Set<String> classes) {
this.position = position;
this.name = name;
this.voice = voice;
this.classes = classes;
}
public static StartTag buildStartTag(String fullTagExpression, int position) {
fullTagExpression = fullTagExpression.trim();
Assertions.checkArgument(!fullTagExpression.isEmpty());
int voiceStartIndex = fullTagExpression.indexOf(" ");
String voice;
if (voiceStartIndex == -1) {
voice = "";
} else {
voice = fullTagExpression.substring(voiceStartIndex).trim();
fullTagExpression = fullTagExpression.substring(0, voiceStartIndex);
}
String[] nameAndClasses = Util.split(fullTagExpression, "\\.");
String name = nameAndClasses[0];
Set<String> classes = new HashSet<>();
for (int i = 1; i < nameAndClasses.length; i++) {
classes.add(nameAndClasses[i]);
}
return new StartTag(name, position, voice, classes);
}
public static StartTag buildWholeCueVirtualTag() {
return new StartTag(
/* name= */ "",
/* position= */ 0,
/* voice= */ "",
/* classes= */ Collections.emptySet());
}
}
/** Information about a complete element (i.e. start tag and end position). */
private static class Element {
private static final Comparator<Element> BY_START_POSITION_ASC =
(e1, e2) -> Integer.compare(e1.startTag.position, e2.startTag.position);
private final StartTag startTag;
/**
* The position of the end of this element's text in the un-marked-up cue text (i.e. the
* corollary to {@link StartTag#position}).
*/
private final int endPosition;
private Element(StartTag startTag, int endPosition) {
this.startTag = startTag;
this.endPosition = endPosition;
}
}
}
|
apache/maven-plugins | 35,625 | maven-project-info-reports-plugin/src/main/java/org/apache/maven/report/projectinfo/DependencyConvergenceReport.java | package org.apache.maven.report.projectinfo;
/*
* 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.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.resolver.ArtifactCollector;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.doxia.sink.Sink;
import org.apache.maven.doxia.sink.SinkEventAttributeSet;
import org.apache.maven.doxia.sink.SinkEventAttributes;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.report.projectinfo.dependencies.DependencyVersionMap;
import org.apache.maven.report.projectinfo.dependencies.SinkSerializingDependencyNodeVisitor;
import org.apache.maven.reporting.MavenReportException;
import org.apache.maven.shared.artifact.filter.StrictPatternIncludesArtifactFilter;
import org.apache.maven.shared.dependency.tree.DependencyNode;
import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder;
import org.apache.maven.shared.dependency.tree.DependencyTreeBuilderException;
import org.apache.maven.shared.dependency.tree.filter.AncestorOrSelfDependencyNodeFilter;
import org.apache.maven.shared.dependency.tree.filter.AndDependencyNodeFilter;
import org.apache.maven.shared.dependency.tree.filter.ArtifactDependencyNodeFilter;
import org.apache.maven.shared.dependency.tree.filter.DependencyNodeFilter;
import org.apache.maven.shared.dependency.tree.traversal.BuildingDependencyNodeVisitor;
import org.apache.maven.shared.dependency.tree.traversal.CollectingDependencyNodeVisitor;
import org.apache.maven.shared.dependency.tree.traversal.DependencyNodeVisitor;
import org.apache.maven.shared.dependency.tree.traversal.FilteringDependencyNodeVisitor;
/**
* Generates the Project Dependency Convergence report for (reactor) builds.
*
* @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
* @author <a href="mailto:vincent.siveton@gmail.com">Vincent Siveton </a>
* @author <a href="mailto:wangyf2010@gmail.com">Simon Wang </a>
* @version $Id$
* @since 2.0
*/
@Mojo( name = "dependency-convergence", aggregator = true )
public class DependencyConvergenceReport
extends AbstractProjectInfoReport
{
/** URL for the 'icon_success_sml.gif' image */
private static final String IMG_SUCCESS_URL = "images/icon_success_sml.gif";
/** URL for the 'icon_error_sml.gif' image */
private static final String IMG_ERROR_URL = "images/icon_error_sml.gif";
private static final int FULL_CONVERGENCE = 100;
// ----------------------------------------------------------------------
// Mojo parameters
// ----------------------------------------------------------------------
/**
* The projects in the current build. The effective POM for each of these projects will written.
*/
@Parameter( property = "reactorProjects", required = true, readonly = true )
private List<MavenProject> reactorProjects;
/**
* Dependency tree builder, will use it to build dependency tree.
*/
@Component
DependencyTreeBuilder dependencyTreeBuilder;
/**
* Use it to build dependency(artifact) tree
*/
@Component
ArtifactFactory factory;
/**
* Use it to get artifact metadata source for dependency tree building.
*/
@Component
ArtifactMetadataSource metadataSource;
/**
* Artifact collector - takes a set of original artifacts and resolves all of the best versions to use along with
* their metadata.
*/
@Component
ArtifactCollector collector;
ArtifactFilter filter = null;
private Map<MavenProject, DependencyNode> projectMap = new HashMap<MavenProject, DependencyNode>();
// ----------------------------------------------------------------------
// Public methods
// ----------------------------------------------------------------------
/** {@inheritDoc} */
public String getOutputName()
{
return "dependency-convergence";
}
@Override
protected String getI18Nsection()
{
return "dependency-convergence";
}
// ----------------------------------------------------------------------
// Protected methods
// ----------------------------------------------------------------------
@Override
protected void executeReport( Locale locale )
throws MavenReportException
{
Sink sink = getSink();
sink.head();
sink.title();
if ( isReactorBuild() )
{
sink.text( getI18nString( locale, "reactor.title" ) );
}
else
{
sink.text( getI18nString( locale, "title" ) );
}
sink.title_();
sink.head_();
sink.body();
sink.section1();
sink.sectionTitle1();
if ( isReactorBuild() )
{
sink.text( getI18nString( locale, "reactor.title" ) );
}
else
{
sink.text( getI18nString( locale, "title" ) );
}
sink.sectionTitle1_();
DependencyAnalyzeResult dependencyResult = analyzeDependencyTree();
int convergence = calculateConvergence( dependencyResult );
if ( convergence < FULL_CONVERGENCE )
{
// legend
generateLegend( locale, sink );
sink.lineBreak();
}
// stats
generateStats( locale, sink, dependencyResult );
sink.section1_();
if ( convergence < FULL_CONVERGENCE )
{
// convergence
generateConvergence( locale, sink, dependencyResult );
}
sink.body_();
sink.flush();
sink.close();
}
// ----------------------------------------------------------------------
// Private methods
// ----------------------------------------------------------------------
/**
* Get snapshots dependencies from all dependency map.
*
* @param dependencyMap
* @return snapshots dependencies
*/
// CHECKSTYLE_OFF: LineLength
private List<ReverseDependencyLink> getSnapshotDependencies( Map<String, List<ReverseDependencyLink>> dependencyMap )
// CHECKSTYLE_ON: LineLength
{
List<ReverseDependencyLink> snapshots = new ArrayList<ReverseDependencyLink>();
for ( Map.Entry<String, List<ReverseDependencyLink>> entry : dependencyMap.entrySet() )
{
List<ReverseDependencyLink> depList = entry.getValue();
Map<String, List<ReverseDependencyLink>> artifactMap = getSortedUniqueArtifactMap( depList );
for ( Map.Entry<String, List<ReverseDependencyLink>> artEntry : artifactMap.entrySet() )
{
String version = artEntry.getKey();
boolean isReactorProject = false;
Iterator<ReverseDependencyLink> iterator = artEntry.getValue().iterator();
// It if enough to check just the first dependency here, because
// the dependency is the same in all the RDLs in the List. It's the
// reactorProjects that are different.
ReverseDependencyLink rdl = null;
if ( iterator.hasNext() )
{
rdl = iterator.next();
if ( isReactorProject( rdl.getDependency() ) )
{
isReactorProject = true;
}
}
if ( version.endsWith( "-SNAPSHOT" ) && !isReactorProject && rdl != null )
{
snapshots.add( rdl );
}
}
}
return snapshots;
}
/**
* Generate the convergence table for all dependencies
*
* @param locale
* @param sink
* @param conflictingDependencyMap
*/
private void generateConvergence( Locale locale, Sink sink, DependencyAnalyzeResult result )
{
sink.section2();
sink.sectionTitle2();
if ( isReactorBuild() )
{
sink.text( getI18nString( locale, "convergence.caption" ) );
}
else
{
sink.text( getI18nString( locale, "convergence.single.caption" ) );
}
sink.sectionTitle2_();
// print conflicting dependencies
for ( Map.Entry<String, List<ReverseDependencyLink>> entry : result.getConflicting().entrySet() )
{
String key = entry.getKey();
List<ReverseDependencyLink> depList = entry.getValue();
sink.section3();
sink.sectionTitle3();
sink.text( key );
sink.sectionTitle3_();
generateDependencyDetails( locale, sink, depList );
sink.section3_();
}
// print out snapshots jars
for ( ReverseDependencyLink dependencyLink : result.getSnapshots() )
{
sink.section3();
sink.sectionTitle3();
Dependency dep = dependencyLink.getDependency();
sink.text( dep.getGroupId() + ":" + dep.getArtifactId() );
sink.sectionTitle3_();
List<ReverseDependencyLink> depList = new ArrayList<ReverseDependencyLink>();
depList.add( dependencyLink );
generateDependencyDetails( locale, sink, depList );
sink.section3_();
}
sink.section2_();
}
/**
* Generate the detail table for a given dependency
*
* @param sink
* @param depList
*/
private void generateDependencyDetails( Locale locale, Sink sink, List<ReverseDependencyLink> depList )
{
sink.table();
Map<String, List<ReverseDependencyLink>> artifactMap = getSortedUniqueArtifactMap( depList );
sink.tableRow();
sink.tableCell();
iconError( locale, sink );
sink.tableCell_();
sink.tableCell();
sink.table();
for ( String version : artifactMap.keySet() )
{
sink.tableRow();
sink.tableCell( new SinkEventAttributeSet( new String[] { SinkEventAttributes.WIDTH, "25%" } ) );
sink.text( version );
sink.tableCell_();
sink.tableCell();
generateVersionDetails( sink, artifactMap, version );
sink.tableCell_();
sink.tableRow_();
}
sink.table_();
sink.tableCell_();
sink.tableRow_();
sink.table_();
}
/**
* Generate version details for a given dependency
*
* @param sink
* @param artifactMap
* @param version
*/
// CHECKSTYLE_OFF: LineLength
private void generateVersionDetails( Sink sink, Map<String, List<ReverseDependencyLink>> artifactMap, String version )
// CHECKSTYLE_ON: LineLength
{
sink.numberedList( 0 ); // Use lower alpha numbering
List<ReverseDependencyLink> depList = artifactMap.get( version );
List<DependencyNode> projectNodes = getProjectNodes( depList );
if ( projectNodes == null || projectNodes.size() == 0 )
{
getLog().warn( "Can't find project nodes for dependency list: " + depList.get( 0 ).getDependency() );
return;
}
Collections.sort( projectNodes, new DependencyNodeComparator() );
for ( DependencyNode projectNode : projectNodes )
{
if ( isReactorBuild() )
{
sink.numberedListItem();
}
showVersionDetails( projectNode, depList, sink );
if ( isReactorBuild() )
{
sink.numberedListItem_();
}
sink.lineBreak();
}
sink.numberedList_();
}
private List<DependencyNode> getProjectNodes( List<ReverseDependencyLink> depList )
{
List<DependencyNode> projectNodes = new ArrayList<DependencyNode>();
for ( ReverseDependencyLink depLink : depList )
{
MavenProject project = depLink.getProject();
DependencyNode projectNode = this.projectMap.get( project );
if ( projectNode != null && !projectNodes.contains( projectNode ) )
{
projectNodes.add( projectNode );
}
}
return projectNodes;
}
private void showVersionDetails( DependencyNode projectNode, List<ReverseDependencyLink> depList, Sink sink )
{
if ( depList == null || depList.isEmpty() )
{
return;
}
Dependency dependency = depList.get( 0 ).getDependency();
String key =
dependency.getGroupId() + ":" + dependency.getArtifactId() + ":" + dependency.getType() + ":"
+ dependency.getVersion();
serializeDependencyTree( projectNode, key, sink );
}
/**
* Serializes the specified dependency tree to a string.
*
* @param rootNode the dependency tree root node to serialize
* @return the serialized dependency tree
*/
private void serializeDependencyTree( DependencyNode rootNode, String key, Sink sink )
{
DependencyNodeVisitor visitor = getSerializingDependencyNodeVisitor( sink );
visitor = new BuildingDependencyNodeVisitor( visitor );
DependencyNodeFilter filter = createDependencyNodeFilter( key );
if ( filter != null )
{
CollectingDependencyNodeVisitor collectingVisitor = new CollectingDependencyNodeVisitor();
DependencyNodeVisitor firstPassVisitor = new FilteringDependencyNodeVisitor( collectingVisitor, filter );
rootNode.accept( firstPassVisitor );
DependencyNodeFilter secondPassFilter =
new AncestorOrSelfDependencyNodeFilter( collectingVisitor.getNodes() );
visitor = new FilteringDependencyNodeVisitor( visitor, secondPassFilter );
}
rootNode.accept( visitor );
}
/**
* Gets the dependency node filter to use when serializing the dependency graph.
*
* @return the dependency node filter, or <code>null</code> if none required
*/
private DependencyNodeFilter createDependencyNodeFilter( String includes )
{
List<DependencyNodeFilter> filters = new ArrayList<DependencyNodeFilter>();
// filter includes
if ( includes != null )
{
List<String> patterns = Arrays.asList( includes.split( "," ) );
getLog().debug( "+ Filtering dependency tree by artifact include patterns: " + patterns );
ArtifactFilter artifactFilter = new StrictPatternIncludesArtifactFilter( patterns );
filters.add( new ArtifactDependencyNodeFilter( artifactFilter ) );
}
return filters.isEmpty() ? null : new AndDependencyNodeFilter( filters );
}
/**
* @param sink {@link Sink}
* @return {@link DependencyNodeVisitor}
*/
public DependencyNodeVisitor getSerializingDependencyNodeVisitor( Sink sink )
{
return new SinkSerializingDependencyNodeVisitor( sink );
}
/**
* Produce a Map of relationships between dependencies (its version) and reactor projects. This is the structure of
* the Map:
*
* <pre>
* +--------------------+----------------------------------+
* | key | value |
* +--------------------+----------------------------------+
* | version of a | A List of ReverseDependencyLinks |
* | dependency | which each look like this: |
* | | +------------+-----------------+ |
* | | | dependency | reactor project | |
* | | +------------+-----------------+ |
* +--------------------+----------------------------------+
* </pre>
*
* @return A Map of sorted unique artifacts
*/
private Map<String, List<ReverseDependencyLink>> getSortedUniqueArtifactMap( List<ReverseDependencyLink> depList )
{
Map<String, List<ReverseDependencyLink>> uniqueArtifactMap = new TreeMap<String, List<ReverseDependencyLink>>();
for ( ReverseDependencyLink rdl : depList )
{
String key = rdl.getDependency().getVersion();
List<ReverseDependencyLink> projectList = uniqueArtifactMap.get( key );
if ( projectList == null )
{
projectList = new ArrayList<ReverseDependencyLink>();
}
projectList.add( rdl );
uniqueArtifactMap.put( key, projectList );
}
return uniqueArtifactMap;
}
/**
* Generate the legend table
*
* @param locale
* @param sink
*/
private void generateLegend( Locale locale, Sink sink )
{
sink.table();
sink.tableCaption();
sink.bold();
sink.text( getI18nString( locale, "legend" ) );
sink.bold_();
sink.tableCaption_();
sink.tableRow();
sink.tableCell();
iconError( locale, sink );
sink.tableCell_();
sink.tableCell();
sink.text( getI18nString( locale, "legend.different" ) );
sink.tableCell_();
sink.tableRow_();
sink.table_();
}
/**
* Generate the statistic table
*
* @param locale
* @param sink
* @param dependencyMap
*/
private void generateStats( Locale locale, Sink sink, DependencyAnalyzeResult result )
{
int depCount = result.getDependencyCount();
int artifactCount = result.getArtifactCount();
int snapshotCount = result.getSnapshotCount();
int conflictingCount = result.getConflictingCount();
int convergence = calculateConvergence( result );
// Create report
sink.table();
sink.tableCaption();
sink.bold();
sink.text( getI18nString( locale, "stats.caption" ) );
sink.bold_();
sink.tableCaption_();
if ( isReactorBuild() )
{
sink.tableRow();
sink.tableHeaderCell();
sink.text( getI18nString( locale, "stats.modules" ) );
sink.tableHeaderCell_();
sink.tableCell();
sink.text( String.valueOf( reactorProjects.size() ) );
sink.tableCell_();
sink.tableRow_();
}
sink.tableRow();
sink.tableHeaderCell();
sink.text( getI18nString( locale, "stats.dependencies" ) );
sink.tableHeaderCell_();
sink.tableCell();
sink.text( String.valueOf( depCount ) );
sink.tableCell_();
sink.tableRow_();
sink.tableRow();
sink.tableHeaderCell();
sink.text( getI18nString( locale, "stats.artifacts" ) );
sink.tableHeaderCell_();
sink.tableCell();
sink.text( String.valueOf( artifactCount ) );
sink.tableCell_();
sink.tableRow_();
sink.tableRow();
sink.tableHeaderCell();
sink.text( getI18nString( locale, "stats.conflicting" ) );
sink.tableHeaderCell_();
sink.tableCell();
sink.text( String.valueOf( conflictingCount ) );
sink.tableCell_();
sink.tableRow_();
sink.tableRow();
sink.tableHeaderCell();
sink.text( getI18nString( locale, "stats.snapshots" ) );
sink.tableHeaderCell_();
sink.tableCell();
sink.text( String.valueOf( snapshotCount ) );
sink.tableCell_();
sink.tableRow_();
sink.tableRow();
sink.tableHeaderCell();
sink.text( getI18nString( locale, "stats.convergence" ) );
sink.tableHeaderCell_();
sink.tableCell();
if ( convergence < FULL_CONVERGENCE )
{
iconError( locale, sink );
}
else
{
iconSuccess( locale, sink );
}
sink.nonBreakingSpace();
sink.bold();
sink.text( String.valueOf( convergence ) + " %" );
sink.bold_();
sink.tableCell_();
sink.tableRow_();
sink.tableRow();
sink.tableHeaderCell();
sink.text( getI18nString( locale, "stats.readyrelease" ) );
sink.tableHeaderCell_();
sink.tableCell();
if ( convergence >= FULL_CONVERGENCE && snapshotCount <= 0 )
{
iconSuccess( locale, sink );
sink.nonBreakingSpace();
sink.bold();
sink.text( getI18nString( locale, "stats.readyrelease.success" ) );
sink.bold_();
}
else
{
iconError( locale, sink );
sink.nonBreakingSpace();
sink.bold();
sink.text( getI18nString( locale, "stats.readyrelease.error" ) );
sink.bold_();
if ( convergence < FULL_CONVERGENCE )
{
sink.lineBreak();
sink.text( getI18nString( locale, "stats.readyrelease.error.convergence" ) );
}
if ( snapshotCount > 0 )
{
sink.lineBreak();
sink.text( getI18nString( locale, "stats.readyrelease.error.snapshots" ) );
}
}
sink.tableCell_();
sink.tableRow_();
sink.table_();
}
/**
* Check to see if the specified dependency is among the reactor projects.
*
* @param dependency The dependency to check
* @return true if and only if the dependency is a reactor project
*/
private boolean isReactorProject( Dependency dependency )
{
for ( MavenProject mavenProject : reactorProjects )
{
if ( mavenProject.getGroupId().equals( dependency.getGroupId() )
&& mavenProject.getArtifactId().equals( dependency.getArtifactId() ) )
{
if ( getLog().isDebugEnabled() )
{
getLog().debug( dependency + " is a reactor project" );
}
return true;
}
}
return false;
}
private boolean isReactorBuild()
{
return this.reactorProjects.size() > 1;
}
private void iconSuccess( Locale locale, Sink sink )
{
sink.figure();
sink.figureCaption();
sink.text( getI18nString( locale, "icon.success" ) );
sink.figureCaption_();
sink.figureGraphics( IMG_SUCCESS_URL );
sink.figure_();
}
private void iconError( Locale locale, Sink sink )
{
sink.figure();
sink.figureCaption();
sink.text( getI18nString( locale, "icon.error" ) );
sink.figureCaption_();
sink.figureGraphics( IMG_ERROR_URL );
sink.figure_();
}
/**
* Produce a DependencyAnalyzeResult, it contains conflicting dependencies map, snapshot dependencies map and all
* dependencies map. Map structure is the relationships between dependencies (its groupId:artifactId) and reactor
* projects. This is the structure of the Map:
*
* <pre>
* +--------------------+----------------------------------+---------------|
* | key | value |
* +--------------------+----------------------------------+---------------|
* | groupId:artifactId | A List of ReverseDependencyLinks |
* | of a dependency | which each look like this: |
* | | +------------+-----------------+-----------------|
* | | | dependency | reactor project | dependency node |
* | | +------------+-----------------+-----------------|
* +--------------------+--------------------------------------------------|
* </pre>
*
* @return DependencyAnalyzeResult contains conflicting dependencies map, snapshot dependencies map and all
* dependencies map.
* @throws MavenReportException
*/
private DependencyAnalyzeResult analyzeDependencyTree()
throws MavenReportException
{
Map<String, List<ReverseDependencyLink>> conflictingDependencyMap =
new TreeMap<String, List<ReverseDependencyLink>>();
Map<String, List<ReverseDependencyLink>> allDependencies = new TreeMap<String, List<ReverseDependencyLink>>();
for ( MavenProject reactorProject : reactorProjects )
{
DependencyNode node = getNode( reactorProject );
this.projectMap.put( reactorProject, node );
getConflictingDependencyMap( conflictingDependencyMap, reactorProject, node );
getAllDependencyMap( allDependencies, reactorProject, node );
}
return populateDependencyAnalyzeResult( conflictingDependencyMap, allDependencies );
}
/**
* Produce DependencyAnalyzeResult base on conflicting dependencies map, all dependencies map.
*
* @param conflictingDependencyMap
* @param allDependencies
* @return DependencyAnalyzeResult contains conflicting dependencies map, snapshot dependencies map and all
* dependencies map.
*/
// CHECKSTYLE_OFF: LineLength
private DependencyAnalyzeResult populateDependencyAnalyzeResult( Map<String, List<ReverseDependencyLink>> conflictingDependencyMap,
Map<String, List<ReverseDependencyLink>> allDependencies )
// CHECKSTYLE_ON: LineLength
{
DependencyAnalyzeResult dependencyResult = new DependencyAnalyzeResult();
dependencyResult.setAll( allDependencies );
dependencyResult.setConflicting( conflictingDependencyMap );
List<ReverseDependencyLink> snapshots = getSnapshotDependencies( allDependencies );
dependencyResult.setSnapshots( snapshots );
return dependencyResult;
}
/**
* Get conflicting dependency map base on specified dependency node.
*
* @param conflictingDependencyMap
* @param reactorProject
* @param node
*/
private void getConflictingDependencyMap( Map<String, List<ReverseDependencyLink>> conflictingDependencyMap,
MavenProject reactorProject, DependencyNode node )
{
DependencyVersionMap visitor = new DependencyVersionMap();
visitor.setUniqueVersions( true );
node.accept( visitor );
for ( List<DependencyNode> nodes : visitor.getConflictedVersionNumbers() )
{
DependencyNode dependencyNode = nodes.get( 0 );
String key = dependencyNode.getArtifact().getGroupId() + ":" + dependencyNode.getArtifact().getArtifactId();
List<ReverseDependencyLink> dependencyList = conflictingDependencyMap.get( key );
if ( dependencyList == null )
{
dependencyList = new ArrayList<ReverseDependencyLink>();
}
// CHECKSTYLE_OFF: LineLength
dependencyList.add( new ReverseDependencyLink( toDependency( dependencyNode.getArtifact() ), reactorProject ) );
// CHECKSTYLE_ON: LineLength
for ( DependencyNode workNode : nodes.subList( 1, nodes.size() ) )
{
// CHECKSTYLE_OFF: LineLength
dependencyList.add( new ReverseDependencyLink( toDependency( workNode.getArtifact() ), reactorProject ) );
// CHECKSTYLE_ON: LineLength
}
conflictingDependencyMap.put( key, dependencyList );
}
}
/**
* Get all dependencies (both directive & transitive dependencies) by specified dependency node.
*
* @param allDependencies
* @param reactorProject
* @param node
*/
private void getAllDependencyMap( Map<String, List<ReverseDependencyLink>> allDependencies,
MavenProject reactorProject, DependencyNode node )
{
Set<Artifact> artifacts = getAllDescendants( node );
for ( Artifact art : artifacts )
{
String key = art.getGroupId() + ":" + art.getArtifactId();
List<ReverseDependencyLink> reverseDepependencies = allDependencies.get( key );
if ( reverseDepependencies == null )
{
reverseDepependencies = new ArrayList<ReverseDependencyLink>();
}
if ( !containsDependency( reverseDepependencies, art ) )
{
reverseDepependencies.add( new ReverseDependencyLink( toDependency( art ), reactorProject ) );
}
allDependencies.put( key, reverseDepependencies );
}
}
/**
* Convert Artifact to Dependency
*
* @param artifact
* @return Dependency object
*/
private Dependency toDependency( Artifact artifact )
{
Dependency dependency = new Dependency();
dependency.setGroupId( artifact.getGroupId() );
dependency.setArtifactId( artifact.getArtifactId() );
dependency.setVersion( artifact.getVersion() );
dependency.setClassifier( artifact.getClassifier() );
dependency.setScope( artifact.getScope() );
return dependency;
}
/**
* To check whether dependency list contains a given artifact.
*
* @param reverseDependencies
* @param art
* @return contains:true; Not contains:false;
*/
private boolean containsDependency( List<ReverseDependencyLink> reverseDependencies, Artifact art )
{
for ( ReverseDependencyLink revDependency : reverseDependencies )
{
Dependency dep = revDependency.getDependency();
if ( dep.getGroupId().equals( art.getGroupId() ) && dep.getArtifactId().equals( art.getArtifactId() )
&& dep.getVersion().equals( art.getVersion() ) )
{
return true;
}
}
return false;
}
/**
* Get root node of dependency tree for a given project
*
* @param project
* @return root node of dependency tree
* @throws MavenReportException
*/
private DependencyNode getNode( MavenProject project )
throws MavenReportException
{
try
{
DependencyNode node =
(DependencyNode) dependencyTreeBuilder.buildDependencyTree( project, localRepository, factory,
metadataSource, filter, collector );
return node;
}
catch ( DependencyTreeBuilderException e )
{
throw new MavenReportException( "Could not build dependency tree: " + e.getMessage(), e );
}
}
/**
* Get all descendants nodes for a given dependency node.
*
* @param node
* @return set of descendants artifacts.
*/
private Set<Artifact> getAllDescendants( DependencyNode node )
{
Set<Artifact> children = null;
if ( node.getChildren() != null )
{
children = new HashSet<Artifact>();
for ( DependencyNode depNode : node.getChildren() )
{
children.add( depNode.getArtifact() );
Set<Artifact> subNodes = getAllDescendants( depNode );
if ( subNodes != null )
{
children.addAll( subNodes );
}
}
}
return children;
}
private int calculateConvergence( DependencyAnalyzeResult result )
{
return (int) ( ( (double) result.getDependencyCount()
/ (double) result.getArtifactCount() ) * FULL_CONVERGENCE );
}
/**
* Internal object
*/
private static class ReverseDependencyLink
{
private Dependency dependency;
protected MavenProject project;
ReverseDependencyLink( Dependency dependency, MavenProject project )
{
this.dependency = dependency;
this.project = project;
}
public Dependency getDependency()
{
return dependency;
}
public MavenProject getProject()
{
return project;
}
@Override
public String toString()
{
return project.getId();
}
}
/**
* Internal ReverseDependencyLink comparator
*/
static class DependencyNodeComparator
implements Comparator<DependencyNode>
{
/** {@inheritDoc} */
public int compare( DependencyNode p1, DependencyNode p2 )
{
return p1.getArtifact().getId().compareTo( p2.getArtifact().getId() );
}
}
/**
* Internal object
*/
private class DependencyAnalyzeResult
{
Map<String, List<ReverseDependencyLink>> all;
List<ReverseDependencyLink> snapshots;
Map<String, List<ReverseDependencyLink>> conflicting;
public void setAll( Map<String, List<ReverseDependencyLink>> all )
{
this.all = all;
}
public List<ReverseDependencyLink> getSnapshots()
{
return snapshots;
}
public void setSnapshots( List<ReverseDependencyLink> snapshots )
{
this.snapshots = snapshots;
}
public Map<String, List<ReverseDependencyLink>> getConflicting()
{
return conflicting;
}
public void setConflicting( Map<String, List<ReverseDependencyLink>> conflicting )
{
this.conflicting = conflicting;
}
public int getDependencyCount()
{
return all.size();
}
public int getSnapshotCount()
{
return this.snapshots.size();
}
public int getConflictingCount()
{
return this.conflicting.size();
}
public int getArtifactCount()
{
int artifactCount = 0;
for ( List<ReverseDependencyLink> depList : this.all.values() )
{
Map<String, List<ReverseDependencyLink>> artifactMap = getSortedUniqueArtifactMap( depList );
artifactCount += artifactMap.size();
}
return artifactCount;
}
}
}
|
apache/hadoop | 35,653 | hadoop-hdfs-project/hadoop-hdfs-nfs/src/test/java/org/apache/hadoop/hdfs/nfs/nfs3/TestRpcProgramNfs3.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.nfs.nfs3;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.EnumSet;
import io.netty.channel.Channel;
import org.apache.hadoop.crypto.key.JavaKeyStoreProvider;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystemTestHelper;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.client.CreateEncryptionZoneFlag;
import org.apache.hadoop.hdfs.client.HdfsAdmin;
import org.apache.hadoop.hdfs.nfs.conf.NfsConfigKeys;
import org.apache.hadoop.hdfs.nfs.conf.NfsConfiguration;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.nfs.nfs3.FileHandle;
import org.apache.hadoop.nfs.nfs3.Nfs3Constant;
import org.apache.hadoop.nfs.nfs3.Nfs3Constant.WriteStableHow;
import org.apache.hadoop.nfs.nfs3.Nfs3Status;
import org.apache.hadoop.nfs.nfs3.request.ACCESS3Request;
import org.apache.hadoop.nfs.nfs3.request.COMMIT3Request;
import org.apache.hadoop.nfs.nfs3.request.CREATE3Request;
import org.apache.hadoop.nfs.nfs3.request.FSINFO3Request;
import org.apache.hadoop.nfs.nfs3.request.FSSTAT3Request;
import org.apache.hadoop.nfs.nfs3.request.GETATTR3Request;
import org.apache.hadoop.nfs.nfs3.request.LOOKUP3Request;
import org.apache.hadoop.nfs.nfs3.request.MKDIR3Request;
import org.apache.hadoop.nfs.nfs3.request.PATHCONF3Request;
import org.apache.hadoop.nfs.nfs3.request.READ3Request;
import org.apache.hadoop.nfs.nfs3.request.READDIR3Request;
import org.apache.hadoop.nfs.nfs3.request.READDIRPLUS3Request;
import org.apache.hadoop.nfs.nfs3.request.READLINK3Request;
import org.apache.hadoop.nfs.nfs3.request.REMOVE3Request;
import org.apache.hadoop.nfs.nfs3.request.RENAME3Request;
import org.apache.hadoop.nfs.nfs3.request.RMDIR3Request;
import org.apache.hadoop.nfs.nfs3.request.SETATTR3Request;
import org.apache.hadoop.nfs.nfs3.request.SYMLINK3Request;
import org.apache.hadoop.nfs.nfs3.request.SetAttr3;
import org.apache.hadoop.nfs.nfs3.request.SetAttr3.SetAttrField;
import org.apache.hadoop.nfs.nfs3.request.WRITE3Request;
import org.apache.hadoop.nfs.nfs3.response.ACCESS3Response;
import org.apache.hadoop.nfs.nfs3.response.COMMIT3Response;
import org.apache.hadoop.nfs.nfs3.response.CREATE3Response;
import org.apache.hadoop.nfs.nfs3.response.FSINFO3Response;
import org.apache.hadoop.nfs.nfs3.response.FSSTAT3Response;
import org.apache.hadoop.nfs.nfs3.response.GETATTR3Response;
import org.apache.hadoop.nfs.nfs3.response.LOOKUP3Response;
import org.apache.hadoop.nfs.nfs3.response.MKDIR3Response;
import org.apache.hadoop.nfs.nfs3.response.PATHCONF3Response;
import org.apache.hadoop.nfs.nfs3.response.READ3Response;
import org.apache.hadoop.nfs.nfs3.response.READDIR3Response;
import org.apache.hadoop.nfs.nfs3.response.READDIRPLUS3Response;
import org.apache.hadoop.nfs.nfs3.response.READLINK3Response;
import org.apache.hadoop.nfs.nfs3.response.REMOVE3Response;
import org.apache.hadoop.nfs.nfs3.response.RENAME3Response;
import org.apache.hadoop.nfs.nfs3.response.RMDIR3Response;
import org.apache.hadoop.nfs.nfs3.response.SETATTR3Response;
import org.apache.hadoop.nfs.nfs3.response.SYMLINK3Response;
import org.apache.hadoop.nfs.nfs3.response.WRITE3Response;
import org.apache.hadoop.oncrpc.XDR;
import org.apache.hadoop.oncrpc.security.SecurityHandler;
import org.apache.hadoop.security.IdMappingConstant;
import org.apache.hadoop.security.authorize.DefaultImpersonationProvider;
import org.apache.hadoop.security.authorize.ProxyUsers;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
/**
* Tests for {@link RpcProgramNfs3}
*/
public class TestRpcProgramNfs3 {
static DistributedFileSystem hdfs;
static MiniDFSCluster cluster = null;
static NfsConfiguration config = new NfsConfiguration();
static HdfsAdmin dfsAdmin;
static NameNode nn;
static Nfs3 nfs;
static RpcProgramNfs3 nfsd;
static SecurityHandler securityHandler;
static SecurityHandler securityHandlerUnpriviledged;
static String testdir = "/tmp";
private static final String TEST_KEY = "test_key";
private static FileSystemTestHelper fsHelper;
private static File testRootDir;
private static final EnumSet<CreateEncryptionZoneFlag> NO_TRASH =
EnumSet.of(CreateEncryptionZoneFlag.NO_TRASH);
@BeforeAll
public static void setup() throws Exception {
String currentUser = System.getProperty("user.name");
config.set("fs.permissions.umask-mode", "u=rwx,g=,o=");
config.set(DefaultImpersonationProvider.getTestProvider()
.getProxySuperuserGroupConfKey(currentUser), "*");
config.set(DefaultImpersonationProvider.getTestProvider()
.getProxySuperuserIpConfKey(currentUser), "*");
fsHelper = new FileSystemTestHelper();
// Set up java key store
String testRoot = fsHelper.getTestRootDir();
testRootDir = new File(testRoot).getAbsoluteFile();
final Path jksPath = new Path(testRootDir.toString(), "test.jks");
config.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH,
JavaKeyStoreProvider.SCHEME_NAME + "://file" + jksPath.toUri());
ProxyUsers.refreshSuperUserGroupsConfiguration(config);
cluster = new MiniDFSCluster.Builder(config).numDataNodes(1).build();
cluster.waitActive();
hdfs = cluster.getFileSystem();
nn = cluster.getNameNode();
dfsAdmin = new HdfsAdmin(cluster.getURI(), config);
// Use ephemeral ports in case tests are running in parallel
config.setInt("nfs3.mountd.port", 0);
config.setInt("nfs3.server.port", 0);
// Start NFS with allowed.hosts set to "* rw"
config.set("dfs.nfs.exports.allowed.hosts", "* rw");
nfs = new Nfs3(config);
nfs.startServiceInternal(false);
nfsd = (RpcProgramNfs3) nfs.getRpcProgram();
hdfs.getClient().setKeyProvider(nn.getNamesystem().getProvider());
DFSTestUtil.createKey(TEST_KEY, cluster, config);
// Mock SecurityHandler which returns system user.name
securityHandler = mock(SecurityHandler.class);
when(securityHandler.getUser()).thenReturn(currentUser);
// Mock SecurityHandler which returns a dummy username "harry"
securityHandlerUnpriviledged = mock(SecurityHandler.class);
when(securityHandlerUnpriviledged.getUser()).thenReturn("harry");
}
@AfterAll
public static void shutdown() throws Exception {
if (cluster != null) {
cluster.shutdown();
}
}
@BeforeEach
public void createFiles() throws IllegalArgumentException, IOException {
hdfs.delete(new Path(testdir), true);
hdfs.mkdirs(new Path(testdir));
hdfs.mkdirs(new Path(testdir + "/foo"));
DFSTestUtil.createFile(hdfs, new Path(testdir + "/bar"), 0, (short) 1, 0);
}
@Test
@Timeout(value = 60)
public void testGetattr() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar");
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
XDR xdr_req = new XDR();
GETATTR3Request req = new GETATTR3Request(handle);
req.serialize(xdr_req);
// Attempt by an unpriviledged user should fail.
GETATTR3Response response1 = nfsd.getattr(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code");
// Attempt by a priviledged user should pass.
GETATTR3Response response2 = nfsd.getattr(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code");
}
@Test
@Timeout(value = 60)
public void testSetattr() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
XDR xdr_req = new XDR();
FileHandle handle = new FileHandle(dirId, namenodeId);
SetAttr3 symAttr = new SetAttr3(0, 1, 0, 0, null, null,
EnumSet.of(SetAttrField.UID));
SETATTR3Request req = new SETATTR3Request(handle, symAttr, false, null);
req.serialize(xdr_req);
// Attempt by an unprivileged user should fail.
SETATTR3Response response1 = nfsd.setattr(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code");
// Attempt by a priviledged user should pass.
SETATTR3Response response2 = nfsd.setattr(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code");
}
@Test
@Timeout(value = 60)
public void testLookup() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
LOOKUP3Request lookupReq = new LOOKUP3Request(handle, "bar");
XDR xdr_req = new XDR();
lookupReq.serialize(xdr_req);
// Attempt by an unpriviledged user should fail.
LOOKUP3Response response1 = nfsd.lookup(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code");
// Attempt by a priviledged user should pass.
LOOKUP3Response response2 = nfsd.lookup(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code");
}
@Test
@Timeout(value = 60)
public void testAccess() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar");
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
XDR xdr_req = new XDR();
ACCESS3Request req = new ACCESS3Request(handle);
req.serialize(xdr_req);
// Attempt by an unpriviledged user should fail.
ACCESS3Response response1 = nfsd.access(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code");
// Attempt by a priviledged user should pass.
ACCESS3Response response2 = nfsd.access(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code");
}
@Test
@Timeout(value = 60)
public void testReadlink() throws Exception {
// Create a symlink first.
HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
XDR xdr_req = new XDR();
FileHandle handle = new FileHandle(dirId, namenodeId);
SYMLINK3Request req = new SYMLINK3Request(handle, "fubar", new SetAttr3(),
"bar");
req.serialize(xdr_req);
SYMLINK3Response response = nfsd.symlink(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response.getStatus(), "Incorrect return code:");
// Now perform readlink operations.
FileHandle handle2 = response.getObjFileHandle();
XDR xdr_req2 = new XDR();
READLINK3Request req2 = new READLINK3Request(handle2);
req2.serialize(xdr_req2);
// Attempt by an unpriviledged user should fail.
READLINK3Response response1 = nfsd.readlink(xdr_req2.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a priviledged user should pass.
READLINK3Response response2 = nfsd.readlink(xdr_req2.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code:");
}
@Test
@Timeout(value = 60)
public void testRead() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar");
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
READ3Request readReq = new READ3Request(handle, 0, 5);
XDR xdr_req = new XDR();
readReq.serialize(xdr_req);
// Attempt by an unpriviledged user should fail.
READ3Response response1 = nfsd.read(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a priviledged user should pass.
READ3Response response2 = nfsd.read(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code:");
}
@Test
@Timeout(value = 120)
public void testEncryptedReadWrite() throws Exception {
final int len = 8192;
final Path zone = new Path("/zone");
hdfs.mkdirs(zone);
dfsAdmin.createEncryptionZone(zone, TEST_KEY, NO_TRASH);
final byte[] buffer = new byte[len];
for (int i = 0; i < len; i++) {
buffer[i] = (byte) i;
}
final String encFile1 = "/zone/myfile";
createFileUsingNfs(encFile1, buffer);
commit(encFile1, len);
assertArrayEquals(
getFileContentsUsingNfs(encFile1, len),
getFileContentsUsingDfs(encFile1, len), "encFile1 not equal");
/*
* Same thing except this time create the encrypted file using DFS.
*/
final String encFile2 = "/zone/myfile2";
final Path encFile2Path = new Path(encFile2);
DFSTestUtil.createFile(hdfs, encFile2Path, len, (short) 1, 0xFEED);
assertArrayEquals(
getFileContentsUsingNfs(encFile2, len),
getFileContentsUsingDfs(encFile2, len), "encFile2 not equal");
}
private void createFileUsingNfs(String fileName, byte[] buffer)
throws Exception {
DFSTestUtil.createFile(hdfs, new Path(fileName), 0, (short) 1, 0);
final HdfsFileStatus status = nn.getRpcServer().getFileInfo(fileName);
final long dirId = status.getFileId();
final int namenodeId = Nfs3Utils.getNamenodeId(config);
final FileHandle handle = new FileHandle(dirId, namenodeId);
final WRITE3Request writeReq = new WRITE3Request(handle, 0,
buffer.length, WriteStableHow.DATA_SYNC, ByteBuffer.wrap(buffer));
final XDR xdr_req = new XDR();
writeReq.serialize(xdr_req);
final WRITE3Response response = nfsd.write(xdr_req.asReadOnlyWrap(),
null, 1, securityHandler,
new InetSocketAddress("localhost", 1234));
assertEquals(null, response, "Incorrect response: ");
}
private byte[] getFileContentsUsingNfs(String fileName, int len)
throws Exception {
final HdfsFileStatus status = nn.getRpcServer().getFileInfo(fileName);
final long dirId = status.getFileId();
final int namenodeId = Nfs3Utils.getNamenodeId(config);
final FileHandle handle = new FileHandle(dirId, namenodeId);
final READ3Request readReq = new READ3Request(handle, 0, len);
final XDR xdr_req = new XDR();
readReq.serialize(xdr_req);
final READ3Response response = nfsd.read(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response.getStatus(), "Incorrect return code: ");
assertTrue(response.isEof(), "expected full read");
return response.getData().array();
}
private byte[] getFileContentsUsingDfs(String fileName, int len)
throws Exception {
final FSDataInputStream in = hdfs.open(new Path(fileName));
final byte[] ret = new byte[len];
in.readFully(ret);
try {
in.readByte();
fail("expected end of file");
} catch (EOFException e) {
// expected. Unfortunately there is no associated message to check
}
in.close();
return ret;
}
private void commit(String fileName, int len) throws Exception {
final HdfsFileStatus status = nn.getRpcServer().getFileInfo(fileName);
final long dirId = status.getFileId();
final int namenodeId = Nfs3Utils.getNamenodeId(config);
final FileHandle handle = new FileHandle(dirId, namenodeId);
final XDR xdr_req = new XDR();
final COMMIT3Request req = new COMMIT3Request(handle, 0, len);
req.serialize(xdr_req);
Channel ch = mock(Channel.class);
COMMIT3Response response2 = nfsd.commit(xdr_req.asReadOnlyWrap(),
ch, 1, securityHandler,
new InetSocketAddress("localhost", 1234));
assertEquals(null, response2, "Incorrect COMMIT3Response:");
}
@Test
@Timeout(value = 60)
public void testWrite() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar");
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
byte[] buffer = new byte[10];
for (int i = 0; i < 10; i++) {
buffer[i] = (byte) i;
}
WRITE3Request writeReq = new WRITE3Request(handle, 0, 10,
WriteStableHow.DATA_SYNC, ByteBuffer.wrap(buffer));
XDR xdr_req = new XDR();
writeReq.serialize(xdr_req);
// Attempt by an unpriviledged user should fail.
WRITE3Response response1 = nfsd.write(xdr_req.asReadOnlyWrap(),
null, 1, securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a priviledged user should pass.
WRITE3Response response2 = nfsd.write(xdr_req.asReadOnlyWrap(),
null, 1, securityHandler,
new InetSocketAddress("localhost", 1234));
assertEquals(null, response2, "Incorrect response:");
}
@Test
@Timeout(value = 60)
public void testCreate() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
XDR xdr_req = new XDR();
FileHandle handle = new FileHandle(dirId, namenodeId);
CREATE3Request req = new CREATE3Request(handle, "fubar",
Nfs3Constant.CREATE_UNCHECKED, new SetAttr3(), 0);
req.serialize(xdr_req);
// Attempt by an unpriviledged user should fail.
CREATE3Response response1 = nfsd.create(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a priviledged user should pass.
CREATE3Response response2 = nfsd.create(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code:");
}
@Test
@Timeout(value = 60)
public void testMkdir() throws Exception {//FixME
HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
XDR xdr_req = new XDR();
FileHandle handle = new FileHandle(dirId, namenodeId);
MKDIR3Request req = new MKDIR3Request(handle, "fubar1", new SetAttr3());
req.serialize(xdr_req);
// Attempt to mkdir by an unprivileged user should fail.
MKDIR3Response response1 = nfsd.mkdir(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
XDR xdr_req2 = new XDR();
MKDIR3Request req2 = new MKDIR3Request(handle, "fubar2", new SetAttr3());
req2.serialize(xdr_req2);
// Attempt to mkdir by a privileged user should pass.
MKDIR3Response response2 = nfsd.mkdir(xdr_req2.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code:");
}
@Test
@Timeout(value = 60)
public void testSymlink() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
XDR xdr_req = new XDR();
FileHandle handle = new FileHandle(dirId, namenodeId);
SYMLINK3Request req = new SYMLINK3Request(handle, "fubar", new SetAttr3(),
"bar");
req.serialize(xdr_req);
// Attempt by an unprivileged user should fail.
SYMLINK3Response response1 = nfsd.symlink(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a privileged user should pass.
SYMLINK3Response response2 = nfsd.symlink(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code:");
}
@Test
@Timeout(value = 60)
public void testRemove() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
XDR xdr_req = new XDR();
FileHandle handle = new FileHandle(dirId, namenodeId);
REMOVE3Request req = new REMOVE3Request(handle, "bar");
req.serialize(xdr_req);
// Attempt by an unpriviledged user should fail.
REMOVE3Response response1 = nfsd.remove(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a priviledged user should pass.
REMOVE3Response response2 = nfsd.remove(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code:");
}
@Test
@Timeout(value = 60)
public void testRmdir() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
XDR xdr_req = new XDR();
FileHandle handle = new FileHandle(dirId, namenodeId);
RMDIR3Request req = new RMDIR3Request(handle, "foo");
req.serialize(xdr_req);
// Attempt by an unprivileged user should fail.
RMDIR3Response response1 = nfsd.rmdir(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a privileged user should pass.
RMDIR3Response response2 = nfsd.rmdir(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code:");
}
@Test
@Timeout(value = 60)
public void testRename() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
XDR xdr_req = new XDR();
FileHandle handle = new FileHandle(dirId, namenodeId);
RENAME3Request req = new RENAME3Request(handle, "bar", handle, "fubar");
req.serialize(xdr_req);
// Attempt by an unprivileged user should fail.
RENAME3Response response1 = nfsd.rename(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a privileged user should pass.
RENAME3Response response2 = nfsd.rename(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code:");
}
@Test
@Timeout(value = 60)
public void testReaddir() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
XDR xdr_req = new XDR();
READDIR3Request req = new READDIR3Request(handle, 0, 0, 100);
req.serialize(xdr_req);
// Attempt by an unpriviledged user should fail.
READDIR3Response response1 = nfsd.readdir(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a priviledged user should pass.
READDIR3Response response2 = nfsd.readdir(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code:");
}
@Test
@Timeout(value = 60)
public void testReaddirplus() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo(testdir);
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
XDR xdr_req = new XDR();
READDIRPLUS3Request req = new READDIRPLUS3Request(handle, 0, 0, 3, 2);
req.serialize(xdr_req);
// Attempt by an unprivileged user should fail.
READDIRPLUS3Response response1 = nfsd.readdirplus(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a privileged user should pass.
READDIRPLUS3Response response2 = nfsd.readdirplus(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code:");
}
@Test
@Timeout(value = 60)
public void testFsstat() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar");
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
XDR xdr_req = new XDR();
FSSTAT3Request req = new FSSTAT3Request(handle);
req.serialize(xdr_req);
// Attempt by an unpriviledged user should fail.
FSSTAT3Response response1 = nfsd.fsstat(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a priviledged user should pass.
FSSTAT3Response response2 = nfsd.fsstat(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code:");
}
@Test
@Timeout(value = 60)
public void testFsinfo() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar");
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
XDR xdr_req = new XDR();
FSINFO3Request req = new FSINFO3Request(handle);
req.serialize(xdr_req);
// Attempt by an unpriviledged user should fail.
FSINFO3Response response1 = nfsd.fsinfo(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a priviledged user should pass.
FSINFO3Response response2 = nfsd.fsinfo(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code:");
}
@Test
@Timeout(value = 60)
public void testPathconf() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar");
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
XDR xdr_req = new XDR();
PATHCONF3Request req = new PATHCONF3Request(handle);
req.serialize(xdr_req);
// Attempt by an unpriviledged user should fail.
PATHCONF3Response response1 = nfsd.pathconf(xdr_req.asReadOnlyWrap(),
securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a priviledged user should pass.
PATHCONF3Response response2 = nfsd.pathconf(xdr_req.asReadOnlyWrap(),
securityHandler, new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3_OK,
response2.getStatus(), "Incorrect return code:");
}
@Test
@Timeout(value = 60)
public void testCommit() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar");
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
XDR xdr_req = new XDR();
COMMIT3Request req = new COMMIT3Request(handle, 0, 5);
req.serialize(xdr_req);
Channel ch = mock(Channel.class);
// Attempt by an unpriviledged user should fail.
COMMIT3Response response1 = nfsd.commit(xdr_req.asReadOnlyWrap(),
ch, 1, securityHandlerUnpriviledged,
new InetSocketAddress("localhost", 1234));
assertEquals(Nfs3Status.NFS3ERR_ACCES,
response1.getStatus(), "Incorrect return code:");
// Attempt by a priviledged user should pass.
COMMIT3Response response2 = nfsd.commit(xdr_req.asReadOnlyWrap(),
ch, 1, securityHandler,
new InetSocketAddress("localhost", 1234));
assertEquals(null, response2, "Incorrect COMMIT3Response:");
}
@Test
@Timeout(value = 10)
public void testIdempotent() {
Object[][] procedures = {
{ Nfs3Constant.NFSPROC3.NULL, 1 },
{ Nfs3Constant.NFSPROC3.GETATTR, 1 },
{ Nfs3Constant.NFSPROC3.SETATTR, 1 },
{ Nfs3Constant.NFSPROC3.LOOKUP, 1 },
{ Nfs3Constant.NFSPROC3.ACCESS, 1 },
{ Nfs3Constant.NFSPROC3.READLINK, 1 },
{ Nfs3Constant.NFSPROC3.READ, 1 },
{ Nfs3Constant.NFSPROC3.WRITE, 1 },
{ Nfs3Constant.NFSPROC3.CREATE, 0 },
{ Nfs3Constant.NFSPROC3.MKDIR, 0 },
{ Nfs3Constant.NFSPROC3.SYMLINK, 0 },
{ Nfs3Constant.NFSPROC3.MKNOD, 0 },
{ Nfs3Constant.NFSPROC3.REMOVE, 0 },
{ Nfs3Constant.NFSPROC3.RMDIR, 0 },
{ Nfs3Constant.NFSPROC3.RENAME, 0 },
{ Nfs3Constant.NFSPROC3.LINK, 0 },
{ Nfs3Constant.NFSPROC3.READDIR, 1 },
{ Nfs3Constant.NFSPROC3.READDIRPLUS, 1 },
{ Nfs3Constant.NFSPROC3.FSSTAT, 1 },
{ Nfs3Constant.NFSPROC3.FSINFO, 1 },
{ Nfs3Constant.NFSPROC3.PATHCONF, 1 },
{ Nfs3Constant.NFSPROC3.COMMIT, 1 } };
for (Object[] procedure : procedures) {
boolean idempotent = procedure[1].equals(Integer.valueOf(1));
Nfs3Constant.NFSPROC3 proc = (Nfs3Constant.NFSPROC3)procedure[0];
if (idempotent) {
assertTrue(proc.isIdempotent(), ("Procedure " + proc + " should be idempotent"));
} else {
assertFalse(proc.isIdempotent(), ("Procedure " + proc + " should be non-idempotent"));
}
}
}
@Test
public void testDeprecatedKeys() {
NfsConfiguration conf = new NfsConfiguration();
conf.setInt("nfs3.server.port", 998);
assertTrue(conf.getInt(NfsConfigKeys.DFS_NFS_SERVER_PORT_KEY, 0) == 998);
conf.setInt("nfs3.mountd.port", 999);
assertTrue(conf.getInt(NfsConfigKeys.DFS_NFS_MOUNTD_PORT_KEY, 0) == 999);
conf.set("dfs.nfs.exports.allowed.hosts", "host1");
assertTrue(conf.get(CommonConfigurationKeys.NFS_EXPORTS_ALLOWED_HOSTS_KEY)
.equals("host1"));
conf.setInt("dfs.nfs.exports.cache.expirytime.millis", 1000);
assertTrue(conf.getInt(
Nfs3Constant.NFS_EXPORTS_CACHE_EXPIRYTIME_MILLIS_KEY, 0) == 1000);
conf.setInt("hadoop.nfs.userupdate.milly", 10);
assertTrue(conf.getInt(IdMappingConstant.USERGROUPID_UPDATE_MILLIS_KEY, 0) == 10);
conf.set("dfs.nfs3.dump.dir", "/nfs/tmp");
assertTrue(conf.get(NfsConfigKeys.DFS_NFS_FILE_DUMP_DIR_KEY).equals(
"/nfs/tmp"));
conf.setBoolean("dfs.nfs3.enableDump", false);
assertTrue(conf.getBoolean(NfsConfigKeys.DFS_NFS_FILE_DUMP_KEY, true) == false);
conf.setInt("dfs.nfs3.max.open.files", 500);
assertTrue(conf.getInt(NfsConfigKeys.DFS_NFS_MAX_OPEN_FILES_KEY, 0) == 500);
conf.setInt("dfs.nfs3.stream.timeout", 6000);
assertTrue(conf.getInt(NfsConfigKeys.DFS_NFS_STREAM_TIMEOUT_KEY, 0) == 6000);
conf.set("dfs.nfs3.export.point", "/dir1");
assertTrue(conf.get(NfsConfigKeys.DFS_NFS_EXPORT_POINT_KEY).equals("/dir1"));
}
}
|
google/ExoPlayer | 35,811 | demos/transformer/src/main/java/com/google/android/exoplayer2/transformerdemo/TransformerActivity.java | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.transformerdemo;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.READ_MEDIA_VIDEO;
import static com.google.android.exoplayer2.transformer.Transformer.PROGRESS_STATE_NOT_STARTED;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static com.google.android.exoplayer2.util.Assertions.checkState;
import static com.google.android.exoplayer2.util.Assertions.checkStateNotNull;
import static com.google.android.exoplayer2.util.Util.SDK_INT;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.opengl.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.audio.AudioProcessor;
import com.google.android.exoplayer2.audio.SilenceSkippingAudioProcessor;
import com.google.android.exoplayer2.audio.SonicAudioProcessor;
import com.google.android.exoplayer2.effect.BitmapOverlay;
import com.google.android.exoplayer2.effect.Contrast;
import com.google.android.exoplayer2.effect.DrawableOverlay;
import com.google.android.exoplayer2.effect.GlEffect;
import com.google.android.exoplayer2.effect.GlShaderProgram;
import com.google.android.exoplayer2.effect.HslAdjustment;
import com.google.android.exoplayer2.effect.OverlayEffect;
import com.google.android.exoplayer2.effect.OverlaySettings;
import com.google.android.exoplayer2.effect.Presentation;
import com.google.android.exoplayer2.effect.RgbAdjustment;
import com.google.android.exoplayer2.effect.RgbFilter;
import com.google.android.exoplayer2.effect.RgbMatrix;
import com.google.android.exoplayer2.effect.ScaleAndRotateTransformation;
import com.google.android.exoplayer2.effect.SingleColorLut;
import com.google.android.exoplayer2.effect.TextOverlay;
import com.google.android.exoplayer2.effect.TextureOverlay;
import com.google.android.exoplayer2.transformer.Composition;
import com.google.android.exoplayer2.transformer.DefaultEncoderFactory;
import com.google.android.exoplayer2.transformer.DefaultMuxer;
import com.google.android.exoplayer2.transformer.EditedMediaItem;
import com.google.android.exoplayer2.transformer.EditedMediaItemSequence;
import com.google.android.exoplayer2.transformer.Effects;
import com.google.android.exoplayer2.transformer.ExportException;
import com.google.android.exoplayer2.transformer.ExportResult;
import com.google.android.exoplayer2.transformer.ProgressHolder;
import com.google.android.exoplayer2.transformer.TransformationRequest;
import com.google.android.exoplayer2.transformer.Transformer;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.StyledPlayerView;
import com.google.android.exoplayer2.upstream.DataSourceBitmapLoader;
import com.google.android.exoplayer2.util.BitmapLoader;
import com.google.android.exoplayer2.util.DebugTextViewHelper;
import com.google.android.exoplayer2.util.DebugViewProvider;
import com.google.android.exoplayer2.util.Effect;
import com.google.android.exoplayer2.util.GlUtil;
import com.google.android.exoplayer2.util.Log;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.progressindicator.LinearProgressIndicator;
import com.google.common.base.Stopwatch;
import com.google.common.base.Ticker;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ListenableFuture;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.RequiresNonNull;
/**
* An {@link Activity} that exports and plays media using {@link Transformer}.
*
* @deprecated com.google.android.exoplayer2 is deprecated. Please migrate to androidx.media3 (which
* contains the same ExoPlayer code). See <a
* href="https://developer.android.com/guide/topics/media/media3/getting-started/migration-guide">the
* migration guide</a> for more details, including a script to help with the migration.
*/
@Deprecated
public final class TransformerActivity extends AppCompatActivity {
private static final String TAG = "TransformerActivity";
private @MonotonicNonNull Button displayInputButton;
private @MonotonicNonNull MaterialCardView inputCardView;
private @MonotonicNonNull TextView inputTextView;
private @MonotonicNonNull ImageView inputImageView;
private @MonotonicNonNull StyledPlayerView inputPlayerView;
private @MonotonicNonNull StyledPlayerView outputPlayerView;
private @MonotonicNonNull TextView outputVideoTextView;
private @MonotonicNonNull TextView debugTextView;
private @MonotonicNonNull TextView informationTextView;
private @MonotonicNonNull ViewGroup progressViewGroup;
private @MonotonicNonNull LinearProgressIndicator progressIndicator;
private @MonotonicNonNull Stopwatch exportStopwatch;
private @MonotonicNonNull AspectRatioFrameLayout debugFrame;
@Nullable private DebugTextViewHelper debugTextViewHelper;
@Nullable private ExoPlayer inputPlayer;
@Nullable private ExoPlayer outputPlayer;
@Nullable private Transformer transformer;
@Nullable private File externalCacheFile;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.transformer_activity);
inputCardView = findViewById(R.id.input_card_view);
inputTextView = findViewById(R.id.input_text_view);
inputImageView = findViewById(R.id.input_image_view);
inputPlayerView = findViewById(R.id.input_player_view);
outputPlayerView = findViewById(R.id.output_player_view);
outputVideoTextView = findViewById(R.id.output_video_text_view);
debugTextView = findViewById(R.id.debug_text_view);
informationTextView = findViewById(R.id.information_text_view);
progressViewGroup = findViewById(R.id.progress_view_group);
progressIndicator = findViewById(R.id.progress_indicator);
debugFrame = findViewById(R.id.debug_aspect_ratio_frame_layout);
displayInputButton = findViewById(R.id.display_input_button);
displayInputButton.setOnClickListener(this::toggleInputVideoDisplay);
exportStopwatch =
Stopwatch.createUnstarted(
new Ticker() {
@Override
public long read() {
return android.os.SystemClock.elapsedRealtimeNanos();
}
});
}
@Override
protected void onStart() {
super.onStart();
checkNotNull(progressIndicator);
checkNotNull(informationTextView);
checkNotNull(exportStopwatch);
checkNotNull(inputCardView);
checkNotNull(inputTextView);
checkNotNull(inputImageView);
checkNotNull(inputPlayerView);
checkNotNull(outputPlayerView);
checkNotNull(outputVideoTextView);
checkNotNull(debugTextView);
checkNotNull(progressViewGroup);
checkNotNull(debugFrame);
checkNotNull(displayInputButton);
startExport();
inputPlayerView.onResume();
outputPlayerView.onResume();
}
@Override
protected void onStop() {
super.onStop();
checkNotNull(transformer).cancel();
transformer = null;
// The stop watch is reset after cancelling the export, in case cancelling causes the stop watch
// to be stopped in a transformer callback.
checkNotNull(exportStopwatch).reset();
checkNotNull(inputPlayerView).onPause();
checkNotNull(outputPlayerView).onPause();
releasePlayer();
checkNotNull(externalCacheFile).delete();
externalCacheFile = null;
}
@RequiresNonNull({
"displayInputButton",
"inputCardView",
"inputTextView",
"inputImageView",
"inputPlayerView",
"outputPlayerView",
"outputVideoTextView",
"debugTextView",
"informationTextView",
"progressIndicator",
"exportStopwatch",
"progressViewGroup",
"debugFrame",
})
private void startExport() {
requestReadVideoPermission(/* activity= */ this);
Intent intent = getIntent();
Uri inputUri = checkNotNull(intent.getData());
try {
externalCacheFile = createExternalCacheFile("transformer-output.mp4");
} catch (IOException e) {
throw new IllegalStateException(e);
}
String filePath = externalCacheFile.getAbsolutePath();
@Nullable Bundle bundle = intent.getExtras();
MediaItem mediaItem = createMediaItem(bundle, inputUri);
try {
Transformer transformer = createTransformer(bundle, inputUri, filePath);
Composition composition = createComposition(mediaItem, bundle);
exportStopwatch.start();
transformer.start(composition, filePath);
this.transformer = transformer;
} catch (PackageManager.NameNotFoundException e) {
throw new IllegalStateException(e);
}
displayInputButton.setVisibility(View.GONE);
inputCardView.setVisibility(View.GONE);
outputPlayerView.setVisibility(View.GONE);
outputVideoTextView.setVisibility(View.GONE);
debugTextView.setVisibility(View.GONE);
informationTextView.setText(R.string.export_started);
progressViewGroup.setVisibility(View.VISIBLE);
Handler mainHandler = new Handler(getMainLooper());
ProgressHolder progressHolder = new ProgressHolder();
mainHandler.post(
new Runnable() {
@Override
public void run() {
if (transformer != null
&& transformer.getProgress(progressHolder) != PROGRESS_STATE_NOT_STARTED) {
progressIndicator.setProgress(progressHolder.progress);
informationTextView.setText(
getString(R.string.export_timer, exportStopwatch.elapsed(TimeUnit.SECONDS)));
mainHandler.postDelayed(/* r= */ this, /* delayMillis= */ 500);
}
}
});
}
private MediaItem createMediaItem(@Nullable Bundle bundle, Uri uri) {
MediaItem.Builder mediaItemBuilder = new MediaItem.Builder().setUri(uri);
if (bundle != null) {
long trimStartMs =
bundle.getLong(ConfigurationActivity.TRIM_START_MS, /* defaultValue= */ C.TIME_UNSET);
long trimEndMs =
bundle.getLong(ConfigurationActivity.TRIM_END_MS, /* defaultValue= */ C.TIME_UNSET);
if (trimStartMs != C.TIME_UNSET && trimEndMs != C.TIME_UNSET) {
mediaItemBuilder.setClippingConfiguration(
new MediaItem.ClippingConfiguration.Builder()
.setStartPositionMs(trimStartMs)
.setEndPositionMs(trimEndMs)
.build());
}
}
return mediaItemBuilder.build();
}
@RequiresNonNull({
"inputCardView",
"inputTextView",
"inputImageView",
"inputPlayerView",
"outputPlayerView",
"outputVideoTextView",
"displayInputButton",
"debugTextView",
"informationTextView",
"exportStopwatch",
"progressViewGroup",
"debugFrame",
})
private Transformer createTransformer(@Nullable Bundle bundle, Uri inputUri, String filePath) {
Transformer.Builder transformerBuilder = new Transformer.Builder(/* context= */ this);
if (bundle != null) {
TransformationRequest.Builder requestBuilder = new TransformationRequest.Builder();
@Nullable String audioMimeType = bundle.getString(ConfigurationActivity.AUDIO_MIME_TYPE);
if (audioMimeType != null) {
requestBuilder.setAudioMimeType(audioMimeType);
}
@Nullable String videoMimeType = bundle.getString(ConfigurationActivity.VIDEO_MIME_TYPE);
if (videoMimeType != null) {
requestBuilder.setVideoMimeType(videoMimeType);
}
requestBuilder.setHdrMode(bundle.getInt(ConfigurationActivity.HDR_MODE));
transformerBuilder.setTransformationRequest(requestBuilder.build());
transformerBuilder.setEncoderFactory(
new DefaultEncoderFactory.Builder(this.getApplicationContext())
.setEnableFallback(bundle.getBoolean(ConfigurationActivity.ENABLE_FALLBACK))
.build());
if (!bundle.getBoolean(ConfigurationActivity.ABORT_SLOW_EXPORT)) {
transformerBuilder.setMuxerFactory(
new DefaultMuxer.Factory(/* maxDelayBetweenSamplesMs= */ C.TIME_UNSET));
}
if (bundle.getBoolean(ConfigurationActivity.ENABLE_DEBUG_PREVIEW)) {
transformerBuilder.setDebugViewProvider(new DemoDebugViewProvider());
}
}
return transformerBuilder
.addListener(
new Transformer.Listener() {
@Override
public void onCompleted(Composition composition, ExportResult exportResult) {
TransformerActivity.this.onCompleted(inputUri, filePath);
}
@Override
public void onError(
Composition composition,
ExportResult exportResult,
ExportException exportException) {
TransformerActivity.this.onError(exportException);
}
})
.build();
}
/** Creates a cache file, resetting it if it already exists. */
private File createExternalCacheFile(String fileName) throws IOException {
File file = new File(getExternalCacheDir(), fileName);
if (file.exists() && !file.delete()) {
throw new IllegalStateException("Could not delete the previous export output file");
}
if (!file.createNewFile()) {
throw new IllegalStateException("Could not create the export output file");
}
return file;
}
@RequiresNonNull({
"inputCardView",
"outputPlayerView",
"exportStopwatch",
"progressViewGroup",
})
private Composition createComposition(MediaItem mediaItem, @Nullable Bundle bundle)
throws PackageManager.NameNotFoundException {
EditedMediaItem.Builder editedMediaItemBuilder = new EditedMediaItem.Builder(mediaItem);
// For image inputs. Automatically ignored if input is audio/video.
editedMediaItemBuilder.setDurationUs(5_000_000).setFrameRate(30);
boolean forceAudioTrack = false;
if (bundle != null) {
ImmutableList<AudioProcessor> audioProcessors = createAudioProcessorsFromBundle(bundle);
ImmutableList<Effect> videoEffects = createVideoEffectsFromBundle(bundle);
editedMediaItemBuilder
.setRemoveAudio(bundle.getBoolean(ConfigurationActivity.SHOULD_REMOVE_AUDIO))
.setRemoveVideo(bundle.getBoolean(ConfigurationActivity.SHOULD_REMOVE_VIDEO))
.setFlattenForSlowMotion(
bundle.getBoolean(ConfigurationActivity.SHOULD_FLATTEN_FOR_SLOW_MOTION))
.setEffects(new Effects(audioProcessors, videoEffects));
forceAudioTrack = bundle.getBoolean(ConfigurationActivity.FORCE_AUDIO_TRACK);
}
List<EditedMediaItem> editedMediaItems = new ArrayList<>();
editedMediaItems.add(editedMediaItemBuilder.build());
List<EditedMediaItemSequence> sequences = new ArrayList<>();
sequences.add(new EditedMediaItemSequence(editedMediaItems));
return new Composition.Builder(sequences)
.experimentalSetForceAudioTrack(forceAudioTrack)
.build();
}
private ImmutableList<AudioProcessor> createAudioProcessorsFromBundle(Bundle bundle) {
@Nullable
boolean[] selectedAudioEffects =
bundle.getBooleanArray(ConfigurationActivity.AUDIO_EFFECTS_SELECTIONS);
if (selectedAudioEffects == null) {
return ImmutableList.of();
}
ImmutableList.Builder<AudioProcessor> processors = new ImmutableList.Builder<>();
if (selectedAudioEffects[ConfigurationActivity.HIGH_PITCHED_INDEX]
|| selectedAudioEffects[ConfigurationActivity.SAMPLE_RATE_INDEX]) {
SonicAudioProcessor sonicAudioProcessor = new SonicAudioProcessor();
if (selectedAudioEffects[ConfigurationActivity.HIGH_PITCHED_INDEX]) {
sonicAudioProcessor.setPitch(2f);
}
if (selectedAudioEffects[ConfigurationActivity.SAMPLE_RATE_INDEX]) {
sonicAudioProcessor.setOutputSampleRateHz(48_000);
}
processors.add(sonicAudioProcessor);
}
if (selectedAudioEffects[ConfigurationActivity.SKIP_SILENCE_INDEX]) {
SilenceSkippingAudioProcessor silenceSkippingAudioProcessor =
new SilenceSkippingAudioProcessor();
silenceSkippingAudioProcessor.setEnabled(true);
processors.add(silenceSkippingAudioProcessor);
}
return processors.build();
}
private ImmutableList<Effect> createVideoEffectsFromBundle(Bundle bundle)
throws PackageManager.NameNotFoundException {
boolean[] selectedEffects =
checkStateNotNull(bundle.getBooleanArray(ConfigurationActivity.VIDEO_EFFECTS_SELECTIONS));
ImmutableList.Builder<Effect> effects = new ImmutableList.Builder<>();
if (selectedEffects[ConfigurationActivity.DIZZY_CROP_INDEX]) {
effects.add(MatrixTransformationFactory.createDizzyCropEffect());
}
if (selectedEffects[ConfigurationActivity.EDGE_DETECTOR_INDEX]) {
try {
Class<?> clazz =
Class.forName("com.google.android.exoplayer2.transformerdemo.MediaPipeShaderProgram");
Constructor<?> constructor =
clazz.getConstructor(
Context.class,
boolean.class,
String.class,
boolean.class,
String.class,
String.class);
effects.add(
(GlEffect)
(Context context, boolean useHdr) -> {
try {
return (GlShaderProgram)
constructor.newInstance(
context,
useHdr,
/* graphName= */ "edge_detector_mediapipe_graph.binarypb",
/* isSingleFrameGraph= */ true,
/* inputStreamName= */ "input_video",
/* outputStreamName= */ "output_video");
} catch (Exception e) {
runOnUiThread(() -> showToast(R.string.no_media_pipe_error));
throw new RuntimeException("Failed to load MediaPipeShaderProgram", e);
}
});
} catch (Exception e) {
showToast(R.string.no_media_pipe_error);
}
}
if (selectedEffects[ConfigurationActivity.COLOR_FILTERS_INDEX]) {
switch (bundle.getInt(ConfigurationActivity.COLOR_FILTER_SELECTION)) {
case ConfigurationActivity.COLOR_FILTER_GRAYSCALE:
effects.add(RgbFilter.createGrayscaleFilter());
break;
case ConfigurationActivity.COLOR_FILTER_INVERTED:
effects.add(RgbFilter.createInvertedFilter());
break;
case ConfigurationActivity.COLOR_FILTER_SEPIA:
// W3C Sepia RGBA matrix with sRGB as a target color space:
// https://www.w3.org/TR/filter-effects-1/#sepiaEquivalent
// The matrix is defined for the sRGB color space and the Transformer library
// uses a linear RGB color space internally. Meaning this is only for demonstration
// purposes and it does not display a correct sepia frame.
float[] sepiaMatrix = {
0.393f, 0.349f, 0.272f, 0, 0.769f, 0.686f, 0.534f, 0, 0.189f, 0.168f, 0.131f, 0, 0, 0,
0, 1
};
effects.add((RgbMatrix) (presentationTimeUs, useHdr) -> sepiaMatrix);
break;
default:
throw new IllegalStateException(
"Unexpected color filter "
+ bundle.getInt(ConfigurationActivity.COLOR_FILTER_SELECTION));
}
}
if (selectedEffects[ConfigurationActivity.MAP_WHITE_TO_GREEN_LUT_INDEX]) {
int length = 3;
int[][][] mapWhiteToGreenLut = new int[length][length][length];
int scale = 255 / (length - 1);
for (int r = 0; r < length; r++) {
for (int g = 0; g < length; g++) {
for (int b = 0; b < length; b++) {
mapWhiteToGreenLut[r][g][b] =
Color.rgb(/* red= */ r * scale, /* green= */ g * scale, /* blue= */ b * scale);
}
}
}
mapWhiteToGreenLut[length - 1][length - 1][length - 1] = Color.GREEN;
effects.add(SingleColorLut.createFromCube(mapWhiteToGreenLut));
}
if (selectedEffects[ConfigurationActivity.RGB_ADJUSTMENTS_INDEX]) {
effects.add(
new RgbAdjustment.Builder()
.setRedScale(bundle.getFloat(ConfigurationActivity.RGB_ADJUSTMENT_RED_SCALE))
.setGreenScale(bundle.getFloat(ConfigurationActivity.RGB_ADJUSTMENT_GREEN_SCALE))
.setBlueScale(bundle.getFloat(ConfigurationActivity.RGB_ADJUSTMENT_BLUE_SCALE))
.build());
}
if (selectedEffects[ConfigurationActivity.HSL_ADJUSTMENT_INDEX]) {
effects.add(
new HslAdjustment.Builder()
.adjustHue(bundle.getFloat(ConfigurationActivity.HSL_ADJUSTMENTS_HUE))
.adjustSaturation(bundle.getFloat(ConfigurationActivity.HSL_ADJUSTMENTS_SATURATION))
.adjustLightness(bundle.getFloat(ConfigurationActivity.HSL_ADJUSTMENTS_LIGHTNESS))
.build());
}
if (selectedEffects[ConfigurationActivity.CONTRAST_INDEX]) {
effects.add(new Contrast(bundle.getFloat(ConfigurationActivity.CONTRAST_VALUE)));
}
if (selectedEffects[ConfigurationActivity.PERIODIC_VIGNETTE_INDEX]) {
effects.add(
(GlEffect)
(Context context, boolean useHdr) ->
new PeriodicVignetteShaderProgram(
context,
useHdr,
bundle.getFloat(ConfigurationActivity.PERIODIC_VIGNETTE_CENTER_X),
bundle.getFloat(ConfigurationActivity.PERIODIC_VIGNETTE_CENTER_Y),
/* minInnerRadius= */ bundle.getFloat(
ConfigurationActivity.PERIODIC_VIGNETTE_INNER_RADIUS),
/* maxInnerRadius= */ bundle.getFloat(
ConfigurationActivity.PERIODIC_VIGNETTE_OUTER_RADIUS),
bundle.getFloat(ConfigurationActivity.PERIODIC_VIGNETTE_OUTER_RADIUS)));
}
if (selectedEffects[ConfigurationActivity.SPIN_3D_INDEX]) {
effects.add(MatrixTransformationFactory.createSpin3dEffect());
}
if (selectedEffects[ConfigurationActivity.ZOOM_IN_INDEX]) {
effects.add(MatrixTransformationFactory.createZoomInTransition());
}
@Nullable OverlayEffect overlayEffect = createOverlayEffectFromBundle(bundle, selectedEffects);
if (overlayEffect != null) {
effects.add(overlayEffect);
}
float scaleX = bundle.getFloat(ConfigurationActivity.SCALE_X, /* defaultValue= */ 1);
float scaleY = bundle.getFloat(ConfigurationActivity.SCALE_Y, /* defaultValue= */ 1);
float rotateDegrees =
bundle.getFloat(ConfigurationActivity.ROTATE_DEGREES, /* defaultValue= */ 0);
if (scaleX != 1f || scaleY != 1f || rotateDegrees != 0f) {
effects.add(
new ScaleAndRotateTransformation.Builder()
.setScale(scaleX, scaleY)
.setRotationDegrees(rotateDegrees)
.build());
}
int resolutionHeight =
bundle.getInt(ConfigurationActivity.RESOLUTION_HEIGHT, /* defaultValue= */ C.LENGTH_UNSET);
if (resolutionHeight != C.LENGTH_UNSET) {
effects.add(Presentation.createForHeight(resolutionHeight));
}
return effects.build();
}
@Nullable
private OverlayEffect createOverlayEffectFromBundle(Bundle bundle, boolean[] selectedEffects)
throws PackageManager.NameNotFoundException {
ImmutableList.Builder<TextureOverlay> overlaysBuilder = new ImmutableList.Builder<>();
if (selectedEffects[ConfigurationActivity.OVERLAY_LOGO_AND_TIMER_INDEX]) {
float[] logoPositioningMatrix = GlUtil.create4x4IdentityMatrix();
Matrix.translateM(
logoPositioningMatrix, /* mOffset= */ 0, /* x= */ -0.95f, /* y= */ -0.95f, /* z= */ 1);
OverlaySettings logoSettings =
new OverlaySettings.Builder()
.setMatrix(logoPositioningMatrix)
.setAnchor(/* x= */ -1f, /* y= */ -1f)
.build();
Drawable logo = getPackageManager().getApplicationIcon(getPackageName());
logo.setBounds(
/* left= */ 0, /* top= */ 0, logo.getIntrinsicWidth(), logo.getIntrinsicHeight());
TextureOverlay logoOverlay = DrawableOverlay.createStaticDrawableOverlay(logo, logoSettings);
TextureOverlay timerOverlay = new TimerOverlay();
overlaysBuilder.add(logoOverlay, timerOverlay);
}
if (selectedEffects[ConfigurationActivity.BITMAP_OVERLAY_INDEX]) {
OverlaySettings overlaySettings =
new OverlaySettings.Builder()
.setAlpha(
bundle.getFloat(
ConfigurationActivity.BITMAP_OVERLAY_ALPHA, /* defaultValue= */ 1))
.build();
BitmapOverlay bitmapOverlay =
BitmapOverlay.createStaticBitmapOverlay(
getApplicationContext(),
Uri.parse(checkNotNull(bundle.getString(ConfigurationActivity.BITMAP_OVERLAY_URI))),
overlaySettings);
overlaysBuilder.add(bitmapOverlay);
}
if (selectedEffects[ConfigurationActivity.TEXT_OVERLAY_INDEX]) {
OverlaySettings overlaySettings =
new OverlaySettings.Builder()
.setAlpha(
bundle.getFloat(ConfigurationActivity.TEXT_OVERLAY_ALPHA, /* defaultValue= */ 1))
.build();
SpannableString overlayText =
new SpannableString(
checkNotNull(bundle.getString(ConfigurationActivity.TEXT_OVERLAY_TEXT)));
overlayText.setSpan(
new ForegroundColorSpan(bundle.getInt(ConfigurationActivity.TEXT_OVERLAY_TEXT_COLOR)),
/* start= */ 0,
overlayText.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextOverlay textOverlay = TextOverlay.createStaticTextOverlay(overlayText, overlaySettings);
overlaysBuilder.add(textOverlay);
}
ImmutableList<TextureOverlay> overlays = overlaysBuilder.build();
return overlays.isEmpty() ? null : new OverlayEffect(overlays);
}
@RequiresNonNull({
"informationTextView",
"progressViewGroup",
"debugFrame",
"exportStopwatch",
})
private void onError(ExportException exportException) {
exportStopwatch.stop();
informationTextView.setText(R.string.export_error);
progressViewGroup.setVisibility(View.GONE);
debugFrame.removeAllViews();
Toast.makeText(getApplicationContext(), "Export error: " + exportException, Toast.LENGTH_LONG)
.show();
Log.e(TAG, "Export error", exportException);
}
@RequiresNonNull({
"inputCardView",
"inputTextView",
"inputImageView",
"inputPlayerView",
"outputPlayerView",
"outputVideoTextView",
"debugTextView",
"displayInputButton",
"informationTextView",
"progressViewGroup",
"debugFrame",
"exportStopwatch",
})
private void onCompleted(Uri inputUri, String filePath) {
exportStopwatch.stop();
informationTextView.setText(
getString(R.string.export_completed, exportStopwatch.elapsed(TimeUnit.SECONDS), filePath));
progressViewGroup.setVisibility(View.GONE);
debugFrame.removeAllViews();
inputCardView.setVisibility(View.VISIBLE);
outputPlayerView.setVisibility(View.VISIBLE);
outputVideoTextView.setVisibility(View.VISIBLE);
debugTextView.setVisibility(View.VISIBLE);
displayInputButton.setVisibility(View.VISIBLE);
playMediaItems(MediaItem.fromUri(inputUri), MediaItem.fromUri("file://" + filePath));
Log.d(TAG, "Output file path: file://" + filePath);
}
@RequiresNonNull({
"inputCardView",
"inputTextView",
"inputImageView",
"inputPlayerView",
"outputPlayerView",
"debugTextView",
})
private void playMediaItems(MediaItem inputMediaItem, MediaItem outputMediaItem) {
inputPlayerView.setPlayer(null);
outputPlayerView.setPlayer(null);
releasePlayer();
Uri uri = checkNotNull(inputMediaItem.localConfiguration).uri;
ExoPlayer outputPlayer = new ExoPlayer.Builder(/* context= */ this).build();
outputPlayerView.setPlayer(outputPlayer);
outputPlayerView.setControllerAutoShow(false);
outputPlayer.setMediaItem(outputMediaItem);
outputPlayer.prepare();
this.outputPlayer = outputPlayer;
// Only support showing jpg images.
if (uri.toString().endsWith("jpg")) {
inputPlayerView.setVisibility(View.GONE);
inputImageView.setVisibility(View.VISIBLE);
inputTextView.setText(getString(R.string.input_image));
BitmapLoader bitmapLoader = new DataSourceBitmapLoader(getApplicationContext());
ListenableFuture<Bitmap> future = bitmapLoader.loadBitmap(uri);
try {
Bitmap bitmap = future.get();
inputImageView.setImageBitmap(bitmap);
} catch (ExecutionException | InterruptedException e) {
throw new IllegalArgumentException("Failed to load bitmap.", e);
}
} else {
inputPlayerView.setVisibility(View.VISIBLE);
inputImageView.setVisibility(View.GONE);
inputTextView.setText(getString(R.string.input_video_no_sound));
ExoPlayer inputPlayer = new ExoPlayer.Builder(/* context= */ this).build();
inputPlayerView.setPlayer(inputPlayer);
inputPlayerView.setControllerAutoShow(false);
inputPlayerView.setOnClickListener(this::onClickingPlayerView);
outputPlayerView.setOnClickListener(this::onClickingPlayerView);
inputPlayer.setMediaItem(inputMediaItem);
inputPlayer.prepare();
this.inputPlayer = inputPlayer;
inputPlayer.setVolume(0f);
inputPlayer.play();
}
outputPlayer.play();
debugTextViewHelper = new DebugTextViewHelper(outputPlayer, debugTextView);
debugTextViewHelper.start();
}
private void onClickingPlayerView(View view) {
if (view == inputPlayerView) {
if (inputPlayer != null && inputTextView != null) {
inputPlayer.setVolume(1f);
inputTextView.setText(R.string.input_video_playing_sound);
}
checkNotNull(outputPlayer).setVolume(0f);
checkNotNull(outputVideoTextView).setText(R.string.output_video_no_sound);
} else {
if (inputPlayer != null && inputTextView != null) {
inputPlayer.setVolume(0f);
inputTextView.setText(getString(R.string.input_video_no_sound));
}
checkNotNull(outputPlayer).setVolume(1f);
checkNotNull(outputVideoTextView).setText(R.string.output_video_playing_sound);
}
}
private void releasePlayer() {
if (debugTextViewHelper != null) {
debugTextViewHelper.stop();
debugTextViewHelper = null;
}
if (inputPlayer != null) {
inputPlayer.release();
inputPlayer = null;
}
if (outputPlayer != null) {
outputPlayer.release();
outputPlayer = null;
}
}
private static void requestReadVideoPermission(AppCompatActivity activity) {
String permission = SDK_INT >= 33 ? READ_MEDIA_VIDEO : READ_EXTERNAL_STORAGE;
if (ActivityCompat.checkSelfPermission(activity, permission)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[] {permission}, /* requestCode= */ 0);
}
}
private void showToast(@StringRes int messageResource) {
Toast.makeText(getApplicationContext(), getString(messageResource), Toast.LENGTH_LONG).show();
}
@RequiresNonNull({
"inputCardView",
"displayInputButton",
})
private void toggleInputVideoDisplay(View view) {
if (inputCardView.getVisibility() == View.GONE) {
inputCardView.setVisibility(View.VISIBLE);
displayInputButton.setText(getString(R.string.hide_input_video));
} else if (inputCardView.getVisibility() == View.VISIBLE) {
if (inputPlayer != null) {
inputPlayer.pause();
}
inputCardView.setVisibility(View.GONE);
displayInputButton.setText(getString(R.string.show_input_video));
}
}
private final class DemoDebugViewProvider implements DebugViewProvider {
private @MonotonicNonNull SurfaceView surfaceView;
private int width;
private int height;
public DemoDebugViewProvider() {
width = C.LENGTH_UNSET;
height = C.LENGTH_UNSET;
}
@Nullable
@Override
public SurfaceView getDebugPreviewSurfaceView(int width, int height) {
checkState(
surfaceView == null || (this.width == width && this.height == height),
"Transformer should not change the output size mid-export.");
if (surfaceView != null) {
return surfaceView;
}
this.width = width;
this.height = height;
// Update the UI on the main thread and wait for the output surface to be available.
CountDownLatch surfaceCreatedCountDownLatch = new CountDownLatch(1);
runOnUiThread(
() -> {
surfaceView = new SurfaceView(/* context= */ TransformerActivity.this);
AspectRatioFrameLayout debugFrame = checkNotNull(TransformerActivity.this.debugFrame);
debugFrame.addView(surfaceView);
debugFrame.setAspectRatio((float) width / height);
surfaceView
.getHolder()
.addCallback(
new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
surfaceCreatedCountDownLatch.countDown();
}
@Override
public void surfaceChanged(
SurfaceHolder surfaceHolder, int format, int width, int height) {
// Do nothing.
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
// Do nothing.
}
});
});
try {
surfaceCreatedCountDownLatch.await();
} catch (InterruptedException e) {
Log.w(TAG, "Interrupted waiting for debug surface.");
Thread.currentThread().interrupt();
return null;
}
return surfaceView;
}
}
}
|
googleapis/google-api-java-client-services | 35,891 | clients/google-api-services-compute/beta/1.28.0/com/google/api/services/compute/model/Firewall.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 a Firewall Rule resource.
*
* Firewall rules allow or deny ingress traffic to, and egress traffic from your instances. For more
* information, read Firewall rules.
*
* <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 Firewall extends com.google.api.client.json.GenericJson {
/**
* The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a permitted connection.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Allowed> allowed;
static {
// hack to force ProGuard to consider Allowed 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(Allowed.class);
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String creationTimestamp;
/**
* The list of DENY rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a denied connection.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Denied> denied;
static {
// hack to force ProGuard to consider Denied 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(Denied.class);
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* If destination ranges are specified, the firewall rule applies only to traffic that has
* destination IP address in these ranges. These ranges must be expressed in CIDR format. Only
* IPv4 is supported.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> destinationRanges;
/**
* Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default
* is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for
* `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String direction;
/**
* Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not
* enforced and the network behaves as if it did not exist. If this is unspecified, the firewall
* rule will be enabled.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean disabled;
/**
* Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a
* particular firewall rule. If logging is enabled, logs will be exported to Stackdriver.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean enableLogging;
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.math.BigInteger id;
/**
* [Output Only] Type of the resource. Always compute#firewall for firewall rules.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* This field denotes the logging options for a particular firewall rule. If logging is enabled,
* logs will be exported to Stackdriver.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private FirewallLogConfig logConfig;
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* URL of the network resource for this firewall rule. If not specified when creating a firewall
* rule, the default network is used: global/networks/default If you choose to specify this field,
* you can specify the network as a full or partial URL. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network
* - projects/myproject/global/networks/my-network - global/networks/default
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String network;
/**
* Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default
* value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply.
* Lower values indicate higher priority. For example, a rule with priority `0` has higher
* precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they
* have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To
* avoid conflicts with the implied rules, use a priority number less than `65535`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer priority;
/**
* [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;
/**
* If source ranges are specified, the firewall rule applies only to traffic that has a source IP
* address in these ranges. These ranges must be expressed in CIDR format. One or both of
* sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic
* that has a source IP address within sourceRanges OR a source IP from a resource with a matching
* tag listed in the sourceTags field. The connection does not need to match both fields for the
* rule to apply. Only IPv4 is supported.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sourceRanges;
/**
* If source service accounts are specified, the firewall rules apply only to traffic originating
* from an instance with a service account in this list. Source service accounts cannot be used to
* control traffic to an instance's external IP address because service accounts are associated
* with an instance, not an IP address. sourceRanges can be set at the same time as
* sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP
* address within the sourceRanges OR a source IP that belongs to an instance with service account
* listed in sourceServiceAccount. The connection does not need to match both fields for the
* firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or
* targetTags.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sourceServiceAccounts;
/**
* If source tags are specified, the firewall rule applies only to traffic with source IPs that
* match the primary network interfaces of VM instances that have the tag and are in the same VPC
* network. Source tags cannot be used to control traffic to an instance's external IP address, it
* only applies to traffic between instances in the same virtual network. Because tags are
* associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be
* set. If both fields are set, the firewall applies to traffic that has a source IP address
* within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags
* field. The connection does not need to match both fields for the firewall to apply.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sourceTags;
/**
* A list of service accounts indicating sets of instances located in the network that may make
* network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same
* time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are
* specified, the firewall rule applies to all instances on the specified network.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> targetServiceAccounts;
/**
* A list of tags that controls which instances the firewall rule applies to. If targetTags are
* specified, then the firewall rule applies only to instances in the VPC network that have one of
* those tags. If no targetTags are specified, the firewall rule applies to all instances on the
* specified network.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> targetTags;
/**
* The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a permitted connection.
* @return value or {@code null} for none
*/
public java.util.List<Allowed> getAllowed() {
return allowed;
}
/**
* The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a permitted connection.
* @param allowed allowed or {@code null} for none
*/
public Firewall setAllowed(java.util.List<Allowed> allowed) {
this.allowed = allowed;
return this;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @return value or {@code null} for none
*/
public java.lang.String getCreationTimestamp() {
return creationTimestamp;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @param creationTimestamp creationTimestamp or {@code null} for none
*/
public Firewall setCreationTimestamp(java.lang.String creationTimestamp) {
this.creationTimestamp = creationTimestamp;
return this;
}
/**
* The list of DENY rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a denied connection.
* @return value or {@code null} for none
*/
public java.util.List<Denied> getDenied() {
return denied;
}
/**
* The list of DENY rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a denied connection.
* @param denied denied or {@code null} for none
*/
public Firewall setDenied(java.util.List<Denied> denied) {
this.denied = denied;
return this;
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* @param description description or {@code null} for none
*/
public Firewall setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* If destination ranges are specified, the firewall rule applies only to traffic that has
* destination IP address in these ranges. These ranges must be expressed in CIDR format. Only
* IPv4 is supported.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getDestinationRanges() {
return destinationRanges;
}
/**
* If destination ranges are specified, the firewall rule applies only to traffic that has
* destination IP address in these ranges. These ranges must be expressed in CIDR format. Only
* IPv4 is supported.
* @param destinationRanges destinationRanges or {@code null} for none
*/
public Firewall setDestinationRanges(java.util.List<java.lang.String> destinationRanges) {
this.destinationRanges = destinationRanges;
return this;
}
/**
* Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default
* is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for
* `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields.
* @return value or {@code null} for none
*/
public java.lang.String getDirection() {
return direction;
}
/**
* Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default
* is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for
* `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields.
* @param direction direction or {@code null} for none
*/
public Firewall setDirection(java.lang.String direction) {
this.direction = direction;
return this;
}
/**
* Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not
* enforced and the network behaves as if it did not exist. If this is unspecified, the firewall
* rule will be enabled.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDisabled() {
return disabled;
}
/**
* Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not
* enforced and the network behaves as if it did not exist. If this is unspecified, the firewall
* rule will be enabled.
* @param disabled disabled or {@code null} for none
*/
public Firewall setDisabled(java.lang.Boolean disabled) {
this.disabled = disabled;
return this;
}
/**
* Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a
* particular firewall rule. If logging is enabled, logs will be exported to Stackdriver.
* @return value or {@code null} for none
*/
public java.lang.Boolean getEnableLogging() {
return enableLogging;
}
/**
* Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a
* particular firewall rule. If logging is enabled, logs will be exported to Stackdriver.
* @param enableLogging enableLogging or {@code null} for none
*/
public Firewall setEnableLogging(java.lang.Boolean enableLogging) {
this.enableLogging = enableLogging;
return this;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @return value or {@code null} for none
*/
public java.math.BigInteger getId() {
return id;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @param id id or {@code null} for none
*/
public Firewall setId(java.math.BigInteger id) {
this.id = id;
return this;
}
/**
* [Output Only] Type of the resource. Always compute#firewall for firewall rules.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* [Output Only] Type of the resource. Always compute#firewall for firewall rules.
* @param kind kind or {@code null} for none
*/
public Firewall setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* This field denotes the logging options for a particular firewall rule. If logging is enabled,
* logs will be exported to Stackdriver.
* @return value or {@code null} for none
*/
public FirewallLogConfig getLogConfig() {
return logConfig;
}
/**
* This field denotes the logging options for a particular firewall rule. If logging is enabled,
* logs will be exported to Stackdriver.
* @param logConfig logConfig or {@code null} for none
*/
public Firewall setLogConfig(FirewallLogConfig logConfig) {
this.logConfig = logConfig;
return this;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* @param name name or {@code null} for none
*/
public Firewall setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* URL of the network resource for this firewall rule. If not specified when creating a firewall
* rule, the default network is used: global/networks/default If you choose to specify this field,
* you can specify the network as a full or partial URL. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network
* - projects/myproject/global/networks/my-network - global/networks/default
* @return value or {@code null} for none
*/
public java.lang.String getNetwork() {
return network;
}
/**
* URL of the network resource for this firewall rule. If not specified when creating a firewall
* rule, the default network is used: global/networks/default If you choose to specify this field,
* you can specify the network as a full or partial URL. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network
* - projects/myproject/global/networks/my-network - global/networks/default
* @param network network or {@code null} for none
*/
public Firewall setNetwork(java.lang.String network) {
this.network = network;
return this;
}
/**
* Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default
* value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply.
* Lower values indicate higher priority. For example, a rule with priority `0` has higher
* precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they
* have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To
* avoid conflicts with the implied rules, use a priority number less than `65535`.
* @return value or {@code null} for none
*/
public java.lang.Integer getPriority() {
return priority;
}
/**
* Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default
* value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply.
* Lower values indicate higher priority. For example, a rule with priority `0` has higher
* precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they
* have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To
* avoid conflicts with the implied rules, use a priority number less than `65535`.
* @param priority priority or {@code null} for none
*/
public Firewall setPriority(java.lang.Integer priority) {
this.priority = priority;
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 Firewall setSelfLink(java.lang.String selfLink) {
this.selfLink = selfLink;
return this;
}
/**
* If source ranges are specified, the firewall rule applies only to traffic that has a source IP
* address in these ranges. These ranges must be expressed in CIDR format. One or both of
* sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic
* that has a source IP address within sourceRanges OR a source IP from a resource with a matching
* tag listed in the sourceTags field. The connection does not need to match both fields for the
* rule to apply. Only IPv4 is supported.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSourceRanges() {
return sourceRanges;
}
/**
* If source ranges are specified, the firewall rule applies only to traffic that has a source IP
* address in these ranges. These ranges must be expressed in CIDR format. One or both of
* sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic
* that has a source IP address within sourceRanges OR a source IP from a resource with a matching
* tag listed in the sourceTags field. The connection does not need to match both fields for the
* rule to apply. Only IPv4 is supported.
* @param sourceRanges sourceRanges or {@code null} for none
*/
public Firewall setSourceRanges(java.util.List<java.lang.String> sourceRanges) {
this.sourceRanges = sourceRanges;
return this;
}
/**
* If source service accounts are specified, the firewall rules apply only to traffic originating
* from an instance with a service account in this list. Source service accounts cannot be used to
* control traffic to an instance's external IP address because service accounts are associated
* with an instance, not an IP address. sourceRanges can be set at the same time as
* sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP
* address within the sourceRanges OR a source IP that belongs to an instance with service account
* listed in sourceServiceAccount. The connection does not need to match both fields for the
* firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or
* targetTags.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSourceServiceAccounts() {
return sourceServiceAccounts;
}
/**
* If source service accounts are specified, the firewall rules apply only to traffic originating
* from an instance with a service account in this list. Source service accounts cannot be used to
* control traffic to an instance's external IP address because service accounts are associated
* with an instance, not an IP address. sourceRanges can be set at the same time as
* sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP
* address within the sourceRanges OR a source IP that belongs to an instance with service account
* listed in sourceServiceAccount. The connection does not need to match both fields for the
* firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or
* targetTags.
* @param sourceServiceAccounts sourceServiceAccounts or {@code null} for none
*/
public Firewall setSourceServiceAccounts(java.util.List<java.lang.String> sourceServiceAccounts) {
this.sourceServiceAccounts = sourceServiceAccounts;
return this;
}
/**
* If source tags are specified, the firewall rule applies only to traffic with source IPs that
* match the primary network interfaces of VM instances that have the tag and are in the same VPC
* network. Source tags cannot be used to control traffic to an instance's external IP address, it
* only applies to traffic between instances in the same virtual network. Because tags are
* associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be
* set. If both fields are set, the firewall applies to traffic that has a source IP address
* within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags
* field. The connection does not need to match both fields for the firewall to apply.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSourceTags() {
return sourceTags;
}
/**
* If source tags are specified, the firewall rule applies only to traffic with source IPs that
* match the primary network interfaces of VM instances that have the tag and are in the same VPC
* network. Source tags cannot be used to control traffic to an instance's external IP address, it
* only applies to traffic between instances in the same virtual network. Because tags are
* associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be
* set. If both fields are set, the firewall applies to traffic that has a source IP address
* within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags
* field. The connection does not need to match both fields for the firewall to apply.
* @param sourceTags sourceTags or {@code null} for none
*/
public Firewall setSourceTags(java.util.List<java.lang.String> sourceTags) {
this.sourceTags = sourceTags;
return this;
}
/**
* A list of service accounts indicating sets of instances located in the network that may make
* network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same
* time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are
* specified, the firewall rule applies to all instances on the specified network.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTargetServiceAccounts() {
return targetServiceAccounts;
}
/**
* A list of service accounts indicating sets of instances located in the network that may make
* network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same
* time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are
* specified, the firewall rule applies to all instances on the specified network.
* @param targetServiceAccounts targetServiceAccounts or {@code null} for none
*/
public Firewall setTargetServiceAccounts(java.util.List<java.lang.String> targetServiceAccounts) {
this.targetServiceAccounts = targetServiceAccounts;
return this;
}
/**
* A list of tags that controls which instances the firewall rule applies to. If targetTags are
* specified, then the firewall rule applies only to instances in the VPC network that have one of
* those tags. If no targetTags are specified, the firewall rule applies to all instances on the
* specified network.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTargetTags() {
return targetTags;
}
/**
* A list of tags that controls which instances the firewall rule applies to. If targetTags are
* specified, then the firewall rule applies only to instances in the VPC network that have one of
* those tags. If no targetTags are specified, the firewall rule applies to all instances on the
* specified network.
* @param targetTags targetTags or {@code null} for none
*/
public Firewall setTargetTags(java.util.List<java.lang.String> targetTags) {
this.targetTags = targetTags;
return this;
}
@Override
public Firewall set(String fieldName, Object value) {
return (Firewall) super.set(fieldName, value);
}
@Override
public Firewall clone() {
return (Firewall) super.clone();
}
/**
* Model definition for FirewallAllowed.
*/
public static final class Allowed extends com.google.api.client.json.GenericJson {
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("IPProtocol")
private java.lang.String iPProtocol;
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> ports;
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @return value or {@code null} for none
*/
public java.lang.String getIPProtocol() {
return iPProtocol;
}
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @param iPProtocol iPProtocol or {@code null} for none
*/
public Allowed setIPProtocol(java.lang.String iPProtocol) {
this.iPProtocol = iPProtocol;
return this;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getPorts() {
return ports;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* @param ports ports or {@code null} for none
*/
public Allowed setPorts(java.util.List<java.lang.String> ports) {
this.ports = ports;
return this;
}
@Override
public Allowed set(String fieldName, Object value) {
return (Allowed) super.set(fieldName, value);
}
@Override
public Allowed clone() {
return (Allowed) super.clone();
}
}
/**
* Model definition for FirewallDenied.
*/
public static final class Denied extends com.google.api.client.json.GenericJson {
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("IPProtocol")
private java.lang.String iPProtocol;
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> ports;
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @return value or {@code null} for none
*/
public java.lang.String getIPProtocol() {
return iPProtocol;
}
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @param iPProtocol iPProtocol or {@code null} for none
*/
public Denied setIPProtocol(java.lang.String iPProtocol) {
this.iPProtocol = iPProtocol;
return this;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getPorts() {
return ports;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* @param ports ports or {@code null} for none
*/
public Denied setPorts(java.util.List<java.lang.String> ports) {
this.ports = ports;
return this;
}
@Override
public Denied set(String fieldName, Object value) {
return (Denied) super.set(fieldName, value);
}
@Override
public Denied clone() {
return (Denied) super.clone();
}
}
}
|
googleapis/google-api-java-client-services | 35,891 | clients/google-api-services-compute/beta/1.29.2/com/google/api/services/compute/model/Firewall.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 a Firewall Rule resource.
*
* Firewall rules allow or deny ingress traffic to, and egress traffic from your instances. For more
* information, read Firewall rules.
*
* <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 Firewall extends com.google.api.client.json.GenericJson {
/**
* The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a permitted connection.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Allowed> allowed;
static {
// hack to force ProGuard to consider Allowed 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(Allowed.class);
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String creationTimestamp;
/**
* The list of DENY rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a denied connection.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Denied> denied;
static {
// hack to force ProGuard to consider Denied 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(Denied.class);
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* If destination ranges are specified, the firewall rule applies only to traffic that has
* destination IP address in these ranges. These ranges must be expressed in CIDR format. Only
* IPv4 is supported.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> destinationRanges;
/**
* Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default
* is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for
* `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String direction;
/**
* Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not
* enforced and the network behaves as if it did not exist. If this is unspecified, the firewall
* rule will be enabled.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean disabled;
/**
* Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a
* particular firewall rule. If logging is enabled, logs will be exported to Stackdriver.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean enableLogging;
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.math.BigInteger id;
/**
* [Output Only] Type of the resource. Always compute#firewall for firewall rules.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* This field denotes the logging options for a particular firewall rule. If logging is enabled,
* logs will be exported to Stackdriver.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private FirewallLogConfig logConfig;
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* URL of the network resource for this firewall rule. If not specified when creating a firewall
* rule, the default network is used: global/networks/default If you choose to specify this field,
* you can specify the network as a full or partial URL. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network
* - projects/myproject/global/networks/my-network - global/networks/default
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String network;
/**
* Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default
* value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply.
* Lower values indicate higher priority. For example, a rule with priority `0` has higher
* precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they
* have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To
* avoid conflicts with the implied rules, use a priority number less than `65535`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer priority;
/**
* [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;
/**
* If source ranges are specified, the firewall rule applies only to traffic that has a source IP
* address in these ranges. These ranges must be expressed in CIDR format. One or both of
* sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic
* that has a source IP address within sourceRanges OR a source IP from a resource with a matching
* tag listed in the sourceTags field. The connection does not need to match both fields for the
* rule to apply. Only IPv4 is supported.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sourceRanges;
/**
* If source service accounts are specified, the firewall rules apply only to traffic originating
* from an instance with a service account in this list. Source service accounts cannot be used to
* control traffic to an instance's external IP address because service accounts are associated
* with an instance, not an IP address. sourceRanges can be set at the same time as
* sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP
* address within the sourceRanges OR a source IP that belongs to an instance with service account
* listed in sourceServiceAccount. The connection does not need to match both fields for the
* firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or
* targetTags.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sourceServiceAccounts;
/**
* If source tags are specified, the firewall rule applies only to traffic with source IPs that
* match the primary network interfaces of VM instances that have the tag and are in the same VPC
* network. Source tags cannot be used to control traffic to an instance's external IP address, it
* only applies to traffic between instances in the same virtual network. Because tags are
* associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be
* set. If both fields are set, the firewall applies to traffic that has a source IP address
* within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags
* field. The connection does not need to match both fields for the firewall to apply.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sourceTags;
/**
* A list of service accounts indicating sets of instances located in the network that may make
* network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same
* time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are
* specified, the firewall rule applies to all instances on the specified network.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> targetServiceAccounts;
/**
* A list of tags that controls which instances the firewall rule applies to. If targetTags are
* specified, then the firewall rule applies only to instances in the VPC network that have one of
* those tags. If no targetTags are specified, the firewall rule applies to all instances on the
* specified network.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> targetTags;
/**
* The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a permitted connection.
* @return value or {@code null} for none
*/
public java.util.List<Allowed> getAllowed() {
return allowed;
}
/**
* The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a permitted connection.
* @param allowed allowed or {@code null} for none
*/
public Firewall setAllowed(java.util.List<Allowed> allowed) {
this.allowed = allowed;
return this;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @return value or {@code null} for none
*/
public java.lang.String getCreationTimestamp() {
return creationTimestamp;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @param creationTimestamp creationTimestamp or {@code null} for none
*/
public Firewall setCreationTimestamp(java.lang.String creationTimestamp) {
this.creationTimestamp = creationTimestamp;
return this;
}
/**
* The list of DENY rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a denied connection.
* @return value or {@code null} for none
*/
public java.util.List<Denied> getDenied() {
return denied;
}
/**
* The list of DENY rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a denied connection.
* @param denied denied or {@code null} for none
*/
public Firewall setDenied(java.util.List<Denied> denied) {
this.denied = denied;
return this;
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* @param description description or {@code null} for none
*/
public Firewall setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* If destination ranges are specified, the firewall rule applies only to traffic that has
* destination IP address in these ranges. These ranges must be expressed in CIDR format. Only
* IPv4 is supported.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getDestinationRanges() {
return destinationRanges;
}
/**
* If destination ranges are specified, the firewall rule applies only to traffic that has
* destination IP address in these ranges. These ranges must be expressed in CIDR format. Only
* IPv4 is supported.
* @param destinationRanges destinationRanges or {@code null} for none
*/
public Firewall setDestinationRanges(java.util.List<java.lang.String> destinationRanges) {
this.destinationRanges = destinationRanges;
return this;
}
/**
* Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default
* is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for
* `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields.
* @return value or {@code null} for none
*/
public java.lang.String getDirection() {
return direction;
}
/**
* Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default
* is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for
* `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields.
* @param direction direction or {@code null} for none
*/
public Firewall setDirection(java.lang.String direction) {
this.direction = direction;
return this;
}
/**
* Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not
* enforced and the network behaves as if it did not exist. If this is unspecified, the firewall
* rule will be enabled.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDisabled() {
return disabled;
}
/**
* Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not
* enforced and the network behaves as if it did not exist. If this is unspecified, the firewall
* rule will be enabled.
* @param disabled disabled or {@code null} for none
*/
public Firewall setDisabled(java.lang.Boolean disabled) {
this.disabled = disabled;
return this;
}
/**
* Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a
* particular firewall rule. If logging is enabled, logs will be exported to Stackdriver.
* @return value or {@code null} for none
*/
public java.lang.Boolean getEnableLogging() {
return enableLogging;
}
/**
* Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a
* particular firewall rule. If logging is enabled, logs will be exported to Stackdriver.
* @param enableLogging enableLogging or {@code null} for none
*/
public Firewall setEnableLogging(java.lang.Boolean enableLogging) {
this.enableLogging = enableLogging;
return this;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @return value or {@code null} for none
*/
public java.math.BigInteger getId() {
return id;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @param id id or {@code null} for none
*/
public Firewall setId(java.math.BigInteger id) {
this.id = id;
return this;
}
/**
* [Output Only] Type of the resource. Always compute#firewall for firewall rules.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* [Output Only] Type of the resource. Always compute#firewall for firewall rules.
* @param kind kind or {@code null} for none
*/
public Firewall setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* This field denotes the logging options for a particular firewall rule. If logging is enabled,
* logs will be exported to Stackdriver.
* @return value or {@code null} for none
*/
public FirewallLogConfig getLogConfig() {
return logConfig;
}
/**
* This field denotes the logging options for a particular firewall rule. If logging is enabled,
* logs will be exported to Stackdriver.
* @param logConfig logConfig or {@code null} for none
*/
public Firewall setLogConfig(FirewallLogConfig logConfig) {
this.logConfig = logConfig;
return this;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* @param name name or {@code null} for none
*/
public Firewall setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* URL of the network resource for this firewall rule. If not specified when creating a firewall
* rule, the default network is used: global/networks/default If you choose to specify this field,
* you can specify the network as a full or partial URL. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network
* - projects/myproject/global/networks/my-network - global/networks/default
* @return value or {@code null} for none
*/
public java.lang.String getNetwork() {
return network;
}
/**
* URL of the network resource for this firewall rule. If not specified when creating a firewall
* rule, the default network is used: global/networks/default If you choose to specify this field,
* you can specify the network as a full or partial URL. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network
* - projects/myproject/global/networks/my-network - global/networks/default
* @param network network or {@code null} for none
*/
public Firewall setNetwork(java.lang.String network) {
this.network = network;
return this;
}
/**
* Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default
* value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply.
* Lower values indicate higher priority. For example, a rule with priority `0` has higher
* precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they
* have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To
* avoid conflicts with the implied rules, use a priority number less than `65535`.
* @return value or {@code null} for none
*/
public java.lang.Integer getPriority() {
return priority;
}
/**
* Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default
* value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply.
* Lower values indicate higher priority. For example, a rule with priority `0` has higher
* precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they
* have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To
* avoid conflicts with the implied rules, use a priority number less than `65535`.
* @param priority priority or {@code null} for none
*/
public Firewall setPriority(java.lang.Integer priority) {
this.priority = priority;
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 Firewall setSelfLink(java.lang.String selfLink) {
this.selfLink = selfLink;
return this;
}
/**
* If source ranges are specified, the firewall rule applies only to traffic that has a source IP
* address in these ranges. These ranges must be expressed in CIDR format. One or both of
* sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic
* that has a source IP address within sourceRanges OR a source IP from a resource with a matching
* tag listed in the sourceTags field. The connection does not need to match both fields for the
* rule to apply. Only IPv4 is supported.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSourceRanges() {
return sourceRanges;
}
/**
* If source ranges are specified, the firewall rule applies only to traffic that has a source IP
* address in these ranges. These ranges must be expressed in CIDR format. One or both of
* sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic
* that has a source IP address within sourceRanges OR a source IP from a resource with a matching
* tag listed in the sourceTags field. The connection does not need to match both fields for the
* rule to apply. Only IPv4 is supported.
* @param sourceRanges sourceRanges or {@code null} for none
*/
public Firewall setSourceRanges(java.util.List<java.lang.String> sourceRanges) {
this.sourceRanges = sourceRanges;
return this;
}
/**
* If source service accounts are specified, the firewall rules apply only to traffic originating
* from an instance with a service account in this list. Source service accounts cannot be used to
* control traffic to an instance's external IP address because service accounts are associated
* with an instance, not an IP address. sourceRanges can be set at the same time as
* sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP
* address within the sourceRanges OR a source IP that belongs to an instance with service account
* listed in sourceServiceAccount. The connection does not need to match both fields for the
* firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or
* targetTags.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSourceServiceAccounts() {
return sourceServiceAccounts;
}
/**
* If source service accounts are specified, the firewall rules apply only to traffic originating
* from an instance with a service account in this list. Source service accounts cannot be used to
* control traffic to an instance's external IP address because service accounts are associated
* with an instance, not an IP address. sourceRanges can be set at the same time as
* sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP
* address within the sourceRanges OR a source IP that belongs to an instance with service account
* listed in sourceServiceAccount. The connection does not need to match both fields for the
* firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or
* targetTags.
* @param sourceServiceAccounts sourceServiceAccounts or {@code null} for none
*/
public Firewall setSourceServiceAccounts(java.util.List<java.lang.String> sourceServiceAccounts) {
this.sourceServiceAccounts = sourceServiceAccounts;
return this;
}
/**
* If source tags are specified, the firewall rule applies only to traffic with source IPs that
* match the primary network interfaces of VM instances that have the tag and are in the same VPC
* network. Source tags cannot be used to control traffic to an instance's external IP address, it
* only applies to traffic between instances in the same virtual network. Because tags are
* associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be
* set. If both fields are set, the firewall applies to traffic that has a source IP address
* within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags
* field. The connection does not need to match both fields for the firewall to apply.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSourceTags() {
return sourceTags;
}
/**
* If source tags are specified, the firewall rule applies only to traffic with source IPs that
* match the primary network interfaces of VM instances that have the tag and are in the same VPC
* network. Source tags cannot be used to control traffic to an instance's external IP address, it
* only applies to traffic between instances in the same virtual network. Because tags are
* associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be
* set. If both fields are set, the firewall applies to traffic that has a source IP address
* within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags
* field. The connection does not need to match both fields for the firewall to apply.
* @param sourceTags sourceTags or {@code null} for none
*/
public Firewall setSourceTags(java.util.List<java.lang.String> sourceTags) {
this.sourceTags = sourceTags;
return this;
}
/**
* A list of service accounts indicating sets of instances located in the network that may make
* network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same
* time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are
* specified, the firewall rule applies to all instances on the specified network.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTargetServiceAccounts() {
return targetServiceAccounts;
}
/**
* A list of service accounts indicating sets of instances located in the network that may make
* network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same
* time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are
* specified, the firewall rule applies to all instances on the specified network.
* @param targetServiceAccounts targetServiceAccounts or {@code null} for none
*/
public Firewall setTargetServiceAccounts(java.util.List<java.lang.String> targetServiceAccounts) {
this.targetServiceAccounts = targetServiceAccounts;
return this;
}
/**
* A list of tags that controls which instances the firewall rule applies to. If targetTags are
* specified, then the firewall rule applies only to instances in the VPC network that have one of
* those tags. If no targetTags are specified, the firewall rule applies to all instances on the
* specified network.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTargetTags() {
return targetTags;
}
/**
* A list of tags that controls which instances the firewall rule applies to. If targetTags are
* specified, then the firewall rule applies only to instances in the VPC network that have one of
* those tags. If no targetTags are specified, the firewall rule applies to all instances on the
* specified network.
* @param targetTags targetTags or {@code null} for none
*/
public Firewall setTargetTags(java.util.List<java.lang.String> targetTags) {
this.targetTags = targetTags;
return this;
}
@Override
public Firewall set(String fieldName, Object value) {
return (Firewall) super.set(fieldName, value);
}
@Override
public Firewall clone() {
return (Firewall) super.clone();
}
/**
* Model definition for FirewallAllowed.
*/
public static final class Allowed extends com.google.api.client.json.GenericJson {
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("IPProtocol")
private java.lang.String iPProtocol;
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> ports;
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @return value or {@code null} for none
*/
public java.lang.String getIPProtocol() {
return iPProtocol;
}
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @param iPProtocol iPProtocol or {@code null} for none
*/
public Allowed setIPProtocol(java.lang.String iPProtocol) {
this.iPProtocol = iPProtocol;
return this;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getPorts() {
return ports;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* @param ports ports or {@code null} for none
*/
public Allowed setPorts(java.util.List<java.lang.String> ports) {
this.ports = ports;
return this;
}
@Override
public Allowed set(String fieldName, Object value) {
return (Allowed) super.set(fieldName, value);
}
@Override
public Allowed clone() {
return (Allowed) super.clone();
}
}
/**
* Model definition for FirewallDenied.
*/
public static final class Denied extends com.google.api.client.json.GenericJson {
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("IPProtocol")
private java.lang.String iPProtocol;
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> ports;
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @return value or {@code null} for none
*/
public java.lang.String getIPProtocol() {
return iPProtocol;
}
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @param iPProtocol iPProtocol or {@code null} for none
*/
public Denied setIPProtocol(java.lang.String iPProtocol) {
this.iPProtocol = iPProtocol;
return this;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getPorts() {
return ports;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* @param ports ports or {@code null} for none
*/
public Denied setPorts(java.util.List<java.lang.String> ports) {
this.ports = ports;
return this;
}
@Override
public Denied set(String fieldName, Object value) {
return (Denied) super.set(fieldName, value);
}
@Override
public Denied clone() {
return (Denied) super.clone();
}
}
}
|
googleapis/google-cloud-java | 35,611 | java-datacatalog/proto-google-cloud-datacatalog-v1beta1/src/main/java/com/google/cloud/datacatalog/v1beta1/ListTagsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/datacatalog/v1beta1/datacatalog.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.datacatalog.v1beta1;
/**
*
*
* <pre>
* Response message for
* [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags].
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.v1beta1.ListTagsResponse}
*/
public final class ListTagsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.datacatalog.v1beta1.ListTagsResponse)
ListTagsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListTagsResponse.newBuilder() to construct.
private ListTagsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListTagsResponse() {
tags_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListTagsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.v1beta1.Datacatalog
.internal_static_google_cloud_datacatalog_v1beta1_ListTagsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.v1beta1.Datacatalog
.internal_static_google_cloud_datacatalog_v1beta1_ListTagsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.v1beta1.ListTagsResponse.class,
com.google.cloud.datacatalog.v1beta1.ListTagsResponse.Builder.class);
}
public static final int TAGS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.datacatalog.v1beta1.Tag> tags_;
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.datacatalog.v1beta1.Tag> getTagsList() {
return tags_;
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.datacatalog.v1beta1.TagOrBuilder>
getTagsOrBuilderList() {
return tags_;
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
@java.lang.Override
public int getTagsCount() {
return tags_.size();
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
@java.lang.Override
public com.google.cloud.datacatalog.v1beta1.Tag getTags(int index) {
return tags_.get(index);
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
@java.lang.Override
public com.google.cloud.datacatalog.v1beta1.TagOrBuilder getTagsOrBuilder(int index) {
return tags_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results. It is set to empty if no items
* remain in results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results. It is set to empty if no items
* remain in 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 < tags_.size(); i++) {
output.writeMessage(1, tags_.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 < tags_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, tags_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.datacatalog.v1beta1.ListTagsResponse)) {
return super.equals(obj);
}
com.google.cloud.datacatalog.v1beta1.ListTagsResponse other =
(com.google.cloud.datacatalog.v1beta1.ListTagsResponse) obj;
if (!getTagsList().equals(other.getTagsList())) 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 (getTagsCount() > 0) {
hash = (37 * hash) + TAGS_FIELD_NUMBER;
hash = (53 * hash) + getTagsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.datacatalog.v1beta1.ListTagsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1beta1.ListTagsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1beta1.ListTagsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1beta1.ListTagsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1beta1.ListTagsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1beta1.ListTagsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1beta1.ListTagsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1beta1.ListTagsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1beta1.ListTagsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1beta1.ListTagsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1beta1.ListTagsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1beta1.ListTagsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.datacatalog.v1beta1.ListTagsResponse 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
* [ListTags][google.cloud.datacatalog.v1beta1.DataCatalog.ListTags].
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.v1beta1.ListTagsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.datacatalog.v1beta1.ListTagsResponse)
com.google.cloud.datacatalog.v1beta1.ListTagsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.v1beta1.Datacatalog
.internal_static_google_cloud_datacatalog_v1beta1_ListTagsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.v1beta1.Datacatalog
.internal_static_google_cloud_datacatalog_v1beta1_ListTagsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.v1beta1.ListTagsResponse.class,
com.google.cloud.datacatalog.v1beta1.ListTagsResponse.Builder.class);
}
// Construct using com.google.cloud.datacatalog.v1beta1.ListTagsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (tagsBuilder_ == null) {
tags_ = java.util.Collections.emptyList();
} else {
tags_ = null;
tagsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.datacatalog.v1beta1.Datacatalog
.internal_static_google_cloud_datacatalog_v1beta1_ListTagsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1beta1.ListTagsResponse getDefaultInstanceForType() {
return com.google.cloud.datacatalog.v1beta1.ListTagsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.datacatalog.v1beta1.ListTagsResponse build() {
com.google.cloud.datacatalog.v1beta1.ListTagsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1beta1.ListTagsResponse buildPartial() {
com.google.cloud.datacatalog.v1beta1.ListTagsResponse result =
new com.google.cloud.datacatalog.v1beta1.ListTagsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.datacatalog.v1beta1.ListTagsResponse result) {
if (tagsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
tags_ = java.util.Collections.unmodifiableList(tags_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.tags_ = tags_;
} else {
result.tags_ = tagsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.datacatalog.v1beta1.ListTagsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.datacatalog.v1beta1.ListTagsResponse) {
return mergeFrom((com.google.cloud.datacatalog.v1beta1.ListTagsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.datacatalog.v1beta1.ListTagsResponse other) {
if (other == com.google.cloud.datacatalog.v1beta1.ListTagsResponse.getDefaultInstance())
return this;
if (tagsBuilder_ == null) {
if (!other.tags_.isEmpty()) {
if (tags_.isEmpty()) {
tags_ = other.tags_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureTagsIsMutable();
tags_.addAll(other.tags_);
}
onChanged();
}
} else {
if (!other.tags_.isEmpty()) {
if (tagsBuilder_.isEmpty()) {
tagsBuilder_.dispose();
tagsBuilder_ = null;
tags_ = other.tags_;
bitField0_ = (bitField0_ & ~0x00000001);
tagsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getTagsFieldBuilder()
: null;
} else {
tagsBuilder_.addAllMessages(other.tags_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.datacatalog.v1beta1.Tag m =
input.readMessage(
com.google.cloud.datacatalog.v1beta1.Tag.parser(), extensionRegistry);
if (tagsBuilder_ == null) {
ensureTagsIsMutable();
tags_.add(m);
} else {
tagsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.datacatalog.v1beta1.Tag> tags_ =
java.util.Collections.emptyList();
private void ensureTagsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
tags_ = new java.util.ArrayList<com.google.cloud.datacatalog.v1beta1.Tag>(tags_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1beta1.Tag,
com.google.cloud.datacatalog.v1beta1.Tag.Builder,
com.google.cloud.datacatalog.v1beta1.TagOrBuilder>
tagsBuilder_;
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public java.util.List<com.google.cloud.datacatalog.v1beta1.Tag> getTagsList() {
if (tagsBuilder_ == null) {
return java.util.Collections.unmodifiableList(tags_);
} else {
return tagsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public int getTagsCount() {
if (tagsBuilder_ == null) {
return tags_.size();
} else {
return tagsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public com.google.cloud.datacatalog.v1beta1.Tag getTags(int index) {
if (tagsBuilder_ == null) {
return tags_.get(index);
} else {
return tagsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public Builder setTags(int index, com.google.cloud.datacatalog.v1beta1.Tag value) {
if (tagsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTagsIsMutable();
tags_.set(index, value);
onChanged();
} else {
tagsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public Builder setTags(
int index, com.google.cloud.datacatalog.v1beta1.Tag.Builder builderForValue) {
if (tagsBuilder_ == null) {
ensureTagsIsMutable();
tags_.set(index, builderForValue.build());
onChanged();
} else {
tagsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public Builder addTags(com.google.cloud.datacatalog.v1beta1.Tag value) {
if (tagsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTagsIsMutable();
tags_.add(value);
onChanged();
} else {
tagsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public Builder addTags(int index, com.google.cloud.datacatalog.v1beta1.Tag value) {
if (tagsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTagsIsMutable();
tags_.add(index, value);
onChanged();
} else {
tagsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public Builder addTags(com.google.cloud.datacatalog.v1beta1.Tag.Builder builderForValue) {
if (tagsBuilder_ == null) {
ensureTagsIsMutable();
tags_.add(builderForValue.build());
onChanged();
} else {
tagsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public Builder addTags(
int index, com.google.cloud.datacatalog.v1beta1.Tag.Builder builderForValue) {
if (tagsBuilder_ == null) {
ensureTagsIsMutable();
tags_.add(index, builderForValue.build());
onChanged();
} else {
tagsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public Builder addAllTags(
java.lang.Iterable<? extends com.google.cloud.datacatalog.v1beta1.Tag> values) {
if (tagsBuilder_ == null) {
ensureTagsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, tags_);
onChanged();
} else {
tagsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public Builder clearTags() {
if (tagsBuilder_ == null) {
tags_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
tagsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public Builder removeTags(int index) {
if (tagsBuilder_ == null) {
ensureTagsIsMutable();
tags_.remove(index);
onChanged();
} else {
tagsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public com.google.cloud.datacatalog.v1beta1.Tag.Builder getTagsBuilder(int index) {
return getTagsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public com.google.cloud.datacatalog.v1beta1.TagOrBuilder getTagsOrBuilder(int index) {
if (tagsBuilder_ == null) {
return tags_.get(index);
} else {
return tagsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public java.util.List<? extends com.google.cloud.datacatalog.v1beta1.TagOrBuilder>
getTagsOrBuilderList() {
if (tagsBuilder_ != null) {
return tagsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(tags_);
}
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public com.google.cloud.datacatalog.v1beta1.Tag.Builder addTagsBuilder() {
return getTagsFieldBuilder()
.addBuilder(com.google.cloud.datacatalog.v1beta1.Tag.getDefaultInstance());
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public com.google.cloud.datacatalog.v1beta1.Tag.Builder addTagsBuilder(int index) {
return getTagsFieldBuilder()
.addBuilder(index, com.google.cloud.datacatalog.v1beta1.Tag.getDefaultInstance());
}
/**
*
*
* <pre>
* [Tag][google.cloud.datacatalog.v1beta1.Tag] details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Tag tags = 1;</code>
*/
public java.util.List<com.google.cloud.datacatalog.v1beta1.Tag.Builder> getTagsBuilderList() {
return getTagsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1beta1.Tag,
com.google.cloud.datacatalog.v1beta1.Tag.Builder,
com.google.cloud.datacatalog.v1beta1.TagOrBuilder>
getTagsFieldBuilder() {
if (tagsBuilder_ == null) {
tagsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1beta1.Tag,
com.google.cloud.datacatalog.v1beta1.Tag.Builder,
com.google.cloud.datacatalog.v1beta1.TagOrBuilder>(
tags_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
tags_ = null;
}
return tagsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results. It is set to empty if no items
* remain in results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results. It is set to empty if no items
* remain in results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results. It is set to empty if no items
* remain in results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results. It is set to empty if no items
* remain in results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results. It is set to empty if no items
* remain in 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.datacatalog.v1beta1.ListTagsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.datacatalog.v1beta1.ListTagsResponse)
private static final com.google.cloud.datacatalog.v1beta1.ListTagsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.datacatalog.v1beta1.ListTagsResponse();
}
public static com.google.cloud.datacatalog.v1beta1.ListTagsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListTagsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListTagsResponse>() {
@java.lang.Override
public ListTagsResponse 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<ListTagsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListTagsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1beta1.ListTagsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,574 | java-discoveryengine/proto-google-cloud-discoveryengine-v1beta/src/main/java/com/google/cloud/discoveryengine/v1beta/RankingRecord.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/discoveryengine/v1beta/rank_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.discoveryengine.v1beta;
/**
*
*
* <pre>
* Record message for
* [RankService.Rank][google.cloud.discoveryengine.v1beta.RankService.Rank]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1beta.RankingRecord}
*/
public final class RankingRecord extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1beta.RankingRecord)
RankingRecordOrBuilder {
private static final long serialVersionUID = 0L;
// Use RankingRecord.newBuilder() to construct.
private RankingRecord(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private RankingRecord() {
id_ = "";
title_ = "";
content_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new RankingRecord();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1beta.RankServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_RankingRecord_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1beta.RankServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_RankingRecord_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1beta.RankingRecord.class,
com.google.cloud.discoveryengine.v1beta.RankingRecord.Builder.class);
}
public static final int ID_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object id_ = "";
/**
*
*
* <pre>
* The unique ID to represent the record.
* </pre>
*
* <code>string id = 1;</code>
*
* @return The id.
*/
@java.lang.Override
public java.lang.String getId() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
}
}
/**
*
*
* <pre>
* The unique ID to represent the record.
* </pre>
*
* <code>string id = 1;</code>
*
* @return The bytes for id.
*/
@java.lang.Override
public com.google.protobuf.ByteString getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TITLE_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object title_ = "";
/**
*
*
* <pre>
* The title of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string title = 2;</code>
*
* @return The title.
*/
@java.lang.Override
public java.lang.String getTitle() {
java.lang.Object ref = title_;
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();
title_ = s;
return s;
}
}
/**
*
*
* <pre>
* The title of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string title = 2;</code>
*
* @return The bytes for title.
*/
@java.lang.Override
public com.google.protobuf.ByteString getTitleBytes() {
java.lang.Object ref = title_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
title_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CONTENT_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object content_ = "";
/**
*
*
* <pre>
* The content of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string content = 3;</code>
*
* @return The content.
*/
@java.lang.Override
public java.lang.String getContent() {
java.lang.Object ref = content_;
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();
content_ = s;
return s;
}
}
/**
*
*
* <pre>
* The content of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string content = 3;</code>
*
* @return The bytes for content.
*/
@java.lang.Override
public com.google.protobuf.ByteString getContentBytes() {
java.lang.Object ref = content_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
content_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SCORE_FIELD_NUMBER = 4;
private float score_ = 0F;
/**
*
*
* <pre>
* The score of this record based on the given query and selected model.
* </pre>
*
* <code>float score = 4;</code>
*
* @return The score.
*/
@java.lang.Override
public float getScore() {
return score_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, id_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(title_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, title_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(content_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, content_);
}
if (java.lang.Float.floatToRawIntBits(score_) != 0) {
output.writeFloat(4, score_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, id_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(title_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, title_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(content_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, content_);
}
if (java.lang.Float.floatToRawIntBits(score_) != 0) {
size += com.google.protobuf.CodedOutputStream.computeFloatSize(4, score_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.discoveryengine.v1beta.RankingRecord)) {
return super.equals(obj);
}
com.google.cloud.discoveryengine.v1beta.RankingRecord other =
(com.google.cloud.discoveryengine.v1beta.RankingRecord) obj;
if (!getId().equals(other.getId())) return false;
if (!getTitle().equals(other.getTitle())) return false;
if (!getContent().equals(other.getContent())) return false;
if (java.lang.Float.floatToIntBits(getScore())
!= java.lang.Float.floatToIntBits(other.getScore())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + ID_FIELD_NUMBER;
hash = (53 * hash) + getId().hashCode();
hash = (37 * hash) + TITLE_FIELD_NUMBER;
hash = (53 * hash) + getTitle().hashCode();
hash = (37 * hash) + CONTENT_FIELD_NUMBER;
hash = (53 * hash) + getContent().hashCode();
hash = (37 * hash) + SCORE_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(getScore());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.discoveryengine.v1beta.RankingRecord parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1beta.RankingRecord parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1beta.RankingRecord parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1beta.RankingRecord parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1beta.RankingRecord parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1beta.RankingRecord parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1beta.RankingRecord parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1beta.RankingRecord parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1beta.RankingRecord parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1beta.RankingRecord parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1beta.RankingRecord parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1beta.RankingRecord parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.discoveryengine.v1beta.RankingRecord 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>
* Record message for
* [RankService.Rank][google.cloud.discoveryengine.v1beta.RankService.Rank]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1beta.RankingRecord}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1beta.RankingRecord)
com.google.cloud.discoveryengine.v1beta.RankingRecordOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1beta.RankServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_RankingRecord_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1beta.RankServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_RankingRecord_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1beta.RankingRecord.class,
com.google.cloud.discoveryengine.v1beta.RankingRecord.Builder.class);
}
// Construct using com.google.cloud.discoveryengine.v1beta.RankingRecord.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
id_ = "";
title_ = "";
content_ = "";
score_ = 0F;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.discoveryengine.v1beta.RankServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_RankingRecord_descriptor;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.RankingRecord getDefaultInstanceForType() {
return com.google.cloud.discoveryengine.v1beta.RankingRecord.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.RankingRecord build() {
com.google.cloud.discoveryengine.v1beta.RankingRecord result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.RankingRecord buildPartial() {
com.google.cloud.discoveryengine.v1beta.RankingRecord result =
new com.google.cloud.discoveryengine.v1beta.RankingRecord(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.discoveryengine.v1beta.RankingRecord result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.id_ = id_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.title_ = title_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.content_ = content_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.score_ = score_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.discoveryengine.v1beta.RankingRecord) {
return mergeFrom((com.google.cloud.discoveryengine.v1beta.RankingRecord) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.discoveryengine.v1beta.RankingRecord other) {
if (other == com.google.cloud.discoveryengine.v1beta.RankingRecord.getDefaultInstance())
return this;
if (!other.getId().isEmpty()) {
id_ = other.id_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getTitle().isEmpty()) {
title_ = other.title_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getContent().isEmpty()) {
content_ = other.content_;
bitField0_ |= 0x00000004;
onChanged();
}
if (other.getScore() != 0F) {
setScore(other.getScore());
}
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:
{
id_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
title_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
content_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 37:
{
score_ = input.readFloat();
bitField0_ |= 0x00000008;
break;
} // case 37
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object id_ = "";
/**
*
*
* <pre>
* The unique ID to represent the record.
* </pre>
*
* <code>string id = 1;</code>
*
* @return The id.
*/
public java.lang.String getId() {
java.lang.Object ref = id_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The unique ID to represent the record.
* </pre>
*
* <code>string id = 1;</code>
*
* @return The bytes for id.
*/
public com.google.protobuf.ByteString getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The unique ID to represent the record.
* </pre>
*
* <code>string id = 1;</code>
*
* @param value The id to set.
* @return This builder for chaining.
*/
public Builder setId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
id_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The unique ID to represent the record.
* </pre>
*
* <code>string id = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearId() {
id_ = getDefaultInstance().getId();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The unique ID to represent the record.
* </pre>
*
* <code>string id = 1;</code>
*
* @param value The bytes for id to set.
* @return This builder for chaining.
*/
public Builder setIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
id_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object title_ = "";
/**
*
*
* <pre>
* The title of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string title = 2;</code>
*
* @return The title.
*/
public java.lang.String getTitle() {
java.lang.Object ref = title_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
title_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The title of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string title = 2;</code>
*
* @return The bytes for title.
*/
public com.google.protobuf.ByteString getTitleBytes() {
java.lang.Object ref = title_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
title_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The title of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string title = 2;</code>
*
* @param value The title to set.
* @return This builder for chaining.
*/
public Builder setTitle(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
title_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The title of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string title = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearTitle() {
title_ = getDefaultInstance().getTitle();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The title of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string title = 2;</code>
*
* @param value The bytes for title to set.
* @return This builder for chaining.
*/
public Builder setTitleBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
title_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object content_ = "";
/**
*
*
* <pre>
* The content of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string content = 3;</code>
*
* @return The content.
*/
public java.lang.String getContent() {
java.lang.Object ref = content_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
content_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The content of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string content = 3;</code>
*
* @return The bytes for content.
*/
public com.google.protobuf.ByteString getContentBytes() {
java.lang.Object ref = content_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
content_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The content of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string content = 3;</code>
*
* @param value The content to set.
* @return This builder for chaining.
*/
public Builder setContent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
content_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The content of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string content = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearContent() {
content_ = getDefaultInstance().getContent();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* The content of the record. Empty by default.
* At least one of
* [title][google.cloud.discoveryengine.v1beta.RankingRecord.title] or
* [content][google.cloud.discoveryengine.v1beta.RankingRecord.content] should
* be set otherwise an INVALID_ARGUMENT error is thrown.
* </pre>
*
* <code>string content = 3;</code>
*
* @param value The bytes for content to set.
* @return This builder for chaining.
*/
public Builder setContentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
content_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private float score_;
/**
*
*
* <pre>
* The score of this record based on the given query and selected model.
* </pre>
*
* <code>float score = 4;</code>
*
* @return The score.
*/
@java.lang.Override
public float getScore() {
return score_;
}
/**
*
*
* <pre>
* The score of this record based on the given query and selected model.
* </pre>
*
* <code>float score = 4;</code>
*
* @param value The score to set.
* @return This builder for chaining.
*/
public Builder setScore(float value) {
score_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* The score of this record based on the given query and selected model.
* </pre>
*
* <code>float score = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearScore() {
bitField0_ = (bitField0_ & ~0x00000008);
score_ = 0F;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.discoveryengine.v1beta.RankingRecord)
}
// @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1beta.RankingRecord)
private static final com.google.cloud.discoveryengine.v1beta.RankingRecord DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1beta.RankingRecord();
}
public static com.google.cloud.discoveryengine.v1beta.RankingRecord getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<RankingRecord> PARSER =
new com.google.protobuf.AbstractParser<RankingRecord>() {
@java.lang.Override
public RankingRecord 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<RankingRecord> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<RankingRecord> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.RankingRecord getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,611 | java-monitoring/proto-google-cloud-monitoring-v3/src/main/java/com/google/monitoring/v3/CreateServiceRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/v3/service_service.proto
// Protobuf Java Version: 3.25.8
package com.google.monitoring.v3;
/**
*
*
* <pre>
* The `CreateService` request.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.CreateServiceRequest}
*/
public final class CreateServiceRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.monitoring.v3.CreateServiceRequest)
CreateServiceRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateServiceRequest.newBuilder() to construct.
private CreateServiceRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateServiceRequest() {
parent_ = "";
serviceId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateServiceRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.ServiceMonitoringServiceProto
.internal_static_google_monitoring_v3_CreateServiceRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.ServiceMonitoringServiceProto
.internal_static_google_monitoring_v3_CreateServiceRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.CreateServiceRequest.class,
com.google.monitoring.v3.CreateServiceRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Resource
* [name](https://cloud.google.com/monitoring/api/v3#project_name) of the
* parent Metrics Scope. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Resource
* [name](https://cloud.google.com/monitoring/api/v3#project_name) of the
* parent Metrics Scope. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SERVICE_ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object serviceId_ = "";
/**
*
*
* <pre>
* Optional. The Service id to use for this Service. If omitted, an id will be
* generated instead. Must match the pattern `[a-z0-9\-]+`
* </pre>
*
* <code>string service_id = 3;</code>
*
* @return The serviceId.
*/
@java.lang.Override
public java.lang.String getServiceId() {
java.lang.Object ref = serviceId_;
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();
serviceId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The Service id to use for this Service. If omitted, an id will be
* generated instead. Must match the pattern `[a-z0-9\-]+`
* </pre>
*
* <code>string service_id = 3;</code>
*
* @return The bytes for serviceId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getServiceIdBytes() {
java.lang.Object ref = serviceId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
serviceId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SERVICE_FIELD_NUMBER = 2;
private com.google.monitoring.v3.Service service_;
/**
*
*
* <pre>
* Required. The `Service` to create.
* </pre>
*
* <code>.google.monitoring.v3.Service service = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the service field is set.
*/
@java.lang.Override
public boolean hasService() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The `Service` to create.
* </pre>
*
* <code>.google.monitoring.v3.Service service = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The service.
*/
@java.lang.Override
public com.google.monitoring.v3.Service getService() {
return service_ == null ? com.google.monitoring.v3.Service.getDefaultInstance() : service_;
}
/**
*
*
* <pre>
* Required. The `Service` to create.
* </pre>
*
* <code>.google.monitoring.v3.Service service = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.monitoring.v3.ServiceOrBuilder getServiceOrBuilder() {
return service_ == null ? com.google.monitoring.v3.Service.getDefaultInstance() : service_;
}
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, getService());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, serviceId_);
}
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, getService());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, serviceId_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.monitoring.v3.CreateServiceRequest)) {
return super.equals(obj);
}
com.google.monitoring.v3.CreateServiceRequest other =
(com.google.monitoring.v3.CreateServiceRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getServiceId().equals(other.getServiceId())) return false;
if (hasService() != other.hasService()) return false;
if (hasService()) {
if (!getService().equals(other.getService())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + SERVICE_ID_FIELD_NUMBER;
hash = (53 * hash) + getServiceId().hashCode();
if (hasService()) {
hash = (37 * hash) + SERVICE_FIELD_NUMBER;
hash = (53 * hash) + getService().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.monitoring.v3.CreateServiceRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.CreateServiceRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.CreateServiceRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.CreateServiceRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.CreateServiceRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.CreateServiceRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.CreateServiceRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.CreateServiceRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.CreateServiceRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.CreateServiceRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.CreateServiceRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.CreateServiceRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.monitoring.v3.CreateServiceRequest 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 `CreateService` request.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.CreateServiceRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.monitoring.v3.CreateServiceRequest)
com.google.monitoring.v3.CreateServiceRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.ServiceMonitoringServiceProto
.internal_static_google_monitoring_v3_CreateServiceRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.ServiceMonitoringServiceProto
.internal_static_google_monitoring_v3_CreateServiceRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.CreateServiceRequest.class,
com.google.monitoring.v3.CreateServiceRequest.Builder.class);
}
// Construct using com.google.monitoring.v3.CreateServiceRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getServiceFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
serviceId_ = "";
service_ = null;
if (serviceBuilder_ != null) {
serviceBuilder_.dispose();
serviceBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.monitoring.v3.ServiceMonitoringServiceProto
.internal_static_google_monitoring_v3_CreateServiceRequest_descriptor;
}
@java.lang.Override
public com.google.monitoring.v3.CreateServiceRequest getDefaultInstanceForType() {
return com.google.monitoring.v3.CreateServiceRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.monitoring.v3.CreateServiceRequest build() {
com.google.monitoring.v3.CreateServiceRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.monitoring.v3.CreateServiceRequest buildPartial() {
com.google.monitoring.v3.CreateServiceRequest result =
new com.google.monitoring.v3.CreateServiceRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.monitoring.v3.CreateServiceRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.serviceId_ = serviceId_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.service_ = serviceBuilder_ == null ? service_ : serviceBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.monitoring.v3.CreateServiceRequest) {
return mergeFrom((com.google.monitoring.v3.CreateServiceRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.monitoring.v3.CreateServiceRequest other) {
if (other == com.google.monitoring.v3.CreateServiceRequest.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getServiceId().isEmpty()) {
serviceId_ = other.serviceId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasService()) {
mergeService(other.getService());
}
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(getServiceFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 18
case 26:
{
serviceId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Resource
* [name](https://cloud.google.com/monitoring/api/v3#project_name) of the
* parent Metrics Scope. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Resource
* [name](https://cloud.google.com/monitoring/api/v3#project_name) of the
* parent Metrics Scope. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Resource
* [name](https://cloud.google.com/monitoring/api/v3#project_name) of the
* parent Metrics Scope. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Resource
* [name](https://cloud.google.com/monitoring/api/v3#project_name) of the
* parent Metrics Scope. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Resource
* [name](https://cloud.google.com/monitoring/api/v3#project_name) of the
* parent Metrics Scope. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object serviceId_ = "";
/**
*
*
* <pre>
* Optional. The Service id to use for this Service. If omitted, an id will be
* generated instead. Must match the pattern `[a-z0-9\-]+`
* </pre>
*
* <code>string service_id = 3;</code>
*
* @return The serviceId.
*/
public java.lang.String getServiceId() {
java.lang.Object ref = serviceId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
serviceId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The Service id to use for this Service. If omitted, an id will be
* generated instead. Must match the pattern `[a-z0-9\-]+`
* </pre>
*
* <code>string service_id = 3;</code>
*
* @return The bytes for serviceId.
*/
public com.google.protobuf.ByteString getServiceIdBytes() {
java.lang.Object ref = serviceId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
serviceId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The Service id to use for this Service. If omitted, an id will be
* generated instead. Must match the pattern `[a-z0-9\-]+`
* </pre>
*
* <code>string service_id = 3;</code>
*
* @param value The serviceId to set.
* @return This builder for chaining.
*/
public Builder setServiceId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
serviceId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The Service id to use for this Service. If omitted, an id will be
* generated instead. Must match the pattern `[a-z0-9\-]+`
* </pre>
*
* <code>string service_id = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearServiceId() {
serviceId_ = getDefaultInstance().getServiceId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The Service id to use for this Service. If omitted, an id will be
* generated instead. Must match the pattern `[a-z0-9\-]+`
* </pre>
*
* <code>string service_id = 3;</code>
*
* @param value The bytes for serviceId to set.
* @return This builder for chaining.
*/
public Builder setServiceIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
serviceId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.monitoring.v3.Service service_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.Service,
com.google.monitoring.v3.Service.Builder,
com.google.monitoring.v3.ServiceOrBuilder>
serviceBuilder_;
/**
*
*
* <pre>
* Required. The `Service` to create.
* </pre>
*
* <code>.google.monitoring.v3.Service service = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the service field is set.
*/
public boolean hasService() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Required. The `Service` to create.
* </pre>
*
* <code>.google.monitoring.v3.Service service = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The service.
*/
public com.google.monitoring.v3.Service getService() {
if (serviceBuilder_ == null) {
return service_ == null ? com.google.monitoring.v3.Service.getDefaultInstance() : service_;
} else {
return serviceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The `Service` to create.
* </pre>
*
* <code>.google.monitoring.v3.Service service = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setService(com.google.monitoring.v3.Service value) {
if (serviceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
service_ = value;
} else {
serviceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The `Service` to create.
* </pre>
*
* <code>.google.monitoring.v3.Service service = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setService(com.google.monitoring.v3.Service.Builder builderForValue) {
if (serviceBuilder_ == null) {
service_ = builderForValue.build();
} else {
serviceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The `Service` to create.
* </pre>
*
* <code>.google.monitoring.v3.Service service = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeService(com.google.monitoring.v3.Service value) {
if (serviceBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& service_ != null
&& service_ != com.google.monitoring.v3.Service.getDefaultInstance()) {
getServiceBuilder().mergeFrom(value);
} else {
service_ = value;
}
} else {
serviceBuilder_.mergeFrom(value);
}
if (service_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The `Service` to create.
* </pre>
*
* <code>.google.monitoring.v3.Service service = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearService() {
bitField0_ = (bitField0_ & ~0x00000004);
service_ = null;
if (serviceBuilder_ != null) {
serviceBuilder_.dispose();
serviceBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The `Service` to create.
* </pre>
*
* <code>.google.monitoring.v3.Service service = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.monitoring.v3.Service.Builder getServiceBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getServiceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The `Service` to create.
* </pre>
*
* <code>.google.monitoring.v3.Service service = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.monitoring.v3.ServiceOrBuilder getServiceOrBuilder() {
if (serviceBuilder_ != null) {
return serviceBuilder_.getMessageOrBuilder();
} else {
return service_ == null ? com.google.monitoring.v3.Service.getDefaultInstance() : service_;
}
}
/**
*
*
* <pre>
* Required. The `Service` to create.
* </pre>
*
* <code>.google.monitoring.v3.Service service = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.Service,
com.google.monitoring.v3.Service.Builder,
com.google.monitoring.v3.ServiceOrBuilder>
getServiceFieldBuilder() {
if (serviceBuilder_ == null) {
serviceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.Service,
com.google.monitoring.v3.Service.Builder,
com.google.monitoring.v3.ServiceOrBuilder>(
getService(), getParentForChildren(), isClean());
service_ = null;
}
return serviceBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.monitoring.v3.CreateServiceRequest)
}
// @@protoc_insertion_point(class_scope:google.monitoring.v3.CreateServiceRequest)
private static final com.google.monitoring.v3.CreateServiceRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.monitoring.v3.CreateServiceRequest();
}
public static com.google.monitoring.v3.CreateServiceRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateServiceRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateServiceRequest>() {
@java.lang.Override
public CreateServiceRequest 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<CreateServiceRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateServiceRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.monitoring.v3.CreateServiceRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/oodt | 35,428 | filemgr/src/test/java/org/apache/oodt/cas/filemgr/catalog/TestLuceneCatalog.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.oodt.cas.filemgr.catalog;
import org.apache.oodt.cas.filemgr.metadata.CoreMetKeys;
import org.apache.oodt.cas.filemgr.structs.BooleanQueryCriteria;
import org.apache.oodt.cas.filemgr.structs.Product;
import org.apache.oodt.cas.filemgr.structs.ProductPage;
import org.apache.oodt.cas.filemgr.structs.ProductType;
import org.apache.oodt.cas.filemgr.structs.Query;
import org.apache.oodt.cas.filemgr.structs.Reference;
import org.apache.oodt.cas.filemgr.structs.TermQueryCriteria;
import org.apache.oodt.cas.filemgr.structs.exceptions.CatalogException;
import org.apache.oodt.cas.metadata.Metadata;
import com.google.common.collect.Lists;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import junit.framework.TestCase;
import org.junit.Ignore;
/**
* @author woollard
* @author mattmann
*
* @version $Revision$
*
* <p>
* Test suite for the {@link LuceneCatalog} and {@link LuceneCatalogFactory}.
* </p>.
*/
public class TestLuceneCatalog extends TestCase {
private static Logger LOG = Logger.getLogger(TestLuceneCatalog.class.getName());
private LuceneCatalog myCat;
private String tmpDirPath = null;
private static final int catPageSize = 20;
private Properties initialProperties = new Properties(
System.getProperties());
public void setUpProperties() {
Properties properties = new Properties(System.getProperties());
// set the log levels
URL loggingPropertiesUrl = this.getClass().getResource(
"/test.logging.properties");
System.setProperty("java.util.logging.config.file", new File(
loggingPropertiesUrl.getFile()).getAbsolutePath());
// first load the example configuration
try {
URL filemgrPropertiesUrl = this.getClass().getResource(
"/filemgr.properties");
properties.load(new FileInputStream(
filemgrPropertiesUrl.getFile()));
} catch (Exception e) {
fail(e.getMessage());
}
// get a temp directory
File tempDir = null;
File tempFile;
try {
tempFile = File.createTempFile("foo", "bar");
tempFile.deleteOnExit();
tempDir = tempFile.getParentFile();
} catch (Exception e) {
fail(e.getMessage());
}
tmpDirPath = tempDir.getAbsolutePath();
if (!tmpDirPath.endsWith("/")) {
tmpDirPath += "/";
}
tmpDirPath += "testCat/";
// now override the catalog ones
System.setProperty(
"org.apache.oodt.cas.filemgr.catalog.lucene.idxPath",
tmpDirPath);
System.setProperty(
"org.apache.oodt.cas.filemgr.catalog.lucene.pageSize", "20");
System.setProperty(
"org.apache.oodt.cas.filemgr.catalog.lucene.commitLockTimeout.seconds",
"60");
System.setProperty(
"org.apache.oodt.cas.filemgr.catalog.lucene.writeLockTimeout.seconds",
"60");
System.setProperty(
"org.apache.oodt.cas.filemgr.catalog.lucene.mergeFactor",
"20");
System.setProperty(
"org.apache.oodt.cas.filemgr.catalog.datasource.lenientFields",
"false");
// now override the val layer ones
URL examplesCoreUrl = this.getClass().getResource(
"/examples/core");
System.setProperty("org.apache.oodt.cas.filemgr.validation.dirs",
"file://" + new File(examplesCoreUrl.getFile()).getAbsolutePath());
//System.setProperties(properties);
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
setUpProperties();
myCat = (LuceneCatalog) new LuceneCatalogFactory().createCatalog();
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
// now remove the temporary directory used
if (tmpDirPath != null) {
File tmpDir = new File(tmpDirPath);
File[] tmpFiles = tmpDir.listFiles();
if (tmpFiles != null && tmpFiles.length > 0) {
for (File tmpFile : tmpFiles) {
tmpFile.delete();
}
tmpDir.delete();
}
if (myCat != null) {
myCat = null;
}
}
// System.setProperties(initialProperties);
}
/**
* @since OODT-382
*/
public void testNoCatalogDirectoryQueries() {
// Test querying against a catalog directory that has not yet been created or is empty.
// The LuceneCatalogFactory should be creating the index directory if not there.
try {
myCat.getTopNProducts(10);
} catch (Exception e) {
fail(e.getMessage());
}
}
public void testGetMetadata() throws CatalogException {
Product product = getTestProduct();
myCat.addProduct(product);
myCat.addProductReferences(product);
Metadata m = new Metadata();
m.addMetadata(CoreMetKeys.FILE_LOCATION, Lists.newArrayList("/loc/1", "/loc/2"));
myCat.addMetadata(m, product);
Metadata rndTripMet = myCat.getMetadata(product);
assertNotNull(rndTripMet);
assertEquals(2, rndTripMet.getAllMetadata(CoreMetKeys.FILE_LOCATION).size());
assertTrue(rndTripMet.getAllMetadata(CoreMetKeys.FILE_LOCATION).contains("/loc/1"));
assertTrue(rndTripMet.getAllMetadata(CoreMetKeys.FILE_LOCATION).contains("/loc/2"));
}
public void testGetReducedMetadata() throws CatalogException {
Product product = getTestProduct();
myCat.addProduct(product);
myCat.addProductReferences(product);
Metadata m = new Metadata();
m.addMetadata(CoreMetKeys.FILE_LOCATION, Lists.newArrayList("/loc/1", "/loc/2"));
myCat.addMetadata(m, product);
Metadata rndTripMet = myCat.getReducedMetadata(product,
Lists.newArrayList(CoreMetKeys.FILE_LOCATION));
assertNotNull(rndTripMet);
assertEquals(2, rndTripMet.getAllMetadata(CoreMetKeys.FILE_LOCATION).size());
assertTrue(rndTripMet.getAllMetadata(CoreMetKeys.FILE_LOCATION).contains("/loc/1"));
assertTrue(rndTripMet.getAllMetadata(CoreMetKeys.FILE_LOCATION).contains("/loc/2"));
}
public void testGetReducedMetadataNull() throws CatalogException {
Product p = getTestProduct();
myCat.addProduct(p);
myCat.addProductReferences(p);
myCat.addMetadata(new Metadata(), p);
// should not throw NPE here
Metadata rndTripMet = myCat.getReducedMetadata(p, Lists.newArrayList(CoreMetKeys.FILENAME));
assertNotNull(rndTripMet);
// should return null if met key has no value
assertNull(rndTripMet.getAllMetadata(CoreMetKeys.FILENAME));
}
public void testRemoveProduct() {
Product productToRemove = getTestProduct();
// override name
productToRemove.setProductName("removeme");
try {
myCat.addProduct(productToRemove);
myCat.addMetadata(getTestMetadata("tempProduct"), productToRemove);
} catch (Exception e) {
fail(e.getMessage());
}
Product retProduct = null;
ProductType type = new ProductType();
type.setName("GenericFile");
type.setProductTypeId("urn:oodt:GenericFile");
try {
retProduct = myCat.getProductByName("removeme");
retProduct.setProductType(type);
} catch (Exception e) {
fail(e.getMessage());
}
assertNotNull(retProduct);
try {
myCat.removeProduct(retProduct);
} catch (Exception e) {
fail(e.getMessage());
}
Product retProdAfterRemove = null;
try {
retProdAfterRemove = myCat.getProductByName("removeme");
} catch (Exception e) {
fail(e.getMessage());
}
assertNull(retProdAfterRemove);
}
public void testModifyProduct() {
Product testProduct = getTestProduct();
try {
myCat.addProduct(testProduct);
myCat.addMetadata(getTestMetadata("tempProduct"), testProduct);
} catch (Exception e) {
fail(e.getMessage());
}
assertNotNull(testProduct);
assertEquals("test", testProduct.getProductName());
// now change something
testProduct.setProductName("f002");
try {
myCat.modifyProduct(testProduct);
} catch (Exception e) {
fail(e.getMessage());
}
assertNotNull(testProduct);
Product retProduct;
try {
retProduct = myCat.getProductByName("f002");
assertNotNull(retProduct);
assertEquals("f002", retProduct.getProductName());
} catch (Exception e) {
fail(e.getMessage());
}
}
/**
* @since OODT-133
*
*/
public void testFirstProductOnlyOnFirstPage() {
// add catPageSize of the test Product
// then add a product called "ShouldBeFirstForPage.txt"
// make sure it's the first one on the 2nd page
Product testProd = getTestProduct();
Metadata met = getTestMetadata("test");
for (int i = 0; i < catPageSize; i++) {
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
}
testProd.setProductName("ShouldBeFirstForPage.txt");
met.replaceMetadata("CAS.ProdutName", "ShouldBeFirstForPage.txt");
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
try {
assertNotNull(myCat.getProducts());
assertEquals(21, myCat.getProducts().size());
} catch (Exception e) {
fail(e.getMessage());
}
ProductType type = new ProductType();
type.setProductTypeId("urn:oodt:GenericFile");
type.setName("GenericFile");
assertNotNull(myCat.getFirstPage(type));
assertNotNull(myCat.getFirstPage(type).getPageProducts());
assertEquals(catPageSize, myCat.getFirstPage(type).getPageProducts()
.size());
ProductPage page = myCat.getNextPage(type, myCat.getFirstPage(type));
assertNotNull(page);
assertNotNull(page.getPageProducts());
assertEquals(1, page.getPageProducts().size());
assertEquals(2, page.getTotalPages());
assertNotNull(page.getPageProducts().get(0));
Product retProd = page.getPageProducts().get(0);
assertEquals("ShouldBeFirstForPage.txt", retProd.getProductName());
}
public void testGetLastProductOnLastPage() {
// add catPageSize of the test Product
// then add a product called "ShouldBeFirstForPage.txt"
// make sure it's the first one on the 2nd page
Product testProd = getTestProduct();
Metadata met = getTestMetadata("test");
for (int i = 0; i < catPageSize; i++) {
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
}
testProd.setProductName("ShouldBeFirstForPage.txt");
met.replaceMetadata("CAS.ProdutName", "ShouldBeFirstForPage.txt");
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
try {
assertNotNull(myCat.getProducts());
assertEquals(21, myCat.getProducts().size());
} catch (Exception e) {
fail(e.getMessage());
}
ProductType type = new ProductType();
type.setProductTypeId("urn:oodt:GenericFile");
type.setName("GenericFile");
assertNotNull(myCat.getLastProductPage(type));
assertNotNull(myCat.getLastProductPage(type).getPageProducts());
assertEquals(1, myCat.getLastProductPage(type).getPageProducts()
.size());
ProductPage page = myCat.getLastProductPage(type);
assertNotNull(page);
assertNotNull(page.getPageProducts());
assertEquals(1, page.getPageProducts().size());
assertEquals(2, page.getTotalPages());
List<Product> prods = page.getPageProducts();
assertNotNull(page.getPageProducts().get(0));
Product retProd = page.getPageProducts().get(0);
assertEquals("ShouldBeFirstForPage.txt", retProd.getProductName());
}
public void testGetTopNProducts() {
// add catPageSize of the test Product
// then add a product called "ShouldBeFirstForPage.txt"
// make sure it's the first one on the 2nd page
Product testProd = getTestProduct();
Metadata met = getTestMetadata("test");
for (int i = 0; i < catPageSize; i++) {
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
}
testProd.setProductName("ShouldBeFirstForPage.txt");
met.replaceMetadata("CAS.ProdutName", "ShouldBeFirstForPage.txt");
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
try {
assertNotNull(myCat.getProducts());
assertEquals(21, myCat.getProducts().size());
} catch (Exception e) {
fail(e.getMessage());
}
try {
assertNotNull(myCat.getTopNProducts(5));
assertEquals(5, myCat.getTopNProducts(5).size());
Product retProd = myCat.getTopNProducts(5).get(0);
assertEquals("test", retProd.getProductName());
} catch (CatalogException e) {
LOG.log(Level.SEVERE, e.getMessage());
}
}
public void testGetNextPageNullType(){
Product testProd = getTestProduct();
Metadata met = getTestMetadata("test");
for (int i = 0; i < catPageSize; i++) {
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
}
testProd.setProductName("ShouldBeFirstForPage.txt");
met.replaceMetadata("CAS.ProdutName", "ShouldBeFirstForPage.txt");
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
try {
assertNotNull(myCat.getProducts());
assertEquals(21, myCat.getProducts().size());
} catch (Exception e) {
fail(e.getMessage());
}
ProductType type = new ProductType();
type.setProductTypeId("urn:oodt:GenericFile");
type.setName("GenericFile");
assertNotNull(myCat.getFirstPage(type));
assertNotNull(myCat.getFirstPage(type).getPageProducts());
assertEquals(catPageSize, myCat.getFirstPage(type).getPageProducts()
.size());
ProductPage page = myCat.getNextPage(null, myCat.getFirstPage(type));
assertNotNull(page);
assertEquals(0, page.getPageNum());
assertEquals(0, page.getTotalPages());
assertEquals(0, page.getPageSize());
}
public void testGetNextPageNullCurrentPage(){
Product testProd = getTestProduct();
Metadata met = getTestMetadata("test");
for (int i = 0; i < catPageSize; i++) {
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
}
testProd.setProductName("ShouldBeFirstForPage.txt");
met.replaceMetadata("CAS.ProdutName", "ShouldBeFirstForPage.txt");
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
try {
assertNotNull(myCat.getProducts());
assertEquals(21, myCat.getProducts().size());
} catch (Exception e) {
fail(e.getMessage());
}
ProductType type = new ProductType();
type.setProductTypeId("urn:oodt:GenericFile");
type.setName("GenericFile");
assertNotNull(myCat.getFirstPage(type));
assertNotNull(myCat.getFirstPage(type).getPageProducts());
assertEquals(catPageSize, myCat.getFirstPage(type).getPageProducts()
.size());
ProductPage page = myCat.getNextPage(type, null);
assertNotNull(page);
assertNotNull(page.getPageProducts());
assertEquals(20, page.getPageProducts().size());
assertEquals(2, page.getTotalPages());
assertNotNull(page.getPageProducts().get(0));
Product retProd = page.getPageProducts().get(0);
assertEquals("test", retProd.getProductName());
}
public void testGetNextPageCurrentPageIsLastPage(){
Product testProd = getTestProduct();
Metadata met = getTestMetadata("test");
for (int i = 0; i < catPageSize; i++) {
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
}
testProd.setProductName("ShouldBeFirstForPage.txt");
met.replaceMetadata("CAS.ProdutName", "ShouldBeFirstForPage.txt");
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
try {
assertNotNull(myCat.getProducts());
assertEquals(21, myCat.getProducts().size());
} catch (Exception e) {
fail(e.getMessage());
}
ProductType type = new ProductType();
type.setProductTypeId("urn:oodt:GenericFile");
type.setName("GenericFile");
assertNotNull(myCat.getFirstPage(type));
assertNotNull(myCat.getFirstPage(type).getPageProducts());
assertEquals(catPageSize, myCat.getFirstPage(type).getPageProducts()
.size());
ProductPage page = myCat.getNextPage(type, myCat.getLastProductPage(type));
assertNotNull(page);
assertNotNull(page.getPageProducts());
assertEquals(1, page.getPageProducts().size());
assertEquals(2, page.getTotalPages());
assertNotNull(page.getPageProducts().get(0));
Product retProd = page.getPageProducts().get(0);
assertEquals("ShouldBeFirstForPage.txt", retProd.getProductName());
}
public void testGetPrevPage(){
Product testProd = getTestProduct();
Metadata met = getTestMetadata("test");
for (int i = 0; i < catPageSize; i++) {
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
}
testProd.setProductName("ShouldBeFirstForPage.txt");
met.replaceMetadata("CAS.ProdutName", "ShouldBeFirstForPage.txt");
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
try {
assertNotNull(myCat.getProducts());
assertEquals(21, myCat.getProducts().size());
} catch (Exception e) {
fail(e.getMessage());
}
ProductType type = new ProductType();
type.setProductTypeId("urn:oodt:GenericFile");
type.setName("GenericFile");
assertNotNull(myCat.getFirstPage(type));
assertNotNull(myCat.getFirstPage(type).getPageProducts());
assertEquals(catPageSize, myCat.getFirstPage(type).getPageProducts()
.size());
ProductPage page2 = myCat.getNextPage(type, myCat.getFirstPage(type));
ProductPage page = myCat.getPrevPage(type, page2);
assertEquals(2, page2.getPageNum());
assertEquals(1, page.getPageNum());
}
public void testGetPrevPageNullCurrentPage(){
Product testProd = getTestProduct();
Metadata met = getTestMetadata("test");
for (int i = 0; i < catPageSize; i++) {
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
}
testProd.setProductName("ShouldBeFirstForPage.txt");
met.replaceMetadata("CAS.ProdutName", "ShouldBeFirstForPage.txt");
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
try {
assertNotNull(myCat.getProducts());
assertEquals(21, myCat.getProducts().size());
} catch (Exception e) {
fail(e.getMessage());
}
ProductType type = new ProductType();
type.setProductTypeId("urn:oodt:GenericFile");
type.setName("GenericFile");
assertNotNull(myCat.getFirstPage(type));
assertNotNull(myCat.getFirstPage(type).getPageProducts());
assertEquals(catPageSize, myCat.getFirstPage(type).getPageProducts()
.size());
ProductPage page = myCat.getPrevPage(type, null);
assertNotNull(page);
assertNotNull(page.getPageProducts());
assertEquals(20, page.getPageProducts().size());
assertEquals(2, page.getTotalPages());
assertNotNull(page.getPageProducts().get(0));
Product retProd = page.getPageProducts().get(0);
assertEquals("test", retProd.getProductName());
}
public void testGetPrevPageCurrentPageIsFirstPage(){
Product testProd = getTestProduct();
Metadata met = getTestMetadata("test");
for (int i = 0; i < catPageSize; i++) {
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
}
testProd.setProductName("ShouldBeFirstForPage.txt");
met.replaceMetadata("CAS.ProdutName", "ShouldBeFirstForPage.txt");
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
try {
assertNotNull(myCat.getProducts());
assertEquals(21, myCat.getProducts().size());
} catch (Exception e) {
fail(e.getMessage());
}
ProductType type = new ProductType();
type.setProductTypeId("urn:oodt:GenericFile");
type.setName("GenericFile");
assertNotNull(myCat.getFirstPage(type));
assertNotNull(myCat.getFirstPage(type).getPageProducts());
assertEquals(catPageSize, myCat.getFirstPage(type).getPageProducts()
.size());
ProductPage page = myCat.getPrevPage(type, myCat.getFirstPage(type));
assertNotNull(page);
assertNotNull(page.getPageProducts());
assertEquals(20, page.getPageProducts().size());
assertEquals(2, page.getTotalPages());
assertNotNull(page.getPageProducts().get(0));
Product retProd = page.getPageProducts().get(0);
assertEquals("test", retProd.getProductName());
}
public void testGetPrevPageNullProductType(){
Product testProd = getTestProduct();
Metadata met = getTestMetadata("test");
for (int i = 0; i < catPageSize; i++) {
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
}
testProd.setProductName("ShouldBeFirstForPage.txt");
met.replaceMetadata("CAS.ProdutName", "ShouldBeFirstForPage.txt");
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
try {
assertNotNull(myCat.getProducts());
assertEquals(21, myCat.getProducts().size());
} catch (Exception e) {
fail(e.getMessage());
}
ProductType type = new ProductType();
type.setProductTypeId("urn:oodt:GenericFile");
type.setName("GenericFile");
assertNotNull(myCat.getFirstPage(type));
assertNotNull(myCat.getFirstPage(type).getPageProducts());
assertEquals(catPageSize, myCat.getFirstPage(type).getPageProducts()
.size());
ProductPage page2 = myCat.getNextPage(type, myCat.getFirstPage(type));
ProductPage page = myCat.getPrevPage(null, page2);
assertNotNull(page);
assertEquals(0, page.getPageNum());
assertEquals(0, page.getPageSize());
assertEquals(0, page.getTotalPages());
}
public void testGetTopNProductsByType() {
Product testProd = getTestProduct();
Metadata met = getTestMetadata("test");
for (int i = 0; i < catPageSize; i++) {
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
}
testProd.setProductName("ShouldBeFirstForPage.txt");
met.replaceMetadata("CAS.ProdutName", "ShouldBeFirstForPage.txt");
try {
myCat.addProduct(testProd);
myCat.addMetadata(met, testProd);
} catch (Exception e) {
fail(e.getMessage());
}
try {
assertNotNull(myCat.getProducts());
assertEquals(21, myCat.getProducts().size());
} catch (Exception e) {
fail(e.getMessage());
}
ProductType type = new ProductType();
type.setProductTypeId("urn:oodt:GenericFile");
type.setName("GenericFile");
try {
assertNotNull(myCat.getTopNProducts(5, type));
assertEquals(5, myCat.getTopNProducts(5, type).size());
Product retProd = myCat.getTopNProducts(5, type).get(0);
assertEquals("test", retProd.getProductName());
} catch (CatalogException e) {
LOG.log(Level.SEVERE, e.getMessage());
}
}
/**
* @since OODT-141
*/
public void testTopResults(){
Product testProduct = getTestProduct();
try{
myCat.addProduct(testProduct);
myCat.addMetadata(getTestMetadata("tempProduct"), testProduct);
myCat.getTopNProducts(20);
}
catch(Exception e){
LOG.log(Level.SEVERE, e.getMessage());
fail(e.getMessage());
}
}
public void testAddProduct() {
Product testProduct = getTestProduct();
try {
myCat.addProduct(testProduct);
myCat.addMetadata(getTestMetadata("tempProduct"), testProduct);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
fail(e.getMessage());
}
Product retProduct;
try {
retProduct = myCat.getProductByName("test");
assertNotNull(retProduct);
assertEquals("test", retProduct.getProductName());
assertEquals(Product.STRUCTURE_FLAT, retProduct
.getProductStructure());
assertNotNull(retProduct.getProductType());
assertEquals("urn:oodt:GenericFile", retProduct.getProductType()
.getProductTypeId());
assertEquals(Product.STATUS_TRANSFER, retProduct
.getTransferStatus());
} catch (Exception e) {
fail(e.getMessage());
}
}
public void testAddMetadata() {
Metadata met = new Metadata();
met.addMetadata("ProductStructure", Product.STRUCTURE_FLAT);
Product testProduct = getTestProduct();
try {
myCat.addProduct(testProduct);
myCat.addMetadata(met, testProduct);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
fail(e.getMessage());
}
try {
Metadata retMet = myCat.getMetadata(testProduct);
assertNotNull(retMet);
assertTrue(retMet.containsKey(CoreMetKeys.PRODUCT_STRUCTURE));
assertEquals(Product.STRUCTURE_FLAT, retMet
.getMetadata(CoreMetKeys.PRODUCT_STRUCTURE));
} catch (CatalogException e) {
fail(e.getMessage());
}
}
public void testRemoveMetadata() {
Metadata met = new Metadata();
met.addMetadata("Filename", "tempProduct");
met.addMetadata("ProductStructure", "Flat");
Product testProduct = getTestProduct();
try {
myCat.addProduct(testProduct);
myCat.addMetadata(met, testProduct);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
fail(e.getMessage());
}
try {
myCat.removeMetadata(met, testProduct);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
fail(e.getMessage());
}
try {
Metadata retMet = myCat.getMetadata(testProduct);
String retValue = retMet.getMetadata("Filename");
assertNull(retValue);
} catch (CatalogException e) {
LOG.log(Level.SEVERE, e.getMessage());
fail(e.getMessage());
}
}
public void testPagedQuery(){
// Add a couple of Products and associated Metadata
Product testProduct = null;
for(int i = 0; i < catPageSize + 1; i++){
testProduct = Product.getDefaultFlatProduct("test" + i,
"urn:oodt:GenericFile");
testProduct.getProductType().setName("GenericFile");
Reference ref = new Reference("file:///foo.txt", "file:///bar.txt", 100);
Vector<Reference> references = new Vector<Reference>();
references.add(ref);
testProduct.setProductReferences(references);
Metadata met = new Metadata();
met.addMetadata("Filename", "tempProduct" + i);
met.addMetadata("ProductStructure", "Flat");
try {
myCat.addProduct(testProduct);
myCat.addMetadata(met, testProduct);
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
fail(e.getMessage());
}
}
// Formulate a test query
Query query = new Query();
BooleanQueryCriteria bqc = new BooleanQueryCriteria();
try{
bqc.setOperator(BooleanQueryCriteria.AND);
}catch (Exception e){
LOG.log(Level.SEVERE, e.getMessage());
fail(e.getMessage());
}
TermQueryCriteria tqc = new TermQueryCriteria();
tqc.setElementName("ProductStructure");
tqc.setValue("Flat");
try{
bqc.addTerm(tqc);
}catch (Exception e){
LOG.log(Level.SEVERE, e.getMessage());
fail(e.getMessage());
}
tqc = new TermQueryCriteria();
tqc.setElementName("Filename");
tqc.setValue("tempProduct1");
try{
bqc.addTerm(tqc);
}catch (Exception e){
LOG.log(Level.SEVERE, e.getMessage());
fail(e.getMessage());
}
query.addCriterion(bqc);
// Perform the query and validate results
ProductPage page = null;
try{
page = myCat.pagedQuery(query, testProduct.getProductType(), 1);
}catch (Exception e){
LOG.log(Level.SEVERE, e.getMessage());
fail(e.getMessage());
}
assertEquals(page.getPageProducts().size(), 1);
assertEquals(page.getPageProducts().get(0).getProductName(), "test1");
assertEquals(page.getPageNum(), 1);
assertEquals(page.getTotalPages(), 1);
}
/*@Ignore
public void testNullIndexPath(){
System.clearProperty("org.apache.oodt.cas.filemgr.catalog.lucene.idxPath");
Properties sysProps = System.getProperties();
sysProps.remove("org.apache.oodt.cas.filemgr.catalog.lucene.idxPath");
try{
LuceneCatalogFactory fact = new LuceneCatalogFactory();
fail( "Missing exception" );
} catch( IllegalArgumentException e ) {
Assert.assertThat(e.getMessage(), CoreMatchers.containsString("error initializing lucene catalog: "));
}
}*/
public void testCreateCatalogException(){
//TODO Use the TestAppender to make sure that an exception thrown is caught and logged.
}
private static Product getTestProduct() {
Product testProduct = Product.getDefaultFlatProduct("test",
"urn:oodt:GenericFile");
testProduct.getProductType().setName("GenericFile");
// set references
Reference ref = new Reference("file:///foo.txt", "file:///bar.txt", 100);
Vector references = new Vector();
references.add(ref);
testProduct.setProductReferences(references);
return testProduct;
}
private static Metadata getTestMetadata(String prodName) {
Metadata met = new Metadata();
met.addMetadata("CAS.ProductName", prodName);
return met;
}
}
|
apache/iotdb | 35,886 | iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/sink/protocol/thrift/async/IoTDBDataRegionAsyncSink.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iotdb.db.pipe.sink.protocol.thrift.async;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.commons.audit.UserEntity;
import org.apache.iotdb.commons.client.async.AsyncPipeDataTransferServiceClient;
import org.apache.iotdb.commons.pipe.config.PipeConfig;
import org.apache.iotdb.commons.pipe.event.EnrichedEvent;
import org.apache.iotdb.commons.pipe.resource.log.PipeLogger;
import org.apache.iotdb.commons.pipe.sink.protocol.IoTDBSink;
import org.apache.iotdb.db.pipe.event.common.deletion.PipeDeleteDataNodeEvent;
import org.apache.iotdb.db.pipe.event.common.heartbeat.PipeHeartbeatEvent;
import org.apache.iotdb.db.pipe.event.common.tablet.PipeInsertNodeTabletInsertionEvent;
import org.apache.iotdb.db.pipe.event.common.tablet.PipeRawTabletInsertionEvent;
import org.apache.iotdb.db.pipe.event.common.terminate.PipeTerminateEvent;
import org.apache.iotdb.db.pipe.event.common.tsfile.PipeTsFileInsertionEvent;
import org.apache.iotdb.db.pipe.metric.sink.PipeDataRegionSinkMetrics;
import org.apache.iotdb.db.pipe.metric.source.PipeDataRegionEventCounter;
import org.apache.iotdb.db.pipe.sink.client.IoTDBDataNodeAsyncClientManager;
import org.apache.iotdb.db.pipe.sink.payload.evolvable.batch.PipeTabletEventBatch;
import org.apache.iotdb.db.pipe.sink.payload.evolvable.batch.PipeTabletEventPlainBatch;
import org.apache.iotdb.db.pipe.sink.payload.evolvable.batch.PipeTabletEventTsFileBatch;
import org.apache.iotdb.db.pipe.sink.payload.evolvable.batch.PipeTransferBatchReqBuilder;
import org.apache.iotdb.db.pipe.sink.payload.evolvable.request.PipeTransferTabletBinaryReqV2;
import org.apache.iotdb.db.pipe.sink.payload.evolvable.request.PipeTransferTabletInsertNodeReqV2;
import org.apache.iotdb.db.pipe.sink.payload.evolvable.request.PipeTransferTabletRawReqV2;
import org.apache.iotdb.db.pipe.sink.protocol.thrift.async.handler.PipeTransferTabletBatchEventHandler;
import org.apache.iotdb.db.pipe.sink.protocol.thrift.async.handler.PipeTransferTabletInsertNodeEventHandler;
import org.apache.iotdb.db.pipe.sink.protocol.thrift.async.handler.PipeTransferTabletRawEventHandler;
import org.apache.iotdb.db.pipe.sink.protocol.thrift.async.handler.PipeTransferTrackableHandler;
import org.apache.iotdb.db.pipe.sink.protocol.thrift.async.handler.PipeTransferTsFileHandler;
import org.apache.iotdb.db.pipe.sink.protocol.thrift.sync.IoTDBDataRegionSyncSink;
import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertNode;
import org.apache.iotdb.metrics.type.Histogram;
import org.apache.iotdb.pipe.api.PipeConnector;
import org.apache.iotdb.pipe.api.annotation.TableModel;
import org.apache.iotdb.pipe.api.annotation.TreeModel;
import org.apache.iotdb.pipe.api.customizer.configuration.PipeConnectorRuntimeConfiguration;
import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameterValidator;
import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameters;
import org.apache.iotdb.pipe.api.event.Event;
import org.apache.iotdb.pipe.api.event.dml.insertion.TabletInsertionEvent;
import org.apache.iotdb.pipe.api.event.dml.insertion.TsFileInsertionEvent;
import org.apache.iotdb.pipe.api.exception.PipeException;
import org.apache.iotdb.service.rpc.thrift.TPipeTransferReq;
import com.google.common.collect.ImmutableSet;
import org.apache.tsfile.exception.write.WriteProcessException;
import org.apache.tsfile.utils.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant.CONNECTOR_ENABLE_SEND_TSFILE_LIMIT;
import static org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant.CONNECTOR_ENABLE_SEND_TSFILE_LIMIT_DEFAULT_VALUE;
import static org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant.CONNECTOR_LEADER_CACHE_ENABLE_DEFAULT_VALUE;
import static org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant.CONNECTOR_LEADER_CACHE_ENABLE_KEY;
import static org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant.SINK_ENABLE_SEND_TSFILE_LIMIT;
import static org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant.SINK_IOTDB_SSL_ENABLE_KEY;
import static org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant.SINK_IOTDB_SSL_TRUST_STORE_PATH_KEY;
import static org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant.SINK_IOTDB_SSL_TRUST_STORE_PWD_KEY;
import static org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant.SINK_LEADER_CACHE_ENABLE_KEY;
@TreeModel
@TableModel
public class IoTDBDataRegionAsyncSink extends IoTDBSink {
private static final Logger LOGGER = LoggerFactory.getLogger(IoTDBDataRegionAsyncSink.class);
private static final String THRIFT_ERROR_FORMATTER_WITHOUT_ENDPOINT =
"Failed to borrow client from client pool when sending to receiver.";
private static final String THRIFT_ERROR_FORMATTER_WITH_ENDPOINT =
"Exception occurred while sending to receiver %s:%s.";
private static final boolean isSplitTSFileBatchModeEnabled = true;
private final IoTDBDataRegionSyncSink syncSink = new IoTDBDataRegionSyncSink();
private final BlockingQueue<Event> retryEventQueue = new LinkedBlockingQueue<>();
private final BlockingQueue<TsFileInsertionEvent> retryTsFileQueue = new LinkedBlockingQueue<>();
private final PipeDataRegionEventCounter retryEventQueueEventCounter =
new PipeDataRegionEventCounter();
private IoTDBDataNodeAsyncClientManager clientManager;
private IoTDBDataNodeAsyncClientManager transferTsFileClientManager;
// It is necessary to ensure that other classes that inherit Async Connector will not have NPE
public AtomicInteger transferTsFileCounter = new AtomicInteger(0);
private PipeTransferBatchReqBuilder tabletBatchBuilder;
// use these variables to prevent reference count leaks under some corner cases when closing
private final AtomicBoolean isClosed = new AtomicBoolean(false);
private final Map<PipeTransferTrackableHandler, PipeTransferTrackableHandler> pendingHandlers =
new ConcurrentHashMap<>();
private boolean enableSendTsFileLimit;
@Override
public void validate(final PipeParameterValidator validator) throws Exception {
super.validate(validator);
syncSink.validate(validator);
final PipeParameters parameters = validator.getParameters();
validator.validate(
args -> !((boolean) args[0] || (boolean) args[1] || (boolean) args[2]),
"Only 'iotdb-thrift-ssl-sink' supports SSL transmission currently.",
parameters.getBooleanOrDefault(SINK_IOTDB_SSL_ENABLE_KEY, false),
parameters.hasAttribute(SINK_IOTDB_SSL_TRUST_STORE_PATH_KEY),
parameters.hasAttribute(SINK_IOTDB_SSL_TRUST_STORE_PWD_KEY));
}
@Override
public void customize(
final PipeParameters parameters, final PipeConnectorRuntimeConfiguration configuration)
throws Exception {
super.customize(parameters, configuration);
syncSink.customize(parameters, configuration);
clientManager =
new IoTDBDataNodeAsyncClientManager(
nodeUrls,
parameters.getBooleanOrDefault(
Arrays.asList(SINK_LEADER_CACHE_ENABLE_KEY, CONNECTOR_LEADER_CACHE_ENABLE_KEY),
CONNECTOR_LEADER_CACHE_ENABLE_DEFAULT_VALUE),
loadBalanceStrategy,
new UserEntity(Long.parseLong(userId), username, cliHostname),
password,
shouldReceiverConvertOnTypeMismatch,
loadTsFileStrategy,
loadTsFileValidation,
shouldMarkAsPipeRequest,
false);
transferTsFileClientManager =
new IoTDBDataNodeAsyncClientManager(
nodeUrls,
parameters.getBooleanOrDefault(
Arrays.asList(SINK_LEADER_CACHE_ENABLE_KEY, CONNECTOR_LEADER_CACHE_ENABLE_KEY),
CONNECTOR_LEADER_CACHE_ENABLE_DEFAULT_VALUE),
loadBalanceStrategy,
new UserEntity(Long.parseLong(userId), username, cliHostname),
password,
shouldReceiverConvertOnTypeMismatch,
loadTsFileStrategy,
loadTsFileValidation,
shouldMarkAsPipeRequest,
isSplitTSFileBatchModeEnabled);
if (isTabletBatchModeEnabled) {
tabletBatchBuilder = new PipeTransferBatchReqBuilder(parameters);
}
enableSendTsFileLimit =
parameters.getBooleanOrDefault(
Arrays.asList(SINK_ENABLE_SEND_TSFILE_LIMIT, CONNECTOR_ENABLE_SEND_TSFILE_LIMIT),
CONNECTOR_ENABLE_SEND_TSFILE_LIMIT_DEFAULT_VALUE);
}
@Override
// Synchronized to avoid close connector when transfer event
public synchronized void handshake() throws Exception {
syncSink.handshake();
}
@Override
public void heartbeat() throws Exception {
if (!isClosed()) {
syncSink.heartbeat();
}
}
@Override
public void transfer(final TabletInsertionEvent tabletInsertionEvent) throws Exception {
transferQueuedEventsIfNecessary(false);
if (!(tabletInsertionEvent instanceof PipeInsertNodeTabletInsertionEvent)
&& !(tabletInsertionEvent instanceof PipeRawTabletInsertionEvent)) {
LOGGER.warn(
"IoTDBThriftAsyncConnector only support PipeInsertNodeTabletInsertionEvent and PipeRawTabletInsertionEvent. "
+ "Current event: {}.",
tabletInsertionEvent);
return;
}
if (isTabletBatchModeEnabled) {
tabletBatchBuilder.onEvent(tabletInsertionEvent);
transferBatchedEventsIfNecessary();
} else {
transferInEventWithoutCheck(tabletInsertionEvent);
}
}
private void transferInBatchWithoutCheck(
final Pair<TEndPoint, PipeTabletEventBatch> endPointAndBatch)
throws IOException, WriteProcessException {
if (Objects.isNull(endPointAndBatch)) {
return;
}
final PipeTabletEventBatch batch = endPointAndBatch.getRight();
if (batch instanceof PipeTabletEventPlainBatch) {
transfer(
endPointAndBatch.getLeft(),
new PipeTransferTabletBatchEventHandler((PipeTabletEventPlainBatch) batch, this));
} else if (batch instanceof PipeTabletEventTsFileBatch) {
final PipeTabletEventTsFileBatch tsFileBatch = (PipeTabletEventTsFileBatch) batch;
final List<Pair<String, File>> dbTsFilePairs = tsFileBatch.sealTsFiles();
final Map<Pair<String, Long>, Double> pipe2WeightMap = tsFileBatch.deepCopyPipe2WeightMap();
final List<EnrichedEvent> events = tsFileBatch.deepCopyEvents();
final AtomicInteger eventsReferenceCount = new AtomicInteger(dbTsFilePairs.size());
final AtomicBoolean eventsHadBeenAddedToRetryQueue = new AtomicBoolean(false);
try {
for (final Pair<String, File> sealedFile : dbTsFilePairs) {
transfer(
new PipeTransferTsFileHandler(
this,
pipe2WeightMap,
events,
eventsReferenceCount,
eventsHadBeenAddedToRetryQueue,
sealedFile.right,
null,
false,
sealedFile.left));
}
} catch (final Throwable t) {
LOGGER.warn("Failed to transfer tsfile batch ({}).", dbTsFilePairs, t);
if (eventsHadBeenAddedToRetryQueue.compareAndSet(false, true)) {
addFailureEventsToRetryQueue(events);
}
}
} else {
LOGGER.warn(
"Unsupported batch type {} when transferring tablet insertion event.", batch.getClass());
}
endPointAndBatch.getRight().onSuccess();
}
private boolean transferInEventWithoutCheck(final TabletInsertionEvent tabletInsertionEvent)
throws Exception {
if (tabletInsertionEvent instanceof PipeInsertNodeTabletInsertionEvent) {
final PipeInsertNodeTabletInsertionEvent pipeInsertNodeTabletInsertionEvent =
(PipeInsertNodeTabletInsertionEvent) tabletInsertionEvent;
// We increase the reference count for this event to determine if the event may be released.
if (!pipeInsertNodeTabletInsertionEvent.increaseReferenceCount(
IoTDBDataRegionAsyncSink.class.getName())) {
return false;
}
final InsertNode insertNode = pipeInsertNodeTabletInsertionEvent.getInsertNode();
final String databaseName =
pipeInsertNodeTabletInsertionEvent.isTableModelEvent()
? pipeInsertNodeTabletInsertionEvent.getTableModelDatabaseName()
: null;
final TPipeTransferReq pipeTransferReq =
compressIfNeeded(
Objects.isNull(insertNode)
? PipeTransferTabletBinaryReqV2.toTPipeTransferReq(
pipeInsertNodeTabletInsertionEvent.getByteBuffer(), databaseName)
: PipeTransferTabletInsertNodeReqV2.toTPipeTransferReq(insertNode, databaseName));
final PipeTransferTabletInsertNodeEventHandler pipeTransferInsertNodeReqHandler =
new PipeTransferTabletInsertNodeEventHandler(
pipeInsertNodeTabletInsertionEvent, pipeTransferReq, this);
transfer(
// getDeviceId() may return null for InsertRowsNode
pipeInsertNodeTabletInsertionEvent.getDeviceId(), pipeTransferInsertNodeReqHandler);
} else { // tabletInsertionEvent instanceof PipeRawTabletInsertionEvent
final PipeRawTabletInsertionEvent pipeRawTabletInsertionEvent =
(PipeRawTabletInsertionEvent) tabletInsertionEvent;
// We increase the reference count for this event to determine if the event may be released.
if (!pipeRawTabletInsertionEvent.increaseReferenceCount(
IoTDBDataRegionAsyncSink.class.getName())) {
return false;
}
final TPipeTransferReq pipeTransferTabletRawReq =
compressIfNeeded(
PipeTransferTabletRawReqV2.toTPipeTransferReq(
pipeRawTabletInsertionEvent.convertToTablet(),
pipeRawTabletInsertionEvent.isAligned(),
pipeRawTabletInsertionEvent.isTableModelEvent()
? pipeRawTabletInsertionEvent.getTableModelDatabaseName()
: null));
final PipeTransferTabletRawEventHandler pipeTransferTabletReqHandler =
new PipeTransferTabletRawEventHandler(
pipeRawTabletInsertionEvent, pipeTransferTabletRawReq, this);
transfer(pipeRawTabletInsertionEvent.getDeviceId(), pipeTransferTabletReqHandler);
}
return true;
}
private void transfer(
final TEndPoint endPoint,
final PipeTransferTabletBatchEventHandler pipeTransferTabletBatchEventHandler) {
AsyncPipeDataTransferServiceClient client = null;
try {
client = clientManager.borrowClient(endPoint);
pipeTransferTabletBatchEventHandler.transfer(client);
} catch (final Exception ex) {
logOnClientException(client, ex);
pipeTransferTabletBatchEventHandler.onError(ex);
}
}
private void transfer(
final String deviceId,
final PipeTransferTabletInsertNodeEventHandler pipeTransferInsertNodeReqHandler) {
AsyncPipeDataTransferServiceClient client = null;
try {
client = clientManager.borrowClient(deviceId);
pipeTransferInsertNodeReqHandler.transfer(client);
} catch (final Exception ex) {
logOnClientException(client, ex);
pipeTransferInsertNodeReqHandler.onError(ex);
}
}
private void transfer(
final String deviceId, final PipeTransferTabletRawEventHandler pipeTransferTabletReqHandler) {
AsyncPipeDataTransferServiceClient client = null;
try {
client = clientManager.borrowClient(deviceId);
pipeTransferTabletReqHandler.transfer(client);
} catch (final Exception ex) {
logOnClientException(client, ex);
pipeTransferTabletReqHandler.onError(ex);
}
}
@Override
public void transfer(final TsFileInsertionEvent tsFileInsertionEvent) throws Exception {
transferQueuedEventsIfNecessary(false);
transferBatchedEventsIfNecessary();
if (!(tsFileInsertionEvent instanceof PipeTsFileInsertionEvent)) {
LOGGER.warn(
"IoTDBThriftAsyncConnector only support PipeTsFileInsertionEvent. Current event: {}.",
tsFileInsertionEvent);
return;
}
transferWithoutCheck(tsFileInsertionEvent);
}
private boolean transferWithoutCheck(final TsFileInsertionEvent tsFileInsertionEvent)
throws Exception {
final PipeTsFileInsertionEvent pipeTsFileInsertionEvent =
(PipeTsFileInsertionEvent) tsFileInsertionEvent;
// We increase the reference count for this event to determine if the event may be released.
if (!pipeTsFileInsertionEvent.increaseReferenceCount(
IoTDBDataRegionAsyncSink.class.getName())) {
return false;
}
// We assume that no exceptions will be thrown after reference count is increased.
try {
// Just in case. To avoid the case that exception occurred when constructing the handler.
if (!pipeTsFileInsertionEvent.getTsFile().exists()) {
throw new FileNotFoundException(pipeTsFileInsertionEvent.getTsFile().getAbsolutePath());
}
final PipeTransferTsFileHandler pipeTransferTsFileHandler =
new PipeTransferTsFileHandler(
this,
Collections.singletonMap(
new Pair<>(
pipeTsFileInsertionEvent.getPipeName(),
pipeTsFileInsertionEvent.getCreationTime()),
1.0),
Collections.singletonList(pipeTsFileInsertionEvent),
new AtomicInteger(1),
new AtomicBoolean(false),
pipeTsFileInsertionEvent.getTsFile(),
pipeTsFileInsertionEvent.getModFile(),
pipeTsFileInsertionEvent.isWithMod()
&& clientManager.supportModsIfIsDataNodeReceiver(),
pipeTsFileInsertionEvent.isTableModelEvent()
? pipeTsFileInsertionEvent.getTableModelDatabaseName()
: null);
transfer(pipeTransferTsFileHandler);
return true;
} catch (final Exception e) {
// Just in case. To avoid the case that exception occurred when constructing the handler.
pipeTsFileInsertionEvent.decreaseReferenceCount(
IoTDBDataRegionAsyncSink.class.getName(), false);
throw e;
}
}
private void transfer(final PipeTransferTsFileHandler pipeTransferTsFileHandler) {
transferTsFileCounter.incrementAndGet();
CompletableFuture<Void> completableFuture =
CompletableFuture.supplyAsync(
() -> {
AsyncPipeDataTransferServiceClient client = null;
try {
client = transferTsFileClientManager.borrowClient();
pipeTransferTsFileHandler.transfer(transferTsFileClientManager, client);
} catch (final Exception ex) {
logOnClientException(client, ex);
pipeTransferTsFileHandler.onError(ex);
} finally {
transferTsFileCounter.decrementAndGet();
}
return null;
},
transferTsFileClientManager.getExecutor());
if (PipeConfig.getInstance().isTransferTsFileSync() || !isRealtimeFirst) {
try {
completableFuture.get();
} catch (final Exception e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
LOGGER.warn(
"Transfer tsfile event {} asynchronously was interrupted.",
pipeTransferTsFileHandler.getTsFile(),
e);
}
pipeTransferTsFileHandler.onError(e);
LOGGER.warn(
"Failed to transfer tsfile event {} asynchronously.",
pipeTransferTsFileHandler.getTsFile(),
e);
}
}
}
@Override
public void transfer(final Event event) throws Exception {
transferQueuedEventsIfNecessary(true);
transferBatchedEventsIfNecessary();
if (!(event instanceof PipeHeartbeatEvent
|| event instanceof PipeDeleteDataNodeEvent
|| event instanceof PipeTerminateEvent)) {
LOGGER.warn(
"IoTDBThriftAsyncConnector does not support transferring generic event: {}.", event);
return;
}
syncSink.transfer(event);
}
/** Try its best to commit data in order. Flush can also be a trigger to transfer batched data. */
private void transferBatchedEventsIfNecessary() throws IOException, WriteProcessException {
if (!isTabletBatchModeEnabled || tabletBatchBuilder.isEmpty()) {
return;
}
for (final Pair<TEndPoint, PipeTabletEventBatch> endPointAndBatch :
tabletBatchBuilder.getAllNonEmptyAndShouldEmitBatches()) {
transferInBatchWithoutCheck(endPointAndBatch);
}
}
@Override
public TPipeTransferReq compressIfNeeded(final TPipeTransferReq req) throws IOException {
if (Objects.isNull(compressionTimer) && Objects.nonNull(attributeSortedString)) {
compressionTimer =
PipeDataRegionSinkMetrics.getInstance().getCompressionTimer(attributeSortedString);
}
return super.compressIfNeeded(req);
}
//////////////////////////// Leader cache update ////////////////////////////
public void updateLeaderCache(final String deviceId, final TEndPoint endPoint) {
clientManager.updateLeaderCache(deviceId, endPoint);
}
//////////////////////////// Exception handlers ////////////////////////////
private void logOnClientException(
final AsyncPipeDataTransferServiceClient client, final Exception e) {
if (client == null) {
PipeLogger.log(LOGGER::warn, THRIFT_ERROR_FORMATTER_WITHOUT_ENDPOINT);
} else {
client.resetMethodStateIfStopped();
PipeLogger.log(
LOGGER::warn,
e,
String.format(THRIFT_ERROR_FORMATTER_WITH_ENDPOINT, client.getIp(), client.getPort()));
}
}
/**
* Transfer queued {@link Event}s which are waiting for retry.
*
* @see PipeConnector#transfer(Event) for more details.
* @see PipeConnector#transfer(TabletInsertionEvent) for more details.
* @see PipeConnector#transfer(TsFileInsertionEvent) for more details.
*/
private void transferQueuedEventsIfNecessary(final boolean forced) {
if ((retryEventQueue.isEmpty() && retryTsFileQueue.isEmpty())
|| (!forced
&& retryEventQueueEventCounter.getTabletInsertionEventCount()
< PipeConfig.getInstance()
.getPipeAsyncConnectorForcedRetryTabletEventQueueSizeThreshold()
&& retryEventQueueEventCounter.getTsFileInsertionEventCount()
< PipeConfig.getInstance()
.getPipeAsyncConnectorForcedRetryTsFileEventQueueSizeThreshold()
&& retryEventQueue.size() + retryTsFileQueue.size()
< PipeConfig.getInstance()
.getPipeAsyncConnectorForcedRetryTotalEventQueueSizeThreshold())) {
return;
}
final long retryStartTime = System.currentTimeMillis();
final int remainingEvents = retryEventQueue.size() + retryTsFileQueue.size();
while (!retryEventQueue.isEmpty() || !retryTsFileQueue.isEmpty()) {
synchronized (this) {
if (isClosed.get()) {
return;
}
if (retryEventQueue.isEmpty() && retryTsFileQueue.isEmpty()) {
break;
}
final Event peekedEvent;
final Event polledEvent;
if (!retryEventQueue.isEmpty()) {
peekedEvent = retryEventQueue.peek();
if (peekedEvent instanceof PipeInsertNodeTabletInsertionEvent) {
retryTransfer((PipeInsertNodeTabletInsertionEvent) peekedEvent);
} else if (peekedEvent instanceof PipeRawTabletInsertionEvent) {
retryTransfer((PipeRawTabletInsertionEvent) peekedEvent);
} else {
LOGGER.warn(
"IoTDBThriftAsyncConnector does not support transfer generic event: {}.",
peekedEvent);
}
polledEvent = retryEventQueue.poll();
} else {
if (transferTsFileCounter.get()
>= PipeConfig.getInstance().getPipeRealTimeQueueMaxWaitingTsFileSize()) {
return;
}
peekedEvent = retryTsFileQueue.peek();
retryTransfer((PipeTsFileInsertionEvent) peekedEvent);
polledEvent = retryTsFileQueue.poll();
}
retryEventQueueEventCounter.decreaseEventCount(polledEvent);
if (polledEvent != peekedEvent) {
LOGGER.error(
"The event polled from the queue is not the same as the event peeked from the queue. "
+ "Peeked event: {}, polled event: {}.",
peekedEvent,
polledEvent);
}
if (polledEvent != null && LOGGER.isDebugEnabled()) {
LOGGER.debug("Polled event {} from retry queue.", polledEvent);
}
}
// Stop retrying if the execution time exceeds the threshold for better realtime performance
if (System.currentTimeMillis() - retryStartTime
> PipeConfig.getInstance().getPipeAsyncConnectorMaxRetryExecutionTimeMsPerCall()) {
if (retryEventQueueEventCounter.getTabletInsertionEventCount()
< PipeConfig.getInstance()
.getPipeAsyncConnectorForcedRetryTabletEventQueueSizeThreshold()
&& retryEventQueueEventCounter.getTsFileInsertionEventCount()
< PipeConfig.getInstance()
.getPipeAsyncConnectorForcedRetryTsFileEventQueueSizeThreshold()
&& retryEventQueue.size() + retryTsFileQueue.size()
< PipeConfig.getInstance()
.getPipeAsyncConnectorForcedRetryTotalEventQueueSizeThreshold()) {
return;
}
if (remainingEvents <= retryEventQueue.size() + retryTsFileQueue.size()) {
throw new PipeException(
"Failed to retry transferring events in the retry queue. Remaining events: "
+ (retryEventQueue.size() + retryTsFileQueue.size())
+ " (tablet events: "
+ retryEventQueueEventCounter.getTabletInsertionEventCount()
+ ", tsfile events: "
+ retryEventQueueEventCounter.getTsFileInsertionEventCount()
+ ").");
}
}
}
}
private void retryTransfer(final TabletInsertionEvent tabletInsertionEvent) {
if (isTabletBatchModeEnabled) {
try {
tabletBatchBuilder.onEvent(tabletInsertionEvent);
transferBatchedEventsIfNecessary();
if (tabletInsertionEvent instanceof EnrichedEvent) {
((EnrichedEvent) tabletInsertionEvent)
.decreaseReferenceCount(IoTDBDataRegionAsyncSink.class.getName(), false);
}
} catch (final Exception e) {
addFailureEventToRetryQueue(tabletInsertionEvent);
}
return;
}
// Tablet batch mode is not enabled, so we need to transfer the event directly.
try {
if (transferInEventWithoutCheck(tabletInsertionEvent)) {
if (tabletInsertionEvent instanceof EnrichedEvent) {
((EnrichedEvent) tabletInsertionEvent)
.decreaseReferenceCount(IoTDBDataRegionAsyncSink.class.getName(), false);
}
} else {
addFailureEventToRetryQueue(tabletInsertionEvent);
}
} catch (final Exception e) {
if (tabletInsertionEvent instanceof EnrichedEvent) {
((EnrichedEvent) tabletInsertionEvent)
.decreaseReferenceCount(IoTDBDataRegionAsyncSink.class.getName(), false);
}
addFailureEventToRetryQueue(tabletInsertionEvent);
}
}
private void retryTransfer(final PipeTsFileInsertionEvent tsFileInsertionEvent) {
try {
if (transferWithoutCheck(tsFileInsertionEvent)) {
tsFileInsertionEvent.decreaseReferenceCount(
IoTDBDataRegionAsyncSink.class.getName(), false);
} else {
addFailureEventToRetryQueue(tsFileInsertionEvent);
}
} catch (final Exception e) {
tsFileInsertionEvent.decreaseReferenceCount(IoTDBDataRegionAsyncSink.class.getName(), false);
addFailureEventToRetryQueue(tsFileInsertionEvent);
}
}
/**
* Add failure {@link Event} to retry queue.
*
* @param event {@link Event} to retry
*/
@SuppressWarnings("java:S899")
public void addFailureEventToRetryQueue(final Event event) {
if (event instanceof EnrichedEvent && ((EnrichedEvent) event).isReleased()) {
return;
}
if (isClosed.get()) {
if (event instanceof EnrichedEvent) {
((EnrichedEvent) event).clearReferenceCount(IoTDBDataRegionAsyncSink.class.getName());
}
return;
}
if (event instanceof PipeTsFileInsertionEvent) {
retryTsFileQueue.offer((PipeTsFileInsertionEvent) event);
retryEventQueueEventCounter.increaseEventCount(event);
} else {
retryEventQueue.offer(event);
retryEventQueueEventCounter.increaseEventCount(event);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Added event {} to retry queue.", event);
}
if (isClosed.get()) {
if (event instanceof EnrichedEvent) {
((EnrichedEvent) event).clearReferenceCount(IoTDBDataRegionAsyncSink.class.getName());
}
}
}
/**
* Add failure {@link EnrichedEvent}s to retry queue.
*
* @param events {@link EnrichedEvent}s to retry
*/
public void addFailureEventsToRetryQueue(final Iterable<EnrichedEvent> events) {
events.forEach(this::addFailureEventToRetryQueue);
}
public boolean isEnableSendTsFileLimit() {
return enableSendTsFileLimit;
}
//////////////////////////// Operations for close ////////////////////////////
@Override
public synchronized void discardEventsOfPipe(final String pipeNameToDrop, final int regionId) {
if (isTabletBatchModeEnabled) {
tabletBatchBuilder.discardEventsOfPipe(pipeNameToDrop, regionId);
}
retryEventQueue.removeIf(
event -> {
if (event instanceof EnrichedEvent
&& pipeNameToDrop.equals(((EnrichedEvent) event).getPipeName())
&& regionId == ((EnrichedEvent) event).getRegionId()) {
((EnrichedEvent) event).clearReferenceCount(IoTDBDataRegionAsyncSink.class.getName());
retryEventQueueEventCounter.decreaseEventCount(event);
return true;
}
return false;
});
retryTsFileQueue.removeIf(
event -> {
if (event instanceof EnrichedEvent
&& pipeNameToDrop.equals(((EnrichedEvent) event).getPipeName())
&& regionId == ((EnrichedEvent) event).getRegionId()) {
((EnrichedEvent) event).clearReferenceCount(IoTDBDataRegionAsyncSink.class.getName());
retryEventQueueEventCounter.decreaseEventCount(event);
return true;
}
return false;
});
}
@Override
// synchronized to avoid close connector when transfer event
public synchronized void close() {
isClosed.set(true);
syncSink.close();
if (tabletBatchBuilder != null) {
tabletBatchBuilder.close();
}
// ensure all on-the-fly handlers have been cleared
if (hasPendingHandlers()) {
ImmutableSet.copyOf(pendingHandlers.keySet())
.forEach(
handler -> {
handler.clearEventsReferenceCount();
eliminateHandler(handler, true);
});
}
try {
if (clientManager != null) {
clientManager.close();
}
if (transferTsFileClientManager != null) {
transferTsFileClientManager.close();
}
} catch (final Exception e) {
LOGGER.warn("Failed to close client manager.", e);
}
// clear reference count of events in retry queue after closing async client
clearRetryEventsReferenceCount();
super.close();
}
public synchronized void clearRetryEventsReferenceCount() {
while (!retryEventQueue.isEmpty() || !retryTsFileQueue.isEmpty()) {
final Event event =
retryTsFileQueue.isEmpty() ? retryEventQueue.poll() : retryTsFileQueue.poll();
retryEventQueueEventCounter.decreaseEventCount(event);
if (event instanceof EnrichedEvent) {
((EnrichedEvent) event).clearReferenceCount(IoTDBDataRegionAsyncSink.class.getName());
}
}
}
//////////////////////// APIs provided for metric framework ////////////////////////
public int getRetryEventQueueSize() {
return retryEventQueue.size() + retryTsFileQueue.size();
}
public int getBatchSize() {
return Objects.nonNull(tabletBatchBuilder) ? tabletBatchBuilder.size() : 0;
}
public int getPendingHandlersSize() {
return pendingHandlers.size();
}
//////////////////////// APIs provided for PipeTransferTrackableHandler ////////////////////////
public boolean isClosed() {
return isClosed.get();
}
public void trackHandler(final PipeTransferTrackableHandler handler) {
pendingHandlers.put(handler, handler);
}
public void eliminateHandler(
final PipeTransferTrackableHandler handler, final boolean closeClient) {
if (closeClient) {
handler.closeClient();
}
handler.close();
pendingHandlers.remove(handler);
}
public boolean hasPendingHandlers() {
return !pendingHandlers.isEmpty();
}
public void setTransferTsFileCounter(AtomicInteger transferTsFileCounter) {
this.transferTsFileCounter = transferTsFileCounter;
}
@Override
public void setTabletBatchSizeHistogram(Histogram tabletBatchSizeHistogram) {
if (tabletBatchBuilder != null) {
tabletBatchBuilder.setTabletBatchSizeHistogram(tabletBatchSizeHistogram);
}
}
@Override
public void setTsFileBatchSizeHistogram(Histogram tsFileBatchSizeHistogram) {
if (tabletBatchBuilder != null) {
tabletBatchBuilder.setTsFileBatchSizeHistogram(tsFileBatchSizeHistogram);
}
}
@Override
public void setTabletBatchTimeIntervalHistogram(Histogram tabletBatchTimeIntervalHistogram) {
if (tabletBatchBuilder != null) {
tabletBatchBuilder.setTabletBatchTimeIntervalHistogram(tabletBatchTimeIntervalHistogram);
}
}
@Override
public void setTsFileBatchTimeIntervalHistogram(Histogram tsFileBatchTimeIntervalHistogram) {
if (tabletBatchBuilder != null) {
tabletBatchBuilder.setTsFileBatchTimeIntervalHistogram(tsFileBatchTimeIntervalHistogram);
}
}
@Override
public void setBatchEventSizeHistogram(Histogram eventSizeHistogram) {
if (tabletBatchBuilder != null) {
tabletBatchBuilder.setEventSizeHistogram(eventSizeHistogram);
}
}
}
|
apache/sentry | 35,703 | sentry-service/sentry-service-api/src/gen/thrift/gen-javabean/org/apache/sentry/api/generic/thrift/TRenamePrivilegesRequest.java | /**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.sentry.api.generic.thrift;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)")
public class TRenamePrivilegesRequest implements org.apache.thrift.TBase<TRenamePrivilegesRequest, TRenamePrivilegesRequest._Fields>, java.io.Serializable, Cloneable, Comparable<TRenamePrivilegesRequest> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TRenamePrivilegesRequest");
private static final org.apache.thrift.protocol.TField PROTOCOL_VERSION_FIELD_DESC = new org.apache.thrift.protocol.TField("protocol_version", org.apache.thrift.protocol.TType.I32, (short)1);
private static final org.apache.thrift.protocol.TField REQUESTOR_USER_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("requestorUserName", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField COMPONENT_FIELD_DESC = new org.apache.thrift.protocol.TField("component", org.apache.thrift.protocol.TType.STRING, (short)3);
private static final org.apache.thrift.protocol.TField SERVICE_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("serviceName", org.apache.thrift.protocol.TType.STRING, (short)4);
private static final org.apache.thrift.protocol.TField OLD_AUTHORIZABLES_FIELD_DESC = new org.apache.thrift.protocol.TField("oldAuthorizables", org.apache.thrift.protocol.TType.LIST, (short)5);
private static final org.apache.thrift.protocol.TField NEW_AUTHORIZABLES_FIELD_DESC = new org.apache.thrift.protocol.TField("newAuthorizables", org.apache.thrift.protocol.TType.LIST, (short)6);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new TRenamePrivilegesRequestStandardSchemeFactory());
schemes.put(TupleScheme.class, new TRenamePrivilegesRequestTupleSchemeFactory());
}
private int protocol_version; // required
private String requestorUserName; // required
private String component; // required
private String serviceName; // required
private List<TAuthorizable> oldAuthorizables; // required
private List<TAuthorizable> newAuthorizables; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
PROTOCOL_VERSION((short)1, "protocol_version"),
REQUESTOR_USER_NAME((short)2, "requestorUserName"),
COMPONENT((short)3, "component"),
SERVICE_NAME((short)4, "serviceName"),
OLD_AUTHORIZABLES((short)5, "oldAuthorizables"),
NEW_AUTHORIZABLES((short)6, "newAuthorizables");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // PROTOCOL_VERSION
return PROTOCOL_VERSION;
case 2: // REQUESTOR_USER_NAME
return REQUESTOR_USER_NAME;
case 3: // COMPONENT
return COMPONENT;
case 4: // SERVICE_NAME
return SERVICE_NAME;
case 5: // OLD_AUTHORIZABLES
return OLD_AUTHORIZABLES;
case 6: // NEW_AUTHORIZABLES
return NEW_AUTHORIZABLES;
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 IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __PROTOCOL_VERSION_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.PROTOCOL_VERSION, new org.apache.thrift.meta_data.FieldMetaData("protocol_version", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
tmpMap.put(_Fields.REQUESTOR_USER_NAME, new org.apache.thrift.meta_data.FieldMetaData("requestorUserName", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.COMPONENT, new org.apache.thrift.meta_data.FieldMetaData("component", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.SERVICE_NAME, new org.apache.thrift.meta_data.FieldMetaData("serviceName", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.OLD_AUTHORIZABLES, new org.apache.thrift.meta_data.FieldMetaData("oldAuthorizables", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TAuthorizable.class))));
tmpMap.put(_Fields.NEW_AUTHORIZABLES, new org.apache.thrift.meta_data.FieldMetaData("newAuthorizables", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TAuthorizable.class))));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TRenamePrivilegesRequest.class, metaDataMap);
}
public TRenamePrivilegesRequest() {
this.protocol_version = 2;
}
public TRenamePrivilegesRequest(
int protocol_version,
String requestorUserName,
String component,
String serviceName,
List<TAuthorizable> oldAuthorizables,
List<TAuthorizable> newAuthorizables)
{
this();
this.protocol_version = protocol_version;
setProtocol_versionIsSet(true);
this.requestorUserName = requestorUserName;
this.component = component;
this.serviceName = serviceName;
this.oldAuthorizables = oldAuthorizables;
this.newAuthorizables = newAuthorizables;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public TRenamePrivilegesRequest(TRenamePrivilegesRequest other) {
__isset_bitfield = other.__isset_bitfield;
this.protocol_version = other.protocol_version;
if (other.isSetRequestorUserName()) {
this.requestorUserName = other.requestorUserName;
}
if (other.isSetComponent()) {
this.component = other.component;
}
if (other.isSetServiceName()) {
this.serviceName = other.serviceName;
}
if (other.isSetOldAuthorizables()) {
List<TAuthorizable> __this__oldAuthorizables = new ArrayList<TAuthorizable>(other.oldAuthorizables.size());
for (TAuthorizable other_element : other.oldAuthorizables) {
__this__oldAuthorizables.add(new TAuthorizable(other_element));
}
this.oldAuthorizables = __this__oldAuthorizables;
}
if (other.isSetNewAuthorizables()) {
List<TAuthorizable> __this__newAuthorizables = new ArrayList<TAuthorizable>(other.newAuthorizables.size());
for (TAuthorizable other_element : other.newAuthorizables) {
__this__newAuthorizables.add(new TAuthorizable(other_element));
}
this.newAuthorizables = __this__newAuthorizables;
}
}
public TRenamePrivilegesRequest deepCopy() {
return new TRenamePrivilegesRequest(this);
}
@Override
public void clear() {
this.protocol_version = 2;
this.requestorUserName = null;
this.component = null;
this.serviceName = null;
this.oldAuthorizables = null;
this.newAuthorizables = null;
}
public int getProtocol_version() {
return this.protocol_version;
}
public void setProtocol_version(int protocol_version) {
this.protocol_version = protocol_version;
setProtocol_versionIsSet(true);
}
public void unsetProtocol_version() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __PROTOCOL_VERSION_ISSET_ID);
}
/** Returns true if field protocol_version is set (has been assigned a value) and false otherwise */
public boolean isSetProtocol_version() {
return EncodingUtils.testBit(__isset_bitfield, __PROTOCOL_VERSION_ISSET_ID);
}
public void setProtocol_versionIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __PROTOCOL_VERSION_ISSET_ID, value);
}
public String getRequestorUserName() {
return this.requestorUserName;
}
public void setRequestorUserName(String requestorUserName) {
this.requestorUserName = requestorUserName;
}
public void unsetRequestorUserName() {
this.requestorUserName = null;
}
/** Returns true if field requestorUserName is set (has been assigned a value) and false otherwise */
public boolean isSetRequestorUserName() {
return this.requestorUserName != null;
}
public void setRequestorUserNameIsSet(boolean value) {
if (!value) {
this.requestorUserName = null;
}
}
public String getComponent() {
return this.component;
}
public void setComponent(String component) {
this.component = component;
}
public void unsetComponent() {
this.component = null;
}
/** Returns true if field component is set (has been assigned a value) and false otherwise */
public boolean isSetComponent() {
return this.component != null;
}
public void setComponentIsSet(boolean value) {
if (!value) {
this.component = null;
}
}
public String getServiceName() {
return this.serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public void unsetServiceName() {
this.serviceName = null;
}
/** Returns true if field serviceName is set (has been assigned a value) and false otherwise */
public boolean isSetServiceName() {
return this.serviceName != null;
}
public void setServiceNameIsSet(boolean value) {
if (!value) {
this.serviceName = null;
}
}
public int getOldAuthorizablesSize() {
return (this.oldAuthorizables == null) ? 0 : this.oldAuthorizables.size();
}
public java.util.Iterator<TAuthorizable> getOldAuthorizablesIterator() {
return (this.oldAuthorizables == null) ? null : this.oldAuthorizables.iterator();
}
public void addToOldAuthorizables(TAuthorizable elem) {
if (this.oldAuthorizables == null) {
this.oldAuthorizables = new ArrayList<TAuthorizable>();
}
this.oldAuthorizables.add(elem);
}
public List<TAuthorizable> getOldAuthorizables() {
return this.oldAuthorizables;
}
public void setOldAuthorizables(List<TAuthorizable> oldAuthorizables) {
this.oldAuthorizables = oldAuthorizables;
}
public void unsetOldAuthorizables() {
this.oldAuthorizables = null;
}
/** Returns true if field oldAuthorizables is set (has been assigned a value) and false otherwise */
public boolean isSetOldAuthorizables() {
return this.oldAuthorizables != null;
}
public void setOldAuthorizablesIsSet(boolean value) {
if (!value) {
this.oldAuthorizables = null;
}
}
public int getNewAuthorizablesSize() {
return (this.newAuthorizables == null) ? 0 : this.newAuthorizables.size();
}
public java.util.Iterator<TAuthorizable> getNewAuthorizablesIterator() {
return (this.newAuthorizables == null) ? null : this.newAuthorizables.iterator();
}
public void addToNewAuthorizables(TAuthorizable elem) {
if (this.newAuthorizables == null) {
this.newAuthorizables = new ArrayList<TAuthorizable>();
}
this.newAuthorizables.add(elem);
}
public List<TAuthorizable> getNewAuthorizables() {
return this.newAuthorizables;
}
public void setNewAuthorizables(List<TAuthorizable> newAuthorizables) {
this.newAuthorizables = newAuthorizables;
}
public void unsetNewAuthorizables() {
this.newAuthorizables = null;
}
/** Returns true if field newAuthorizables is set (has been assigned a value) and false otherwise */
public boolean isSetNewAuthorizables() {
return this.newAuthorizables != null;
}
public void setNewAuthorizablesIsSet(boolean value) {
if (!value) {
this.newAuthorizables = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case PROTOCOL_VERSION:
if (value == null) {
unsetProtocol_version();
} else {
setProtocol_version((Integer)value);
}
break;
case REQUESTOR_USER_NAME:
if (value == null) {
unsetRequestorUserName();
} else {
setRequestorUserName((String)value);
}
break;
case COMPONENT:
if (value == null) {
unsetComponent();
} else {
setComponent((String)value);
}
break;
case SERVICE_NAME:
if (value == null) {
unsetServiceName();
} else {
setServiceName((String)value);
}
break;
case OLD_AUTHORIZABLES:
if (value == null) {
unsetOldAuthorizables();
} else {
setOldAuthorizables((List<TAuthorizable>)value);
}
break;
case NEW_AUTHORIZABLES:
if (value == null) {
unsetNewAuthorizables();
} else {
setNewAuthorizables((List<TAuthorizable>)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case PROTOCOL_VERSION:
return getProtocol_version();
case REQUESTOR_USER_NAME:
return getRequestorUserName();
case COMPONENT:
return getComponent();
case SERVICE_NAME:
return getServiceName();
case OLD_AUTHORIZABLES:
return getOldAuthorizables();
case NEW_AUTHORIZABLES:
return getNewAuthorizables();
}
throw new 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 IllegalArgumentException();
}
switch (field) {
case PROTOCOL_VERSION:
return isSetProtocol_version();
case REQUESTOR_USER_NAME:
return isSetRequestorUserName();
case COMPONENT:
return isSetComponent();
case SERVICE_NAME:
return isSetServiceName();
case OLD_AUTHORIZABLES:
return isSetOldAuthorizables();
case NEW_AUTHORIZABLES:
return isSetNewAuthorizables();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof TRenamePrivilegesRequest)
return this.equals((TRenamePrivilegesRequest)that);
return false;
}
public boolean equals(TRenamePrivilegesRequest that) {
if (that == null)
return false;
boolean this_present_protocol_version = true;
boolean that_present_protocol_version = true;
if (this_present_protocol_version || that_present_protocol_version) {
if (!(this_present_protocol_version && that_present_protocol_version))
return false;
if (this.protocol_version != that.protocol_version)
return false;
}
boolean this_present_requestorUserName = true && this.isSetRequestorUserName();
boolean that_present_requestorUserName = true && that.isSetRequestorUserName();
if (this_present_requestorUserName || that_present_requestorUserName) {
if (!(this_present_requestorUserName && that_present_requestorUserName))
return false;
if (!this.requestorUserName.equals(that.requestorUserName))
return false;
}
boolean this_present_component = true && this.isSetComponent();
boolean that_present_component = true && that.isSetComponent();
if (this_present_component || that_present_component) {
if (!(this_present_component && that_present_component))
return false;
if (!this.component.equals(that.component))
return false;
}
boolean this_present_serviceName = true && this.isSetServiceName();
boolean that_present_serviceName = true && that.isSetServiceName();
if (this_present_serviceName || that_present_serviceName) {
if (!(this_present_serviceName && that_present_serviceName))
return false;
if (!this.serviceName.equals(that.serviceName))
return false;
}
boolean this_present_oldAuthorizables = true && this.isSetOldAuthorizables();
boolean that_present_oldAuthorizables = true && that.isSetOldAuthorizables();
if (this_present_oldAuthorizables || that_present_oldAuthorizables) {
if (!(this_present_oldAuthorizables && that_present_oldAuthorizables))
return false;
if (!this.oldAuthorizables.equals(that.oldAuthorizables))
return false;
}
boolean this_present_newAuthorizables = true && this.isSetNewAuthorizables();
boolean that_present_newAuthorizables = true && that.isSetNewAuthorizables();
if (this_present_newAuthorizables || that_present_newAuthorizables) {
if (!(this_present_newAuthorizables && that_present_newAuthorizables))
return false;
if (!this.newAuthorizables.equals(that.newAuthorizables))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_protocol_version = true;
list.add(present_protocol_version);
if (present_protocol_version)
list.add(protocol_version);
boolean present_requestorUserName = true && (isSetRequestorUserName());
list.add(present_requestorUserName);
if (present_requestorUserName)
list.add(requestorUserName);
boolean present_component = true && (isSetComponent());
list.add(present_component);
if (present_component)
list.add(component);
boolean present_serviceName = true && (isSetServiceName());
list.add(present_serviceName);
if (present_serviceName)
list.add(serviceName);
boolean present_oldAuthorizables = true && (isSetOldAuthorizables());
list.add(present_oldAuthorizables);
if (present_oldAuthorizables)
list.add(oldAuthorizables);
boolean present_newAuthorizables = true && (isSetNewAuthorizables());
list.add(present_newAuthorizables);
if (present_newAuthorizables)
list.add(newAuthorizables);
return list.hashCode();
}
@Override
public int compareTo(TRenamePrivilegesRequest other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetProtocol_version()).compareTo(other.isSetProtocol_version());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetProtocol_version()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.protocol_version, other.protocol_version);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetRequestorUserName()).compareTo(other.isSetRequestorUserName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetRequestorUserName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.requestorUserName, other.requestorUserName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetComponent()).compareTo(other.isSetComponent());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetComponent()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.component, other.component);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetServiceName()).compareTo(other.isSetServiceName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetServiceName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.serviceName, other.serviceName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetOldAuthorizables()).compareTo(other.isSetOldAuthorizables());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetOldAuthorizables()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.oldAuthorizables, other.oldAuthorizables);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetNewAuthorizables()).compareTo(other.isSetNewAuthorizables());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetNewAuthorizables()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.newAuthorizables, other.newAuthorizables);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("TRenamePrivilegesRequest(");
boolean first = true;
sb.append("protocol_version:");
sb.append(this.protocol_version);
first = false;
if (!first) sb.append(", ");
sb.append("requestorUserName:");
if (this.requestorUserName == null) {
sb.append("null");
} else {
sb.append(this.requestorUserName);
}
first = false;
if (!first) sb.append(", ");
sb.append("component:");
if (this.component == null) {
sb.append("null");
} else {
sb.append(this.component);
}
first = false;
if (!first) sb.append(", ");
sb.append("serviceName:");
if (this.serviceName == null) {
sb.append("null");
} else {
sb.append(this.serviceName);
}
first = false;
if (!first) sb.append(", ");
sb.append("oldAuthorizables:");
if (this.oldAuthorizables == null) {
sb.append("null");
} else {
sb.append(this.oldAuthorizables);
}
first = false;
if (!first) sb.append(", ");
sb.append("newAuthorizables:");
if (this.newAuthorizables == null) {
sb.append("null");
} else {
sb.append(this.newAuthorizables);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
if (!isSetProtocol_version()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'protocol_version' is unset! Struct:" + toString());
}
if (!isSetRequestorUserName()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'requestorUserName' is unset! Struct:" + toString());
}
if (!isSetComponent()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'component' is unset! Struct:" + toString());
}
if (!isSetServiceName()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'serviceName' is unset! Struct:" + toString());
}
if (!isSetOldAuthorizables()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'oldAuthorizables' is unset! Struct:" + toString());
}
if (!isSetNewAuthorizables()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'newAuthorizables' 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, 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 TRenamePrivilegesRequestStandardSchemeFactory implements SchemeFactory {
public TRenamePrivilegesRequestStandardScheme getScheme() {
return new TRenamePrivilegesRequestStandardScheme();
}
}
private static class TRenamePrivilegesRequestStandardScheme extends StandardScheme<TRenamePrivilegesRequest> {
public void read(org.apache.thrift.protocol.TProtocol iprot, TRenamePrivilegesRequest 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: // PROTOCOL_VERSION
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.protocol_version = iprot.readI32();
struct.setProtocol_versionIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // REQUESTOR_USER_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.requestorUserName = iprot.readString();
struct.setRequestorUserNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // COMPONENT
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.component = iprot.readString();
struct.setComponentIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // SERVICE_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.serviceName = iprot.readString();
struct.setServiceNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 5: // OLD_AUTHORIZABLES
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list56 = iprot.readListBegin();
struct.oldAuthorizables = new ArrayList<TAuthorizable>(_list56.size);
TAuthorizable _elem57;
for (int _i58 = 0; _i58 < _list56.size; ++_i58)
{
_elem57 = new TAuthorizable();
_elem57.read(iprot);
struct.oldAuthorizables.add(_elem57);
}
iprot.readListEnd();
}
struct.setOldAuthorizablesIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 6: // NEW_AUTHORIZABLES
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list59 = iprot.readListBegin();
struct.newAuthorizables = new ArrayList<TAuthorizable>(_list59.size);
TAuthorizable _elem60;
for (int _i61 = 0; _i61 < _list59.size; ++_i61)
{
_elem60 = new TAuthorizable();
_elem60.read(iprot);
struct.newAuthorizables.add(_elem60);
}
iprot.readListEnd();
}
struct.setNewAuthorizablesIsSet(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, TRenamePrivilegesRequest struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(PROTOCOL_VERSION_FIELD_DESC);
oprot.writeI32(struct.protocol_version);
oprot.writeFieldEnd();
if (struct.requestorUserName != null) {
oprot.writeFieldBegin(REQUESTOR_USER_NAME_FIELD_DESC);
oprot.writeString(struct.requestorUserName);
oprot.writeFieldEnd();
}
if (struct.component != null) {
oprot.writeFieldBegin(COMPONENT_FIELD_DESC);
oprot.writeString(struct.component);
oprot.writeFieldEnd();
}
if (struct.serviceName != null) {
oprot.writeFieldBegin(SERVICE_NAME_FIELD_DESC);
oprot.writeString(struct.serviceName);
oprot.writeFieldEnd();
}
if (struct.oldAuthorizables != null) {
oprot.writeFieldBegin(OLD_AUTHORIZABLES_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.oldAuthorizables.size()));
for (TAuthorizable _iter62 : struct.oldAuthorizables)
{
_iter62.write(oprot);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
if (struct.newAuthorizables != null) {
oprot.writeFieldBegin(NEW_AUTHORIZABLES_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.newAuthorizables.size()));
for (TAuthorizable _iter63 : struct.newAuthorizables)
{
_iter63.write(oprot);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class TRenamePrivilegesRequestTupleSchemeFactory implements SchemeFactory {
public TRenamePrivilegesRequestTupleScheme getScheme() {
return new TRenamePrivilegesRequestTupleScheme();
}
}
private static class TRenamePrivilegesRequestTupleScheme extends TupleScheme<TRenamePrivilegesRequest> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, TRenamePrivilegesRequest struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
oprot.writeI32(struct.protocol_version);
oprot.writeString(struct.requestorUserName);
oprot.writeString(struct.component);
oprot.writeString(struct.serviceName);
{
oprot.writeI32(struct.oldAuthorizables.size());
for (TAuthorizable _iter64 : struct.oldAuthorizables)
{
_iter64.write(oprot);
}
}
{
oprot.writeI32(struct.newAuthorizables.size());
for (TAuthorizable _iter65 : struct.newAuthorizables)
{
_iter65.write(oprot);
}
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, TRenamePrivilegesRequest struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
struct.protocol_version = iprot.readI32();
struct.setProtocol_versionIsSet(true);
struct.requestorUserName = iprot.readString();
struct.setRequestorUserNameIsSet(true);
struct.component = iprot.readString();
struct.setComponentIsSet(true);
struct.serviceName = iprot.readString();
struct.setServiceNameIsSet(true);
{
org.apache.thrift.protocol.TList _list66 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
struct.oldAuthorizables = new ArrayList<TAuthorizable>(_list66.size);
TAuthorizable _elem67;
for (int _i68 = 0; _i68 < _list66.size; ++_i68)
{
_elem67 = new TAuthorizable();
_elem67.read(iprot);
struct.oldAuthorizables.add(_elem67);
}
}
struct.setOldAuthorizablesIsSet(true);
{
org.apache.thrift.protocol.TList _list69 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
struct.newAuthorizables = new ArrayList<TAuthorizable>(_list69.size);
TAuthorizable _elem70;
for (int _i71 = 0; _i71 < _list69.size; ++_i71)
{
_elem70 = new TAuthorizable();
_elem70.read(iprot);
struct.newAuthorizables.add(_elem70);
}
}
struct.setNewAuthorizablesIsSet(true);
}
}
}
|
googleapis/google-cloud-java | 35,714 | java-dataplex/proto-google-cloud-dataplex-v1/src/main/java/com/google/cloud/dataplex/v1/UpdateEncryptionConfigRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dataplex/v1/cmek.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dataplex.v1;
/**
*
*
* <pre>
* Update EncryptionConfig Request
* </pre>
*
* Protobuf type {@code google.cloud.dataplex.v1.UpdateEncryptionConfigRequest}
*/
public final class UpdateEncryptionConfigRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dataplex.v1.UpdateEncryptionConfigRequest)
UpdateEncryptionConfigRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateEncryptionConfigRequest.newBuilder() to construct.
private UpdateEncryptionConfigRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateEncryptionConfigRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateEncryptionConfigRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dataplex.v1.CmekProto
.internal_static_google_cloud_dataplex_v1_UpdateEncryptionConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataplex.v1.CmekProto
.internal_static_google_cloud_dataplex_v1_UpdateEncryptionConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest.class,
com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest.Builder.class);
}
private int bitField0_;
public static final int ENCRYPTION_CONFIG_FIELD_NUMBER = 1;
private com.google.cloud.dataplex.v1.EncryptionConfig encryptionConfig_;
/**
*
*
* <pre>
* Required. The EncryptionConfig to update.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EncryptionConfig encryption_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the encryptionConfig field is set.
*/
@java.lang.Override
public boolean hasEncryptionConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The EncryptionConfig to update.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EncryptionConfig encryption_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The encryptionConfig.
*/
@java.lang.Override
public com.google.cloud.dataplex.v1.EncryptionConfig getEncryptionConfig() {
return encryptionConfig_ == null
? com.google.cloud.dataplex.v1.EncryptionConfig.getDefaultInstance()
: encryptionConfig_;
}
/**
*
*
* <pre>
* Required. The EncryptionConfig to update.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EncryptionConfig encryption_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.dataplex.v1.EncryptionConfigOrBuilder getEncryptionConfigOrBuilder() {
return encryptionConfig_ == null
? com.google.cloud.dataplex.v1.EncryptionConfig.getDefaultInstance()
: encryptionConfig_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Optional. Mask of fields to update.
* The service treats an omitted field mask as an implied field mask
* equivalent to all fields that are populated (have a non-empty value).
* </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. Mask of fields to update.
* The service treats an omitted field mask as an implied field mask
* equivalent to all fields that are populated (have a non-empty value).
* </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. Mask of fields to update.
* The service treats an omitted field mask as an implied field mask
* equivalent to all fields that are populated (have a non-empty value).
* </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, getEncryptionConfig());
}
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, getEncryptionConfig());
}
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.dataplex.v1.UpdateEncryptionConfigRequest)) {
return super.equals(obj);
}
com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest other =
(com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest) obj;
if (hasEncryptionConfig() != other.hasEncryptionConfig()) return false;
if (hasEncryptionConfig()) {
if (!getEncryptionConfig().equals(other.getEncryptionConfig())) 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 (hasEncryptionConfig()) {
hash = (37 * hash) + ENCRYPTION_CONFIG_FIELD_NUMBER;
hash = (53 * hash) + getEncryptionConfig().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.dataplex.v1.UpdateEncryptionConfigRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Update EncryptionConfig Request
* </pre>
*
* Protobuf type {@code google.cloud.dataplex.v1.UpdateEncryptionConfigRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dataplex.v1.UpdateEncryptionConfigRequest)
com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dataplex.v1.CmekProto
.internal_static_google_cloud_dataplex_v1_UpdateEncryptionConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataplex.v1.CmekProto
.internal_static_google_cloud_dataplex_v1_UpdateEncryptionConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest.class,
com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest.Builder.class);
}
// Construct using com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getEncryptionConfigFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
encryptionConfig_ = null;
if (encryptionConfigBuilder_ != null) {
encryptionConfigBuilder_.dispose();
encryptionConfigBuilder_ = 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.dataplex.v1.CmekProto
.internal_static_google_cloud_dataplex_v1_UpdateEncryptionConfigRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest getDefaultInstanceForType() {
return com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest build() {
com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest buildPartial() {
com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest result =
new com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.encryptionConfig_ =
encryptionConfigBuilder_ == null ? encryptionConfig_ : encryptionConfigBuilder_.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.dataplex.v1.UpdateEncryptionConfigRequest) {
return mergeFrom((com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest other) {
if (other == com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest.getDefaultInstance())
return this;
if (other.hasEncryptionConfig()) {
mergeEncryptionConfig(other.getEncryptionConfig());
}
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(
getEncryptionConfigFieldBuilder().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.dataplex.v1.EncryptionConfig encryptionConfig_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataplex.v1.EncryptionConfig,
com.google.cloud.dataplex.v1.EncryptionConfig.Builder,
com.google.cloud.dataplex.v1.EncryptionConfigOrBuilder>
encryptionConfigBuilder_;
/**
*
*
* <pre>
* Required. The EncryptionConfig to update.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EncryptionConfig encryption_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the encryptionConfig field is set.
*/
public boolean hasEncryptionConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The EncryptionConfig to update.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EncryptionConfig encryption_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The encryptionConfig.
*/
public com.google.cloud.dataplex.v1.EncryptionConfig getEncryptionConfig() {
if (encryptionConfigBuilder_ == null) {
return encryptionConfig_ == null
? com.google.cloud.dataplex.v1.EncryptionConfig.getDefaultInstance()
: encryptionConfig_;
} else {
return encryptionConfigBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The EncryptionConfig to update.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EncryptionConfig encryption_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setEncryptionConfig(com.google.cloud.dataplex.v1.EncryptionConfig value) {
if (encryptionConfigBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
encryptionConfig_ = value;
} else {
encryptionConfigBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The EncryptionConfig to update.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EncryptionConfig encryption_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setEncryptionConfig(
com.google.cloud.dataplex.v1.EncryptionConfig.Builder builderForValue) {
if (encryptionConfigBuilder_ == null) {
encryptionConfig_ = builderForValue.build();
} else {
encryptionConfigBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The EncryptionConfig to update.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EncryptionConfig encryption_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeEncryptionConfig(com.google.cloud.dataplex.v1.EncryptionConfig value) {
if (encryptionConfigBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& encryptionConfig_ != null
&& encryptionConfig_
!= com.google.cloud.dataplex.v1.EncryptionConfig.getDefaultInstance()) {
getEncryptionConfigBuilder().mergeFrom(value);
} else {
encryptionConfig_ = value;
}
} else {
encryptionConfigBuilder_.mergeFrom(value);
}
if (encryptionConfig_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The EncryptionConfig to update.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EncryptionConfig encryption_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearEncryptionConfig() {
bitField0_ = (bitField0_ & ~0x00000001);
encryptionConfig_ = null;
if (encryptionConfigBuilder_ != null) {
encryptionConfigBuilder_.dispose();
encryptionConfigBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The EncryptionConfig to update.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EncryptionConfig encryption_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.dataplex.v1.EncryptionConfig.Builder getEncryptionConfigBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getEncryptionConfigFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The EncryptionConfig to update.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EncryptionConfig encryption_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.dataplex.v1.EncryptionConfigOrBuilder getEncryptionConfigOrBuilder() {
if (encryptionConfigBuilder_ != null) {
return encryptionConfigBuilder_.getMessageOrBuilder();
} else {
return encryptionConfig_ == null
? com.google.cloud.dataplex.v1.EncryptionConfig.getDefaultInstance()
: encryptionConfig_;
}
}
/**
*
*
* <pre>
* Required. The EncryptionConfig to update.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EncryptionConfig encryption_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataplex.v1.EncryptionConfig,
com.google.cloud.dataplex.v1.EncryptionConfig.Builder,
com.google.cloud.dataplex.v1.EncryptionConfigOrBuilder>
getEncryptionConfigFieldBuilder() {
if (encryptionConfigBuilder_ == null) {
encryptionConfigBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataplex.v1.EncryptionConfig,
com.google.cloud.dataplex.v1.EncryptionConfig.Builder,
com.google.cloud.dataplex.v1.EncryptionConfigOrBuilder>(
getEncryptionConfig(), getParentForChildren(), isClean());
encryptionConfig_ = null;
}
return encryptionConfigBuilder_;
}
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. Mask of fields to update.
* The service treats an omitted field mask as an implied field mask
* equivalent to all fields that are populated (have a non-empty value).
* </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. Mask of fields to update.
* The service treats an omitted field mask as an implied field mask
* equivalent to all fields that are populated (have a non-empty value).
* </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. Mask of fields to update.
* The service treats an omitted field mask as an implied field mask
* equivalent to all fields that are populated (have a non-empty value).
* </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. Mask of fields to update.
* The service treats an omitted field mask as an implied field mask
* equivalent to all fields that are populated (have a non-empty value).
* </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. Mask of fields to update.
* The service treats an omitted field mask as an implied field mask
* equivalent to all fields that are populated (have a non-empty value).
* </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. Mask of fields to update.
* The service treats an omitted field mask as an implied field mask
* equivalent to all fields that are populated (have a non-empty value).
* </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. Mask of fields to update.
* The service treats an omitted field mask as an implied field mask
* equivalent to all fields that are populated (have a non-empty value).
* </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. Mask of fields to update.
* The service treats an omitted field mask as an implied field mask
* equivalent to all fields that are populated (have a non-empty value).
* </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. Mask of fields to update.
* The service treats an omitted field mask as an implied field mask
* equivalent to all fields that are populated (have a non-empty value).
* </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.dataplex.v1.UpdateEncryptionConfigRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.dataplex.v1.UpdateEncryptionConfigRequest)
private static final com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest();
}
public static com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateEncryptionConfigRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateEncryptionConfigRequest>() {
@java.lang.Override
public UpdateEncryptionConfigRequest 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<UpdateEncryptionConfigRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateEncryptionConfigRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dataplex.v1.UpdateEncryptionConfigRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/ignite | 35,885 | modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/LogicalRelImplementor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.query.calcite.exec;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.apache.calcite.rel.RelCollation;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Intersect;
import org.apache.calcite.rel.core.JoinRelType;
import org.apache.calcite.rel.core.Minus;
import org.apache.calcite.rel.core.Spool;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.util.ImmutableBitSet;
import org.apache.ignite.internal.processors.failure.FailureProcessor;
import org.apache.ignite.internal.processors.query.QueryUtils;
import org.apache.ignite.internal.processors.query.calcite.exec.RowHandler.RowFactory;
import org.apache.ignite.internal.processors.query.calcite.exec.exp.ExpressionFactory;
import org.apache.ignite.internal.processors.query.calcite.exec.exp.RangeIterable;
import org.apache.ignite.internal.processors.query.calcite.exec.exp.agg.AccumulatorWrapper;
import org.apache.ignite.internal.processors.query.calcite.exec.exp.agg.AggregateType;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.AbstractSetOpNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.CollectNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.CorrelatedNestedLoopJoinNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.FilterNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.HashAggregateNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.Inbox;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.IndexSpoolNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.IntersectNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.LimitNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.MergeJoinNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.MinusNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.ModifyNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.NestedLoopJoinNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.Node;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.Outbox;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.ProjectNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.ScanNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.ScanStorageNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.SortAggregateNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.SortNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.TableSpoolNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.UncollectNode;
import org.apache.ignite.internal.processors.query.calcite.exec.rel.UnionAllNode;
import org.apache.ignite.internal.processors.query.calcite.metadata.AffinityService;
import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
import org.apache.ignite.internal.processors.query.calcite.prepare.bounds.SearchBounds;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteCollect;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteCorrelatedNestedLoopJoin;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteExchange;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteFilter;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteHashIndexSpool;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteIndexBound;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteIndexCount;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteIndexScan;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteLimit;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteMergeJoin;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteNestedLoopJoin;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteProject;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteReceiver;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteRel;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteRelVisitor;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteSender;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteSort;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteSortedIndexSpool;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteTableFunctionScan;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteTableModify;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteTableScan;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteTableSpool;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteTrimExchange;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteUncollect;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteUnionAll;
import org.apache.ignite.internal.processors.query.calcite.rel.IgniteValues;
import org.apache.ignite.internal.processors.query.calcite.rel.agg.IgniteColocatedHashAggregate;
import org.apache.ignite.internal.processors.query.calcite.rel.agg.IgniteColocatedSortAggregate;
import org.apache.ignite.internal.processors.query.calcite.rel.agg.IgniteMapHashAggregate;
import org.apache.ignite.internal.processors.query.calcite.rel.agg.IgniteMapSortAggregate;
import org.apache.ignite.internal.processors.query.calcite.rel.agg.IgniteReduceHashAggregate;
import org.apache.ignite.internal.processors.query.calcite.rel.agg.IgniteReduceSortAggregate;
import org.apache.ignite.internal.processors.query.calcite.rel.set.IgniteSetOp;
import org.apache.ignite.internal.processors.query.calcite.rule.LogicalScanConverterRule;
import org.apache.ignite.internal.processors.query.calcite.schema.CacheTableDescriptor;
import org.apache.ignite.internal.processors.query.calcite.schema.IgniteIndex;
import org.apache.ignite.internal.processors.query.calcite.schema.IgniteTable;
import org.apache.ignite.internal.processors.query.calcite.trait.Destination;
import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution;
import org.apache.ignite.internal.processors.query.calcite.trait.TraitUtils;
import org.apache.ignite.internal.processors.query.calcite.type.IgniteTypeFactory;
import org.apache.ignite.internal.processors.query.calcite.util.Commons;
import org.apache.ignite.internal.processors.query.calcite.util.RexUtils;
import org.apache.ignite.internal.util.typedef.F;
import static org.apache.calcite.rel.RelDistribution.Type.HASH_DISTRIBUTED;
import static org.apache.calcite.sql.SqlKind.IS_DISTINCT_FROM;
import static org.apache.calcite.sql.SqlKind.IS_NOT_DISTINCT_FROM;
import static org.apache.ignite.internal.processors.query.calcite.util.TypeUtils.combinedRowType;
/**
* Implements a query plan.
*/
@SuppressWarnings("TypeMayBeWeakened")
public class LogicalRelImplementor<Row> implements IgniteRelVisitor<Node<Row>> {
/** */
public static final String CNLJ_NOT_SUPPORTED_JOIN_ASSERTION_MSG = "only INNER and LEFT join supported by IgniteCorrelatedNestedLoop";
/** */
private final ExecutionContext<Row> ctx;
/** */
private final AffinityService affSrvc;
/** */
private final ExchangeService exchangeSvc;
/** */
private final MailboxRegistry mailboxRegistry;
/** */
private final ExpressionFactory<Row> expressionFactory;
/**
* @param ctx Root context.
* @param affSrvc Affinity service.
* @param mailboxRegistry Mailbox registry.
* @param exchangeSvc Exchange service.
* @param failure Failure processor.
*/
public LogicalRelImplementor(
ExecutionContext<Row> ctx,
AffinityService affSrvc,
MailboxRegistry mailboxRegistry,
ExchangeService exchangeSvc,
FailureProcessor failure
) {
this.affSrvc = affSrvc;
this.mailboxRegistry = mailboxRegistry;
this.exchangeSvc = exchangeSvc;
this.ctx = ctx;
expressionFactory = ctx.expressionFactory();
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteSender rel) {
IgniteDistribution distribution = rel.distribution();
Destination<Row> dest = distribution.destination(ctx, affSrvc, ctx.target());
// Outbox fragment ID is used as exchange ID as well.
Outbox<Row> outbox =
new Outbox<>(ctx, rel.getRowType(), exchangeSvc, mailboxRegistry, rel.exchangeId(), rel.targetFragmentId(), dest);
Node<Row> input = visit(rel.getInput());
if (distribution.function().affinity()) { // Affinity key can't be null, so filter out null values.
assert distribution.getKeys().size() == 1 : "Unexpected affinity keys count: " +
distribution.getKeys().size() + ", must be 1";
int affKey = distribution.getKeys().get(0);
RelDataTypeField affFld = rel.getRowType().getFieldList().get(affKey);
assert affFld != null : "Unexpected affinity key field: " + affKey;
if (affFld.getType().isNullable()) {
FilterNode<Row> filter = new FilterNode<>(ctx, rel.getRowType(),
r -> ctx.rowHandler().get(affKey, r) != null);
filter.register(input);
input = filter;
}
}
outbox.register(input);
mailboxRegistry.register(outbox);
return outbox;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteFilter rel) {
Predicate<Row> pred = expressionFactory.predicate(rel.getCondition(), rel.getRowType());
FilterNode<Row> node = new FilterNode<>(ctx, rel.getRowType(), pred);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteTrimExchange rel) {
assert TraitUtils.distribution(rel).getType() == HASH_DISTRIBUTED;
IgniteDistribution distr = rel.distribution();
Destination<Row> dest = distr.destination(ctx, affSrvc, ctx.group(rel.sourceId()));
UUID locNodeId = ctx.localNodeId();
FilterNode<Row> node = new FilterNode<>(ctx, rel.getRowType(), r -> Objects.equals(locNodeId, F.first(dest.targets(r))));
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteProject rel) {
Function<Row, Row> prj = expressionFactory.project(rel.getProjects(), rel.getInput().getRowType());
ProjectNode<Row> node = new ProjectNode<>(ctx, rel.getRowType(), prj);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteNestedLoopJoin rel) {
RelDataType outType = rel.getRowType();
RelDataType leftType = rel.getLeft().getRowType();
RelDataType rightType = rel.getRight().getRowType();
JoinRelType joinType = rel.getJoinType();
RelDataType rowType = combinedRowType(ctx.getTypeFactory(), leftType, rightType);
BiPredicate<Row, Row> cond = expressionFactory.biPredicate(rel.getCondition(), rowType);
Node<Row> node = NestedLoopJoinNode.create(ctx, outType, leftType, rightType, joinType, cond);
Node<Row> leftInput = visit(rel.getLeft());
Node<Row> rightInput = visit(rel.getRight());
node.register(F.asList(leftInput, rightInput));
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteCorrelatedNestedLoopJoin rel) {
RelDataType outType = rel.getRowType();
RelDataType leftType = rel.getLeft().getRowType();
RelDataType rightType = rel.getRight().getRowType();
RelDataType rowType = combinedRowType(ctx.getTypeFactory(), leftType, rightType);
BiPredicate<Row, Row> cond = expressionFactory.biPredicate(rel.getCondition(), rowType);
assert rel.getJoinType() == JoinRelType.INNER || rel.getJoinType() == JoinRelType.LEFT
: CNLJ_NOT_SUPPORTED_JOIN_ASSERTION_MSG;
Node<Row> node = new CorrelatedNestedLoopJoinNode<>(ctx, outType, cond, rel.getVariablesSet(),
rel.getJoinType());
Node<Row> leftInput = visit(rel.getLeft());
Node<Row> rightInput = visit(rel.getRight());
node.register(F.asList(leftInput, rightInput));
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteMergeJoin rel) {
RelDataType outType = rel.getRowType();
RelDataType leftType = rel.getLeft().getRowType();
RelDataType rightType = rel.getRight().getRowType();
JoinRelType joinType = rel.getJoinType();
int pairsCnt = rel.analyzeCondition().pairs().size();
Comparator<Row> comp = expressionFactory.comparator(
rel.leftCollation().getFieldCollations().subList(0, pairsCnt),
rel.rightCollation().getFieldCollations().subList(0, pairsCnt),
rel.getCondition().getKind() == IS_NOT_DISTINCT_FROM || rel.getCondition().getKind() == IS_DISTINCT_FROM
);
Node<Row> node = MergeJoinNode.create(ctx, outType, leftType, rightType, joinType, comp, hasExchange(rel));
Node<Row> leftInput = visit(rel.getLeft());
Node<Row> rightInput = visit(rel.getRight());
node.register(F.asList(leftInput, rightInput));
return node;
}
/** */
private boolean hasExchange(RelNode rel) {
if (rel instanceof IgniteReceiver)
return true;
for (RelNode in : rel.getInputs()) {
if (hasExchange(in))
return true;
}
return false;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteIndexScan rel) {
RexNode condition = rel.condition();
List<RexNode> projects = rel.projects();
IgniteTable tbl = rel.getTable().unwrap(IgniteTable.class);
IgniteTypeFactory typeFactory = ctx.getTypeFactory();
ImmutableBitSet requiredColumns = rel.requiredColumns();
List<SearchBounds> searchBounds = rel.searchBounds();
RelDataType rowType = tbl.getRowType(typeFactory, requiredColumns);
Predicate<Row> filters = condition == null ? null : expressionFactory.predicate(condition, rowType);
Function<Row, Row> prj = projects == null ? null : expressionFactory.project(projects, rowType);
RangeIterable<Row> ranges = searchBounds == null ? null :
expressionFactory.ranges(searchBounds, rel.collation(), tbl.getRowType(typeFactory));
ColocationGroup grp = ctx.group(rel.sourceId());
IgniteIndex idx = tbl.getIndex(rel.indexName());
if (idx != null && !tbl.isIndexRebuildInProgress()) {
Iterable<Row> rowsIter = idx.scan(ctx, grp, ranges, requiredColumns);
return new ScanStorageNode<>(tbl.name() + '.' + idx.name(), ctx, rowType, rowsIter, filters, prj);
}
else {
// Index was invalidated after planning, workaround through table-scan -> sort -> index spool.
// If there are correlates in filter or project, spool node is required to provide ability to rewind input.
// Sort node is required if output should be sorted or if spool node required (to provide search by
// index conditions).
// Additionally, project node is required in case of spool inserted, since spool requires unmodified
// original input for filtering by index conditions.
boolean filterHasCorrelation = condition != null && RexUtils.hasCorrelation(condition);
boolean projectHasCorrelation = projects != null && RexUtils.hasCorrelation(projects);
boolean spoolNodeRequired = projectHasCorrelation || filterHasCorrelation;
boolean projNodeRequired = projects != null && spoolNodeRequired;
Iterable<Row> rowsIter = tbl.scan(
ctx,
grp,
requiredColumns
);
// If there are projects in the scan node - after the scan we already have target row type.
if (!spoolNodeRequired && projects != null)
rowType = rel.getRowType();
Node<Row> node = new ScanStorageNode<>(tbl.name(), ctx, rowType, rowsIter, filterHasCorrelation ? null : filters,
projNodeRequired ? null : prj);
RelCollation collation = rel.collation();
if ((!spoolNodeRequired && projects != null) || requiredColumns != null) {
collation = collation.apply(LogicalScanConverterRule.createMapping(
spoolNodeRequired ? null : projects,
requiredColumns,
tbl.getRowType(typeFactory).getFieldCount()
));
}
boolean sortNodeRequired = !collation.getFieldCollations().isEmpty();
if (sortNodeRequired) {
SortNode<Row> sortNode = new SortNode<>(ctx, rowType, expressionFactory.comparator(collation));
sortNode.register(node);
node = sortNode;
}
if (spoolNodeRequired) {
if (searchBounds != null && requiredColumns != null) {
// Remap index find predicate according to rowType of the spool.
List<SearchBounds> remappedSearchBounds = new ArrayList<>(requiredColumns.cardinality());
for (int i = requiredColumns.nextSetBit(0); i != -1; i = requiredColumns.nextSetBit(i + 1))
remappedSearchBounds.add(searchBounds.get(i));
// Collation and row type are already remapped taking into account requiredColumns.
ranges = expressionFactory.ranges(remappedSearchBounds, collation, rowType);
}
IndexSpoolNode<Row> spoolNode = IndexSpoolNode.createTreeSpool(
ctx,
rowType,
collation,
expressionFactory.comparator(collation),
filterHasCorrelation ? filters : null, // Not correlated filter included into table scan.
ranges
);
spoolNode.register(node);
node = spoolNode;
}
if (projNodeRequired) {
ProjectNode<Row> projectNode = new ProjectNode<>(ctx, rel.getRowType(), prj);
projectNode.register(node);
node = projectNode;
}
return node;
}
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteIndexCount rel) {
IgniteTable tbl = rel.getTable().unwrap(IgniteTable.class);
IgniteIndex idx = tbl.getIndex(rel.indexName());
if (idx != null && !tbl.isIndexRebuildInProgress()) {
return new ScanStorageNode<>(tbl.name() + '.' + idx.name() + "_COUNT", ctx, rel.getRowType(),
idx.count(ctx, ctx.group(rel.sourceId()), rel.notNull()));
}
else {
CollectNode<Row> replacement = CollectNode.createCountCollector(ctx);
replacement.register(
new ScanStorageNode<>(
tbl.name(),
ctx,
rel.getTable().getRowType(),
tbl.scan(ctx, ctx.group(rel.sourceId()), ImmutableBitSet.of(rel.fieldIndex())),
rel.notNull() ? r -> ctx.rowHandler().get(0, r) != null : null,
null
)
);
return replacement;
}
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteIndexBound idxBndRel) {
IgniteTable tbl = idxBndRel.getTable().unwrap(IgniteTable.class);
IgniteIndex idx = tbl.getIndex(idxBndRel.indexName());
IgniteTypeFactory typeFactory = ctx.getTypeFactory();
ColocationGroup grp = ctx.group(idxBndRel.sourceId());
ImmutableBitSet requiredColumns = idxBndRel.requiredColumns();
RelDataType rowType = tbl.getRowType(typeFactory, requiredColumns);
if (idx != null && !tbl.isIndexRebuildInProgress()) {
return new ScanStorageNode<>(tbl.name() + '.' + idx.name() + "_BOUND", ctx, rowType,
idx.firstOrLast(idxBndRel.first(), ctx, grp, requiredColumns));
}
else {
assert requiredColumns.cardinality() == 1;
Iterable<Row> rowsIter = tbl.scan(ctx, grp, idxBndRel.requiredColumns());
Node<Row> scanNode = new ScanStorageNode<>(tbl.name(), ctx, rowType, rowsIter,
r -> ctx.rowHandler().get(0, r) != null, null);
RelCollation collation = idx.collation().apply(LogicalScanConverterRule.createMapping(
null,
requiredColumns,
tbl.getRowType(typeFactory).getFieldCount()
));
Comparator<Row> cmp = expressionFactory.comparator(collation);
assert cmp != null;
SortNode<Row> sortNode = new SortNode<>(
ctx,
rowType,
idxBndRel.first() ? cmp : cmp.reversed(),
null,
() -> 1
);
sortNode.register(scanNode);
return sortNode;
}
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteTableScan rel) {
RexNode condition = rel.condition();
List<RexNode> projects = rel.projects();
ImmutableBitSet requiredColumns = rel.requiredColumns();
IgniteTable tbl = rel.getTable().unwrap(IgniteTable.class);
IgniteTypeFactory typeFactory = ctx.getTypeFactory();
RelDataType rowType = tbl.getRowType(typeFactory, requiredColumns);
Predicate<Row> filters = condition == null ? null : expressionFactory.predicate(condition, rowType);
Function<Row, Row> prj = projects == null ? null : expressionFactory.project(projects, rowType);
ColocationGroup grp = ctx.group(rel.sourceId());
IgniteIndex idx = tbl.getIndex(QueryUtils.PRIMARY_KEY_INDEX);
if (idx != null && !tbl.isIndexRebuildInProgress()) {
Iterable<Row> rowsIter = idx.scan(ctx, grp, null, requiredColumns);
return new ScanStorageNode<>(tbl.name() + '.' + idx.name(), ctx, rowType, rowsIter, filters, prj);
}
else {
Iterable<Row> rowsIter = tbl.scan(ctx, grp, requiredColumns);
return new ScanStorageNode<>(tbl.name(), ctx, rowType, rowsIter, filters, prj);
}
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteValues rel) {
List<RexLiteral> vals = Commons.flat(Commons.cast(rel.getTuples()));
RelDataType rowType = rel.getRowType();
return new ScanNode<>(ctx, rowType, expressionFactory.values(vals, rowType));
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteUnionAll rel) {
UnionAllNode<Row> node = new UnionAllNode<>(ctx, rel.getRowType());
List<Node<Row>> inputs = Commons.transform(rel.getInputs(), this::visit);
node.register(inputs);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteLimit rel) {
Supplier<Integer> offset = (rel.offset() == null) ? null : expressionFactory.execute(rel.offset());
Supplier<Integer> fetch = (rel.fetch() == null) ? null : expressionFactory.execute(rel.fetch());
LimitNode<Row> node = new LimitNode<>(ctx, rel.getRowType(), offset, fetch);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteSort rel) {
RelCollation collation = rel.getCollation();
Supplier<Integer> offset = (rel.offset == null) ? null : expressionFactory.execute(rel.offset);
Supplier<Integer> fetch = (rel.fetch == null) ? null : expressionFactory.execute(rel.fetch);
SortNode<Row> node = new SortNode<>(ctx, rel.getRowType(), expressionFactory.comparator(collation), offset,
fetch);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteTableSpool rel) {
TableSpoolNode<Row> node = new TableSpoolNode<>(ctx, rel.getRowType(), rel.readType == Spool.Type.LAZY);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteSortedIndexSpool rel) {
RelCollation collation = rel.collation();
assert rel.searchBounds() != null : rel;
Predicate<Row> filter = expressionFactory.predicate(rel.condition(), rel.getRowType());
RangeIterable<Row> ranges = expressionFactory.ranges(rel.searchBounds(), collation, rel.getRowType());
IndexSpoolNode<Row> node = IndexSpoolNode.createTreeSpool(
ctx,
rel.getRowType(),
collation,
expressionFactory.comparator(collation),
filter,
ranges
);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteHashIndexSpool rel) {
Supplier<Row> searchRow = expressionFactory.rowSource(rel.searchRow());
Predicate<Row> filter = expressionFactory.predicate(rel.condition(), rel.getRowType());
IndexSpoolNode<Row> node = IndexSpoolNode.createHashSpool(
ctx,
rel.getRowType(),
ImmutableBitSet.of(rel.keys()),
filter,
searchRow,
rel.allowNulls()
);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteSetOp rel) {
RelDataType rowType = rel.getRowType();
RowFactory<Row> rowFactory = ctx.rowHandler().factory(ctx.getTypeFactory(), rowType);
List<Node<Row>> inputs = Commons.transform(rel.getInputs(), this::visit);
AbstractSetOpNode<Row> node;
if (rel instanceof Minus)
node = new MinusNode<>(ctx, rowType, rel.aggregateType(), rel.all(), rowFactory);
else if (rel instanceof Intersect)
node = new IntersectNode<>(ctx, rowType, rel.aggregateType(), rel.all(), rowFactory, rel.getInputs().size());
else
throw new AssertionError();
node.register(inputs);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteTableFunctionScan rel) {
Supplier<Iterable<?>> dataSupplier = expressionFactory.execute(rel.getCall());
RelDataType rowType = rel.getRowType();
RowFactory<Row> rowFactory = ctx.rowHandler().factory(ctx.getTypeFactory(), rowType);
return new ScanNode<>(ctx, rowType, new TableFunctionScan<>(rowType, dataSupplier, rowFactory));
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteTableModify rel) {
switch (rel.getOperation()) {
case INSERT:
case UPDATE:
case DELETE:
case MERGE:
ModifyNode<Row> node = new ModifyNode<>(ctx, rel.getRowType(), rel.getTable().unwrap(CacheTableDescriptor.class),
rel.getOperation(), rel.getUpdateColumnList());
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
default:
throw new AssertionError();
}
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteReceiver rel) {
Inbox<Row> inbox = (Inbox<Row>)mailboxRegistry.register(
new Inbox<>(ctx, exchangeSvc, mailboxRegistry, rel.exchangeId(), rel.sourceFragmentId()));
// here may be an already created (to consume rows from remote nodes) inbox
// without proper context, we need to init it with a right one.
inbox.init(ctx, rel.getRowType(), ctx.remotes(rel.exchangeId()), expressionFactory.comparator(rel.collation()));
return inbox;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteColocatedHashAggregate rel) {
AggregateType type = AggregateType.SINGLE;
RelDataType rowType = rel.getRowType();
RelDataType inputType = rel.getInput().getRowType();
Supplier<List<AccumulatorWrapper<Row>>> accFactory = expressionFactory.accumulatorsFactory(
type, rel.getAggCallList(), inputType);
RowFactory<Row> rowFactory = ctx.rowHandler().factory(ctx.getTypeFactory(), rowType);
HashAggregateNode<Row> node = new HashAggregateNode<>(ctx, rowType, type, rel.getGroupSets(), accFactory, rowFactory);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteMapHashAggregate rel) {
AggregateType type = AggregateType.MAP;
RelDataType rowType = rel.getRowType();
RelDataType inputType = rel.getInput().getRowType();
Supplier<List<AccumulatorWrapper<Row>>> accFactory = expressionFactory.accumulatorsFactory(
type, rel.getAggCallList(), inputType);
RowFactory<Row> rowFactory = ctx.rowHandler().factory(ctx.getTypeFactory(), rowType);
HashAggregateNode<Row> node = new HashAggregateNode<>(ctx, rowType, type, rel.getGroupSets(), accFactory, rowFactory);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteReduceHashAggregate rel) {
AggregateType type = AggregateType.REDUCE;
RelDataType rowType = rel.getRowType();
Supplier<List<AccumulatorWrapper<Row>>> accFactory = expressionFactory.accumulatorsFactory(
type, rel.getAggregateCalls(), null);
RowFactory<Row> rowFactory = ctx.rowHandler().factory(ctx.getTypeFactory(), rowType);
HashAggregateNode<Row> node = new HashAggregateNode<>(ctx, rowType, type, rel.getGroupSets(), accFactory, rowFactory);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteColocatedSortAggregate rel) {
AggregateType type = AggregateType.SINGLE;
RelDataType rowType = rel.getRowType();
RelDataType inputType = rel.getInput().getRowType();
Supplier<List<AccumulatorWrapper<Row>>> accFactory = expressionFactory.accumulatorsFactory(
type,
rel.getAggCallList(),
inputType
);
RowFactory<Row> rowFactory = ctx.rowHandler().factory(ctx.getTypeFactory(), rowType);
SortAggregateNode<Row> node = new SortAggregateNode<>(
ctx,
rowType,
type,
rel.getGroupSet(),
accFactory,
rowFactory,
expressionFactory.comparator(rel.collation())
);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteMapSortAggregate rel) {
AggregateType type = AggregateType.MAP;
RelDataType rowType = rel.getRowType();
RelDataType inputType = rel.getInput().getRowType();
Supplier<List<AccumulatorWrapper<Row>>> accFactory = expressionFactory.accumulatorsFactory(
type,
rel.getAggCallList(),
inputType
);
RowFactory<Row> rowFactory = ctx.rowHandler().factory(ctx.getTypeFactory(), rowType);
SortAggregateNode<Row> node = new SortAggregateNode<>(
ctx,
rowType,
type,
rel.getGroupSet(),
accFactory,
rowFactory,
expressionFactory.comparator(rel.collation())
);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteReduceSortAggregate rel) {
AggregateType type = AggregateType.REDUCE;
RelDataType rowType = rel.getRowType();
Supplier<List<AccumulatorWrapper<Row>>> accFactory = expressionFactory.accumulatorsFactory(
type,
rel.getAggregateCalls(),
null
);
RowFactory<Row> rowFactory = ctx.rowHandler().factory(ctx.getTypeFactory(), rowType);
SortAggregateNode<Row> node = new SortAggregateNode<>(
ctx,
rowType,
type,
rel.getGroupSet(),
accFactory,
rowFactory,
expressionFactory.comparator(rel.collation())
);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteCollect rel) {
RelDataType outType = rel.getRowType();
CollectNode<Row> node = new CollectNode<>(ctx, outType);
Node<Row> input = visit(rel.getInput());
node.register(input);
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteUncollect rel) {
UncollectNode<Row> node = new UncollectNode<>(
ctx,
rel.getInput().getRowType(),
rel.getRowType(),
rel.withOrdinality
);
node.register(visit(rel.getInput()));
return node;
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteRel rel) {
return rel.accept(this);
}
/** {@inheritDoc} */
@Override public Node<Row> visit(IgniteExchange rel) {
throw new AssertionError();
}
/** */
private Node<Row> visit(RelNode rel) {
return visit((IgniteRel)rel);
}
/** */
public <T extends Node<Row>> T go(IgniteRel rel) {
return (T)visit(rel);
}
}
|
googleapis/google-cloud-java | 35,701 | java-run/proto-google-cloud-run-v2/src/main/java/com/google/cloud/run/v2/ResourceRequirements.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/run/v2/k8s.min.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.run.v2;
/**
*
*
* <pre>
* ResourceRequirements describes the compute resource requirements.
* </pre>
*
* Protobuf type {@code google.cloud.run.v2.ResourceRequirements}
*/
public final class ResourceRequirements extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.run.v2.ResourceRequirements)
ResourceRequirementsOrBuilder {
private static final long serialVersionUID = 0L;
// Use ResourceRequirements.newBuilder() to construct.
private ResourceRequirements(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ResourceRequirements() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ResourceRequirements();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.run.v2.K8sMinProto
.internal_static_google_cloud_run_v2_ResourceRequirements_descriptor;
}
@SuppressWarnings({"rawtypes"})
@java.lang.Override
protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection(
int number) {
switch (number) {
case 1:
return internalGetLimits();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.run.v2.K8sMinProto
.internal_static_google_cloud_run_v2_ResourceRequirements_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.run.v2.ResourceRequirements.class,
com.google.cloud.run.v2.ResourceRequirements.Builder.class);
}
public static final int LIMITS_FIELD_NUMBER = 1;
private static final class LimitsDefaultEntryHolder {
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.run.v2.K8sMinProto
.internal_static_google_cloud_run_v2_ResourceRequirements_LimitsEntry_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> limits_;
private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetLimits() {
if (limits_ == null) {
return com.google.protobuf.MapField.emptyMapField(LimitsDefaultEntryHolder.defaultEntry);
}
return limits_;
}
public int getLimitsCount() {
return internalGetLimits().getMap().size();
}
/**
*
*
* <pre>
* Only `memory` and `cpu` keys in the map are supported.
*
* <p>Notes:
* * The only supported values for CPU are '1', '2', '4', and '8'. Setting 4
* CPU requires at least 2Gi of memory. For more information, go to
* https://cloud.google.com/run/docs/configuring/cpu.
* * For supported 'memory' values and syntax, go to
* https://cloud.google.com/run/docs/configuring/memory-limits
* </pre>
*
* <code>map<string, string> limits = 1;</code>
*/
@java.lang.Override
public boolean containsLimits(java.lang.String key) {
if (key == null) {
throw new NullPointerException("map key");
}
return internalGetLimits().getMap().containsKey(key);
}
/** Use {@link #getLimitsMap()} instead. */
@java.lang.Override
@java.lang.Deprecated
public java.util.Map<java.lang.String, java.lang.String> getLimits() {
return getLimitsMap();
}
/**
*
*
* <pre>
* Only `memory` and `cpu` keys in the map are supported.
*
* <p>Notes:
* * The only supported values for CPU are '1', '2', '4', and '8'. Setting 4
* CPU requires at least 2Gi of memory. For more information, go to
* https://cloud.google.com/run/docs/configuring/cpu.
* * For supported 'memory' values and syntax, go to
* https://cloud.google.com/run/docs/configuring/memory-limits
* </pre>
*
* <code>map<string, string> limits = 1;</code>
*/
@java.lang.Override
public java.util.Map<java.lang.String, java.lang.String> getLimitsMap() {
return internalGetLimits().getMap();
}
/**
*
*
* <pre>
* Only `memory` and `cpu` keys in the map are supported.
*
* <p>Notes:
* * The only supported values for CPU are '1', '2', '4', and '8'. Setting 4
* CPU requires at least 2Gi of memory. For more information, go to
* https://cloud.google.com/run/docs/configuring/cpu.
* * For supported 'memory' values and syntax, go to
* https://cloud.google.com/run/docs/configuring/memory-limits
* </pre>
*
* <code>map<string, string> limits = 1;</code>
*/
@java.lang.Override
public /* nullable */ java.lang.String getLimitsOrDefault(
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 = internalGetLimits().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
*
*
* <pre>
* Only `memory` and `cpu` keys in the map are supported.
*
* <p>Notes:
* * The only supported values for CPU are '1', '2', '4', and '8'. Setting 4
* CPU requires at least 2Gi of memory. For more information, go to
* https://cloud.google.com/run/docs/configuring/cpu.
* * For supported 'memory' values and syntax, go to
* https://cloud.google.com/run/docs/configuring/memory-limits
* </pre>
*
* <code>map<string, string> limits = 1;</code>
*/
@java.lang.Override
public java.lang.String getLimitsOrThrow(java.lang.String key) {
if (key == null) {
throw new NullPointerException("map key");
}
java.util.Map<java.lang.String, java.lang.String> map = internalGetLimits().getMap();
if (!map.containsKey(key)) {
throw new java.lang.IllegalArgumentException();
}
return map.get(key);
}
public static final int CPU_IDLE_FIELD_NUMBER = 2;
private boolean cpuIdle_ = false;
/**
*
*
* <pre>
* Determines whether CPU is only allocated during requests (true by default).
* However, if ResourceRequirements is set, the caller must explicitly
* set this field to true to preserve the default behavior.
* </pre>
*
* <code>bool cpu_idle = 2;</code>
*
* @return The cpuIdle.
*/
@java.lang.Override
public boolean getCpuIdle() {
return cpuIdle_;
}
public static final int STARTUP_CPU_BOOST_FIELD_NUMBER = 3;
private boolean startupCpuBoost_ = false;
/**
*
*
* <pre>
* Determines whether CPU should be boosted on startup of a new container
* instance above the requested CPU threshold, this can help reduce cold-start
* latency.
* </pre>
*
* <code>bool startup_cpu_boost = 3;</code>
*
* @return The startupCpuBoost.
*/
@java.lang.Override
public boolean getStartupCpuBoost() {
return startupCpuBoost_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(
output, internalGetLimits(), LimitsDefaultEntryHolder.defaultEntry, 1);
if (cpuIdle_ != false) {
output.writeBool(2, cpuIdle_);
}
if (startupCpuBoost_ != false) {
output.writeBool(3, startupCpuBoost_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (java.util.Map.Entry<java.lang.String, java.lang.String> entry :
internalGetLimits().getMap().entrySet()) {
com.google.protobuf.MapEntry<java.lang.String, java.lang.String> limits__ =
LimitsDefaultEntryHolder.defaultEntry
.newBuilderForType()
.setKey(entry.getKey())
.setValue(entry.getValue())
.build();
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, limits__);
}
if (cpuIdle_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(2, cpuIdle_);
}
if (startupCpuBoost_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, startupCpuBoost_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.run.v2.ResourceRequirements)) {
return super.equals(obj);
}
com.google.cloud.run.v2.ResourceRequirements other =
(com.google.cloud.run.v2.ResourceRequirements) obj;
if (!internalGetLimits().equals(other.internalGetLimits())) return false;
if (getCpuIdle() != other.getCpuIdle()) return false;
if (getStartupCpuBoost() != other.getStartupCpuBoost()) 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 (!internalGetLimits().getMap().isEmpty()) {
hash = (37 * hash) + LIMITS_FIELD_NUMBER;
hash = (53 * hash) + internalGetLimits().hashCode();
}
hash = (37 * hash) + CPU_IDLE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getCpuIdle());
hash = (37 * hash) + STARTUP_CPU_BOOST_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getStartupCpuBoost());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.run.v2.ResourceRequirements parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.run.v2.ResourceRequirements parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.run.v2.ResourceRequirements parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.run.v2.ResourceRequirements parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.run.v2.ResourceRequirements parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.run.v2.ResourceRequirements parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.run.v2.ResourceRequirements parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.run.v2.ResourceRequirements parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.run.v2.ResourceRequirements parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.run.v2.ResourceRequirements parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.run.v2.ResourceRequirements parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.run.v2.ResourceRequirements parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.run.v2.ResourceRequirements 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>
* ResourceRequirements describes the compute resource requirements.
* </pre>
*
* Protobuf type {@code google.cloud.run.v2.ResourceRequirements}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.run.v2.ResourceRequirements)
com.google.cloud.run.v2.ResourceRequirementsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.run.v2.K8sMinProto
.internal_static_google_cloud_run_v2_ResourceRequirements_descriptor;
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection(
int number) {
switch (number) {
case 1:
return internalGetLimits();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapFieldReflectionAccessor internalGetMutableMapFieldReflection(
int number) {
switch (number) {
case 1:
return internalGetMutableLimits();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.run.v2.K8sMinProto
.internal_static_google_cloud_run_v2_ResourceRequirements_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.run.v2.ResourceRequirements.class,
com.google.cloud.run.v2.ResourceRequirements.Builder.class);
}
// Construct using com.google.cloud.run.v2.ResourceRequirements.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
internalGetMutableLimits().clear();
cpuIdle_ = false;
startupCpuBoost_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.run.v2.K8sMinProto
.internal_static_google_cloud_run_v2_ResourceRequirements_descriptor;
}
@java.lang.Override
public com.google.cloud.run.v2.ResourceRequirements getDefaultInstanceForType() {
return com.google.cloud.run.v2.ResourceRequirements.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.run.v2.ResourceRequirements build() {
com.google.cloud.run.v2.ResourceRequirements result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.run.v2.ResourceRequirements buildPartial() {
com.google.cloud.run.v2.ResourceRequirements result =
new com.google.cloud.run.v2.ResourceRequirements(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.run.v2.ResourceRequirements result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.limits_ = internalGetLimits();
result.limits_.makeImmutable();
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.cpuIdle_ = cpuIdle_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.startupCpuBoost_ = startupCpuBoost_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.run.v2.ResourceRequirements) {
return mergeFrom((com.google.cloud.run.v2.ResourceRequirements) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.run.v2.ResourceRequirements other) {
if (other == com.google.cloud.run.v2.ResourceRequirements.getDefaultInstance()) return this;
internalGetMutableLimits().mergeFrom(other.internalGetLimits());
bitField0_ |= 0x00000001;
if (other.getCpuIdle() != false) {
setCpuIdle(other.getCpuIdle());
}
if (other.getStartupCpuBoost() != false) {
setStartupCpuBoost(other.getStartupCpuBoost());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.protobuf.MapEntry<java.lang.String, java.lang.String> limits__ =
input.readMessage(
LimitsDefaultEntryHolder.defaultEntry.getParserForType(),
extensionRegistry);
internalGetMutableLimits()
.getMutableMap()
.put(limits__.getKey(), limits__.getValue());
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
cpuIdle_ = input.readBool();
bitField0_ |= 0x00000002;
break;
} // case 16
case 24:
{
startupCpuBoost_ = input.readBool();
bitField0_ |= 0x00000004;
break;
} // case 24
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.protobuf.MapField<java.lang.String, java.lang.String> limits_;
private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetLimits() {
if (limits_ == null) {
return com.google.protobuf.MapField.emptyMapField(LimitsDefaultEntryHolder.defaultEntry);
}
return limits_;
}
private com.google.protobuf.MapField<java.lang.String, java.lang.String>
internalGetMutableLimits() {
if (limits_ == null) {
limits_ = com.google.protobuf.MapField.newMapField(LimitsDefaultEntryHolder.defaultEntry);
}
if (!limits_.isMutable()) {
limits_ = limits_.copy();
}
bitField0_ |= 0x00000001;
onChanged();
return limits_;
}
public int getLimitsCount() {
return internalGetLimits().getMap().size();
}
/**
*
*
* <pre>
* Only `memory` and `cpu` keys in the map are supported.
*
* <p>Notes:
* * The only supported values for CPU are '1', '2', '4', and '8'. Setting 4
* CPU requires at least 2Gi of memory. For more information, go to
* https://cloud.google.com/run/docs/configuring/cpu.
* * For supported 'memory' values and syntax, go to
* https://cloud.google.com/run/docs/configuring/memory-limits
* </pre>
*
* <code>map<string, string> limits = 1;</code>
*/
@java.lang.Override
public boolean containsLimits(java.lang.String key) {
if (key == null) {
throw new NullPointerException("map key");
}
return internalGetLimits().getMap().containsKey(key);
}
/** Use {@link #getLimitsMap()} instead. */
@java.lang.Override
@java.lang.Deprecated
public java.util.Map<java.lang.String, java.lang.String> getLimits() {
return getLimitsMap();
}
/**
*
*
* <pre>
* Only `memory` and `cpu` keys in the map are supported.
*
* <p>Notes:
* * The only supported values for CPU are '1', '2', '4', and '8'. Setting 4
* CPU requires at least 2Gi of memory. For more information, go to
* https://cloud.google.com/run/docs/configuring/cpu.
* * For supported 'memory' values and syntax, go to
* https://cloud.google.com/run/docs/configuring/memory-limits
* </pre>
*
* <code>map<string, string> limits = 1;</code>
*/
@java.lang.Override
public java.util.Map<java.lang.String, java.lang.String> getLimitsMap() {
return internalGetLimits().getMap();
}
/**
*
*
* <pre>
* Only `memory` and `cpu` keys in the map are supported.
*
* <p>Notes:
* * The only supported values for CPU are '1', '2', '4', and '8'. Setting 4
* CPU requires at least 2Gi of memory. For more information, go to
* https://cloud.google.com/run/docs/configuring/cpu.
* * For supported 'memory' values and syntax, go to
* https://cloud.google.com/run/docs/configuring/memory-limits
* </pre>
*
* <code>map<string, string> limits = 1;</code>
*/
@java.lang.Override
public /* nullable */ java.lang.String getLimitsOrDefault(
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 = internalGetLimits().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
*
*
* <pre>
* Only `memory` and `cpu` keys in the map are supported.
*
* <p>Notes:
* * The only supported values for CPU are '1', '2', '4', and '8'. Setting 4
* CPU requires at least 2Gi of memory. For more information, go to
* https://cloud.google.com/run/docs/configuring/cpu.
* * For supported 'memory' values and syntax, go to
* https://cloud.google.com/run/docs/configuring/memory-limits
* </pre>
*
* <code>map<string, string> limits = 1;</code>
*/
@java.lang.Override
public java.lang.String getLimitsOrThrow(java.lang.String key) {
if (key == null) {
throw new NullPointerException("map key");
}
java.util.Map<java.lang.String, java.lang.String> map = internalGetLimits().getMap();
if (!map.containsKey(key)) {
throw new java.lang.IllegalArgumentException();
}
return map.get(key);
}
public Builder clearLimits() {
bitField0_ = (bitField0_ & ~0x00000001);
internalGetMutableLimits().getMutableMap().clear();
return this;
}
/**
*
*
* <pre>
* Only `memory` and `cpu` keys in the map are supported.
*
* <p>Notes:
* * The only supported values for CPU are '1', '2', '4', and '8'. Setting 4
* CPU requires at least 2Gi of memory. For more information, go to
* https://cloud.google.com/run/docs/configuring/cpu.
* * For supported 'memory' values and syntax, go to
* https://cloud.google.com/run/docs/configuring/memory-limits
* </pre>
*
* <code>map<string, string> limits = 1;</code>
*/
public Builder removeLimits(java.lang.String key) {
if (key == null) {
throw new NullPointerException("map key");
}
internalGetMutableLimits().getMutableMap().remove(key);
return this;
}
/** Use alternate mutation accessors instead. */
@java.lang.Deprecated
public java.util.Map<java.lang.String, java.lang.String> getMutableLimits() {
bitField0_ |= 0x00000001;
return internalGetMutableLimits().getMutableMap();
}
/**
*
*
* <pre>
* Only `memory` and `cpu` keys in the map are supported.
*
* <p>Notes:
* * The only supported values for CPU are '1', '2', '4', and '8'. Setting 4
* CPU requires at least 2Gi of memory. For more information, go to
* https://cloud.google.com/run/docs/configuring/cpu.
* * For supported 'memory' values and syntax, go to
* https://cloud.google.com/run/docs/configuring/memory-limits
* </pre>
*
* <code>map<string, string> limits = 1;</code>
*/
public Builder putLimits(java.lang.String key, java.lang.String value) {
if (key == null) {
throw new NullPointerException("map key");
}
if (value == null) {
throw new NullPointerException("map value");
}
internalGetMutableLimits().getMutableMap().put(key, value);
bitField0_ |= 0x00000001;
return this;
}
/**
*
*
* <pre>
* Only `memory` and `cpu` keys in the map are supported.
*
* <p>Notes:
* * The only supported values for CPU are '1', '2', '4', and '8'. Setting 4
* CPU requires at least 2Gi of memory. For more information, go to
* https://cloud.google.com/run/docs/configuring/cpu.
* * For supported 'memory' values and syntax, go to
* https://cloud.google.com/run/docs/configuring/memory-limits
* </pre>
*
* <code>map<string, string> limits = 1;</code>
*/
public Builder putAllLimits(java.util.Map<java.lang.String, java.lang.String> values) {
internalGetMutableLimits().getMutableMap().putAll(values);
bitField0_ |= 0x00000001;
return this;
}
private boolean cpuIdle_;
/**
*
*
* <pre>
* Determines whether CPU is only allocated during requests (true by default).
* However, if ResourceRequirements is set, the caller must explicitly
* set this field to true to preserve the default behavior.
* </pre>
*
* <code>bool cpu_idle = 2;</code>
*
* @return The cpuIdle.
*/
@java.lang.Override
public boolean getCpuIdle() {
return cpuIdle_;
}
/**
*
*
* <pre>
* Determines whether CPU is only allocated during requests (true by default).
* However, if ResourceRequirements is set, the caller must explicitly
* set this field to true to preserve the default behavior.
* </pre>
*
* <code>bool cpu_idle = 2;</code>
*
* @param value The cpuIdle to set.
* @return This builder for chaining.
*/
public Builder setCpuIdle(boolean value) {
cpuIdle_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Determines whether CPU is only allocated during requests (true by default).
* However, if ResourceRequirements is set, the caller must explicitly
* set this field to true to preserve the default behavior.
* </pre>
*
* <code>bool cpu_idle = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearCpuIdle() {
bitField0_ = (bitField0_ & ~0x00000002);
cpuIdle_ = false;
onChanged();
return this;
}
private boolean startupCpuBoost_;
/**
*
*
* <pre>
* Determines whether CPU should be boosted on startup of a new container
* instance above the requested CPU threshold, this can help reduce cold-start
* latency.
* </pre>
*
* <code>bool startup_cpu_boost = 3;</code>
*
* @return The startupCpuBoost.
*/
@java.lang.Override
public boolean getStartupCpuBoost() {
return startupCpuBoost_;
}
/**
*
*
* <pre>
* Determines whether CPU should be boosted on startup of a new container
* instance above the requested CPU threshold, this can help reduce cold-start
* latency.
* </pre>
*
* <code>bool startup_cpu_boost = 3;</code>
*
* @param value The startupCpuBoost to set.
* @return This builder for chaining.
*/
public Builder setStartupCpuBoost(boolean value) {
startupCpuBoost_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Determines whether CPU should be boosted on startup of a new container
* instance above the requested CPU threshold, this can help reduce cold-start
* latency.
* </pre>
*
* <code>bool startup_cpu_boost = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearStartupCpuBoost() {
bitField0_ = (bitField0_ & ~0x00000004);
startupCpuBoost_ = 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.run.v2.ResourceRequirements)
}
// @@protoc_insertion_point(class_scope:google.cloud.run.v2.ResourceRequirements)
private static final com.google.cloud.run.v2.ResourceRequirements DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.run.v2.ResourceRequirements();
}
public static com.google.cloud.run.v2.ResourceRequirements getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ResourceRequirements> PARSER =
new com.google.protobuf.AbstractParser<ResourceRequirements>() {
@java.lang.Override
public ResourceRequirements 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<ResourceRequirements> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ResourceRequirements> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.run.v2.ResourceRequirements getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/jackrabbit-oak | 35,969 | oak-core/src/main/java/org/apache/jackrabbit/oak/security/user/UserImporter.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.security.user;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.principal.PrincipalIterator;
import org.apache.jackrabbit.api.security.principal.PrincipalManager;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.AuthorizableExistsException;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.Impersonation;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Root;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.commons.collections.IterableUtils;
import org.apache.jackrabbit.oak.commons.collections.MapUtils;
import org.apache.jackrabbit.oak.commons.conditions.Validate;
import org.apache.jackrabbit.oak.commons.time.Stopwatch;
import org.apache.jackrabbit.oak.namepath.NamePathMapper;
import org.apache.jackrabbit.oak.plugins.identifier.IdentifierManager;
import org.apache.jackrabbit.oak.plugins.memory.PropertyStates;
import org.apache.jackrabbit.oak.plugins.tree.TreeUtil;
import org.apache.jackrabbit.oak.security.user.autosave.AutoSaveEnabledManager;
import org.apache.jackrabbit.oak.security.user.monitor.UserMonitor;
import org.apache.jackrabbit.oak.spi.nodetype.NodeTypeConstants;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import org.apache.jackrabbit.oak.spi.security.SecurityProvider;
import org.apache.jackrabbit.oak.spi.security.principal.PrincipalImpl;
import org.apache.jackrabbit.oak.spi.security.user.cache.CacheConstants;
import org.apache.jackrabbit.oak.spi.security.user.UserConfiguration;
import org.apache.jackrabbit.oak.spi.security.user.UserConstants;
import org.apache.jackrabbit.oak.spi.security.user.util.UserUtil;
import org.apache.jackrabbit.oak.spi.whiteboard.Whiteboard;
import org.apache.jackrabbit.oak.spi.whiteboard.WhiteboardAware;
import org.apache.jackrabbit.oak.spi.whiteboard.WhiteboardUtils;
import org.apache.jackrabbit.oak.spi.xml.ImportBehavior;
import org.apache.jackrabbit.oak.spi.xml.NodeInfo;
import org.apache.jackrabbit.oak.spi.xml.PropInfo;
import org.apache.jackrabbit.oak.spi.xml.ProtectedNodeImporter;
import org.apache.jackrabbit.oak.spi.xml.ProtectedPropertyImporter;
import org.apache.jackrabbit.oak.spi.xml.ReferenceChangeTracker;
import org.apache.jackrabbit.oak.spi.xml.TextValue;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.ImportUUIDBehavior;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.PropertyDefinition;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Supplier;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static org.apache.jackrabbit.oak.api.Type.STRINGS;
/**
* {@code UserImporter} implements both {@code ode>ProtectedPropertyImporter}
* and {@code ProtectedNodeImporter} and provides import facilities for protected
* user and group content defined and used by this user management implementation.<p>
* <p>
* The importer is intended to be used by applications that import user content
* extracted from another repository instance and immediately persist the
* imported content using {@link javax.jcr.Session#save()}. Omitting the
* save call will lead to transient, semi-validated user content and eventually
* to inconsistencies.
* <p>
* Note the following restrictions:
* <ul>
* <li>The importer will only be initialized if the user manager exposed by
* the session is an instance of {@code UserManagerImpl}.
* <li>The importer will only be initialized if the editing session starting
* this import is the same as the UserManager's Session instance.
* <li>The jcr:uuid property of user and groups is defined to represent the
* hashed authorizable id as calculated by the UserManager. This importer
* is therefore not able to handle imports with
* {@link ImportUUIDBehavior#IMPORT_UUID_CREATE_NEW}.
* <li>Importing user/group nodes outside of the hierarchy defined by the two
* configuration options
* {@link org.apache.jackrabbit.oak.spi.security.user.UserConstants#PARAM_GROUP_PATH}
* and {@link org.apache.jackrabbit.oak.spi.security.user.UserConstants#PARAM_USER_PATH}
* will fail upon {@code Root#commit()}. The same may
* be true in case of {@link ImportUUIDBehavior#IMPORT_UUID_COLLISION_REPLACE_EXISTING}
* inserting the user/group node at some other place in the node hierarchy.
* <li>The same commit hook will make sure that authorizables are never nested
* and are created below a hierarchy of nt:AuthorizableFolder nodes. This isn't
* enforced by means of node type constraints but only by the API. This importer
* itself currently doesn't perform such a validation check.
* <li>Any attempt to import conflicting data will cause the import to fail
* either immediately or upon calling {@link javax.jcr.Session#save()} with the
* following exceptions:
* <ul>
* <li>{@code rep:members} : Group membership
* <li>{@code rep:impersonators} : Impersonators of a User.
* </ul>
* The import behavior of these two properties is defined by the {@link #PARAM_IMPORT_BEHAVIOR}
* configuration parameter, which can be set to
* <ul>
* <li>{@link ImportBehavior#NAME_IGNORE ignore}: A warning is logged.
* <li>{@link ImportBehavior#NAME_BESTEFFORT best effort}: A warning is logged
* and the importer tries to fix the problem.
* <li>{@link ImportBehavior#NAME_ABORT abort}: The import is immediately
* aborted with a ConstraintViolationException. (<strong>default</strong>)
* </ul>
* </ul>
*/
class UserImporter implements ProtectedPropertyImporter, ProtectedNodeImporter, UserConstants {
private static final Logger log = LoggerFactory.getLogger(UserImporter.class);
private final int importBehavior;
private Root root;
private NamePathMapper namePathMapper;
private ReferenceChangeTracker referenceTracker;
private UserManagerImpl userManager;
private IdentifierManager identifierManager;
private boolean initialized = false;
/**
* Container used to collect group members stored in protected nodes.
*/
private Membership currentMembership;
/**
* map holding the processed memberships. this is needed as both, the property and the node importer, can provide
* memberships during processing. if both would be handled only via the reference tracker {@link Membership#process()}
* would remove the members from the property importer.
*/
private final Map<String, Membership> memberships = new HashMap<>();
/**
* Temporary store for the pw an imported new user to be able to call
* the creation actions irrespective of the order of protected properties
*/
private String currentPw;
/**
* Remember all new principals for impersonation handling.
*/
private final Map<String, Principal> principals = new HashMap<>();
private UserMonitor userMonitor; // do not access directly, but only via the userMonitorSupplier
private Supplier<UserMonitor> userMonitorSupplier;
UserImporter(ConfigurationParameters config) {
importBehavior = UserUtil.getImportBehavior(config);
}
//----------------------------------------------< ProtectedItemImporter >---
@Override
public boolean init(@NotNull Session session, @NotNull Root root, @NotNull NamePathMapper namePathMapper,
boolean isWorkspaceImport, int uuidBehavior,
@NotNull ReferenceChangeTracker referenceTracker, @NotNull SecurityProvider securityProvider) {
if (!(session instanceof JackrabbitSession)) {
log.debug("Importing protected user content requires a JackrabbitSession");
return false;
}
this.root = root;
this.namePathMapper = namePathMapper;
this.referenceTracker = referenceTracker;
if (initialized) {
throw new IllegalStateException("Already initialized");
}
if (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW) {
log.debug("ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW isn't supported when importing users or groups.");
return false;
}
if (!canInitUserManager((JackrabbitSession) session, isWorkspaceImport)) {
return false;
}
userManager = initUserManager(securityProvider, root, namePathMapper);
if (userManager == null) {
return false;
}
/*
* resolve the userMonitor lazily, as resolving that service via the OSGi service registry
* can be costly; this is often a redundant operation, because a UserImporter is typically much more
* frequent initialized than actually used.
*/
userMonitorSupplier = getUserMonitorSupplier(securityProvider);
initialized = true;
return initialized;
}
private Supplier<UserMonitor> getUserMonitorSupplier(SecurityProvider securityProvider) {
return () -> {
if (userMonitor == null) {
if (securityProvider instanceof WhiteboardAware) {
Whiteboard whiteboard = ((WhiteboardAware) securityProvider).getWhiteboard();
UserMonitor monitor = WhiteboardUtils.getService(whiteboard, UserMonitor.class);
if (monitor != null) {
userMonitor = monitor;
}
}
if (userMonitor == null) { // always fall back to the NOOP version
userMonitor = UserMonitor.NOOP;
}
}
return userMonitor;
};
}
private static boolean canInitUserManager(@NotNull JackrabbitSession session, boolean isWorkspaceImport) {
try {
if (!isWorkspaceImport && session.getUserManager().isAutoSave()) {
log.warn("Session import cannot handle user content: UserManager is in autosave mode.");
return false;
}
} catch (RepositoryException e) {
// failed to access user manager or to set the autosave behavior
// -> return false (not initialized) as importer can't operate.
log.error("Failed to initialize UserImporter: ", e);
return false;
}
return true;
}
@Nullable
private static UserManagerImpl initUserManager(@NotNull SecurityProvider securityProvider, @NotNull Root root, @NotNull NamePathMapper namePathMapper) {
UserManager umgr = securityProvider.getConfiguration(UserConfiguration.class).getUserManager(root, namePathMapper);
if (umgr instanceof AutoSaveEnabledManager) {
umgr = ((AutoSaveEnabledManager) umgr).unwrap();
}
if (umgr instanceof UserManagerImpl) {
return (UserManagerImpl) umgr;
} else {
log.error("Unexpected UserManager implementation {}, expected {}", umgr.getClass(), UserManagerImpl.class);
return null;
}
}
// -----------------------------------------< ProtectedPropertyImporter >---
@Override
public boolean handlePropInfo(@NotNull Tree parent, @NotNull PropInfo propInfo, @NotNull PropertyDefinition def) throws RepositoryException {
checkInitialized();
if (isPwdNode(parent)) {
// overwrite any properties generated underneath the rep:pwd node
// by "UserManagerImpl#setPassword" by the properties defined by
// the XML to be imported. see OAK-1943 for the corresponding discussion.
return importPwdNodeProperty(parent, propInfo, def);
} else {
Authorizable a = userManager.getAuthorizable(parent);
if (a == null) {
log.debug("Cannot handle protected PropInfo {}. Node {} doesn't represent an Authorizable.", propInfo, parent);
return false;
}
String propName = propInfo.getName();
if (REP_AUTHORIZABLE_ID.equals(propName)) {
return importAuthorizableId(parent, a, propInfo, def);
} else if (REP_PRINCIPAL_NAME.equals(propName)) {
return importPrincipalName(parent, a, propInfo, def);
} else if (REP_PASSWORD.equals(propName)) {
return importPassword(parent, a, propInfo, def);
} else if (REP_IMPERSONATORS.equals(propName)) {
return importImpersonators(parent, a, propInfo, def);
} else if (REP_DISABLED.equals(propName)) {
return importDisabled(a, propInfo, def);
} else if (REP_MEMBERS.equals(propName)) {
if (!a.isGroup() || !isValid(def, NT_REP_MEMBER_REFERENCES, true)) {
return false;
}
// since group-members are references to user/groups that potentially
// are to be imported later on -> postpone processing to the end.
// see -> process References
getMembership(a.getPath()).addMembers(propInfo.getTextValues());
return true;
} // another protected property -> return false
}
// neither rep:pwd nor authorizable node -> not covered by this importer.
return false;
}
@Override
public void propertiesCompleted(@NotNull Tree protectedParent) throws RepositoryException {
if (isCacheNode(protectedParent)) {
// remove the cache if present
protectedParent.remove();
} else {
Authorizable a = userManager.getAuthorizable(protectedParent);
if (a == null) {
// not an authorizable
return;
}
// make sure the authorizable ID property is always set even if the
// authorizable defined by the imported XML didn't provide rep:authorizableID
if (!protectedParent.hasProperty(REP_AUTHORIZABLE_ID)) {
protectedParent.setProperty(REP_AUTHORIZABLE_ID, a.getID(), Type.STRING);
}
/*
Execute authorizable actions for a NEW user at this point after
having set the password and the principal name (all protected properties
have been processed now).
*/
if (protectedParent.getStatus() == Tree.Status.NEW) {
if (a.isGroup()) {
userManager.onCreate((Group) a);
} else if (((User) a).isSystemUser()) {
userManager.onCreate((User) a);
} else {
userManager.onCreate((User) a, currentPw);
}
}
currentPw = null;
}
}
@Override
public void processReferences() throws RepositoryException {
checkInitialized();
// add all collected memberships to the reference tracker.
for (Membership m: memberships.values()) {
referenceTracker.processedReference(m);
}
memberships.clear();
List<Object> processed = new ArrayList<>();
for (Iterator<Object> it = referenceTracker.getProcessedReferences(); it.hasNext(); ) {
Object reference = it.next();
if (reference instanceof Membership) {
((Membership) reference).process();
processed.add(reference);
} else if (reference instanceof Impersonators) {
((Impersonators) reference).process();
processed.add(reference);
}
}
// successfully processed this entry of the reference tracker
// -> remove from the reference tracker.
referenceTracker.removeReferences(processed);
}
// ---------------------------------------------< ProtectedNodeImporter >---
@Override
public boolean start(@NotNull Tree protectedParent) throws RepositoryException {
Authorizable auth = null;
if (isMemberNode(protectedParent)) {
Tree groupTree = protectedParent;
while (isMemberNode(groupTree)) {
groupTree = groupTree.getParent();
}
auth = userManager.getAuthorizable(groupTree);
} else if (isMemberReferencesListNode(protectedParent)) {
auth = userManager.getAuthorizable(protectedParent.getParent());
} // else: parent node is not of type rep:Members or rep:MemberReferencesList
if (auth == null || !auth.isGroup()) {
log.debug("Cannot handle protected node {}. It doesn't represent a valid Group, nor does any of its parents.", protectedParent);
return false;
} else {
currentMembership = getMembership(auth.getPath());
return true;
}
}
@Override
public void startChildInfo(@NotNull NodeInfo childInfo, @NotNull List<PropInfo> propInfos) {
Validate.checkState(currentMembership != null);
String ntName = childInfo.getPrimaryTypeName();
//noinspection deprecation
if (NT_REP_MEMBERS.equals(ntName)) {
for (PropInfo prop : propInfos) {
for (TextValue tv : prop.getTextValues()) {
currentMembership.addMember(tv.getString());
}
}
} else if (NT_REP_MEMBER_REFERENCES.equals(ntName)) {
for (PropInfo prop : propInfos) {
if (REP_MEMBERS.equals(prop.getName())) {
currentMembership.addMembers(prop.getTextValues());
}
}
} else {
//noinspection deprecation
log.warn("{} is not of type " + NT_REP_MEMBERS + " or " + NT_REP_MEMBER_REFERENCES, childInfo.getName());
}
}
@Override
public void endChildInfo() {
// nothing to do
}
@Override
public void end(@NotNull Tree protectedParent) {
currentMembership = null;
}
//------------------------------------------------------------< private >---
@NotNull
private Membership getMembership(@NotNull String authId) {
return memberships.computeIfAbsent(authId, k -> new Membership(authId));
}
private void checkInitialized() {
if (!initialized) {
throw new IllegalStateException("Not initialized");
}
}
private boolean isValid(@NotNull PropertyDefinition definition, @NotNull String oakNodeTypeName, boolean multipleStatus) {
return multipleStatus == definition.isMultiple() &&
definition.getDeclaringNodeType().isNodeType(namePathMapper.getJcrName(oakNodeTypeName));
}
private boolean importAuthorizableId(@NotNull Tree parent, @NotNull Authorizable a, @NotNull PropInfo propInfo, @NotNull PropertyDefinition def) throws RepositoryException {
if (!isValid(def, NT_REP_AUTHORIZABLE, false)) {
return false;
}
String id = propInfo.getTextValue().getString();
Authorizable existing = userManager.getAuthorizable(id);
if (existing == null) {
String msg = "Cannot handle protected PropInfo " + propInfo + ". Invalid rep:authorizableId.";
log.warn(msg);
throw new ConstraintViolationException(msg);
}
if (a.getPath().equals(existing.getPath())) {
parent.setProperty(REP_AUTHORIZABLE_ID, id);
} else {
throw new AuthorizableExistsException(id);
}
return true;
}
private boolean importPrincipalName(@NotNull Tree parent, @NotNull Authorizable a, @NotNull PropInfo propInfo, @NotNull PropertyDefinition def) throws RepositoryException {
if (!isValid(def, NT_REP_AUTHORIZABLE, false)) {
return false;
}
String principalName = propInfo.getTextValue().getString();
Principal principal = new PrincipalImpl(principalName);
userManager.checkValidPrincipal(principal, a.isGroup());
userManager.setPrincipal(parent, principal);
/*
Remember principal of new user/group for further processing
of impersonators
*/
principals.put(principalName, a.getPrincipal());
return true;
}
private boolean importPassword(@NotNull Tree parent, @NotNull Authorizable a, @NotNull PropInfo propInfo, @NotNull PropertyDefinition def) throws RepositoryException {
if (a.isGroup() || !isValid(def, NT_REP_USER, false)) {
log.warn("Unexpected authorizable or definition for property rep:password");
return false;
}
if (((User) a).isSystemUser()) {
log.warn("System users may not have a password set.");
return false;
}
String pw = propInfo.getTextValue().getString();
userManager.setPassword(parent, a.getID(), pw, true);
currentPw = pw;
return true;
}
private boolean importImpersonators(@NotNull Tree parent, @NotNull Authorizable a, @NotNull PropInfo propInfo, @NotNull PropertyDefinition def) {
if (a.isGroup() || !isValid(def, MIX_REP_IMPERSONATABLE, true)) {
log.warn("Unexpected authorizable or definition for property rep:impersonators");
return false;
}
// since impersonators may be imported later on, postpone processing
// to the end.
// see -> process References
referenceTracker.processedReference(new Impersonators(parent.getPath(), propInfo.getTextValues()));
return true;
}
private boolean importDisabled(@NotNull Authorizable a, @NotNull PropInfo propInfo, @NotNull PropertyDefinition def) throws RepositoryException {
if (a.isGroup() || !isValid(def, NT_REP_USER, false)) {
log.warn("Unexpected authorizable or definition for property rep:disabled");
return false;
}
((User) a).disable(propInfo.getTextValue().getString());
return true;
}
private static boolean isMemberNode(@NotNull Tree tree) {
//noinspection deprecation
return tree.exists() && !tree.isRoot() && NT_REP_MEMBERS.equals(TreeUtil.getPrimaryTypeName(tree));
}
private static boolean isMemberReferencesListNode(@NotNull Tree tree) {
return tree.exists() && NT_REP_MEMBER_REFERENCES_LIST.equals(TreeUtil.getPrimaryTypeName(tree));
}
private static boolean isPwdNode(@NotNull Tree tree) {
return REP_PWD.equals(tree.getName()) && NT_REP_PASSWORD.equals(TreeUtil.getPrimaryTypeName(tree));
}
private static boolean importPwdNodeProperty(@NotNull Tree parent, @NotNull PropInfo propInfo, @NotNull PropertyDefinition def) throws RepositoryException {
String propName = propInfo.getName();
if (propName == null) {
propName = def.getName();
if (propName == null || NodeTypeConstants.RESIDUAL_NAME.equals(propName)) {
return false;
}
}
// overwrite any properties generated underneath the rep:pwd node
// by "UserManagerImpl#setPassword" by the properties defined by
// the XML to be imported. see OAK-1943 for the corresponding discussion.
int targetType = def.getRequiredType();
if (targetType == PropertyType.UNDEFINED) {
targetType = (REP_PASSWORD_LAST_MODIFIED.equals(propName)) ? PropertyType.LONG : PropertyType.STRING;
}
PropertyState property;
if (def.isMultiple()) {
property = PropertyStates.createProperty(propName, propInfo.getValues(targetType));
} else {
property = PropertyStates.createProperty(propName, propInfo.getValue(targetType));
}
parent.setProperty(property);
return true;
}
private static boolean isCacheNode(@NotNull Tree tree) {
return tree.exists() && CacheConstants.REP_CACHE.equals(tree.getName()) && CacheConstants.NT_REP_CACHE.equals(TreeUtil.getPrimaryTypeName(tree));
}
/**
* Handling the import behavior
*
* @param msg The message to log a warning in case of {@link ImportBehavior#IGNORE}
* or {@link ImportBehavior#BESTEFFORT}
* @throws javax.jcr.nodetype.ConstraintViolationException
* If the import
* behavior is {@link ImportBehavior#ABORT}.
*/
private void handleFailure(String msg) throws ConstraintViolationException {
switch (importBehavior) {
case ImportBehavior.ABORT:
throw new ConstraintViolationException(msg);
case ImportBehavior.IGNORE:
case ImportBehavior.BESTEFFORT:
default:
log.warn(msg);
break;
}
}
//------------------------------------------------------< inner classes >---
/**
* Inner class used to postpone import of group membership to the very end
* of the import. This allows to import membership of user/groups that
* are only being created during this import.
*
* @see ImportBehavior For additional configuration options.
*/
private final class Membership {
private final String authorizablePath;
private final Set<String> members = new TreeSet<>();
Membership(String authorizablePath) {
this.authorizablePath = authorizablePath;
}
void addMember(String id) {
members.add(id);
}
void addMembers(List<? extends TextValue> tvs) {
for (TextValue tv : tvs) {
addMember(tv.getString());
}
}
void process() throws RepositoryException {
Authorizable a = userManager.getAuthorizableByPath(authorizablePath);
if (a == null || !a.isGroup()) {
throw new RepositoryException(authorizablePath + " does not represent a valid group.");
}
Group gr = (Group) a;
// 1. collect members to add and to remove.
Map<String, Authorizable> toRemove = new HashMap<>();
for (Iterator<Authorizable> declMembers = gr.getDeclaredMembers(); declMembers.hasNext(); ) {
Authorizable dm = declMembers.next();
toRemove.put(dm.getID(), dm);
}
Map<String, String> nonExisting = new HashMap<>();
Map<String, Authorizable> toAdd = getAuthorizablesToAdd(gr, toRemove, nonExisting);
// 2. adjust members of the group
if (!toRemove.isEmpty()) {
Set<String> failed = gr.removeMembers(toRemove.keySet().toArray(new String[0]));
if (!failed.isEmpty()) {
handleFailure("Failed removing members " + IterableUtils.toString(failed) + " to " + gr);
}
}
if (!toAdd.isEmpty()) {
Set<String> failed = gr.addMembers(toAdd.keySet().toArray(new String[0]));
if (!failed.isEmpty()) {
handleFailure("Failed add members " + IterableUtils.toString(failed) + " to " + gr);
}
}
// handling non-existing members in case of best-effort
if (!nonExisting.isEmpty()) {
Stopwatch watch = Stopwatch.createStarted();
log.debug("ImportBehavior.BESTEFFORT: Found {} entries of rep:members pointing to non-existing authorizables. Adding to rep:members.", nonExisting.size());
Tree groupTree = Utils.getTree(gr, root);
MembershipProvider membershipProvider = userManager.getMembershipProvider();
long totalSize = nonExisting.size();
Set<String> memberContentIds = new HashSet<>(nonExisting.keySet());
Set<String> failedContentIds = membershipProvider.addMembers(groupTree, nonExisting);
memberContentIds.removeAll(failedContentIds);
userManager.onGroupUpdate(gr, false, true, memberContentIds, failedContentIds);
userMonitorSupplier.get().doneUpdateMembers(watch.elapsed(NANOSECONDS), totalSize, failedContentIds.size(), false);
}
}
@NotNull
Map<String, Authorizable> getAuthorizablesToAdd(@NotNull Group gr, @NotNull Map<String, Authorizable> toRemove,
@NotNull Map<String, String> nonExisting) throws RepositoryException {
Map<String, Authorizable> toAdd = MapUtils.newHashMap(members.size());
for (String contentId : members) {
// NOTE: no need to check for re-mapped uuids with the referenceTracker because
// ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW is not supported for user/group imports (see line 189)
Authorizable member = null;
try {
Tree n = getIdentifierManager().getTree(contentId);
member = userManager.getAuthorizable(n);
} catch (RepositoryException e) {
// no such node or failed to retrieve authorizable
// warning is logged below.
}
if (member != null) {
if (toRemove.remove(member.getID()) == null) {
toAdd.put(member.getID(), member);
} // else: no need to remove from rep:members
} else {
handleFailure("New member of " + gr + ": No such authorizable (NodeID = " + contentId + ')');
if (importBehavior == ImportBehavior.BESTEFFORT) {
log.debug("ImportBehavior.BESTEFFORT: Remember non-existing member for processing.");
/* since we ignore the set of failed ids later on and
don't know the real memberId => use fake memberId as
value in the map */
nonExisting.put(contentId, "-");
}
}
}
return toAdd;
}
@NotNull
private IdentifierManager getIdentifierManager() {
if (identifierManager == null) {
identifierManager = new IdentifierManager(root);
}
return identifierManager;
}
}
/**
* Inner class used to postpone import of impersonators to the very end
* of the import. This allows to import impersonation values pointing
* to user that are only being created during this import.
*
* @see ImportBehavior For additional configuration options.
*/
private final class Impersonators {
private final String userPath;
private final Set<String> principalNames = new HashSet<>();
private Impersonators(String userPath, List<? extends TextValue> values) {
this.userPath = userPath;
for (TextValue v : values) {
principalNames.add(v.getString());
}
}
private void process() throws RepositoryException {
Authorizable a = userManager.getAuthorizableByOakPath(userPath);
if (a == null || a.isGroup()) {
throw new RepositoryException(userPath + " does not represent a valid user.");
}
Impersonation imp = requireNonNull(((User) a).getImpersonation());
// 1. collect principals to add and to remove.
Map<String, Principal> toRemove = new HashMap<>();
for (PrincipalIterator pit = imp.getImpersonators(); pit.hasNext(); ) {
Principal p = pit.nextPrincipal();
toRemove.put(p.getName(), p);
}
List<String> toAdd = new ArrayList<>();
for (final String principalName : principalNames) {
if (toRemove.remove(principalName) == null) {
// add it to the list of new impersonators to be added.
toAdd.add(principalName);
} // else: no need to revoke impersonation for the given principal.
}
// 2. adjust set of impersonators
List<String> nonExisting = updateImpersonators(a, imp, toRemove, toAdd);
if (!nonExisting.isEmpty()) {
Tree userTree = Utils.getTree(a, root);
// copy over all existing impersonators to the nonExisting list
PropertyState impersonators = userTree.getProperty(REP_IMPERSONATORS);
if (impersonators != null) {
for (String existing : impersonators.getValue(STRINGS)) {
nonExisting.add(existing);
}
}
// and write back the complete list including those principal
// names that are unknown to principal provider.
userTree.setProperty(REP_IMPERSONATORS, nonExisting, Type.STRINGS);
}
}
@NotNull
private List<String> updateImpersonators(@NotNull Authorizable a, @NotNull Impersonation imp,
@NotNull Map<String, Principal> toRemove, @NotNull List<String> toAdd) throws RepositoryException {
for (Principal p : toRemove.values()) {
if (!imp.revokeImpersonation(p)) {
String principalName = p.getName();
handleFailure("Failed to revoke impersonation for " + principalName + " on " + a);
}
}
List<String> nonExisting = new ArrayList<>();
for (String principalName : toAdd) {
Principal principal = (principals.containsKey(principalName)) ?
principals.get(principalName) :
new PrincipalImpl(principalName);
if (!imp.grantImpersonation(principal)) {
handleFailure("Failed to grant impersonation for " + principalName + " on " + a);
if (importBehavior == ImportBehavior.BESTEFFORT &&
getPrincipalManager().getPrincipal(principalName) == null) {
log.debug("ImportBehavior.BESTEFFORT: Remember non-existing impersonator for special processing.");
nonExisting.add(principalName);
}
}
}
return nonExisting;
}
@NotNull
private PrincipalManager getPrincipalManager() {
return userManager.getPrincipalManager();
}
}
}
|
googleapis/google-api-java-client-services | 35,906 | clients/google-api-services-compute/beta/1.31.0/com/google/api/services/compute/model/Firewall.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 a Firewall Rule resource. Firewall rules allow or deny ingress traffic to, and egress
* traffic from your instances. For more information, read Firewall rules.
*
* <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 Firewall extends com.google.api.client.json.GenericJson {
/**
* The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a permitted connection.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Allowed> allowed;
static {
// hack to force ProGuard to consider Allowed 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(Allowed.class);
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String creationTimestamp;
/**
* The list of DENY rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a denied connection.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Denied> denied;
static {
// hack to force ProGuard to consider Denied 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(Denied.class);
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* If destination ranges are specified, the firewall rule applies only to traffic that has
* destination IP address in these ranges. These ranges must be expressed in CIDR format. Both
* IPv4 and IPv6 are supported.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> destinationRanges;
/**
* Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default
* is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for
* `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String direction;
/**
* Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not
* enforced and the network behaves as if it did not exist. If this is unspecified, the firewall
* rule will be enabled.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean disabled;
/**
* Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a
* particular firewall rule. If logging is enabled, logs will be exported t Cloud Logging.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean enableLogging;
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.math.BigInteger id;
/**
* [Output Only] Type of the resource. Always compute#firewall for firewall rules.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* This field denotes the logging options for a particular firewall rule. If logging is enabled,
* logs will be exported to Cloud Logging.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private FirewallLogConfig logConfig;
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* URL of the network resource for this firewall rule. If not specified when creating a firewall
* rule, the default network is used: global/networks/default If you choose to specify this field,
* you can specify the network as a full or partial URL. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network -
* projects/myproject/global/networks/my-network - global/networks/default
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String network;
/**
* Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default
* value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply.
* Lower values indicate higher priority. For example, a rule with priority `0` has higher
* precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they
* have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To
* avoid conflicts with the implied rules, use a priority number less than `65535`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer priority;
/**
* [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;
/**
* If source ranges are specified, the firewall rule applies only to traffic that has a source IP
* address in these ranges. These ranges must be expressed in CIDR format. One or both of
* sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic
* that has a source IP address within sourceRanges OR a source IP from a resource with a matching
* tag listed in the sourceTags field. The connection does not need to match both fields for the
* rule to apply. Both IPv4 and IPv6 are supported.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sourceRanges;
/**
* If source service accounts are specified, the firewall rules apply only to traffic originating
* from an instance with a service account in this list. Source service accounts cannot be used to
* control traffic to an instance's external IP address because service accounts are associated
* with an instance, not an IP address. sourceRanges can be set at the same time as
* sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP
* address within the sourceRanges OR a source IP that belongs to an instance with service account
* listed in sourceServiceAccount. The connection does not need to match both fields for the
* firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or
* targetTags.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sourceServiceAccounts;
/**
* If source tags are specified, the firewall rule applies only to traffic with source IPs that
* match the primary network interfaces of VM instances that have the tag and are in the same VPC
* network. Source tags cannot be used to control traffic to an instance's external IP address, it
* only applies to traffic between instances in the same virtual network. Because tags are
* associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be
* set. If both fields are set, the firewall applies to traffic that has a source IP address
* within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags
* field. The connection does not need to match both fields for the firewall to apply.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sourceTags;
/**
* A list of service accounts indicating sets of instances located in the network that may make
* network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same
* time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are
* specified, the firewall rule applies to all instances on the specified network.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> targetServiceAccounts;
/**
* A list of tags that controls which instances the firewall rule applies to. If targetTags are
* specified, then the firewall rule applies only to instances in the VPC network that have one of
* those tags. If no targetTags are specified, the firewall rule applies to all instances on the
* specified network.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> targetTags;
/**
* The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a permitted connection.
* @return value or {@code null} for none
*/
public java.util.List<Allowed> getAllowed() {
return allowed;
}
/**
* The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a permitted connection.
* @param allowed allowed or {@code null} for none
*/
public Firewall setAllowed(java.util.List<Allowed> allowed) {
this.allowed = allowed;
return this;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @return value or {@code null} for none
*/
public java.lang.String getCreationTimestamp() {
return creationTimestamp;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @param creationTimestamp creationTimestamp or {@code null} for none
*/
public Firewall setCreationTimestamp(java.lang.String creationTimestamp) {
this.creationTimestamp = creationTimestamp;
return this;
}
/**
* The list of DENY rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a denied connection.
* @return value or {@code null} for none
*/
public java.util.List<Denied> getDenied() {
return denied;
}
/**
* The list of DENY rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a denied connection.
* @param denied denied or {@code null} for none
*/
public Firewall setDenied(java.util.List<Denied> denied) {
this.denied = denied;
return this;
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* @param description description or {@code null} for none
*/
public Firewall setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* If destination ranges are specified, the firewall rule applies only to traffic that has
* destination IP address in these ranges. These ranges must be expressed in CIDR format. Both
* IPv4 and IPv6 are supported.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getDestinationRanges() {
return destinationRanges;
}
/**
* If destination ranges are specified, the firewall rule applies only to traffic that has
* destination IP address in these ranges. These ranges must be expressed in CIDR format. Both
* IPv4 and IPv6 are supported.
* @param destinationRanges destinationRanges or {@code null} for none
*/
public Firewall setDestinationRanges(java.util.List<java.lang.String> destinationRanges) {
this.destinationRanges = destinationRanges;
return this;
}
/**
* Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default
* is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for
* `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields.
* @return value or {@code null} for none
*/
public java.lang.String getDirection() {
return direction;
}
/**
* Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default
* is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for
* `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields.
* @param direction direction or {@code null} for none
*/
public Firewall setDirection(java.lang.String direction) {
this.direction = direction;
return this;
}
/**
* Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not
* enforced and the network behaves as if it did not exist. If this is unspecified, the firewall
* rule will be enabled.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDisabled() {
return disabled;
}
/**
* Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not
* enforced and the network behaves as if it did not exist. If this is unspecified, the firewall
* rule will be enabled.
* @param disabled disabled or {@code null} for none
*/
public Firewall setDisabled(java.lang.Boolean disabled) {
this.disabled = disabled;
return this;
}
/**
* Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a
* particular firewall rule. If logging is enabled, logs will be exported t Cloud Logging.
* @return value or {@code null} for none
*/
public java.lang.Boolean getEnableLogging() {
return enableLogging;
}
/**
* Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a
* particular firewall rule. If logging is enabled, logs will be exported t Cloud Logging.
* @param enableLogging enableLogging or {@code null} for none
*/
public Firewall setEnableLogging(java.lang.Boolean enableLogging) {
this.enableLogging = enableLogging;
return this;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @return value or {@code null} for none
*/
public java.math.BigInteger getId() {
return id;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @param id id or {@code null} for none
*/
public Firewall setId(java.math.BigInteger id) {
this.id = id;
return this;
}
/**
* [Output Only] Type of the resource. Always compute#firewall for firewall rules.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* [Output Only] Type of the resource. Always compute#firewall for firewall rules.
* @param kind kind or {@code null} for none
*/
public Firewall setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* This field denotes the logging options for a particular firewall rule. If logging is enabled,
* logs will be exported to Cloud Logging.
* @return value or {@code null} for none
*/
public FirewallLogConfig getLogConfig() {
return logConfig;
}
/**
* This field denotes the logging options for a particular firewall rule. If logging is enabled,
* logs will be exported to Cloud Logging.
* @param logConfig logConfig or {@code null} for none
*/
public Firewall setLogConfig(FirewallLogConfig logConfig) {
this.logConfig = logConfig;
return this;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* @param name name or {@code null} for none
*/
public Firewall setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* URL of the network resource for this firewall rule. If not specified when creating a firewall
* rule, the default network is used: global/networks/default If you choose to specify this field,
* you can specify the network as a full or partial URL. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network -
* projects/myproject/global/networks/my-network - global/networks/default
* @return value or {@code null} for none
*/
public java.lang.String getNetwork() {
return network;
}
/**
* URL of the network resource for this firewall rule. If not specified when creating a firewall
* rule, the default network is used: global/networks/default If you choose to specify this field,
* you can specify the network as a full or partial URL. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network -
* projects/myproject/global/networks/my-network - global/networks/default
* @param network network or {@code null} for none
*/
public Firewall setNetwork(java.lang.String network) {
this.network = network;
return this;
}
/**
* Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default
* value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply.
* Lower values indicate higher priority. For example, a rule with priority `0` has higher
* precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they
* have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To
* avoid conflicts with the implied rules, use a priority number less than `65535`.
* @return value or {@code null} for none
*/
public java.lang.Integer getPriority() {
return priority;
}
/**
* Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default
* value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply.
* Lower values indicate higher priority. For example, a rule with priority `0` has higher
* precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they
* have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To
* avoid conflicts with the implied rules, use a priority number less than `65535`.
* @param priority priority or {@code null} for none
*/
public Firewall setPriority(java.lang.Integer priority) {
this.priority = priority;
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 Firewall setSelfLink(java.lang.String selfLink) {
this.selfLink = selfLink;
return this;
}
/**
* If source ranges are specified, the firewall rule applies only to traffic that has a source IP
* address in these ranges. These ranges must be expressed in CIDR format. One or both of
* sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic
* that has a source IP address within sourceRanges OR a source IP from a resource with a matching
* tag listed in the sourceTags field. The connection does not need to match both fields for the
* rule to apply. Both IPv4 and IPv6 are supported.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSourceRanges() {
return sourceRanges;
}
/**
* If source ranges are specified, the firewall rule applies only to traffic that has a source IP
* address in these ranges. These ranges must be expressed in CIDR format. One or both of
* sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic
* that has a source IP address within sourceRanges OR a source IP from a resource with a matching
* tag listed in the sourceTags field. The connection does not need to match both fields for the
* rule to apply. Both IPv4 and IPv6 are supported.
* @param sourceRanges sourceRanges or {@code null} for none
*/
public Firewall setSourceRanges(java.util.List<java.lang.String> sourceRanges) {
this.sourceRanges = sourceRanges;
return this;
}
/**
* If source service accounts are specified, the firewall rules apply only to traffic originating
* from an instance with a service account in this list. Source service accounts cannot be used to
* control traffic to an instance's external IP address because service accounts are associated
* with an instance, not an IP address. sourceRanges can be set at the same time as
* sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP
* address within the sourceRanges OR a source IP that belongs to an instance with service account
* listed in sourceServiceAccount. The connection does not need to match both fields for the
* firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or
* targetTags.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSourceServiceAccounts() {
return sourceServiceAccounts;
}
/**
* If source service accounts are specified, the firewall rules apply only to traffic originating
* from an instance with a service account in this list. Source service accounts cannot be used to
* control traffic to an instance's external IP address because service accounts are associated
* with an instance, not an IP address. sourceRanges can be set at the same time as
* sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP
* address within the sourceRanges OR a source IP that belongs to an instance with service account
* listed in sourceServiceAccount. The connection does not need to match both fields for the
* firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or
* targetTags.
* @param sourceServiceAccounts sourceServiceAccounts or {@code null} for none
*/
public Firewall setSourceServiceAccounts(java.util.List<java.lang.String> sourceServiceAccounts) {
this.sourceServiceAccounts = sourceServiceAccounts;
return this;
}
/**
* If source tags are specified, the firewall rule applies only to traffic with source IPs that
* match the primary network interfaces of VM instances that have the tag and are in the same VPC
* network. Source tags cannot be used to control traffic to an instance's external IP address, it
* only applies to traffic between instances in the same virtual network. Because tags are
* associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be
* set. If both fields are set, the firewall applies to traffic that has a source IP address
* within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags
* field. The connection does not need to match both fields for the firewall to apply.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSourceTags() {
return sourceTags;
}
/**
* If source tags are specified, the firewall rule applies only to traffic with source IPs that
* match the primary network interfaces of VM instances that have the tag and are in the same VPC
* network. Source tags cannot be used to control traffic to an instance's external IP address, it
* only applies to traffic between instances in the same virtual network. Because tags are
* associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be
* set. If both fields are set, the firewall applies to traffic that has a source IP address
* within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags
* field. The connection does not need to match both fields for the firewall to apply.
* @param sourceTags sourceTags or {@code null} for none
*/
public Firewall setSourceTags(java.util.List<java.lang.String> sourceTags) {
this.sourceTags = sourceTags;
return this;
}
/**
* A list of service accounts indicating sets of instances located in the network that may make
* network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same
* time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are
* specified, the firewall rule applies to all instances on the specified network.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTargetServiceAccounts() {
return targetServiceAccounts;
}
/**
* A list of service accounts indicating sets of instances located in the network that may make
* network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same
* time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are
* specified, the firewall rule applies to all instances on the specified network.
* @param targetServiceAccounts targetServiceAccounts or {@code null} for none
*/
public Firewall setTargetServiceAccounts(java.util.List<java.lang.String> targetServiceAccounts) {
this.targetServiceAccounts = targetServiceAccounts;
return this;
}
/**
* A list of tags that controls which instances the firewall rule applies to. If targetTags are
* specified, then the firewall rule applies only to instances in the VPC network that have one of
* those tags. If no targetTags are specified, the firewall rule applies to all instances on the
* specified network.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTargetTags() {
return targetTags;
}
/**
* A list of tags that controls which instances the firewall rule applies to. If targetTags are
* specified, then the firewall rule applies only to instances in the VPC network that have one of
* those tags. If no targetTags are specified, the firewall rule applies to all instances on the
* specified network.
* @param targetTags targetTags or {@code null} for none
*/
public Firewall setTargetTags(java.util.List<java.lang.String> targetTags) {
this.targetTags = targetTags;
return this;
}
@Override
public Firewall set(String fieldName, Object value) {
return (Firewall) super.set(fieldName, value);
}
@Override
public Firewall clone() {
return (Firewall) super.clone();
}
/**
* Model definition for FirewallAllowed.
*/
public static final class Allowed extends com.google.api.client.json.GenericJson {
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("IPProtocol")
private java.lang.String iPProtocol;
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port. Example inputs include: ["22"], ["80","443"], and
* ["12345-12349"].
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> ports;
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @return value or {@code null} for none
*/
public java.lang.String getIPProtocol() {
return iPProtocol;
}
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @param iPProtocol iPProtocol or {@code null} for none
*/
public Allowed setIPProtocol(java.lang.String iPProtocol) {
this.iPProtocol = iPProtocol;
return this;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port. Example inputs include: ["22"], ["80","443"], and
* ["12345-12349"].
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getPorts() {
return ports;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port. Example inputs include: ["22"], ["80","443"], and
* ["12345-12349"].
* @param ports ports or {@code null} for none
*/
public Allowed setPorts(java.util.List<java.lang.String> ports) {
this.ports = ports;
return this;
}
@Override
public Allowed set(String fieldName, Object value) {
return (Allowed) super.set(fieldName, value);
}
@Override
public Allowed clone() {
return (Allowed) super.clone();
}
}
/**
* Model definition for FirewallDenied.
*/
public static final class Denied extends com.google.api.client.json.GenericJson {
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("IPProtocol")
private java.lang.String iPProtocol;
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port. Example inputs include: ["22"], ["80","443"], and
* ["12345-12349"].
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> ports;
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @return value or {@code null} for none
*/
public java.lang.String getIPProtocol() {
return iPProtocol;
}
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @param iPProtocol iPProtocol or {@code null} for none
*/
public Denied setIPProtocol(java.lang.String iPProtocol) {
this.iPProtocol = iPProtocol;
return this;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port. Example inputs include: ["22"], ["80","443"], and
* ["12345-12349"].
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getPorts() {
return ports;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port. Example inputs include: ["22"], ["80","443"], and
* ["12345-12349"].
* @param ports ports or {@code null} for none
*/
public Denied setPorts(java.util.List<java.lang.String> ports) {
this.ports = ports;
return this;
}
@Override
public Denied set(String fieldName, Object value) {
return (Denied) super.set(fieldName, value);
}
@Override
public Denied clone() {
return (Denied) super.clone();
}
}
}
|
googleapis/google-cloud-java | 35,608 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/ListTuningJobsRequest.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/genai_tuning_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Request message for
* [GenAiTuningService.ListTuningJobs][google.cloud.aiplatform.v1beta1.GenAiTuningService.ListTuningJobs].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListTuningJobsRequest}
*/
public final class ListTuningJobsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.ListTuningJobsRequest)
ListTuningJobsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListTuningJobsRequest.newBuilder() to construct.
private ListTuningJobsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListTuningJobsRequest() {
parent_ = "";
filter_ = "";
pageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListTuningJobsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.GenAiTuningServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListTuningJobsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.GenAiTuningServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListTuningJobsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.class,
com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The resource name of the Location to list the TuningJobs from.
* Format: `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The resource name of the Location to list the TuningJobs from.
* Format: `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Optional. The standard list filter.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The standard list filter.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 3;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Optional. The standard list page size.
* </pre>
*
* <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Optional. The standard list page token.
* Typically obtained via [ListTuningJob.next_page_token][] of the
* previous GenAiTuningService.ListTuningJob][] call.
* </pre>
*
* <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The standard list page token.
* Typically obtained via [ListTuningJob.next_page_token][] of the
* previous GenAiTuningService.ListTuningJob][] call.
* </pre>
*
* <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, filter_);
}
if (pageSize_ != 0) {
output.writeInt32(3, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, pageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, filter_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, pageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest other =
(com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest 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.ListTuningJobsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest 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.ListTuningJobsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest 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.ListTuningJobsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest 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.ListTuningJobsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest 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.ListTuningJobsRequest 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.ListTuningJobsRequest 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.ListTuningJobsRequest 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
* [GenAiTuningService.ListTuningJobs][google.cloud.aiplatform.v1beta1.GenAiTuningService.ListTuningJobs].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListTuningJobsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ListTuningJobsRequest)
com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.GenAiTuningServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListTuningJobsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.GenAiTuningServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListTuningJobsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.class,
com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
filter_ = "";
pageSize_ = 0;
pageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.GenAiTuningServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListTuningJobsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest build() {
com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest buildPartial() {
com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest result =
new com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.pageToken_ = pageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest other) {
if (other == com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000008;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000004;
break;
} // case 24
case 34:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The resource name of the Location to list the TuningJobs from.
* Format: `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The resource name of the Location to list the TuningJobs from.
* Format: `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The resource name of the Location to list the TuningJobs from.
* Format: `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource name of the Location to list the TuningJobs from.
* Format: `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource name of the Location to list the TuningJobs from.
* Format: `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Optional. The standard list filter.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The standard list filter.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The standard list filter.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The standard list filter.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The standard list filter.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Optional. The standard list page size.
* </pre>
*
* <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Optional. The standard list page size.
* </pre>
*
* <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The standard list page size.
* </pre>
*
* <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000004);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Optional. The standard list page token.
* Typically obtained via [ListTuningJob.next_page_token][] of the
* previous GenAiTuningService.ListTuningJob][] call.
* </pre>
*
* <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The standard list page token.
* Typically obtained via [ListTuningJob.next_page_token][] of the
* previous GenAiTuningService.ListTuningJob][] call.
* </pre>
*
* <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The standard list page token.
* Typically obtained via [ListTuningJob.next_page_token][] of the
* previous GenAiTuningService.ListTuningJob][] call.
* </pre>
*
* <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The standard list page token.
* Typically obtained via [ListTuningJob.next_page_token][] of the
* previous GenAiTuningService.ListTuningJob][] call.
* </pre>
*
* <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The standard list page token.
* Typically obtained via [ListTuningJob.next_page_token][] of the
* previous GenAiTuningService.ListTuningJob][] call.
* </pre>
*
* <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.ListTuningJobsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ListTuningJobsRequest)
private static final com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest();
}
public static com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListTuningJobsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListTuningJobsRequest>() {
@java.lang.Override
public ListTuningJobsRequest 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<ListTuningJobsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListTuningJobsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListTuningJobsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,608 | java-api-gateway/proto-google-cloud-api-gateway-v1/src/main/java/com/google/cloud/apigateway/v1/CreateGatewayRequest.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/apigateway/v1/apigateway.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.apigateway.v1;
/**
*
*
* <pre>
* Request message for ApiGatewayService.CreateGateway
* </pre>
*
* Protobuf type {@code google.cloud.apigateway.v1.CreateGatewayRequest}
*/
public final class CreateGatewayRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.apigateway.v1.CreateGatewayRequest)
CreateGatewayRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateGatewayRequest.newBuilder() to construct.
private CreateGatewayRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateGatewayRequest() {
parent_ = "";
gatewayId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateGatewayRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_CreateGatewayRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_CreateGatewayRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.apigateway.v1.CreateGatewayRequest.class,
com.google.cloud.apigateway.v1.CreateGatewayRequest.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 of the Gateway, of the form:
* `projects/*/locations/*`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Parent resource of the Gateway, of the form:
* `projects/*/locations/*`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int GATEWAY_ID_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object gatewayId_ = "";
/**
*
*
* <pre>
* Required. Identifier to assign to the Gateway. Must be unique within scope of
* the parent resource.
* </pre>
*
* <code>string gateway_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The gatewayId.
*/
@java.lang.Override
public java.lang.String getGatewayId() {
java.lang.Object ref = gatewayId_;
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();
gatewayId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Identifier to assign to the Gateway. Must be unique within scope of
* the parent resource.
* </pre>
*
* <code>string gateway_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for gatewayId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getGatewayIdBytes() {
java.lang.Object ref = gatewayId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
gatewayId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int GATEWAY_FIELD_NUMBER = 3;
private com.google.cloud.apigateway.v1.Gateway gateway_;
/**
*
*
* <pre>
* Required. Gateway resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.Gateway gateway = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the gateway field is set.
*/
@java.lang.Override
public boolean hasGateway() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Gateway resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.Gateway gateway = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The gateway.
*/
@java.lang.Override
public com.google.cloud.apigateway.v1.Gateway getGateway() {
return gateway_ == null
? com.google.cloud.apigateway.v1.Gateway.getDefaultInstance()
: gateway_;
}
/**
*
*
* <pre>
* Required. Gateway resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.Gateway gateway = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.apigateway.v1.GatewayOrBuilder getGatewayOrBuilder() {
return gateway_ == null
? com.google.cloud.apigateway.v1.Gateway.getDefaultInstance()
: gateway_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(gatewayId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, gatewayId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(3, getGateway());
}
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(gatewayId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, gatewayId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getGateway());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.apigateway.v1.CreateGatewayRequest)) {
return super.equals(obj);
}
com.google.cloud.apigateway.v1.CreateGatewayRequest other =
(com.google.cloud.apigateway.v1.CreateGatewayRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getGatewayId().equals(other.getGatewayId())) return false;
if (hasGateway() != other.hasGateway()) return false;
if (hasGateway()) {
if (!getGateway().equals(other.getGateway())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + GATEWAY_ID_FIELD_NUMBER;
hash = (53 * hash) + getGatewayId().hashCode();
if (hasGateway()) {
hash = (37 * hash) + GATEWAY_FIELD_NUMBER;
hash = (53 * hash) + getGateway().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.apigateway.v1.CreateGatewayRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigateway.v1.CreateGatewayRequest 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.apigateway.v1.CreateGatewayRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigateway.v1.CreateGatewayRequest 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.apigateway.v1.CreateGatewayRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigateway.v1.CreateGatewayRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.apigateway.v1.CreateGatewayRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.apigateway.v1.CreateGatewayRequest 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.apigateway.v1.CreateGatewayRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.apigateway.v1.CreateGatewayRequest 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.apigateway.v1.CreateGatewayRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.apigateway.v1.CreateGatewayRequest 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.apigateway.v1.CreateGatewayRequest 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 ApiGatewayService.CreateGateway
* </pre>
*
* Protobuf type {@code google.cloud.apigateway.v1.CreateGatewayRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.apigateway.v1.CreateGatewayRequest)
com.google.cloud.apigateway.v1.CreateGatewayRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_CreateGatewayRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_CreateGatewayRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.apigateway.v1.CreateGatewayRequest.class,
com.google.cloud.apigateway.v1.CreateGatewayRequest.Builder.class);
}
// Construct using com.google.cloud.apigateway.v1.CreateGatewayRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getGatewayFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
gatewayId_ = "";
gateway_ = null;
if (gatewayBuilder_ != null) {
gatewayBuilder_.dispose();
gatewayBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_CreateGatewayRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.apigateway.v1.CreateGatewayRequest getDefaultInstanceForType() {
return com.google.cloud.apigateway.v1.CreateGatewayRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.apigateway.v1.CreateGatewayRequest build() {
com.google.cloud.apigateway.v1.CreateGatewayRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.apigateway.v1.CreateGatewayRequest buildPartial() {
com.google.cloud.apigateway.v1.CreateGatewayRequest result =
new com.google.cloud.apigateway.v1.CreateGatewayRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.apigateway.v1.CreateGatewayRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.gatewayId_ = gatewayId_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.gateway_ = gatewayBuilder_ == null ? gateway_ : gatewayBuilder_.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.apigateway.v1.CreateGatewayRequest) {
return mergeFrom((com.google.cloud.apigateway.v1.CreateGatewayRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.apigateway.v1.CreateGatewayRequest other) {
if (other == com.google.cloud.apigateway.v1.CreateGatewayRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getGatewayId().isEmpty()) {
gatewayId_ = other.gatewayId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasGateway()) {
mergeGateway(other.getGateway());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
gatewayId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getGatewayFieldBuilder().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 of the Gateway, of the form:
* `projects/*/locations/*`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Parent resource of the Gateway, of the form:
* `projects/*/locations/*`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Parent resource of the Gateway, of the form:
* `projects/*/locations/*`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent resource of the Gateway, of the form:
* `projects/*/locations/*`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent resource of the Gateway, of the form:
* `projects/*/locations/*`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object gatewayId_ = "";
/**
*
*
* <pre>
* Required. Identifier to assign to the Gateway. Must be unique within scope of
* the parent resource.
* </pre>
*
* <code>string gateway_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The gatewayId.
*/
public java.lang.String getGatewayId() {
java.lang.Object ref = gatewayId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
gatewayId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Identifier to assign to the Gateway. Must be unique within scope of
* the parent resource.
* </pre>
*
* <code>string gateway_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for gatewayId.
*/
public com.google.protobuf.ByteString getGatewayIdBytes() {
java.lang.Object ref = gatewayId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
gatewayId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Identifier to assign to the Gateway. Must be unique within scope of
* the parent resource.
* </pre>
*
* <code>string gateway_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The gatewayId to set.
* @return This builder for chaining.
*/
public Builder setGatewayId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
gatewayId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Identifier to assign to the Gateway. Must be unique within scope of
* the parent resource.
* </pre>
*
* <code>string gateway_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearGatewayId() {
gatewayId_ = getDefaultInstance().getGatewayId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Identifier to assign to the Gateway. Must be unique within scope of
* the parent resource.
* </pre>
*
* <code>string gateway_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for gatewayId to set.
* @return This builder for chaining.
*/
public Builder setGatewayIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
gatewayId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.cloud.apigateway.v1.Gateway gateway_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.apigateway.v1.Gateway,
com.google.cloud.apigateway.v1.Gateway.Builder,
com.google.cloud.apigateway.v1.GatewayOrBuilder>
gatewayBuilder_;
/**
*
*
* <pre>
* Required. Gateway resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.Gateway gateway = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the gateway field is set.
*/
public boolean hasGateway() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Required. Gateway resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.Gateway gateway = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The gateway.
*/
public com.google.cloud.apigateway.v1.Gateway getGateway() {
if (gatewayBuilder_ == null) {
return gateway_ == null
? com.google.cloud.apigateway.v1.Gateway.getDefaultInstance()
: gateway_;
} else {
return gatewayBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Gateway resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.Gateway gateway = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setGateway(com.google.cloud.apigateway.v1.Gateway value) {
if (gatewayBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
gateway_ = value;
} else {
gatewayBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Gateway resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.Gateway gateway = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setGateway(com.google.cloud.apigateway.v1.Gateway.Builder builderForValue) {
if (gatewayBuilder_ == null) {
gateway_ = builderForValue.build();
} else {
gatewayBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Gateway resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.Gateway gateway = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeGateway(com.google.cloud.apigateway.v1.Gateway value) {
if (gatewayBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& gateway_ != null
&& gateway_ != com.google.cloud.apigateway.v1.Gateway.getDefaultInstance()) {
getGatewayBuilder().mergeFrom(value);
} else {
gateway_ = value;
}
} else {
gatewayBuilder_.mergeFrom(value);
}
if (gateway_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Gateway resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.Gateway gateway = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearGateway() {
bitField0_ = (bitField0_ & ~0x00000004);
gateway_ = null;
if (gatewayBuilder_ != null) {
gatewayBuilder_.dispose();
gatewayBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Gateway resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.Gateway gateway = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.apigateway.v1.Gateway.Builder getGatewayBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getGatewayFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Gateway resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.Gateway gateway = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.apigateway.v1.GatewayOrBuilder getGatewayOrBuilder() {
if (gatewayBuilder_ != null) {
return gatewayBuilder_.getMessageOrBuilder();
} else {
return gateway_ == null
? com.google.cloud.apigateway.v1.Gateway.getDefaultInstance()
: gateway_;
}
}
/**
*
*
* <pre>
* Required. Gateway resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.Gateway gateway = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.apigateway.v1.Gateway,
com.google.cloud.apigateway.v1.Gateway.Builder,
com.google.cloud.apigateway.v1.GatewayOrBuilder>
getGatewayFieldBuilder() {
if (gatewayBuilder_ == null) {
gatewayBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.apigateway.v1.Gateway,
com.google.cloud.apigateway.v1.Gateway.Builder,
com.google.cloud.apigateway.v1.GatewayOrBuilder>(
getGateway(), getParentForChildren(), isClean());
gateway_ = null;
}
return gatewayBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.apigateway.v1.CreateGatewayRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.apigateway.v1.CreateGatewayRequest)
private static final com.google.cloud.apigateway.v1.CreateGatewayRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.apigateway.v1.CreateGatewayRequest();
}
public static com.google.cloud.apigateway.v1.CreateGatewayRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateGatewayRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateGatewayRequest>() {
@java.lang.Override
public CreateGatewayRequest 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<CreateGatewayRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateGatewayRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.apigateway.v1.CreateGatewayRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,671 | java-network-management/proto-google-cloud-network-management-v1beta1/src/main/java/com/google/cloud/networkmanagement/v1beta1/UpdateConnectivityTestRequest.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/networkmanagement/v1beta1/reachability.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.networkmanagement.v1beta1;
/**
*
*
* <pre>
* Request for the `UpdateConnectivityTest` method.
* </pre>
*
* Protobuf type {@code google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest}
*/
public final class UpdateConnectivityTestRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest)
UpdateConnectivityTestRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateConnectivityTestRequest.newBuilder() to construct.
private UpdateConnectivityTestRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateConnectivityTestRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateConnectivityTestRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.networkmanagement.v1beta1.ReachabilityServiceProto
.internal_static_google_cloud_networkmanagement_v1beta1_UpdateConnectivityTestRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.networkmanagement.v1beta1.ReachabilityServiceProto
.internal_static_google_cloud_networkmanagement_v1beta1_UpdateConnectivityTestRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest.class,
com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest.Builder.class);
}
private int bitField0_;
public static final int UPDATE_MASK_FIELD_NUMBER = 1;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field.
* </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 RESOURCE_FIELD_NUMBER = 2;
private com.google.cloud.networkmanagement.v1beta1.ConnectivityTest resource_;
/**
*
*
* <pre>
* Required. Only fields specified in update_mask are updated.
* </pre>
*
* <code>
* .google.cloud.networkmanagement.v1beta1.ConnectivityTest resource = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the resource field is set.
*/
@java.lang.Override
public boolean hasResource() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Only fields specified in update_mask are updated.
* </pre>
*
* <code>
* .google.cloud.networkmanagement.v1beta1.ConnectivityTest resource = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The resource.
*/
@java.lang.Override
public com.google.cloud.networkmanagement.v1beta1.ConnectivityTest getResource() {
return resource_ == null
? com.google.cloud.networkmanagement.v1beta1.ConnectivityTest.getDefaultInstance()
: resource_;
}
/**
*
*
* <pre>
* Required. Only fields specified in update_mask are updated.
* </pre>
*
* <code>
* .google.cloud.networkmanagement.v1beta1.ConnectivityTest resource = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.networkmanagement.v1beta1.ConnectivityTestOrBuilder
getResourceOrBuilder() {
return resource_ == null
? com.google.cloud.networkmanagement.v1beta1.ConnectivityTest.getDefaultInstance()
: resource_;
}
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, getResource());
}
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, getResource());
}
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.networkmanagement.v1beta1.UpdateConnectivityTestRequest)) {
return super.equals(obj);
}
com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest other =
(com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest) obj;
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (hasResource() != other.hasResource()) return false;
if (hasResource()) {
if (!getResource().equals(other.getResource())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
if (hasResource()) {
hash = (37 * hash) + RESOURCE_FIELD_NUMBER;
hash = (53 * hash) + getResource().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest 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.networkmanagement.v1beta1.UpdateConnectivityTestRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest 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.networkmanagement.v1beta1.UpdateConnectivityTestRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest 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.networkmanagement.v1beta1.UpdateConnectivityTestRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest
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.networkmanagement.v1beta1.UpdateConnectivityTestRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest 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.networkmanagement.v1beta1.UpdateConnectivityTestRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for the `UpdateConnectivityTest` method.
* </pre>
*
* Protobuf type {@code google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest)
com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.networkmanagement.v1beta1.ReachabilityServiceProto
.internal_static_google_cloud_networkmanagement_v1beta1_UpdateConnectivityTestRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.networkmanagement.v1beta1.ReachabilityServiceProto
.internal_static_google_cloud_networkmanagement_v1beta1_UpdateConnectivityTestRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest.class,
com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest.Builder
.class);
}
// Construct using
// com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest.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();
getResourceFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
resource_ = null;
if (resourceBuilder_ != null) {
resourceBuilder_.dispose();
resourceBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.networkmanagement.v1beta1.ReachabilityServiceProto
.internal_static_google_cloud_networkmanagement_v1beta1_UpdateConnectivityTestRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest
getDefaultInstanceForType() {
return com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest build() {
com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest result =
buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest buildPartial() {
com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest result =
new com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest 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.resource_ = resourceBuilder_ == null ? resource_ : resourceBuilder_.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.networkmanagement.v1beta1.UpdateConnectivityTestRequest) {
return mergeFrom(
(com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest other) {
if (other
== com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest
.getDefaultInstance()) return this;
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
if (other.hasResource()) {
mergeResource(other.getResource());
}
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(getResourceFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000001);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field.
* </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.networkmanagement.v1beta1.ConnectivityTest resource_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.networkmanagement.v1beta1.ConnectivityTest,
com.google.cloud.networkmanagement.v1beta1.ConnectivityTest.Builder,
com.google.cloud.networkmanagement.v1beta1.ConnectivityTestOrBuilder>
resourceBuilder_;
/**
*
*
* <pre>
* Required. Only fields specified in update_mask are updated.
* </pre>
*
* <code>
* .google.cloud.networkmanagement.v1beta1.ConnectivityTest resource = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the resource field is set.
*/
public boolean hasResource() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Only fields specified in update_mask are updated.
* </pre>
*
* <code>
* .google.cloud.networkmanagement.v1beta1.ConnectivityTest resource = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The resource.
*/
public com.google.cloud.networkmanagement.v1beta1.ConnectivityTest getResource() {
if (resourceBuilder_ == null) {
return resource_ == null
? com.google.cloud.networkmanagement.v1beta1.ConnectivityTest.getDefaultInstance()
: resource_;
} else {
return resourceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Only fields specified in update_mask are updated.
* </pre>
*
* <code>
* .google.cloud.networkmanagement.v1beta1.ConnectivityTest resource = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setResource(com.google.cloud.networkmanagement.v1beta1.ConnectivityTest value) {
if (resourceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
resource_ = value;
} else {
resourceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Only fields specified in update_mask are updated.
* </pre>
*
* <code>
* .google.cloud.networkmanagement.v1beta1.ConnectivityTest resource = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setResource(
com.google.cloud.networkmanagement.v1beta1.ConnectivityTest.Builder builderForValue) {
if (resourceBuilder_ == null) {
resource_ = builderForValue.build();
} else {
resourceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Only fields specified in update_mask are updated.
* </pre>
*
* <code>
* .google.cloud.networkmanagement.v1beta1.ConnectivityTest resource = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeResource(
com.google.cloud.networkmanagement.v1beta1.ConnectivityTest value) {
if (resourceBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& resource_ != null
&& resource_
!= com.google.cloud.networkmanagement.v1beta1.ConnectivityTest
.getDefaultInstance()) {
getResourceBuilder().mergeFrom(value);
} else {
resource_ = value;
}
} else {
resourceBuilder_.mergeFrom(value);
}
if (resource_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Only fields specified in update_mask are updated.
* </pre>
*
* <code>
* .google.cloud.networkmanagement.v1beta1.ConnectivityTest resource = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearResource() {
bitField0_ = (bitField0_ & ~0x00000002);
resource_ = null;
if (resourceBuilder_ != null) {
resourceBuilder_.dispose();
resourceBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Only fields specified in update_mask are updated.
* </pre>
*
* <code>
* .google.cloud.networkmanagement.v1beta1.ConnectivityTest resource = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.networkmanagement.v1beta1.ConnectivityTest.Builder
getResourceBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getResourceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Only fields specified in update_mask are updated.
* </pre>
*
* <code>
* .google.cloud.networkmanagement.v1beta1.ConnectivityTest resource = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.networkmanagement.v1beta1.ConnectivityTestOrBuilder
getResourceOrBuilder() {
if (resourceBuilder_ != null) {
return resourceBuilder_.getMessageOrBuilder();
} else {
return resource_ == null
? com.google.cloud.networkmanagement.v1beta1.ConnectivityTest.getDefaultInstance()
: resource_;
}
}
/**
*
*
* <pre>
* Required. Only fields specified in update_mask are updated.
* </pre>
*
* <code>
* .google.cloud.networkmanagement.v1beta1.ConnectivityTest resource = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.networkmanagement.v1beta1.ConnectivityTest,
com.google.cloud.networkmanagement.v1beta1.ConnectivityTest.Builder,
com.google.cloud.networkmanagement.v1beta1.ConnectivityTestOrBuilder>
getResourceFieldBuilder() {
if (resourceBuilder_ == null) {
resourceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.networkmanagement.v1beta1.ConnectivityTest,
com.google.cloud.networkmanagement.v1beta1.ConnectivityTest.Builder,
com.google.cloud.networkmanagement.v1beta1.ConnectivityTestOrBuilder>(
getResource(), getParentForChildren(), isClean());
resource_ = null;
}
return resourceBuilder_;
}
@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.networkmanagement.v1beta1.UpdateConnectivityTestRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest)
private static final com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest();
}
public static com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateConnectivityTestRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateConnectivityTestRequest>() {
@java.lang.Override
public UpdateConnectivityTestRequest 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<UpdateConnectivityTestRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateConnectivityTestRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.networkmanagement.v1beta1.UpdateConnectivityTestRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,687 | java-shopping-merchant-notifications/proto-google-shopping-merchant-notifications-v1/src/main/java/com/google/shopping/merchant/notifications/v1/CreateNotificationSubscriptionRequest.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/notifications/v1/notificationsapi.proto
// Protobuf Java Version: 3.25.8
package com.google.shopping.merchant.notifications.v1;
/**
*
*
* <pre>
* Request message for the CreateNotificationSubscription method.
* </pre>
*
* Protobuf type {@code
* google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest}
*/
public final class CreateNotificationSubscriptionRequest
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest)
CreateNotificationSubscriptionRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateNotificationSubscriptionRequest.newBuilder() to construct.
private CreateNotificationSubscriptionRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateNotificationSubscriptionRequest() {
parent_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateNotificationSubscriptionRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.notifications.v1.NotificationsApiProto
.internal_static_google_shopping_merchant_notifications_v1_CreateNotificationSubscriptionRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.notifications.v1.NotificationsApiProto
.internal_static_google_shopping_merchant_notifications_v1_CreateNotificationSubscriptionRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
.class,
com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The merchant account that owns the new notification subscription.
* Format: `accounts/{account}`
* </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 merchant account that owns the new notification subscription.
* Format: `accounts/{account}`
* </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 NOTIFICATION_SUBSCRIPTION_FIELD_NUMBER = 2;
private com.google.shopping.merchant.notifications.v1.NotificationSubscription
notificationSubscription_;
/**
*
*
* <pre>
* Required. The notification subscription to create.
* </pre>
*
* <code>
* .google.shopping.merchant.notifications.v1.NotificationSubscription notification_subscription = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the notificationSubscription field is set.
*/
@java.lang.Override
public boolean hasNotificationSubscription() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The notification subscription to create.
* </pre>
*
* <code>
* .google.shopping.merchant.notifications.v1.NotificationSubscription notification_subscription = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The notificationSubscription.
*/
@java.lang.Override
public com.google.shopping.merchant.notifications.v1.NotificationSubscription
getNotificationSubscription() {
return notificationSubscription_ == null
? com.google.shopping.merchant.notifications.v1.NotificationSubscription
.getDefaultInstance()
: notificationSubscription_;
}
/**
*
*
* <pre>
* Required. The notification subscription to create.
* </pre>
*
* <code>
* .google.shopping.merchant.notifications.v1.NotificationSubscription notification_subscription = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.shopping.merchant.notifications.v1.NotificationSubscriptionOrBuilder
getNotificationSubscriptionOrBuilder() {
return notificationSubscription_ == null
? com.google.shopping.merchant.notifications.v1.NotificationSubscription
.getDefaultInstance()
: notificationSubscription_;
}
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, getNotificationSubscription());
}
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, getNotificationSubscription());
}
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.notifications.v1.CreateNotificationSubscriptionRequest)) {
return super.equals(obj);
}
com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest other =
(com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasNotificationSubscription() != other.hasNotificationSubscription()) return false;
if (hasNotificationSubscription()) {
if (!getNotificationSubscription().equals(other.getNotificationSubscription())) 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 (hasNotificationSubscription()) {
hash = (37 * hash) + NOTIFICATION_SUBSCRIPTION_FIELD_NUMBER;
hash = (53 * hash) + getNotificationSubscription().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
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.notifications.v1.CreateNotificationSubscriptionRequest
parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
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.notifications.v1.CreateNotificationSubscriptionRequest
parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
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.notifications.v1.CreateNotificationSubscriptionRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
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.notifications.v1.CreateNotificationSubscriptionRequest
parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
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.notifications.v1.CreateNotificationSubscriptionRequest
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 CreateNotificationSubscription method.
* </pre>
*
* Protobuf type {@code
* google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest)
com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.notifications.v1.NotificationsApiProto
.internal_static_google_shopping_merchant_notifications_v1_CreateNotificationSubscriptionRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.notifications.v1.NotificationsApiProto
.internal_static_google_shopping_merchant_notifications_v1_CreateNotificationSubscriptionRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
.class,
com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
.Builder.class);
}
// Construct using
// com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getNotificationSubscriptionFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
notificationSubscription_ = null;
if (notificationSubscriptionBuilder_ != null) {
notificationSubscriptionBuilder_.dispose();
notificationSubscriptionBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.shopping.merchant.notifications.v1.NotificationsApiProto
.internal_static_google_shopping_merchant_notifications_v1_CreateNotificationSubscriptionRequest_descriptor;
}
@java.lang.Override
public com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
getDefaultInstanceForType() {
return com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
build() {
com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest result =
buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
buildPartial() {
com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest result =
new com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest(
this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.notificationSubscription_ =
notificationSubscriptionBuilder_ == null
? notificationSubscription_
: notificationSubscriptionBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other
instanceof
com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest) {
return mergeFrom(
(com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest)
other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest other) {
if (other
== com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasNotificationSubscription()) {
mergeNotificationSubscription(other.getNotificationSubscription());
}
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(
getNotificationSubscriptionFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The merchant account that owns the new notification subscription.
* Format: `accounts/{account}`
* </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 merchant account that owns the new notification subscription.
* Format: `accounts/{account}`
* </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 merchant account that owns the new notification subscription.
* Format: `accounts/{account}`
* </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 merchant account that owns the new notification subscription.
* Format: `accounts/{account}`
* </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 merchant account that owns the new notification subscription.
* Format: `accounts/{account}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.shopping.merchant.notifications.v1.NotificationSubscription
notificationSubscription_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.notifications.v1.NotificationSubscription,
com.google.shopping.merchant.notifications.v1.NotificationSubscription.Builder,
com.google.shopping.merchant.notifications.v1.NotificationSubscriptionOrBuilder>
notificationSubscriptionBuilder_;
/**
*
*
* <pre>
* Required. The notification subscription to create.
* </pre>
*
* <code>
* .google.shopping.merchant.notifications.v1.NotificationSubscription notification_subscription = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the notificationSubscription field is set.
*/
public boolean hasNotificationSubscription() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The notification subscription to create.
* </pre>
*
* <code>
* .google.shopping.merchant.notifications.v1.NotificationSubscription notification_subscription = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The notificationSubscription.
*/
public com.google.shopping.merchant.notifications.v1.NotificationSubscription
getNotificationSubscription() {
if (notificationSubscriptionBuilder_ == null) {
return notificationSubscription_ == null
? com.google.shopping.merchant.notifications.v1.NotificationSubscription
.getDefaultInstance()
: notificationSubscription_;
} else {
return notificationSubscriptionBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The notification subscription to create.
* </pre>
*
* <code>
* .google.shopping.merchant.notifications.v1.NotificationSubscription notification_subscription = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setNotificationSubscription(
com.google.shopping.merchant.notifications.v1.NotificationSubscription value) {
if (notificationSubscriptionBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
notificationSubscription_ = value;
} else {
notificationSubscriptionBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The notification subscription to create.
* </pre>
*
* <code>
* .google.shopping.merchant.notifications.v1.NotificationSubscription notification_subscription = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setNotificationSubscription(
com.google.shopping.merchant.notifications.v1.NotificationSubscription.Builder
builderForValue) {
if (notificationSubscriptionBuilder_ == null) {
notificationSubscription_ = builderForValue.build();
} else {
notificationSubscriptionBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The notification subscription to create.
* </pre>
*
* <code>
* .google.shopping.merchant.notifications.v1.NotificationSubscription notification_subscription = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeNotificationSubscription(
com.google.shopping.merchant.notifications.v1.NotificationSubscription value) {
if (notificationSubscriptionBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& notificationSubscription_ != null
&& notificationSubscription_
!= com.google.shopping.merchant.notifications.v1.NotificationSubscription
.getDefaultInstance()) {
getNotificationSubscriptionBuilder().mergeFrom(value);
} else {
notificationSubscription_ = value;
}
} else {
notificationSubscriptionBuilder_.mergeFrom(value);
}
if (notificationSubscription_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The notification subscription to create.
* </pre>
*
* <code>
* .google.shopping.merchant.notifications.v1.NotificationSubscription notification_subscription = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearNotificationSubscription() {
bitField0_ = (bitField0_ & ~0x00000002);
notificationSubscription_ = null;
if (notificationSubscriptionBuilder_ != null) {
notificationSubscriptionBuilder_.dispose();
notificationSubscriptionBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The notification subscription to create.
* </pre>
*
* <code>
* .google.shopping.merchant.notifications.v1.NotificationSubscription notification_subscription = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.shopping.merchant.notifications.v1.NotificationSubscription.Builder
getNotificationSubscriptionBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getNotificationSubscriptionFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The notification subscription to create.
* </pre>
*
* <code>
* .google.shopping.merchant.notifications.v1.NotificationSubscription notification_subscription = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.shopping.merchant.notifications.v1.NotificationSubscriptionOrBuilder
getNotificationSubscriptionOrBuilder() {
if (notificationSubscriptionBuilder_ != null) {
return notificationSubscriptionBuilder_.getMessageOrBuilder();
} else {
return notificationSubscription_ == null
? com.google.shopping.merchant.notifications.v1.NotificationSubscription
.getDefaultInstance()
: notificationSubscription_;
}
}
/**
*
*
* <pre>
* Required. The notification subscription to create.
* </pre>
*
* <code>
* .google.shopping.merchant.notifications.v1.NotificationSubscription notification_subscription = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.notifications.v1.NotificationSubscription,
com.google.shopping.merchant.notifications.v1.NotificationSubscription.Builder,
com.google.shopping.merchant.notifications.v1.NotificationSubscriptionOrBuilder>
getNotificationSubscriptionFieldBuilder() {
if (notificationSubscriptionBuilder_ == null) {
notificationSubscriptionBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.notifications.v1.NotificationSubscription,
com.google.shopping.merchant.notifications.v1.NotificationSubscription.Builder,
com.google.shopping.merchant.notifications.v1.NotificationSubscriptionOrBuilder>(
getNotificationSubscription(), getParentForChildren(), isClean());
notificationSubscription_ = null;
}
return notificationSubscriptionBuilder_;
}
@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.notifications.v1.CreateNotificationSubscriptionRequest)
}
// @@protoc_insertion_point(class_scope:google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest)
private static final com.google.shopping.merchant.notifications.v1
.CreateNotificationSubscriptionRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest();
}
public static com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateNotificationSubscriptionRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateNotificationSubscriptionRequest>() {
@java.lang.Override
public CreateNotificationSubscriptionRequest 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<CreateNotificationSubscriptionRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateNotificationSubscriptionRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.shopping.merchant.notifications.v1.CreateNotificationSubscriptionRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,620 | java-shopping-merchant-accounts/proto-google-shopping-merchant-accounts-v1/src/main/java/com/google/shopping/merchant/accounts/v1/UpdateUserRequest.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/user.proto
// Protobuf Java Version: 3.25.8
package com.google.shopping.merchant.accounts.v1;
/**
*
*
* <pre>
* Request message for the `UpdateUser` method.
* </pre>
*
* Protobuf type {@code google.shopping.merchant.accounts.v1.UpdateUserRequest}
*/
public final class UpdateUserRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.shopping.merchant.accounts.v1.UpdateUserRequest)
UpdateUserRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateUserRequest.newBuilder() to construct.
private UpdateUserRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateUserRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateUserRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.accounts.v1.UserProto
.internal_static_google_shopping_merchant_accounts_v1_UpdateUserRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.accounts.v1.UserProto
.internal_static_google_shopping_merchant_accounts_v1_UpdateUserRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.accounts.v1.UpdateUserRequest.class,
com.google.shopping.merchant.accounts.v1.UpdateUserRequest.Builder.class);
}
private int bitField0_;
public static final int USER_FIELD_NUMBER = 1;
private com.google.shopping.merchant.accounts.v1.User user_;
/**
*
*
* <pre>
* Required. The new version of the user.
*
* Use `me` to refer to your own email address, for example
* `accounts/{account}/users/me`.
* </pre>
*
* <code>
* .google.shopping.merchant.accounts.v1.User user = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the user field is set.
*/
@java.lang.Override
public boolean hasUser() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The new version of the user.
*
* Use `me` to refer to your own email address, for example
* `accounts/{account}/users/me`.
* </pre>
*
* <code>
* .google.shopping.merchant.accounts.v1.User user = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The user.
*/
@java.lang.Override
public com.google.shopping.merchant.accounts.v1.User getUser() {
return user_ == null
? com.google.shopping.merchant.accounts.v1.User.getDefaultInstance()
: user_;
}
/**
*
*
* <pre>
* Required. The new version of the user.
*
* Use `me` to refer to your own email address, for example
* `accounts/{account}/users/me`.
* </pre>
*
* <code>
* .google.shopping.merchant.accounts.v1.User user = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.shopping.merchant.accounts.v1.UserOrBuilder getUserOrBuilder() {
return user_ == null
? com.google.shopping.merchant.accounts.v1.User.getDefaultInstance()
: user_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Optional. List of fields being updated.
*
* The following fields are supported (in both `snake_case` and
* `lowerCamelCase`):
*
* - `access_rights`
* </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. List of fields being updated.
*
* The following fields are supported (in both `snake_case` and
* `lowerCamelCase`):
*
* - `access_rights`
* </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. List of fields being updated.
*
* The following fields are supported (in both `snake_case` and
* `lowerCamelCase`):
*
* - `access_rights`
* </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, getUser());
}
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, getUser());
}
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.shopping.merchant.accounts.v1.UpdateUserRequest)) {
return super.equals(obj);
}
com.google.shopping.merchant.accounts.v1.UpdateUserRequest other =
(com.google.shopping.merchant.accounts.v1.UpdateUserRequest) obj;
if (hasUser() != other.hasUser()) return false;
if (hasUser()) {
if (!getUser().equals(other.getUser())) 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 (hasUser()) {
hash = (37 * hash) + USER_FIELD_NUMBER;
hash = (53 * hash) + getUser().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.shopping.merchant.accounts.v1.UpdateUserRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.accounts.v1.UpdateUserRequest 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.UpdateUserRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.accounts.v1.UpdateUserRequest 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.UpdateUserRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.accounts.v1.UpdateUserRequest 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.UpdateUserRequest 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.UpdateUserRequest 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.UpdateUserRequest 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.UpdateUserRequest 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.UpdateUserRequest 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.UpdateUserRequest 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.UpdateUserRequest 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 `UpdateUser` method.
* </pre>
*
* Protobuf type {@code google.shopping.merchant.accounts.v1.UpdateUserRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.shopping.merchant.accounts.v1.UpdateUserRequest)
com.google.shopping.merchant.accounts.v1.UpdateUserRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.accounts.v1.UserProto
.internal_static_google_shopping_merchant_accounts_v1_UpdateUserRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.accounts.v1.UserProto
.internal_static_google_shopping_merchant_accounts_v1_UpdateUserRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.accounts.v1.UpdateUserRequest.class,
com.google.shopping.merchant.accounts.v1.UpdateUserRequest.Builder.class);
}
// Construct using com.google.shopping.merchant.accounts.v1.UpdateUserRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getUserFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
user_ = null;
if (userBuilder_ != null) {
userBuilder_.dispose();
userBuilder_ = 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.shopping.merchant.accounts.v1.UserProto
.internal_static_google_shopping_merchant_accounts_v1_UpdateUserRequest_descriptor;
}
@java.lang.Override
public com.google.shopping.merchant.accounts.v1.UpdateUserRequest getDefaultInstanceForType() {
return com.google.shopping.merchant.accounts.v1.UpdateUserRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.shopping.merchant.accounts.v1.UpdateUserRequest build() {
com.google.shopping.merchant.accounts.v1.UpdateUserRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.shopping.merchant.accounts.v1.UpdateUserRequest buildPartial() {
com.google.shopping.merchant.accounts.v1.UpdateUserRequest result =
new com.google.shopping.merchant.accounts.v1.UpdateUserRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.shopping.merchant.accounts.v1.UpdateUserRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.user_ = userBuilder_ == null ? user_ : userBuilder_.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.shopping.merchant.accounts.v1.UpdateUserRequest) {
return mergeFrom((com.google.shopping.merchant.accounts.v1.UpdateUserRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.shopping.merchant.accounts.v1.UpdateUserRequest other) {
if (other == com.google.shopping.merchant.accounts.v1.UpdateUserRequest.getDefaultInstance())
return this;
if (other.hasUser()) {
mergeUser(other.getUser());
}
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(getUserFieldBuilder().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.shopping.merchant.accounts.v1.User user_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.accounts.v1.User,
com.google.shopping.merchant.accounts.v1.User.Builder,
com.google.shopping.merchant.accounts.v1.UserOrBuilder>
userBuilder_;
/**
*
*
* <pre>
* Required. The new version of the user.
*
* Use `me` to refer to your own email address, for example
* `accounts/{account}/users/me`.
* </pre>
*
* <code>
* .google.shopping.merchant.accounts.v1.User user = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the user field is set.
*/
public boolean hasUser() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The new version of the user.
*
* Use `me` to refer to your own email address, for example
* `accounts/{account}/users/me`.
* </pre>
*
* <code>
* .google.shopping.merchant.accounts.v1.User user = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The user.
*/
public com.google.shopping.merchant.accounts.v1.User getUser() {
if (userBuilder_ == null) {
return user_ == null
? com.google.shopping.merchant.accounts.v1.User.getDefaultInstance()
: user_;
} else {
return userBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The new version of the user.
*
* Use `me` to refer to your own email address, for example
* `accounts/{account}/users/me`.
* </pre>
*
* <code>
* .google.shopping.merchant.accounts.v1.User user = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUser(com.google.shopping.merchant.accounts.v1.User value) {
if (userBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
user_ = value;
} else {
userBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The new version of the user.
*
* Use `me` to refer to your own email address, for example
* `accounts/{account}/users/me`.
* </pre>
*
* <code>
* .google.shopping.merchant.accounts.v1.User user = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUser(com.google.shopping.merchant.accounts.v1.User.Builder builderForValue) {
if (userBuilder_ == null) {
user_ = builderForValue.build();
} else {
userBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The new version of the user.
*
* Use `me` to refer to your own email address, for example
* `accounts/{account}/users/me`.
* </pre>
*
* <code>
* .google.shopping.merchant.accounts.v1.User user = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeUser(com.google.shopping.merchant.accounts.v1.User value) {
if (userBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& user_ != null
&& user_ != com.google.shopping.merchant.accounts.v1.User.getDefaultInstance()) {
getUserBuilder().mergeFrom(value);
} else {
user_ = value;
}
} else {
userBuilder_.mergeFrom(value);
}
if (user_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The new version of the user.
*
* Use `me` to refer to your own email address, for example
* `accounts/{account}/users/me`.
* </pre>
*
* <code>
* .google.shopping.merchant.accounts.v1.User user = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearUser() {
bitField0_ = (bitField0_ & ~0x00000001);
user_ = null;
if (userBuilder_ != null) {
userBuilder_.dispose();
userBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The new version of the user.
*
* Use `me` to refer to your own email address, for example
* `accounts/{account}/users/me`.
* </pre>
*
* <code>
* .google.shopping.merchant.accounts.v1.User user = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.shopping.merchant.accounts.v1.User.Builder getUserBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getUserFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The new version of the user.
*
* Use `me` to refer to your own email address, for example
* `accounts/{account}/users/me`.
* </pre>
*
* <code>
* .google.shopping.merchant.accounts.v1.User user = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.shopping.merchant.accounts.v1.UserOrBuilder getUserOrBuilder() {
if (userBuilder_ != null) {
return userBuilder_.getMessageOrBuilder();
} else {
return user_ == null
? com.google.shopping.merchant.accounts.v1.User.getDefaultInstance()
: user_;
}
}
/**
*
*
* <pre>
* Required. The new version of the user.
*
* Use `me` to refer to your own email address, for example
* `accounts/{account}/users/me`.
* </pre>
*
* <code>
* .google.shopping.merchant.accounts.v1.User user = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.accounts.v1.User,
com.google.shopping.merchant.accounts.v1.User.Builder,
com.google.shopping.merchant.accounts.v1.UserOrBuilder>
getUserFieldBuilder() {
if (userBuilder_ == null) {
userBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.accounts.v1.User,
com.google.shopping.merchant.accounts.v1.User.Builder,
com.google.shopping.merchant.accounts.v1.UserOrBuilder>(
getUser(), getParentForChildren(), isClean());
user_ = null;
}
return userBuilder_;
}
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. List of fields being updated.
*
* The following fields are supported (in both `snake_case` and
* `lowerCamelCase`):
*
* - `access_rights`
* </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. List of fields being updated.
*
* The following fields are supported (in both `snake_case` and
* `lowerCamelCase`):
*
* - `access_rights`
* </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. List of fields being updated.
*
* The following fields are supported (in both `snake_case` and
* `lowerCamelCase`):
*
* - `access_rights`
* </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. List of fields being updated.
*
* The following fields are supported (in both `snake_case` and
* `lowerCamelCase`):
*
* - `access_rights`
* </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. List of fields being updated.
*
* The following fields are supported (in both `snake_case` and
* `lowerCamelCase`):
*
* - `access_rights`
* </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. List of fields being updated.
*
* The following fields are supported (in both `snake_case` and
* `lowerCamelCase`):
*
* - `access_rights`
* </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. List of fields being updated.
*
* The following fields are supported (in both `snake_case` and
* `lowerCamelCase`):
*
* - `access_rights`
* </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. List of fields being updated.
*
* The following fields are supported (in both `snake_case` and
* `lowerCamelCase`):
*
* - `access_rights`
* </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. List of fields being updated.
*
* The following fields are supported (in both `snake_case` and
* `lowerCamelCase`):
*
* - `access_rights`
* </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.shopping.merchant.accounts.v1.UpdateUserRequest)
}
// @@protoc_insertion_point(class_scope:google.shopping.merchant.accounts.v1.UpdateUserRequest)
private static final com.google.shopping.merchant.accounts.v1.UpdateUserRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.shopping.merchant.accounts.v1.UpdateUserRequest();
}
public static com.google.shopping.merchant.accounts.v1.UpdateUserRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateUserRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateUserRequest>() {
@java.lang.Override
public UpdateUserRequest 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<UpdateUserRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateUserRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.shopping.merchant.accounts.v1.UpdateUserRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-api-java-client-services | 35,900 | clients/google-api-services-compute/beta/1.30.1/com/google/api/services/compute/model/Firewall.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 a Firewall Rule resource.
*
* Firewall rules allow or deny ingress traffic to, and egress traffic from your instances. For more
* information, read Firewall rules.
*
* <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 Firewall extends com.google.api.client.json.GenericJson {
/**
* The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a permitted connection.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Allowed> allowed;
static {
// hack to force ProGuard to consider Allowed 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(Allowed.class);
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String creationTimestamp;
/**
* The list of DENY rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a denied connection.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Denied> denied;
static {
// hack to force ProGuard to consider Denied 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(Denied.class);
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* If destination ranges are specified, the firewall rule applies only to traffic that has
* destination IP address in these ranges. These ranges must be expressed in CIDR format. Only
* IPv4 is supported.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> destinationRanges;
/**
* Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default
* is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for
* `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String direction;
/**
* Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not
* enforced and the network behaves as if it did not exist. If this is unspecified, the firewall
* rule will be enabled.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean disabled;
/**
* Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a
* particular firewall rule. If logging is enabled, logs will be exported t Cloud Logging.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean enableLogging;
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.math.BigInteger id;
/**
* [Output Only] Type of the resource. Always compute#firewall for firewall rules.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* This field denotes the logging options for a particular firewall rule. If logging is enabled,
* logs will be exported to Cloud Logging.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private FirewallLogConfig logConfig;
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* URL of the network resource for this firewall rule. If not specified when creating a firewall
* rule, the default network is used: global/networks/default If you choose to specify this field,
* you can specify the network as a full or partial URL. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network
* - projects/myproject/global/networks/my-network - global/networks/default
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String network;
/**
* Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default
* value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply.
* Lower values indicate higher priority. For example, a rule with priority `0` has higher
* precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they
* have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To
* avoid conflicts with the implied rules, use a priority number less than `65535`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer priority;
/**
* [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;
/**
* If source ranges are specified, the firewall rule applies only to traffic that has a source IP
* address in these ranges. These ranges must be expressed in CIDR format. One or both of
* sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic
* that has a source IP address within sourceRanges OR a source IP from a resource with a matching
* tag listed in the sourceTags field. The connection does not need to match both fields for the
* rule to apply. Only IPv4 is supported.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sourceRanges;
/**
* If source service accounts are specified, the firewall rules apply only to traffic originating
* from an instance with a service account in this list. Source service accounts cannot be used to
* control traffic to an instance's external IP address because service accounts are associated
* with an instance, not an IP address. sourceRanges can be set at the same time as
* sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP
* address within the sourceRanges OR a source IP that belongs to an instance with service account
* listed in sourceServiceAccount. The connection does not need to match both fields for the
* firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or
* targetTags.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sourceServiceAccounts;
/**
* If source tags are specified, the firewall rule applies only to traffic with source IPs that
* match the primary network interfaces of VM instances that have the tag and are in the same VPC
* network. Source tags cannot be used to control traffic to an instance's external IP address, it
* only applies to traffic between instances in the same virtual network. Because tags are
* associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be
* set. If both fields are set, the firewall applies to traffic that has a source IP address
* within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags
* field. The connection does not need to match both fields for the firewall to apply.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sourceTags;
/**
* A list of service accounts indicating sets of instances located in the network that may make
* network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same
* time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are
* specified, the firewall rule applies to all instances on the specified network.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> targetServiceAccounts;
/**
* A list of tags that controls which instances the firewall rule applies to. If targetTags are
* specified, then the firewall rule applies only to instances in the VPC network that have one of
* those tags. If no targetTags are specified, the firewall rule applies to all instances on the
* specified network.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> targetTags;
/**
* The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a permitted connection.
* @return value or {@code null} for none
*/
public java.util.List<Allowed> getAllowed() {
return allowed;
}
/**
* The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a permitted connection.
* @param allowed allowed or {@code null} for none
*/
public Firewall setAllowed(java.util.List<Allowed> allowed) {
this.allowed = allowed;
return this;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @return value or {@code null} for none
*/
public java.lang.String getCreationTimestamp() {
return creationTimestamp;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @param creationTimestamp creationTimestamp or {@code null} for none
*/
public Firewall setCreationTimestamp(java.lang.String creationTimestamp) {
this.creationTimestamp = creationTimestamp;
return this;
}
/**
* The list of DENY rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a denied connection.
* @return value or {@code null} for none
*/
public java.util.List<Denied> getDenied() {
return denied;
}
/**
* The list of DENY rules specified by this firewall. Each rule specifies a protocol and port-
* range tuple that describes a denied connection.
* @param denied denied or {@code null} for none
*/
public Firewall setDenied(java.util.List<Denied> denied) {
this.denied = denied;
return this;
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* @param description description or {@code null} for none
*/
public Firewall setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* If destination ranges are specified, the firewall rule applies only to traffic that has
* destination IP address in these ranges. These ranges must be expressed in CIDR format. Only
* IPv4 is supported.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getDestinationRanges() {
return destinationRanges;
}
/**
* If destination ranges are specified, the firewall rule applies only to traffic that has
* destination IP address in these ranges. These ranges must be expressed in CIDR format. Only
* IPv4 is supported.
* @param destinationRanges destinationRanges or {@code null} for none
*/
public Firewall setDestinationRanges(java.util.List<java.lang.String> destinationRanges) {
this.destinationRanges = destinationRanges;
return this;
}
/**
* Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default
* is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for
* `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields.
* @return value or {@code null} for none
*/
public java.lang.String getDirection() {
return direction;
}
/**
* Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default
* is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for
* `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields.
* @param direction direction or {@code null} for none
*/
public Firewall setDirection(java.lang.String direction) {
this.direction = direction;
return this;
}
/**
* Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not
* enforced and the network behaves as if it did not exist. If this is unspecified, the firewall
* rule will be enabled.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDisabled() {
return disabled;
}
/**
* Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not
* enforced and the network behaves as if it did not exist. If this is unspecified, the firewall
* rule will be enabled.
* @param disabled disabled or {@code null} for none
*/
public Firewall setDisabled(java.lang.Boolean disabled) {
this.disabled = disabled;
return this;
}
/**
* Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a
* particular firewall rule. If logging is enabled, logs will be exported t Cloud Logging.
* @return value or {@code null} for none
*/
public java.lang.Boolean getEnableLogging() {
return enableLogging;
}
/**
* Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a
* particular firewall rule. If logging is enabled, logs will be exported t Cloud Logging.
* @param enableLogging enableLogging or {@code null} for none
*/
public Firewall setEnableLogging(java.lang.Boolean enableLogging) {
this.enableLogging = enableLogging;
return this;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @return value or {@code null} for none
*/
public java.math.BigInteger getId() {
return id;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @param id id or {@code null} for none
*/
public Firewall setId(java.math.BigInteger id) {
this.id = id;
return this;
}
/**
* [Output Only] Type of the resource. Always compute#firewall for firewall rules.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* [Output Only] Type of the resource. Always compute#firewall for firewall rules.
* @param kind kind or {@code null} for none
*/
public Firewall setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* This field denotes the logging options for a particular firewall rule. If logging is enabled,
* logs will be exported to Cloud Logging.
* @return value or {@code null} for none
*/
public FirewallLogConfig getLogConfig() {
return logConfig;
}
/**
* This field denotes the logging options for a particular firewall rule. If logging is enabled,
* logs will be exported to Cloud Logging.
* @param logConfig logConfig or {@code null} for none
*/
public Firewall setLogConfig(FirewallLogConfig logConfig) {
this.logConfig = logConfig;
return this;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* @param name name or {@code null} for none
*/
public Firewall setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* URL of the network resource for this firewall rule. If not specified when creating a firewall
* rule, the default network is used: global/networks/default If you choose to specify this field,
* you can specify the network as a full or partial URL. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network
* - projects/myproject/global/networks/my-network - global/networks/default
* @return value or {@code null} for none
*/
public java.lang.String getNetwork() {
return network;
}
/**
* URL of the network resource for this firewall rule. If not specified when creating a firewall
* rule, the default network is used: global/networks/default If you choose to specify this field,
* you can specify the network as a full or partial URL. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network
* - projects/myproject/global/networks/my-network - global/networks/default
* @param network network or {@code null} for none
*/
public Firewall setNetwork(java.lang.String network) {
this.network = network;
return this;
}
/**
* Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default
* value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply.
* Lower values indicate higher priority. For example, a rule with priority `0` has higher
* precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they
* have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To
* avoid conflicts with the implied rules, use a priority number less than `65535`.
* @return value or {@code null} for none
*/
public java.lang.Integer getPriority() {
return priority;
}
/**
* Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default
* value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply.
* Lower values indicate higher priority. For example, a rule with priority `0` has higher
* precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they
* have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To
* avoid conflicts with the implied rules, use a priority number less than `65535`.
* @param priority priority or {@code null} for none
*/
public Firewall setPriority(java.lang.Integer priority) {
this.priority = priority;
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 Firewall setSelfLink(java.lang.String selfLink) {
this.selfLink = selfLink;
return this;
}
/**
* If source ranges are specified, the firewall rule applies only to traffic that has a source IP
* address in these ranges. These ranges must be expressed in CIDR format. One or both of
* sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic
* that has a source IP address within sourceRanges OR a source IP from a resource with a matching
* tag listed in the sourceTags field. The connection does not need to match both fields for the
* rule to apply. Only IPv4 is supported.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSourceRanges() {
return sourceRanges;
}
/**
* If source ranges are specified, the firewall rule applies only to traffic that has a source IP
* address in these ranges. These ranges must be expressed in CIDR format. One or both of
* sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic
* that has a source IP address within sourceRanges OR a source IP from a resource with a matching
* tag listed in the sourceTags field. The connection does not need to match both fields for the
* rule to apply. Only IPv4 is supported.
* @param sourceRanges sourceRanges or {@code null} for none
*/
public Firewall setSourceRanges(java.util.List<java.lang.String> sourceRanges) {
this.sourceRanges = sourceRanges;
return this;
}
/**
* If source service accounts are specified, the firewall rules apply only to traffic originating
* from an instance with a service account in this list. Source service accounts cannot be used to
* control traffic to an instance's external IP address because service accounts are associated
* with an instance, not an IP address. sourceRanges can be set at the same time as
* sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP
* address within the sourceRanges OR a source IP that belongs to an instance with service account
* listed in sourceServiceAccount. The connection does not need to match both fields for the
* firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or
* targetTags.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSourceServiceAccounts() {
return sourceServiceAccounts;
}
/**
* If source service accounts are specified, the firewall rules apply only to traffic originating
* from an instance with a service account in this list. Source service accounts cannot be used to
* control traffic to an instance's external IP address because service accounts are associated
* with an instance, not an IP address. sourceRanges can be set at the same time as
* sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP
* address within the sourceRanges OR a source IP that belongs to an instance with service account
* listed in sourceServiceAccount. The connection does not need to match both fields for the
* firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or
* targetTags.
* @param sourceServiceAccounts sourceServiceAccounts or {@code null} for none
*/
public Firewall setSourceServiceAccounts(java.util.List<java.lang.String> sourceServiceAccounts) {
this.sourceServiceAccounts = sourceServiceAccounts;
return this;
}
/**
* If source tags are specified, the firewall rule applies only to traffic with source IPs that
* match the primary network interfaces of VM instances that have the tag and are in the same VPC
* network. Source tags cannot be used to control traffic to an instance's external IP address, it
* only applies to traffic between instances in the same virtual network. Because tags are
* associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be
* set. If both fields are set, the firewall applies to traffic that has a source IP address
* within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags
* field. The connection does not need to match both fields for the firewall to apply.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSourceTags() {
return sourceTags;
}
/**
* If source tags are specified, the firewall rule applies only to traffic with source IPs that
* match the primary network interfaces of VM instances that have the tag and are in the same VPC
* network. Source tags cannot be used to control traffic to an instance's external IP address, it
* only applies to traffic between instances in the same virtual network. Because tags are
* associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be
* set. If both fields are set, the firewall applies to traffic that has a source IP address
* within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags
* field. The connection does not need to match both fields for the firewall to apply.
* @param sourceTags sourceTags or {@code null} for none
*/
public Firewall setSourceTags(java.util.List<java.lang.String> sourceTags) {
this.sourceTags = sourceTags;
return this;
}
/**
* A list of service accounts indicating sets of instances located in the network that may make
* network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same
* time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are
* specified, the firewall rule applies to all instances on the specified network.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTargetServiceAccounts() {
return targetServiceAccounts;
}
/**
* A list of service accounts indicating sets of instances located in the network that may make
* network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same
* time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are
* specified, the firewall rule applies to all instances on the specified network.
* @param targetServiceAccounts targetServiceAccounts or {@code null} for none
*/
public Firewall setTargetServiceAccounts(java.util.List<java.lang.String> targetServiceAccounts) {
this.targetServiceAccounts = targetServiceAccounts;
return this;
}
/**
* A list of tags that controls which instances the firewall rule applies to. If targetTags are
* specified, then the firewall rule applies only to instances in the VPC network that have one of
* those tags. If no targetTags are specified, the firewall rule applies to all instances on the
* specified network.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTargetTags() {
return targetTags;
}
/**
* A list of tags that controls which instances the firewall rule applies to. If targetTags are
* specified, then the firewall rule applies only to instances in the VPC network that have one of
* those tags. If no targetTags are specified, the firewall rule applies to all instances on the
* specified network.
* @param targetTags targetTags or {@code null} for none
*/
public Firewall setTargetTags(java.util.List<java.lang.String> targetTags) {
this.targetTags = targetTags;
return this;
}
@Override
public Firewall set(String fieldName, Object value) {
return (Firewall) super.set(fieldName, value);
}
@Override
public Firewall clone() {
return (Firewall) super.clone();
}
/**
* Model definition for FirewallAllowed.
*/
public static final class Allowed extends com.google.api.client.json.GenericJson {
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("IPProtocol")
private java.lang.String iPProtocol;
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> ports;
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @return value or {@code null} for none
*/
public java.lang.String getIPProtocol() {
return iPProtocol;
}
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @param iPProtocol iPProtocol or {@code null} for none
*/
public Allowed setIPProtocol(java.lang.String iPProtocol) {
this.iPProtocol = iPProtocol;
return this;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getPorts() {
return ports;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* @param ports ports or {@code null} for none
*/
public Allowed setPorts(java.util.List<java.lang.String> ports) {
this.ports = ports;
return this;
}
@Override
public Allowed set(String fieldName, Object value) {
return (Allowed) super.set(fieldName, value);
}
@Override
public Allowed clone() {
return (Allowed) super.clone();
}
}
/**
* Model definition for FirewallDenied.
*/
public static final class Denied extends com.google.api.client.json.GenericJson {
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key("IPProtocol")
private java.lang.String iPProtocol;
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> ports;
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @return value or {@code null} for none
*/
public java.lang.String getIPProtocol() {
return iPProtocol;
}
/**
* The IP protocol to which this rule applies. The protocol type is required when creating a
* firewall rule. This value can either be one of the following well known protocol strings (tcp,
* udp, icmp, esp, ah, ipip, sctp) or the IP protocol number.
* @param iPProtocol iPProtocol or {@code null} for none
*/
public Denied setIPProtocol(java.lang.String iPProtocol) {
this.iPProtocol = iPProtocol;
return this;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getPorts() {
return ports;
}
/**
* An optional list of ports to which this rule applies. This field is only applicable for the UDP
* or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule
* applies to connections through any port.
*
* Example inputs include: ["22"], ["80","443"], and ["12345-12349"].
* @param ports ports or {@code null} for none
*/
public Denied setPorts(java.util.List<java.lang.String> ports) {
this.ports = ports;
return this;
}
@Override
public Denied set(String fieldName, Object value) {
return (Denied) super.set(fieldName, value);
}
@Override
public Denied clone() {
return (Denied) super.clone();
}
}
}
|
apache/harmony | 35,824 | classlib/modules/luni/src/main/java/java/lang/Math.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.lang;
/**
* Class Math provides basic math constants and operations such as trigonometric
* functions, hyperbolic functions, exponential, logarithms, etc.
*/
public final class Math {
/**
* The double value closest to e, the base of the natural logarithm.
*/
public static final double E = 2.718281828459045;
/**
* The double value closest to pi, the ratio of a circle's circumference to
* its diameter.
*/
public static final double PI = 3.141592653589793;
private static java.util.Random random;
/**
* Prevents this class from being instantiated.
*/
private Math() {
}
/**
* Returns the absolute value of the argument.
* <p>
* Special cases:
* <ul>
* <li>{@code abs(-0.0) = +0.0}</li>
* <li>{@code abs(+infinity) = +infinity}</li>
* <li>{@code abs(-infinity) = +infinity}</li>
* <li>{@code abs(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose absolute value has to be computed.
* @return the absolute value of the argument.
*/
public static double abs(double d) {
long bits = Double.doubleToLongBits(d);
bits &= 0x7fffffffffffffffL;
return Double.longBitsToDouble(bits);
}
/**
* Returns the absolute value of the argument.
* <p>
* Special cases:
* <ul>
* <li>{@code abs(-0.0) = +0.0}</li>
* <li>{@code abs(+infinity) = +infinity}</li>
* <li>{@code abs(-infinity) = +infinity}</li>
* <li>{@code abs(NaN) = NaN}</li>
* </ul>
*
* @param f
* the value whose absolute value has to be computed.
* @return the argument if it is positive, otherwise the negation of the
* argument.
*/
public static float abs(float f) {
int bits = Float.floatToIntBits(f);
bits &= 0x7fffffff;
return Float.intBitsToFloat(bits);
}
/**
* Returns the absolute value of the argument.
* <p>
* If the argument is {@code Integer.MIN_VALUE}, {@code Integer.MIN_VALUE}
* is returned.
*
* @param i
* the value whose absolute value has to be computed.
* @return the argument if it is positive, otherwise the negation of the
* argument.
*/
public static int abs(int i) {
return i >= 0 ? i : -i;
}
/**
* Returns the absolute value of the argument. If the argument is {@code
* Long.MIN_VALUE}, {@code Long.MIN_VALUE} is returned.
*
* @param l
* the value whose absolute value has to be computed.
* @return the argument if it is positive, otherwise the negation of the
* argument.
*/
public static long abs(long l) {
return l >= 0 ? l : -l;
}
/**
* Returns the closest double approximation of the arc cosine of the
* argument within the range {@code [0..pi]}. The returned result is within
* 1 ulp (unit in the last place) of the real result.
* <p>
* Special cases:
* <ul>
* <li>{@code acos((anything > 1) = NaN}</li>
* <li>{@code acos((anything < -1) = NaN}</li>
* <li>{@code acos(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value to compute arc cosine of.
* @return the arc cosine of the argument.
*/
public static native double acos(double d);
/**
* Returns the closest double approximation of the arc sine of the argument
* within the range {@code [-pi/2..pi/2]}. The returned result is within 1
* ulp (unit in the last place) of the real result.
* <p>
* Special cases:
* <ul>
* <li>{@code asin((anything > 1)) = NaN}</li>
* <li>{@code asin((anything < -1)) = NaN}</li>
* <li>{@code asin(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose arc sine has to be computed.
* @return the arc sine of the argument.
*/
public static native double asin(double d);
/**
* Returns the closest double approximation of the arc tangent of the
* argument within the range {@code [-pi/2..pi/2]}. The returned result is
* within 1 ulp (unit in the last place) of the real result.
* <p>
* Special cases:
* <ul>
* <li>{@code atan(+0.0) = +0.0}</li>
* <li>{@code atan(-0.0) = -0.0}</li>
* <li>{@code atan(+infinity) = +pi/2}</li>
* <li>{@code atan(-infinity) = -pi/2}</li>
* <li>{@code atan(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose arc tangent has to be computed.
* @return the arc tangent of the argument.
*/
public static native double atan(double d);
/**
* Returns the closest double approximation of the arc tangent of {@code
* y/x} within the range {@code [-pi..pi]}. This is the angle of the polar
* representation of the rectangular coordinates (x,y). The returned result
* is within 2 ulps (units in the last place) of the real result.
* <p>
* Special cases:
* <ul>
* <li>{@code atan2((anything), NaN ) = NaN;}</li>
* <li>{@code atan2(NaN , (anything) ) = NaN;}</li>
* <li>{@code atan2(+0.0, +(anything but NaN)) = +0.0}</li>
* <li>{@code atan2(-0.0, +(anything but NaN)) = -0.0}</li>
* <li>{@code atan2(+0.0, -(anything but NaN)) = +pi}</li>
* <li>{@code atan2(-0.0, -(anything but NaN)) = -pi}</li>
* <li>{@code atan2(+(anything but 0 and NaN), 0) = +pi/2}</li>
* <li>{@code atan2(-(anything but 0 and NaN), 0) = -pi/2}</li>
* <li>{@code atan2(+(anything but infinity and NaN), +infinity)} {@code =}
* {@code +0.0}</li>
* <li>{@code atan2(-(anything but infinity and NaN), +infinity)} {@code =}
* {@code -0.0}</li>
* <li>{@code atan2(+(anything but infinity and NaN), -infinity) = +pi}</li>
* <li>{@code atan2(-(anything but infinity and NaN), -infinity) = -pi}</li>
* <li>{@code atan2(+infinity, +infinity ) = +pi/4}</li>
* <li>{@code atan2(-infinity, +infinity ) = -pi/4}</li>
* <li>{@code atan2(+infinity, -infinity ) = +3pi/4}</li>
* <li>{@code atan2(-infinity, -infinity ) = -3pi/4}</li>
* <li>{@code atan2(+infinity, (anything but,0, NaN, and infinity))} {@code
* =} {@code +pi/2}</li>
* <li>{@code atan2(-infinity, (anything but,0, NaN, and infinity))} {@code
* =} {@code -pi/2}</li>
* </ul>
*
* @param y
* the numerator of the value whose atan has to be computed.
* @param x
* the denominator of the value whose atan has to be computed.
* @return the arc tangent of {@code y/x}.
*/
public static native double atan2(double x, double y);
/**
* Returns the closest double approximation of the cube root of the
* argument.
* <p>
* Special cases:
* <ul>
* <li>{@code cbrt(+0.0) = +0.0}</li>
* <li>{@code cbrt(-0.0) = -0.0}</li>
* <li>{@code cbrt(+infinity) = +infinity}</li>
* <li>{@code cbrt(-infinity) = -infinity}</li>
* <li>{@code cbrt(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose cube root has to be computed.
* @return the cube root of the argument.
*/
public static native double cbrt(double d);
/**
* Returns the double conversion of the most negative (closest to negative
* infinity) integer value which is greater than the argument.
* <p>
* Special cases:
* <ul>
* <li>{@code ceil(+0.0) = +0.0}</li>
* <li>{@code ceil(-0.0) = -0.0}</li>
* <li>{@code ceil((anything in range (-1,0)) = -0.0}</li>
* <li>{@code ceil(+infinity) = +infinity}</li>
* <li>{@code ceil(-infinity) = -infinity}</li>
* <li>{@code ceil(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose closest integer value has to be computed.
* @return the ceiling of the argument.
*/
public static native double ceil(double d);
/**
* Returns the closest double approximation of the cosine of the argument.
* The returned result is within 1 ulp (unit in the last place) of the real
* result.
* <p>
* Special cases:
* <ul>
* <li>{@code cos(+infinity) = NaN}</li>
* <li>{@code cos(-infinity) = NaN}</li>
* <li>{@code cos(NaN) = NaN}</li>
* </ul>
*
* @param d
* the angle whose cosine has to be computed, in radians.
* @return the cosine of the argument.
*/
public static native double cos(double d);
/**
* Returns the closest double approximation of the hyperbolic cosine of the
* argument. The returned result is within 2.5 ulps (units in the last
* place) of the real result.
* <p>
* Special cases:
* <ul>
* <li>{@code cosh(+infinity) = +infinity}</li>
* <li>{@code cosh(-infinity) = +infinity}</li>
* <li>{@code cosh(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose hyperbolic cosine has to be computed.
* @return the hyperbolic cosine of the argument.
*/
public static native double cosh(double d);
/**
* Returns the closest double approximation of the raising "e" to the power
* of the argument. The returned result is within 1 ulp (unit in the last
* place) of the real result.
* <p>
* Special cases:
* <ul>
* <li>{@code exp(+infinity) = +infinity}</li>
* <li>{@code exp(-infinity) = +0.0}</li>
* <li>{@code exp(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose exponential has to be computed.
* @return the exponential of the argument.
*/
public static native double exp(double d);
/**
* Returns the closest double approximation of <i>{@code e}</i><sup> {@code
* d}</sup>{@code - 1}. If the argument is very close to 0, it is much more
* accurate to use {@code expm1(d)+1} than {@code exp(d)} (due to
* cancellation of significant digits). The returned result is within 1 ulp
* (unit in the last place) of the real result.
* <p>
* For any finite input, the result is not less than -1.0. If the real
* result is within 0.5 ulp of -1, -1.0 is returned.
* <p>
* Special cases:
* <ul>
* <li>{@code expm1(+0.0) = +0.0}</li>
* <li>{@code expm1(-0.0) = -0.0}</li>
* <li>{@code expm1(+infinity) = +infinity}</li>
* <li>{@code expm1(-infinity) = -1.0}</li>
* <li>{@code expm1(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value to compute the <i>{@code e}</i><sup>{@code d} </sup>
* {@code - 1} of.
* @return the <i>{@code e}</i><sup>{@code d}</sup>{@code - 1} value of the
* argument.
*/
public static native double expm1(double d);
/**
* Returns the double conversion of the most positive (closest to positive
* infinity) integer value which is less than the argument.
* <p>
* Special cases:
* <ul>
* <li>{@code floor(+0.0) = +0.0}</li>
* <li>{@code floor(-0.0) = -0.0}</li>
* <li>{@code floor(+infinity) = +infinity}</li>
* <li>{@code floor(-infinity) = -infinity}</li>
* <li>{@code floor(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose closest integer value has to be computed.
* @return the floor of the argument.
*/
public static native double floor(double d);
/**
* Returns {@code sqrt(}<i>{@code x}</i><sup>{@code 2}</sup>{@code +} <i>
* {@code y}</i><sup>{@code 2}</sup>{@code )}. The final result is without
* medium underflow or overflow. The returned result is within 1 ulp (unit
* in the last place) of the real result. If one parameter remains constant,
* the result should be semi-monotonic.
* <p>
* Special cases:
* <ul>
* <li>{@code hypot(+infinity, (anything including NaN)) = +infinity}</li>
* <li>{@code hypot(-infinity, (anything including NaN)) = +infinity}</li>
* <li>{@code hypot((anything including NaN), +infinity) = +infinity}</li>
* <li>{@code hypot((anything including NaN), -infinity) = +infinity}</li>
* <li>{@code hypot(NaN, NaN) = NaN}</li>
* </ul>
*
* @param x
* a double number.
* @param y
* a double number.
* @return the {@code sqrt(}<i>{@code x}</i><sup>{@code 2}</sup>{@code +}
* <i> {@code y}</i><sup>{@code 2}</sup>{@code )} value of the
* arguments.
*/
public static native double hypot(double x, double y);
/**
* Returns the remainder of dividing {@code x} by {@code y} using the IEEE
* 754 rules. The result is {@code x-round(x/p)*p} where {@code round(x/p)}
* is the nearest integer (rounded to even), but without numerical
* cancellation problems.
* <p>
* Special cases:
* <ul>
* <li>{@code IEEEremainder((anything), 0) = NaN}</li>
* <li>{@code IEEEremainder(+infinity, (anything)) = NaN}</li>
* <li>{@code IEEEremainder(-infinity, (anything)) = NaN}</li>
* <li>{@code IEEEremainder(NaN, (anything)) = NaN}</li>
* <li>{@code IEEEremainder((anything), NaN) = NaN}</li>
* <li>{@code IEEEremainder(x, +infinity) = x } where x is anything but
* +/-infinity</li>
* <li>{@code IEEEremainder(x, -infinity) = x } where x is anything but
* +/-infinity</li>
* </ul>
*
* @param x
* the numerator of the operation.
* @param y
* the denominator of the operation.
* @return the IEEE754 floating point reminder of {@code x/y}.
*/
public static native double IEEEremainder(double x, double y);
/**
* Returns the closest double approximation of the natural logarithm of the
* argument. The returned result is within 1 ulp (unit in the last place) of
* the real result.
* <p>
* Special cases:
* <ul>
* <li>{@code log(+0.0) = -infinity}</li>
* <li>{@code log(-0.0) = -infinity}</li>
* <li>{@code log((anything < 0) = NaN}</li>
* <li>{@code log(+infinity) = +infinity}</li>
* <li>{@code log(-infinity) = NaN}</li>
* <li>{@code log(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose log has to be computed.
* @return the natural logarithm of the argument.
*/
public static native double log(double d);
/**
* Returns the closest double approximation of the base 10 logarithm of the
* argument. The returned result is within 1 ulp (unit in the last place) of
* the real result.
* <p>
* Special cases:
* <ul>
* <li>{@code log10(+0.0) = -infinity}</li>
* <li>{@code log10(-0.0) = -infinity}</li>
* <li>{@code log10((anything < 0) = NaN}</li>
* <li>{@code log10(+infinity) = +infinity}</li>
* <li>{@code log10(-infinity) = NaN}</li>
* <li>{@code log10(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose base 10 log has to be computed.
* @return the natural logarithm of the argument.
*/
public static native double log10(double d);
/**
* Returns the closest double approximation of the natural logarithm of the
* sum of the argument and 1. If the argument is very close to 0, it is much
* more accurate to use {@code log1p(d)} than {@code log(1.0+d)} (due to
* numerical cancellation). The returned result is within 1 ulp (unit in the
* last place) of the real result and is semi-monotonic.
* <p>
* Special cases:
* <ul>
* <li>{@code log1p(+0.0) = +0.0}</li>
* <li>{@code log1p(-0.0) = -0.0}</li>
* <li>{@code log1p((anything < 1)) = NaN}</li>
* <li>{@code log1p(-1.0) = -infinity}</li>
* <li>{@code log1p(+infinity) = +infinity}</li>
* <li>{@code log1p(-infinity) = NaN}</li>
* <li>{@code log1p(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value to compute the {@code ln(1+d)} of.
* @return the natural logarithm of the sum of the argument and 1.
*/
public static native double log1p(double d);
/**
* Returns the most positive (closest to positive infinity) of the two
* arguments.
* <p>
* Special cases:
* <ul>
* <li>{@code max(NaN, (anything)) = NaN}</li>
* <li>{@code max((anything), NaN) = NaN}</li>
* <li>{@code max(+0.0, -0.0) = +0.0}</li>
* <li>{@code max(-0.0, +0.0) = +0.0}</li>
* </ul>
*
* @param d1
* the first argument.
* @param d2
* the second argument.
* @return the larger of {@code d1} and {@code d2}.
*/
public static double max(double d1, double d2) {
if (d1 > d2) {
return d1;
}
if (d1 < d2) {
return d2;
}
/* if either arg is NaN, return NaN */
if (d1 != d2) {
return Double.NaN;
}
/* max(+0.0,-0.0) == +0.0 */
/* 0 == Double.doubleToRawLongBits(0.0d) */
if (Double.doubleToRawLongBits(d1) != 0) {
return d2;
}
return 0.0d;
}
/**
* Returns the most positive (closest to positive infinity) of the two
* arguments.
* <p>
* Special cases:
* <ul>
* <li>{@code max(NaN, (anything)) = NaN}</li>
* <li>{@code max((anything), NaN) = NaN}</li>
* <li>{@code max(+0.0, -0.0) = +0.0}</li>
* <li>{@code max(-0.0, +0.0) = +0.0}</li>
* </ul>
*
* @param f1
* the first argument.
* @param f2
* the second argument.
* @return the larger of {@code f1} and {@code f2}.
*/
public static float max(float f1, float f2) {
if (f1 > f2) {
return f1;
}
if (f1 < f2) {
return f2;
}
/* if either arg is NaN, return NaN */
if (f1 != f2) {
return Float.NaN;
}
/* max(+0.0,-0.0) == +0.0 */
/* 0 == Float.floatToRawIntBits(0.0f) */
if (Float.floatToRawIntBits(f1) != 0) {
return f2;
}
return 0.0f;
}
/**
* Returns the most positive (closest to positive infinity) of the two
* arguments.
*
* @param i1
* the first argument.
* @param i2
* the second argument.
* @return the larger of {@code i1} and {@code i2}.
*/
public static int max(int i1, int i2) {
return i1 > i2 ? i1 : i2;
}
/**
* Returns the most positive (closest to positive infinity) of the two
* arguments.
*
* @param l1
* the first argument.
* @param l2
* the second argument.
* @return the larger of {@code l1} and {@code l2}.
*/
public static long max(long l1, long l2) {
return l1 > l2 ? l1 : l2;
}
/**
* Returns the most negative (closest to negative infinity) of the two
* arguments.
* <p>
* Special cases:
* <ul>
* <li>{@code min(NaN, (anything)) = NaN}</li>
* <li>{@code min((anything), NaN) = NaN}</li>
* <li>{@code min(+0.0, -0.0) = -0.0}</li>
* <li>{@code min(-0.0, +0.0) = -0.0}</li>
* </ul>
*
* @param d1
* the first argument.
* @param d2
* the second argument.
* @return the smaller of {@code d1} and {@code d2}.
*/
public static double min(double d1, double d2) {
if (d1 > d2) {
return d2;
}
if (d1 < d2) {
return d1;
}
/* if either arg is NaN, return NaN */
if (d1 != d2) {
return Double.NaN;
}
/* min(+0.0,-0.0) == -0.0 */
/* 0x8000000000000000L == Double.doubleToRawLongBits(-0.0d) */
if (Double.doubleToRawLongBits(d1) == 0x8000000000000000L) {
return -0.0d;
}
return d2;
}
/**
* Returns the most negative (closest to negative infinity) of the two
* arguments.
* <p>
* Special cases:
* <ul>
* <li>{@code min(NaN, (anything)) = NaN}</li>
* <li>{@code min((anything), NaN) = NaN}</li>
* <li>{@code min(+0.0, -0.0) = -0.0}</li>
* <li>{@code min(-0.0, +0.0) = -0.0}</li>
* </ul>
*
* @param f1
* the first argument.
* @param f2
* the second argument.
* @return the smaller of {@code f1} and {@code f2}.
*/
public static float min(float f1, float f2) {
if (f1 > f2) {
return f2;
}
if (f1 < f2) {
return f1;
}
/* if either arg is NaN, return NaN */
if (f1 != f2) {
return Float.NaN;
}
/* min(+0.0,-0.0) == -0.0 */
/* 0x80000000 == Float.floatToRawIntBits(-0.0f) */
if (Float.floatToRawIntBits(f1) == 0x80000000) {
return -0.0f;
}
return f2;
}
/**
* Returns the most negative (closest to negative infinity) of the two
* arguments.
*
* @param i1
* the first argument.
* @param i2
* the second argument.
* @return the smaller of {@code i1} and {@code i2}.
*/
public static int min(int i1, int i2) {
return i1 < i2 ? i1 : i2;
}
/**
* Returns the most negative (closest to negative infinity) of the two
* arguments.
*
* @param l1
* the first argument.
* @param l2
* the second argument.
* @return the smaller of {@code l1} and {@code l2}.
*/
public static long min(long l1, long l2) {
return l1 < l2 ? l1 : l2;
}
/**
* Returns the closest double approximation of the result of raising {@code
* x} to the power of {@code y}.
* <p>
* Special cases:
* <ul>
* <li>{@code pow((anything), +0.0) = 1.0}</li>
* <li>{@code pow((anything), -0.0) = 1.0}</li>
* <li>{@code pow(x, 1.0) = x}</li>
* <li>{@code pow((anything), NaN) = NaN}</li>
* <li>{@code pow(NaN, (anything except 0)) = NaN}</li>
* <li>{@code pow(+/-(|x| > 1), +infinity) = +infinity}</li>
* <li>{@code pow(+/-(|x| > 1), -infinity) = +0.0}</li>
* <li>{@code pow(+/-(|x| < 1), +infinity) = +0.0}</li>
* <li>{@code pow(+/-(|x| < 1), -infinity) = +infinity}</li>
* <li>{@code pow(+/-1.0 , +infinity) = NaN}</li>
* <li>{@code pow(+/-1.0 , -infinity) = NaN}</li>
* <li>{@code pow(+0.0, (+anything except 0, NaN)) = +0.0}</li>
* <li>{@code pow(-0.0, (+anything except 0, NaN, odd integer)) = +0.0}</li>
* <li>{@code pow(+0.0, (-anything except 0, NaN)) = +infinity}</li>
* <li>{@code pow(-0.0, (-anything except 0, NAN, odd integer))} {@code =}
* {@code +infinity}</li>
* <li>{@code pow(-0.0, (odd integer)) = -pow( +0 , (odd integer) )}</li>
* <li>{@code pow(+infinity, (+anything except 0, NaN)) = +infinity}</li>
* <li>{@code pow(+infinity, (-anything except 0, NaN)) = +0.0}</li>
* <li>{@code pow(-infinity, (anything)) = -pow(0, (-anything))}</li>
* <li>{@code pow((-anything), (integer))} {@code =} {@code
* pow(-1,(integer))*pow(+anything,integer) }</li>
* <li>{@code pow((-anything except 0 and inf), (non-integer)) = NAN}</li>
* </ul>
*
* @param x
* the base of the operation.
* @param y
* the exponent of the operation.
* @return {@code x} to the power of {@code y}.
*/
public static native double pow(double x, double y);
/**
* Returns the double conversion of the result of rounding the argument to
* an integer. Tie breaks are rounded towards even.
* <p>
* Special cases:
* <ul>
* <li>{@code rint(+0.0) = +0.0}</li>
* <li>{@code rint(-0.0) = -0.0}</li>
* <li>{@code rint(+infinity) = +infinity}</li>
* <li>{@code rint(-infinity) = -infinity}</li>
* <li>{@code rint(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value to be rounded.
* @return the closest integer to the argument (as a double).
*/
public static native double rint(double d);
/**
* Returns the result of rounding the argument to an integer. The result is
* equivalent to {@code (long) Math.floor(d+0.5)}.
* <p>
* Special cases:
* <ul>
* <li>{@code round(+0.0) = +0.0}</li>
* <li>{@code round(-0.0) = +0.0}</li>
* <li>{@code round((anything > Long.MAX_VALUE) = Long.MAX_VALUE}</li>
* <li>{@code round((anything < Long.MIN_VALUE) = Long.MIN_VALUE}</li>
* <li>{@code round(+infintiy) = Long.MAX_VALUE}</li>
* <li>{@code round(-infintiy) = Long.MIN_VALUE}</li>
* <li>{@code round(NaN) = +0.0}</li>
* </ul>
*
* @param d
* the value to be rounded.
* @return the closest integer to the argument.
*/
public static long round(double d) {
// check for NaN
if (d != d) {
return 0L;
}
return (long) floor(d + 0.5d);
}
/**
* Returns the result of rounding the argument to an integer. The result is
* equivalent to {@code (int) Math.floor(f+0.5)}.
* <p>
* Special cases:
* <ul>
* <li>{@code round(+0.0) = +0.0}</li>
* <li>{@code round(-0.0) = +0.0}</li>
* <li>{@code round((anything > Integer.MAX_VALUE) = Integer.MAX_VALUE}</li>
* <li>{@code round((anything < Integer.MIN_VALUE) = Integer.MIN_VALUE}</li>
* <li>{@code round(+infintiy) = Integer.MAX_VALUE}</li>
* <li>{@code round(-infintiy) = Integer.MIN_VALUE}</li>
* <li>{@code round(NaN) = +0.0}</li>
* </ul>
*
* @param f
* the value to be rounded.
* @return the closest integer to the argument.
*/
public static int round(float f) {
// check for NaN
if (f != f) {
return 0;
}
return (int) floor(f + 0.5f);
}
/**
* Returns the signum function of the argument. If the argument is less than
* zero, it returns -1.0. If the argument is greater than zero, 1.0 is
* returned. If the argument is either positive or negative zero, the
* argument is returned as result.
* <p>
* Special cases:
* <ul>
* <li>{@code signum(+0.0) = +0.0}</li>
* <li>{@code signum(-0.0) = -0.0}</li>
* <li>{@code signum(+infinity) = +1.0}</li>
* <li>{@code signum(-infinity) = -1.0}</li>
* <li>{@code signum(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose signum has to be computed.
* @return the value of the signum function.
*/
public static double signum(double d) {
return StrictMath.signum(d);
}
/**
* Returns the signum function of the argument. If the argument is less than
* zero, it returns -1.0. If the argument is greater than zero, 1.0 is
* returned. If the argument is either positive or negative zero, the
* argument is returned as result.
* <p>
* Special cases:
* <ul>
* <li>{@code signum(+0.0) = +0.0}</li>
* <li>{@code signum(-0.0) = -0.0}</li>
* <li>{@code signum(+infinity) = +1.0}</li>
* <li>{@code signum(-infinity) = -1.0}</li>
* <li>{@code signum(NaN) = NaN}</li>
* </ul>
*
* @param f
* the value whose signum has to be computed.
* @return the value of the signum function.
*/
public static float signum(float f) {
return StrictMath.signum(f);
}
/**
* Returns the closest double approximation of the sine of the argument. The
* returned result is within 1 ulp (unit in the last place) of the real
* result.
* <p>
* Special cases:
* <ul>
* <li>{@code sin(+0.0) = +0.0}</li>
* <li>{@code sin(-0.0) = -0.0}</li>
* <li>{@code sin(+infinity) = NaN}</li>
* <li>{@code sin(-infinity) = NaN}</li>
* <li>{@code sin(NaN) = NaN}</li>
* </ul>
*
* @param d
* the angle whose sin has to be computed, in radians.
* @return the sine of the argument.
*/
public static native double sin(double d);
/**
* Returns the closest double approximation of the hyperbolic sine of the
* argument. The returned result is within 2.5 ulps (units in the last
* place) of the real result.
* <p>
* Special cases:
* <ul>
* <li>{@code sinh(+0.0) = +0.0}</li>
* <li>{@code sinh(-0.0) = -0.0}</li>
* <li>{@code sinh(+infinity) = +infinity}</li>
* <li>{@code sinh(-infinity) = -infinity}</li>
* <li>{@code sinh(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose hyperbolic sine has to be computed.
* @return the hyperbolic sine of the argument.
*/
public static native double sinh(double d);
/**
* Returns the closest double approximation of the square root of the
* argument.
* <p>
* Special cases:
* <ul>
* <li>{@code sqrt(+0.0) = +0.0}</li>
* <li>{@code sqrt(-0.0) = -0.0}</li>
* <li>{@code sqrt( (anything < 0) ) = NaN}</li>
* <li>{@code sqrt(+infinity) = +infinity}</li>
* <li>{@code sqrt(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose square root has to be computed.
* @return the square root of the argument.
*/
public static native double sqrt(double d);
/**
* Returns the closest double approximation of the tangent of the argument.
* The returned result is within 1 ulp (unit in the last place) of the real
* result.
* <p>
* Special cases:
* <ul>
* <li>{@code tan(+0.0) = +0.0}</li>
* <li>{@code tan(-0.0) = -0.0}</li>
* <li>{@code tan(+infinity) = NaN}</li>
* <li>{@code tan(-infinity) = NaN}</li>
* <li>{@code tan(NaN) = NaN}</li>
* </ul>
*
* @param d
* the angle whose tangens has to be computed, in radians.
* @return the tangent of the argument.
*/
public static native double tan(double d);
/**
* Returns the closest double approximation of the hyperbolic tangent of the
* argument. The absolute value is always less than 1. The returned result
* is within 2.5 ulps (units in the last place) of the real result. If the
* real result is within 0.5ulp of 1 or -1, it should return exactly +1 or
* -1.
* <p>
* Special cases:
* <ul>
* <li>{@code tanh(+0.0) = +0.0}</li>
* <li>{@code tanh(-0.0) = -0.0}</li>
* <li>{@code tanh(+infinity) = +1.0}</li>
* <li>{@code tanh(-infinity) = -1.0}</li>
* <li>{@code tanh(NaN) = NaN}</li>
* </ul>
*
* @param d
* the value whose hyperbolic tangent has to be computed.
* @return the hyperbolic tangent of the argument.
*/
public static native double tanh(double d);
/**
* Returns a pseudo-random number between 0.0 (inclusive) and 1.0
* (exclusive).
*
* @return a pseudo-random number.
*/
public static double random() {
if (random == null) {
random = new java.util.Random();
}
return random.nextDouble();
}
/**
* Returns the measure in radians of the supplied degree angle. The result
* is {@code angdeg / 180 * pi}.
* <p>
* Special cases:
* <ul>
* <li>{@code toRadians(+0.0) = +0.0}</li>
* <li>{@code toRadians(-0.0) = -0.0}</li>
* <li>{@code toRadians(+infinity) = +infinity}</li>
* <li>{@code toRadians(-infinity) = -infinity}</li>
* <li>{@code toRadians(NaN) = NaN}</li>
* </ul>
*
* @param angdeg
* an angle in degrees.
* @return the radian measure of the angle.
*/
public static double toRadians(double angdeg) {
return angdeg / 180d * PI;
}
/**
* Returns the measure in degrees of the supplied radian angle. The result
* is {@code angrad * 180 / pi}.
* <p>
* Special cases:
* <ul>
* <li>{@code toDegrees(+0.0) = +0.0}</li>
* <li>{@code toDegrees(-0.0) = -0.0}</li>
* <li>{@code toDegrees(+infinity) = +infinity}</li>
* <li>{@code toDegrees(-infinity) = -infinity}</li>
* <li>{@code toDegrees(NaN) = NaN}</li>
* </ul>
*
* @param angrad
* an angle in radians.
* @return the degree measure of the angle.
*/
public static double toDegrees(double angrad) {
return angrad * 180d / PI;
}
/**
* Returns the argument's ulp (unit in the last place). The size of a ulp of
* a double value is the positive distance between this value and the double
* value next larger in magnitude. For non-NaN {@code x}, {@code ulp(-x) ==
* ulp(x)}.
* <p>
* Special cases:
* <ul>
* <li>{@code ulp(+0.0) = Double.MIN_VALUE}</li>
* <li>{@code ulp(-0.0) = Double.MIN_VALUE}</li>
* <li>{@code ulp(+infintiy) = infinity}</li>
* <li>{@code ulp(-infintiy) = infinity}</li>
* <li>{@code ulp(NaN) = NaN}</li>
* </ul>
*
* @param d
* the floating-point value to compute ulp of.
* @return the size of a ulp of the argument.
*/
public static double ulp(double d) {
// special cases
if (Double.isInfinite(d)) {
return Double.POSITIVE_INFINITY;
} else if (d == Double.MAX_VALUE || d == -Double.MAX_VALUE) {
return pow(2, 971);
}
d = abs(d);
return nextafter(d, Double.MAX_VALUE) - d;
}
/**
* Returns the argument's ulp (unit in the last place). The size of a ulp of
* a float value is the positive distance between this value and the float
* value next larger in magnitude. For non-NaN {@code x}, {@code ulp(-x) ==
* ulp(x)}.
* <p>
* Special cases:
* <ul>
* <li>{@code ulp(+0.0) = Float.MIN_VALUE}</li>
* <li>{@code ulp(-0.0) = Float.MIN_VALUE}</li>
* <li>{@code ulp(+infintiy) = infinity}</li>
* <li>{@code ulp(-infintiy) = infinity}</li>
* <li>{@code ulp(NaN) = NaN}</li>
* </ul>
*
* @param f
* the floating-point value to compute ulp of.
* @return the size of a ulp of the argument.
*/
public static float ulp(float f) {
// special cases
if (Float.isNaN(f)) {
return Float.NaN;
} else if (Float.isInfinite(f)) {
return Float.POSITIVE_INFINITY;
} else if (f == Float.MAX_VALUE || f == -Float.MAX_VALUE) {
return (float) pow(2, 104);
}
f = abs(f);
return nextafterf(f, Float.MAX_VALUE) - f;
}
private native static double nextafter(double x, double y);
private native static float nextafterf(float x, float y);
}
|
googleapis/google-cloud-java | 35,614 | java-translate/proto-google-cloud-translate-v3/src/main/java/com/google/cloud/translate/v3/ListModelsRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/translate/v3/automl_translation.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.translate.v3;
/**
*
*
* <pre>
* Request message for ListModels.
* </pre>
*
* Protobuf type {@code google.cloud.translation.v3.ListModelsRequest}
*/
public final class ListModelsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.translation.v3.ListModelsRequest)
ListModelsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListModelsRequest.newBuilder() to construct.
private ListModelsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListModelsRequest() {
parent_ = "";
filter_ = "";
pageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListModelsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_ListModelsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_ListModelsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.translate.v3.ListModelsRequest.class,
com.google.cloud.translate.v3.ListModelsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Name of the parent project. In form of
* `projects/{project-number-or-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. Name of the parent project. In form of
* `projects/{project-number-or-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 FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Optional. An expression for filtering the models that will be returned.
* Supported filter:
* `dataset_id=${dataset_id}`
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. An expression for filtering the models that will be returned.
* Supported filter:
* `dataset_id=${dataset_id}`
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Optional. Requested page size. The server can return fewer results than
* requested.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Optional. A token identifying a page of results for the server to return.
* Typically obtained from next_page_token field in the response of a
* ListModels call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. A token identifying a page of results for the server to return.
* Typically obtained from next_page_token field in the response of a
* ListModels call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.translate.v3.ListModelsRequest)) {
return super.equals(obj);
}
com.google.cloud.translate.v3.ListModelsRequest other =
(com.google.cloud.translate.v3.ListModelsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.translate.v3.ListModelsRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3.ListModelsRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3.ListModelsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3.ListModelsRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3.ListModelsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3.ListModelsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3.ListModelsRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3.ListModelsRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.translate.v3.ListModelsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3.ListModelsRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.translate.v3.ListModelsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3.ListModelsRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.translate.v3.ListModelsRequest 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 ListModels.
* </pre>
*
* Protobuf type {@code google.cloud.translation.v3.ListModelsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.translation.v3.ListModelsRequest)
com.google.cloud.translate.v3.ListModelsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_ListModelsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_ListModelsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.translate.v3.ListModelsRequest.class,
com.google.cloud.translate.v3.ListModelsRequest.Builder.class);
}
// Construct using com.google.cloud.translate.v3.ListModelsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
filter_ = "";
pageSize_ = 0;
pageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_ListModelsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.translate.v3.ListModelsRequest getDefaultInstanceForType() {
return com.google.cloud.translate.v3.ListModelsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.translate.v3.ListModelsRequest build() {
com.google.cloud.translate.v3.ListModelsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.translate.v3.ListModelsRequest buildPartial() {
com.google.cloud.translate.v3.ListModelsRequest result =
new com.google.cloud.translate.v3.ListModelsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.translate.v3.ListModelsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.pageToken_ = pageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.translate.v3.ListModelsRequest) {
return mergeFrom((com.google.cloud.translate.v3.ListModelsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.translate.v3.ListModelsRequest other) {
if (other == com.google.cloud.translate.v3.ListModelsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000008;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000004;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 34
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Name of the parent project. In form of
* `projects/{project-number-or-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. Name of the parent project. In form of
* `projects/{project-number-or-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. Name of the parent project. In form of
* `projects/{project-number-or-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. Name of the parent project. In form of
* `projects/{project-number-or-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. Name of the parent project. In form of
* `projects/{project-number-or-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 filter_ = "";
/**
*
*
* <pre>
* Optional. An expression for filtering the models that will be returned.
* Supported filter:
* `dataset_id=${dataset_id}`
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. An expression for filtering the models that will be returned.
* Supported filter:
* `dataset_id=${dataset_id}`
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. An expression for filtering the models that will be returned.
* Supported filter:
* `dataset_id=${dataset_id}`
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. An expression for filtering the models that will be returned.
* Supported filter:
* `dataset_id=${dataset_id}`
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. An expression for filtering the models that will be returned.
* Supported filter:
* `dataset_id=${dataset_id}`
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Optional. Requested page size. The server can return fewer results than
* requested.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Optional. Requested page size. The server can return fewer results than
* requested.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Requested page size. The server can return fewer results than
* requested.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000004);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Optional. A token identifying a page of results for the server to return.
* Typically obtained from next_page_token field in the response of a
* ListModels call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. A token identifying a page of results for the server to return.
* Typically obtained from next_page_token field in the response of a
* ListModels call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. A token identifying a page of results for the server to return.
* Typically obtained from next_page_token field in the response of a
* ListModels call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A token identifying a page of results for the server to return.
* Typically obtained from next_page_token field in the response of a
* ListModels call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A token identifying a page of results for the server to return.
* Typically obtained from next_page_token field in the response of a
* ListModels call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 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.translation.v3.ListModelsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.translation.v3.ListModelsRequest)
private static final com.google.cloud.translate.v3.ListModelsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.translate.v3.ListModelsRequest();
}
public static com.google.cloud.translate.v3.ListModelsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListModelsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListModelsRequest>() {
@java.lang.Override
public ListModelsRequest 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<ListModelsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListModelsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.translate.v3.ListModelsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,631 | java-vision/proto-google-cloud-vision-v1/src/main/java/com/google/cloud/vision/v1/ListProductsInProductSetResponse.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>
* Response message for the `ListProductsInProductSet` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1.ListProductsInProductSetResponse}
*/
public final class ListProductsInProductSetResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.vision.v1.ListProductsInProductSetResponse)
ListProductsInProductSetResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListProductsInProductSetResponse.newBuilder() to construct.
private ListProductsInProductSetResponse(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListProductsInProductSetResponse() {
products_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListProductsInProductSetResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_ListProductsInProductSetResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_ListProductsInProductSetResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1.ListProductsInProductSetResponse.class,
com.google.cloud.vision.v1.ListProductsInProductSetResponse.Builder.class);
}
public static final int PRODUCTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.vision.v1.Product> products_;
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.vision.v1.Product> getProductsList() {
return products_;
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.vision.v1.ProductOrBuilder>
getProductsOrBuilderList() {
return products_;
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
@java.lang.Override
public int getProductsCount() {
return products_.size();
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
@java.lang.Override
public com.google.cloud.vision.v1.Product getProducts(int index) {
return products_.get(index);
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
@java.lang.Override
public com.google.cloud.vision.v1.ProductOrBuilder getProductsOrBuilder(int index) {
return products_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < products_.size(); i++) {
output.writeMessage(1, products_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < products_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, products_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.vision.v1.ListProductsInProductSetResponse)) {
return super.equals(obj);
}
com.google.cloud.vision.v1.ListProductsInProductSetResponse other =
(com.google.cloud.vision.v1.ListProductsInProductSetResponse) obj;
if (!getProductsList().equals(other.getProductsList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getProductsCount() > 0) {
hash = (37 * hash) + PRODUCTS_FIELD_NUMBER;
hash = (53 * hash) + getProductsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.vision.v1.ListProductsInProductSetResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1.ListProductsInProductSetResponse 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.ListProductsInProductSetResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1.ListProductsInProductSetResponse 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.ListProductsInProductSetResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1.ListProductsInProductSetResponse 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.ListProductsInProductSetResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1.ListProductsInProductSetResponse 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.ListProductsInProductSetResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1.ListProductsInProductSetResponse 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.ListProductsInProductSetResponse 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.ListProductsInProductSetResponse 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.ListProductsInProductSetResponse 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 `ListProductsInProductSet` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1.ListProductsInProductSetResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.vision.v1.ListProductsInProductSetResponse)
com.google.cloud.vision.v1.ListProductsInProductSetResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_ListProductsInProductSetResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_ListProductsInProductSetResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1.ListProductsInProductSetResponse.class,
com.google.cloud.vision.v1.ListProductsInProductSetResponse.Builder.class);
}
// Construct using com.google.cloud.vision.v1.ListProductsInProductSetResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (productsBuilder_ == null) {
products_ = java.util.Collections.emptyList();
} else {
products_ = null;
productsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_ListProductsInProductSetResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.vision.v1.ListProductsInProductSetResponse getDefaultInstanceForType() {
return com.google.cloud.vision.v1.ListProductsInProductSetResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.vision.v1.ListProductsInProductSetResponse build() {
com.google.cloud.vision.v1.ListProductsInProductSetResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.vision.v1.ListProductsInProductSetResponse buildPartial() {
com.google.cloud.vision.v1.ListProductsInProductSetResponse result =
new com.google.cloud.vision.v1.ListProductsInProductSetResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.vision.v1.ListProductsInProductSetResponse result) {
if (productsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
products_ = java.util.Collections.unmodifiableList(products_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.products_ = products_;
} else {
result.products_ = productsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.vision.v1.ListProductsInProductSetResponse 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.vision.v1.ListProductsInProductSetResponse) {
return mergeFrom((com.google.cloud.vision.v1.ListProductsInProductSetResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.vision.v1.ListProductsInProductSetResponse other) {
if (other == com.google.cloud.vision.v1.ListProductsInProductSetResponse.getDefaultInstance())
return this;
if (productsBuilder_ == null) {
if (!other.products_.isEmpty()) {
if (products_.isEmpty()) {
products_ = other.products_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureProductsIsMutable();
products_.addAll(other.products_);
}
onChanged();
}
} else {
if (!other.products_.isEmpty()) {
if (productsBuilder_.isEmpty()) {
productsBuilder_.dispose();
productsBuilder_ = null;
products_ = other.products_;
bitField0_ = (bitField0_ & ~0x00000001);
productsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getProductsFieldBuilder()
: null;
} else {
productsBuilder_.addAllMessages(other.products_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.vision.v1.Product m =
input.readMessage(
com.google.cloud.vision.v1.Product.parser(), extensionRegistry);
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.add(m);
} else {
productsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.vision.v1.Product> products_ =
java.util.Collections.emptyList();
private void ensureProductsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
products_ = new java.util.ArrayList<com.google.cloud.vision.v1.Product>(products_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vision.v1.Product,
com.google.cloud.vision.v1.Product.Builder,
com.google.cloud.vision.v1.ProductOrBuilder>
productsBuilder_;
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public java.util.List<com.google.cloud.vision.v1.Product> getProductsList() {
if (productsBuilder_ == null) {
return java.util.Collections.unmodifiableList(products_);
} else {
return productsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public int getProductsCount() {
if (productsBuilder_ == null) {
return products_.size();
} else {
return productsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1.Product getProducts(int index) {
if (productsBuilder_ == null) {
return products_.get(index);
} else {
return productsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public Builder setProducts(int index, com.google.cloud.vision.v1.Product value) {
if (productsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProductsIsMutable();
products_.set(index, value);
onChanged();
} else {
productsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public Builder setProducts(
int index, com.google.cloud.vision.v1.Product.Builder builderForValue) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.set(index, builderForValue.build());
onChanged();
} else {
productsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public Builder addProducts(com.google.cloud.vision.v1.Product value) {
if (productsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProductsIsMutable();
products_.add(value);
onChanged();
} else {
productsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public Builder addProducts(int index, com.google.cloud.vision.v1.Product value) {
if (productsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProductsIsMutable();
products_.add(index, value);
onChanged();
} else {
productsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public Builder addProducts(com.google.cloud.vision.v1.Product.Builder builderForValue) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.add(builderForValue.build());
onChanged();
} else {
productsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public Builder addProducts(
int index, com.google.cloud.vision.v1.Product.Builder builderForValue) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.add(index, builderForValue.build());
onChanged();
} else {
productsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public Builder addAllProducts(
java.lang.Iterable<? extends com.google.cloud.vision.v1.Product> values) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, products_);
onChanged();
} else {
productsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public Builder clearProducts() {
if (productsBuilder_ == null) {
products_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
productsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public Builder removeProducts(int index) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.remove(index);
onChanged();
} else {
productsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1.Product.Builder getProductsBuilder(int index) {
return getProductsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1.ProductOrBuilder getProductsOrBuilder(int index) {
if (productsBuilder_ == null) {
return products_.get(index);
} else {
return productsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public java.util.List<? extends com.google.cloud.vision.v1.ProductOrBuilder>
getProductsOrBuilderList() {
if (productsBuilder_ != null) {
return productsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(products_);
}
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1.Product.Builder addProductsBuilder() {
return getProductsFieldBuilder()
.addBuilder(com.google.cloud.vision.v1.Product.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1.Product.Builder addProductsBuilder(int index) {
return getProductsFieldBuilder()
.addBuilder(index, com.google.cloud.vision.v1.Product.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of Products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1.Product products = 1;</code>
*/
public java.util.List<com.google.cloud.vision.v1.Product.Builder> getProductsBuilderList() {
return getProductsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vision.v1.Product,
com.google.cloud.vision.v1.Product.Builder,
com.google.cloud.vision.v1.ProductOrBuilder>
getProductsFieldBuilder() {
if (productsBuilder_ == null) {
productsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vision.v1.Product,
com.google.cloud.vision.v1.Product.Builder,
com.google.cloud.vision.v1.ProductOrBuilder>(
products_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
products_ = null;
}
return productsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.vision.v1.ListProductsInProductSetResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.vision.v1.ListProductsInProductSetResponse)
private static final com.google.cloud.vision.v1.ListProductsInProductSetResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.vision.v1.ListProductsInProductSetResponse();
}
public static com.google.cloud.vision.v1.ListProductsInProductSetResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListProductsInProductSetResponse> PARSER =
new com.google.protobuf.AbstractParser<ListProductsInProductSetResponse>() {
@java.lang.Override
public ListProductsInProductSetResponse 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<ListProductsInProductSetResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListProductsInProductSetResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.vision.v1.ListProductsInProductSetResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,704 | java-shopping-merchant-inventories/proto-google-shopping-merchant-inventories-v1beta/src/main/java/com/google/shopping/merchant/inventories/v1beta/InsertLocalInventoryRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/shopping/merchant/inventories/v1beta/localinventory.proto
// Protobuf Java Version: 3.25.8
package com.google.shopping.merchant.inventories.v1beta;
/**
*
*
* <pre>
* Request message for the `InsertLocalInventory` method.
* </pre>
*
* Protobuf type {@code google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest}
*/
public final class InsertLocalInventoryRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest)
InsertLocalInventoryRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use InsertLocalInventoryRequest.newBuilder() to construct.
private InsertLocalInventoryRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private InsertLocalInventoryRequest() {
parent_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new InsertLocalInventoryRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.inventories.v1beta.LocalInventoryProto
.internal_static_google_shopping_merchant_inventories_v1beta_InsertLocalInventoryRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.inventories.v1beta.LocalInventoryProto
.internal_static_google_shopping_merchant_inventories_v1beta_InsertLocalInventoryRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest.class,
com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest.Builder
.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int LOCAL_INVENTORY_FIELD_NUMBER = 2;
private com.google.shopping.merchant.inventories.v1beta.LocalInventory localInventory_;
/**
*
*
* <pre>
* Required. Local inventory information of the product. If the product
* already has a `LocalInventory` resource for the same `storeCode`, full
* replacement of the `LocalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.LocalInventory local_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the localInventory field is set.
*/
@java.lang.Override
public boolean hasLocalInventory() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Local inventory information of the product. If the product
* already has a `LocalInventory` resource for the same `storeCode`, full
* replacement of the `LocalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.LocalInventory local_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The localInventory.
*/
@java.lang.Override
public com.google.shopping.merchant.inventories.v1beta.LocalInventory getLocalInventory() {
return localInventory_ == null
? com.google.shopping.merchant.inventories.v1beta.LocalInventory.getDefaultInstance()
: localInventory_;
}
/**
*
*
* <pre>
* Required. Local inventory information of the product. If the product
* already has a `LocalInventory` resource for the same `storeCode`, full
* replacement of the `LocalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.LocalInventory local_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.shopping.merchant.inventories.v1beta.LocalInventoryOrBuilder
getLocalInventoryOrBuilder() {
return localInventory_ == null
? com.google.shopping.merchant.inventories.v1beta.LocalInventory.getDefaultInstance()
: localInventory_;
}
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, getLocalInventory());
}
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, getLocalInventory());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj
instanceof com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest)) {
return super.equals(obj);
}
com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest other =
(com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasLocalInventory() != other.hasLocalInventory()) return false;
if (hasLocalInventory()) {
if (!getLocalInventory().equals(other.getLocalInventory())) 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 (hasLocalInventory()) {
hash = (37 * hash) + LOCAL_INVENTORY_FIELD_NUMBER;
hash = (53 * hash) + getLocalInventory().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest 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 `InsertLocalInventory` method.
* </pre>
*
* Protobuf type {@code google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest)
com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.inventories.v1beta.LocalInventoryProto
.internal_static_google_shopping_merchant_inventories_v1beta_InsertLocalInventoryRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.inventories.v1beta.LocalInventoryProto
.internal_static_google_shopping_merchant_inventories_v1beta_InsertLocalInventoryRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest.class,
com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest.Builder
.class);
}
// Construct using
// com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getLocalInventoryFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
localInventory_ = null;
if (localInventoryBuilder_ != null) {
localInventoryBuilder_.dispose();
localInventoryBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.shopping.merchant.inventories.v1beta.LocalInventoryProto
.internal_static_google_shopping_merchant_inventories_v1beta_InsertLocalInventoryRequest_descriptor;
}
@java.lang.Override
public com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
getDefaultInstanceForType() {
return com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest build() {
com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest result =
buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
buildPartial() {
com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest result =
new com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.localInventory_ =
localInventoryBuilder_ == null ? localInventory_ : localInventoryBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other
instanceof com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest) {
return mergeFrom(
(com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest other) {
if (other
== com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasLocalInventory()) {
mergeLocalInventory(other.getLocalInventory());
}
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(getLocalInventoryFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.shopping.merchant.inventories.v1beta.LocalInventory localInventory_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.inventories.v1beta.LocalInventory,
com.google.shopping.merchant.inventories.v1beta.LocalInventory.Builder,
com.google.shopping.merchant.inventories.v1beta.LocalInventoryOrBuilder>
localInventoryBuilder_;
/**
*
*
* <pre>
* Required. Local inventory information of the product. If the product
* already has a `LocalInventory` resource for the same `storeCode`, full
* replacement of the `LocalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.LocalInventory local_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the localInventory field is set.
*/
public boolean hasLocalInventory() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Local inventory information of the product. If the product
* already has a `LocalInventory` resource for the same `storeCode`, full
* replacement of the `LocalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.LocalInventory local_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The localInventory.
*/
public com.google.shopping.merchant.inventories.v1beta.LocalInventory getLocalInventory() {
if (localInventoryBuilder_ == null) {
return localInventory_ == null
? com.google.shopping.merchant.inventories.v1beta.LocalInventory.getDefaultInstance()
: localInventory_;
} else {
return localInventoryBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Local inventory information of the product. If the product
* already has a `LocalInventory` resource for the same `storeCode`, full
* replacement of the `LocalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.LocalInventory local_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setLocalInventory(
com.google.shopping.merchant.inventories.v1beta.LocalInventory value) {
if (localInventoryBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
localInventory_ = value;
} else {
localInventoryBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Local inventory information of the product. If the product
* already has a `LocalInventory` resource for the same `storeCode`, full
* replacement of the `LocalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.LocalInventory local_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setLocalInventory(
com.google.shopping.merchant.inventories.v1beta.LocalInventory.Builder builderForValue) {
if (localInventoryBuilder_ == null) {
localInventory_ = builderForValue.build();
} else {
localInventoryBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Local inventory information of the product. If the product
* already has a `LocalInventory` resource for the same `storeCode`, full
* replacement of the `LocalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.LocalInventory local_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeLocalInventory(
com.google.shopping.merchant.inventories.v1beta.LocalInventory value) {
if (localInventoryBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& localInventory_ != null
&& localInventory_
!= com.google.shopping.merchant.inventories.v1beta.LocalInventory
.getDefaultInstance()) {
getLocalInventoryBuilder().mergeFrom(value);
} else {
localInventory_ = value;
}
} else {
localInventoryBuilder_.mergeFrom(value);
}
if (localInventory_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Local inventory information of the product. If the product
* already has a `LocalInventory` resource for the same `storeCode`, full
* replacement of the `LocalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.LocalInventory local_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearLocalInventory() {
bitField0_ = (bitField0_ & ~0x00000002);
localInventory_ = null;
if (localInventoryBuilder_ != null) {
localInventoryBuilder_.dispose();
localInventoryBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Local inventory information of the product. If the product
* already has a `LocalInventory` resource for the same `storeCode`, full
* replacement of the `LocalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.LocalInventory local_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.shopping.merchant.inventories.v1beta.LocalInventory.Builder
getLocalInventoryBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getLocalInventoryFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Local inventory information of the product. If the product
* already has a `LocalInventory` resource for the same `storeCode`, full
* replacement of the `LocalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.LocalInventory local_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.shopping.merchant.inventories.v1beta.LocalInventoryOrBuilder
getLocalInventoryOrBuilder() {
if (localInventoryBuilder_ != null) {
return localInventoryBuilder_.getMessageOrBuilder();
} else {
return localInventory_ == null
? com.google.shopping.merchant.inventories.v1beta.LocalInventory.getDefaultInstance()
: localInventory_;
}
}
/**
*
*
* <pre>
* Required. Local inventory information of the product. If the product
* already has a `LocalInventory` resource for the same `storeCode`, full
* replacement of the `LocalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.LocalInventory local_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.inventories.v1beta.LocalInventory,
com.google.shopping.merchant.inventories.v1beta.LocalInventory.Builder,
com.google.shopping.merchant.inventories.v1beta.LocalInventoryOrBuilder>
getLocalInventoryFieldBuilder() {
if (localInventoryBuilder_ == null) {
localInventoryBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.inventories.v1beta.LocalInventory,
com.google.shopping.merchant.inventories.v1beta.LocalInventory.Builder,
com.google.shopping.merchant.inventories.v1beta.LocalInventoryOrBuilder>(
getLocalInventory(), getParentForChildren(), isClean());
localInventory_ = null;
}
return localInventoryBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest)
}
// @@protoc_insertion_point(class_scope:google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest)
private static final com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest();
}
public static com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<InsertLocalInventoryRequest> PARSER =
new com.google.protobuf.AbstractParser<InsertLocalInventoryRequest>() {
@java.lang.Override
public InsertLocalInventoryRequest 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<InsertLocalInventoryRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<InsertLocalInventoryRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/ignite-3 | 35,708 | modules/sql-engine/src/test/java/org/apache/ignite/internal/sql/engine/prepare/PrepareServiceImplTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.sql.engine.prepare;
import static org.apache.ignite.internal.sql.engine.prepare.PrepareServiceImpl.PLAN_UPDATER_INITIAL_DELAY;
import static org.apache.ignite.internal.sql.engine.util.SqlTestUtils.assertThrowsSqlException;
import static org.apache.ignite.internal.testframework.IgniteTestUtils.assertThrowsWithCause;
import static org.apache.ignite.internal.testframework.IgniteTestUtils.await;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.time.Duration;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.ignite.internal.hlc.ClockServiceImpl;
import org.apache.ignite.internal.hlc.HybridClockImpl;
import org.apache.ignite.internal.hlc.HybridTimestamp;
import org.apache.ignite.internal.metrics.MetricManagerImpl;
import org.apache.ignite.internal.sql.SqlCommon;
import org.apache.ignite.internal.sql.engine.QueryCancel;
import org.apache.ignite.internal.sql.engine.SqlOperationContext;
import org.apache.ignite.internal.sql.engine.framework.PredefinedSchemaManager;
import org.apache.ignite.internal.sql.engine.framework.TestBuilders;
import org.apache.ignite.internal.sql.engine.framework.VersionedSchemaManager;
import org.apache.ignite.internal.sql.engine.prepare.ddl.DdlSqlToCommandConverter;
import org.apache.ignite.internal.sql.engine.schema.IgniteIndex.Collation;
import org.apache.ignite.internal.sql.engine.schema.IgniteSchema;
import org.apache.ignite.internal.sql.engine.schema.IgniteTable;
import org.apache.ignite.internal.sql.engine.sql.ParsedResult;
import org.apache.ignite.internal.sql.engine.sql.ParserServiceImpl;
import org.apache.ignite.internal.sql.engine.trait.IgniteDistributions;
import org.apache.ignite.internal.sql.engine.util.SqlTestUtils;
import org.apache.ignite.internal.sql.engine.util.cache.Cache;
import org.apache.ignite.internal.sql.engine.util.cache.CacheFactory;
import org.apache.ignite.internal.sql.engine.util.cache.CaffeineCacheFactory;
import org.apache.ignite.internal.sql.engine.util.cache.StatsCounter;
import org.apache.ignite.internal.testframework.BaseIgniteAbstractTest;
import org.apache.ignite.internal.testframework.ExecutorServiceExtension;
import org.apache.ignite.internal.testframework.IgniteTestUtils;
import org.apache.ignite.internal.testframework.InjectExecutorService;
import org.apache.ignite.internal.type.NativeType;
import org.apache.ignite.internal.type.NativeTypes;
import org.apache.ignite.internal.util.ExceptionUtils;
import org.apache.ignite.lang.ErrorGroups.Sql;
import org.apache.ignite.sql.ColumnMetadata;
import org.apache.ignite.sql.ColumnType;
import org.apache.ignite.sql.SqlException;
import org.awaitility.Awaitility;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.AfterEach;
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.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito;
/**
* Tests to verify {@link PrepareServiceImpl}.
*/
@ExtendWith(ExecutorServiceExtension.class)
public class PrepareServiceImplTest extends BaseIgniteAbstractTest {
private static final List<PrepareService> createdServices = new ArrayList<>();
@InjectExecutorService
private static ScheduledExecutorService commonExecutor;
@AfterEach
public void stopServices() throws Exception {
for (PrepareService createdService : createdServices) {
createdService.stop();
}
createdServices.clear();
}
@ParameterizedTest
@MethodSource("insertInvariants")
public void testOptimizedExecutionPath(String insertStatement, boolean applicable) {
PrepareService service = createPlannerService();
PrepareServiceImpl prepare = (PrepareServiceImpl) spy(service);
await(prepare.prepareAsync(
parse(insertStatement),
createContext()
));
if (applicable) {
verify(prepare).prepareDmlOpt(any(), any(), any());
} else {
verify(prepare, never()).prepareDmlOpt(any(), any(), any());
}
}
private static Stream<Arguments> insertInvariants() {
return Stream.of(
Arguments.of("INSERT INTO t VALUES (1, 2)", true),
Arguments.of("INSERT INTO t VALUES (1, 2), (3, 4)", true),
Arguments.of("INSERT INTO t(A, C) VALUES (1, 2)", true),
Arguments.of("INSERT INTO t(C, A) VALUES (2, 1)", true),
Arguments.of("INSERT INTO t(C, A) VALUES ('2'::smallint, 1)", false),
Arguments.of("INSERT INTO t(C, A) VALUES (2, 1), (3, ?)", false),
Arguments.of("INSERT INTO t(C, A) SELECT t.C, t.A from t", false),
Arguments.of("INSERT INTO t VALUES (1, OCTET_LENGTH('TEST'))", false),
Arguments.of("INSERT INTO t VALUES (1, ?)", false),
Arguments.of("INSERT INTO t VALUES (?, 2)", false),
Arguments.of("INSERT INTO t VALUES (?, ?)", false),
Arguments.of("INSERT INTO t VALUES ((SELECT 1), 2)", false),
Arguments.of("INSERT INTO t SELECT t1.c1, t1.c2 FROM (SELECT 1, 2) as t1(c1, c2)", false),
Arguments.of("INSERT INTO t SELECT t1.c1, t1.c2 FROM (SELECT ?::int, ?::int) as t1(c1, c2)", false)
);
}
@Test
public void prepareServiceReturnsExistingPlanForExplain() {
PrepareService service = createPlannerService();
QueryPlan queryPlan = await(service.prepareAsync(
parse("SELECT * FROM t"),
createContext()
));
QueryPlan explainPlan = await(service.prepareAsync(
parse("explain plan for select * from t"),
createContext()
));
assertThat(explainPlan, instanceOf(ExplainPlan.class));
ExplainPlan plan = (ExplainPlan) explainPlan;
assertThat(plan.plan(), sameInstance(queryPlan));
}
@Test
public void prepareServiceCachesPlanCreatedForExplain() {
PrepareService service = createPlannerService();
QueryPlan explainPlan = await(service.prepareAsync(
parse("explain plan for select * from t"),
createContext()
));
QueryPlan queryPlan = await(service.prepareAsync(
parse("SELECT * FROM t"),
createContext()
));
assertThat(explainPlan, instanceOf(ExplainPlan.class));
ExplainPlan plan = (ExplainPlan) explainPlan;
assertThat(plan.plan(), sameInstance(queryPlan));
}
@Test
public void prepareReturnsQueryPlanThatDependsOnParameterTypeMatchInferred() {
PrepareService service = createPlannerService();
QueryPlan queryPlan1 = await(service.prepareAsync(
parse("SELECT * FROM t WHERE a = ? and c = ?"),
createContext()
));
List<ColumnType> parameterTypes = queryPlan1.parameterMetadata().parameterTypes()
.stream()
.map(ParameterType::columnType)
.collect(Collectors.toList());
assertEquals(List.of(ColumnType.INT64, ColumnType.INT32), parameterTypes);
// Parameter types match, we should return plan1.
QueryPlan queryPlan2 = await(service.prepareAsync(
parse("SELECT * FROM t WHERE a = ? and c = ?"),
createContext(1L, 1))
);
assertSame(queryPlan1, queryPlan2);
// Parameter types do not match
QueryPlan queryPlan3 = await(service.prepareAsync(
parse("SELECT * FROM t WHERE a = ? and c = ?"),
createContext(1, 1L)
));
assertNotSame(queryPlan1, queryPlan3);
}
@Test
public void prepareReturnsDmlPlanThatDependsOnParameterTypeMatchInferred() {
PrepareService service = createPlannerService();
QueryPlan queryPlan1 = await(service.prepareAsync(
parse("UPDATE t SET a = ? WHERE c = ?"),
createContext()
));
List<ColumnType> parameterTypes = queryPlan1.parameterMetadata().parameterTypes()
.stream()
.map(ParameterType::columnType)
.collect(Collectors.toList());
assertEquals(List.of(ColumnType.INT64, ColumnType.INT32), parameterTypes);
// Parameter types match, we should return plan1.
QueryPlan queryPlan2 = await(service.prepareAsync(
parse("UPDATE t SET a = ? WHERE c = ?"),
createContext(1L, 1)
));
assertSame(queryPlan1, queryPlan2);
// Parameter types do not match
QueryPlan queryPlan3 = await(service.prepareAsync(
parse("UPDATE t SET a = ? WHERE c = ?"),
createContext(1, 1L)
));
assertNotSame(queryPlan1, queryPlan3);
}
@Test
public void preparePropagatesValidationError() {
PrepareService service = createPlannerService();
assertThrowsSqlException(Sql.STMT_VALIDATION_ERR,
"Ambiguous operator <UNKNOWN> + <UNKNOWN>. Dynamic parameter requires adding explicit type cast",
() -> {
ParsedResult parsedResult = parse("SELECT ? + ?");
SqlOperationContext context = createContext();
await(service.prepareAsync(parsedResult, context));
}
);
}
@ParameterizedTest
@MethodSource("parameterTypes")
public void prepareParamInPredicateAllTypes(NativeType nativeType, int precision, int scale) {
IgniteTable table = TestBuilders.table()
.name("T")
.addColumn("C", nativeType)
.distribution(IgniteDistributions.single())
.build();
IgniteSchema schema = new IgniteSchema("PUBLIC", 0, List.of(table));
PrepareService service = createPlannerService(schema);
Object paramValue = SqlTestUtils.generateValueByType(nativeType);
QueryPlan queryPlan = await(service.prepareAsync(
parse("SELECT * FROM t WHERE c = ?"),
createContext(paramValue)
));
ParameterType parameterType = queryPlan.parameterMetadata().parameterTypes().get(0);
ColumnType columnType = nativeType.spec();
assertEquals(columnType, parameterType.columnType(), "Column type does not match: " + parameterType);
assertEquals(precision, parameterType.precision(), "Precision does not match: " + parameterType);
assertEquals(scale, parameterType.scale(), "Scale does not match: " + parameterType);
assertTrue(parameterType.nullable(), "Nullabilty does not match: " + parameterType);
}
@Test
public void timeoutedPlanShouldBeRemovedFromCache() throws InterruptedException {
IgniteTable igniteTable = TestBuilders.table()
.name("T")
.addColumn("C", NativeTypes.INT32)
.distribution(IgniteDistributions.single())
.build();
// Create a proxy.
IgniteTable spyTable = spy(igniteTable);
// Override and slowdown a method, which is called by Planner, to emulate long planning.
Mockito.doAnswer(inv -> {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// Call original method.
return igniteTable.getRowType(inv.getArgument(0), inv.getArgument(1));
}).when(spyTable).getRowType(any(), any());
IgniteSchema schema = new IgniteSchema("PUBLIC", 0, List.of(igniteTable));
Cache<Object, Object> cache = CaffeineCacheFactory.INSTANCE.create(100);
CacheFactory cacheFactory = new DummyCacheFactory(cache);
PrepareServiceImpl service = createPlannerService(schema, cacheFactory, 100);
StringBuilder stmt = new StringBuilder();
for (int i = 0; i < 100; i++) {
if (i > 0) {
stmt.append("UNION")
.append(System.lineSeparator());
}
stmt.append("SELECT * FROM t WHERE c = ").append(i).append(System.lineSeparator());
}
ParsedResult parsedResult = parse(stmt.toString());
SqlOperationContext context = operationContext().build();
Throwable err = assertThrowsWithCause(
() -> service.prepareAsync(parsedResult, context).get(),
SqlException.class
);
Throwable cause = ExceptionUtils.unwrapCause(err);
SqlException sqlErr = assertInstanceOf(SqlException.class, cause, "Unexpected error. Root error: " + err);
assertEquals(Sql.EXECUTION_CANCELLED_ERR, sqlErr.code(), "Unexpected error: " + sqlErr);
// Cache invalidate does not immediately remove the entry, so we need to wait some time to ensure it is removed.
boolean empty = IgniteTestUtils.waitForCondition(() -> cache.size() == 0, 1000);
assertTrue(empty, "Cache is not empty: " + cache.size());
}
@Test
public void testDoNotFailPlanningOnMissingSchemaThatIsNotUsed() {
IgniteTable table = TestBuilders.table()
.name("T")
.addColumn("C", NativeTypes.INT32)
.distribution(IgniteDistributions.single())
.build();
IgniteSchema schema = new IgniteSchema("TEST", 0, List.of(table));
PrepareService service = createPlannerService(schema);
await(service.prepareAsync(
parse("SELECT * FROM test.t WHERE c = 1"),
operationContext().defaultSchemaName("MISSING").build()
));
}
/** Validates that plan for appropriate tableId will be changed by request. */
@Test
public void statisticUpdatesChangePlans() {
IgniteTable table = TestBuilders.table()
.name("T")
.addColumn("C", NativeTypes.INT32)
.distribution(IgniteDistributions.single())
.build();
IgniteSchema schema = new IgniteSchema("TEST", 0, List.of(table));
PrepareServiceImpl service = createPlannerService(schema, CaffeineCacheFactory.INSTANCE, Integer.MAX_VALUE);
assertThat(service.cache.size(), is(0));
String selectQuery = "SELECT * FROM test.t WHERE c = 1";
QueryPlan selectPlan = await(service.prepareAsync(parse(selectQuery), operationContext().build()));
assertThat(service.cache.size(), is(1));
String insertQuery = "INSERT INTO test.t VALUES(OCTET_LENGTH('TEST')), (2)";
QueryPlan insertPlan = await(service.prepareAsync(parse(insertQuery), operationContext().build()));
assertThat(service.cache.size(), is(2));
service.statisticsChanged(table.id());
Awaitility.await()
.atMost(Duration.ofMillis(2 * PLAN_UPDATER_INITIAL_DELAY))
.until(
() -> !selectPlan.equals(await(service.prepareAsync(parse(selectQuery), operationContext().build())))
);
Awaitility.await()
.atMost(Duration.ofMillis(2 * PLAN_UPDATER_INITIAL_DELAY))
.until(
() -> !insertPlan.equals(await(service.prepareAsync(parse(insertQuery), operationContext().build())))
);
assertThat(service.cache.size(), is(2));
}
@Test
public void planUpdatesForNonCachedTable() {
IgniteTable table1 = TestBuilders.table()
.name("T1")
.addColumn("C", NativeTypes.INT32)
.distribution(IgniteDistributions.single())
.build();
IgniteTable table2 = TestBuilders.table()
.name("T2")
.addColumn("C", NativeTypes.INT32)
.distribution(IgniteDistributions.single())
.build();
IgniteSchema schema = new IgniteSchema("TEST", 0, List.of(table1, table2));
// 1 item cache plan size
PrepareServiceImpl service = (PrepareServiceImpl) createPlannerService(schema, 1);
String selectQuery = "SELECT * FROM test.t1 WHERE c = 1";
await(service.prepareAsync(parse(selectQuery), operationContext().build()));
assertThat(service.cache.size(), is(1));
CacheKey key1 = service.cache.entrySet().iterator().next().getKey();
// different table
String insertQuery = "SELECT * FROM test.t2 WHERE c = 1";
QueryPlan plan2 = await(service.prepareAsync(parse(insertQuery), operationContext().build()));
assertThat(service.cache.size(), is(1));
CacheKey key2 = service.cache.entrySet().iterator().next().getKey();
assertNotEquals(key1, key2);
// not cached table
service.statisticsChanged(table1.id());
// cached table
service.statisticsChanged(table2.id());
Awaitility.await()
.atMost(Duration.ofMillis(2 * PLAN_UPDATER_INITIAL_DELAY))
.until(
() -> !plan2.equals(await(service.prepareAsync(parse(insertQuery), operationContext().build())))
);
}
/** Validate that plan updates only for current catalog version. */
@Test
public void planUpdatesForCurrentCatalogVersion() {
IgniteTable table1 = TestBuilders.table()
.name("T1")
.addColumn("C1", NativeTypes.INT32)
.addColumn("C2", NativeTypes.INT32)
.distribution(IgniteDistributions.single())
.sortedIndex()
.name("T1_C1_IDX")
.addColumn("C1", Collation.ASC_NULLS_LAST)
.end()
.build();
IgniteSchema schema = new IgniteSchema("TEST", 0, List.of(table1));
AtomicInteger ver = new AtomicInteger();
PrepareServiceImpl service = createPlannerService(schema, CaffeineCacheFactory.INSTANCE, 10000,
Integer.MAX_VALUE, 1000, ver);
String selectQuery = "SELECT /*+ FORCE_INDEX(T1_C1_IDX) */ * FROM test.t1 WHERE c1 = 1";
QueryPlan plan1 = await(service.prepareAsync(parse(selectQuery), operationContext().build()));
// catalog version 1
ver.incrementAndGet();
QueryPlan plan2 = await(service.prepareAsync(parse(selectQuery), operationContext().build()));
Awaitility.await()
.atMost(Duration.ofMillis(10000))
.until(
() -> service.cache.size() == 2
);
assertThat(service.cache.size(), is(2));
service.statisticsChanged(table1.id());
Awaitility.await()
.atMost(Duration.ofMillis(2 * PLAN_UPDATER_INITIAL_DELAY))
.until(
() -> !plan2.equals(await(service.prepareAsync(parse(selectQuery), operationContext().build())))
);
// previous catalog, get cached plan
ver.set(0);
assertEquals(plan1, await(service.prepareAsync(parse(selectQuery), operationContext().build())));
}
@Test
public void cachePlanEntriesInvalidatesForCurrentCatalogVersion() {
IgniteTable table1 = TestBuilders.table()
.name("T1")
.addColumn("C1", NativeTypes.INT32)
.distribution(IgniteDistributions.single())
.build();
IgniteSchema schema = new IgniteSchema("TEST", 0, List.of(table1));
AtomicInteger ver = new AtomicInteger();
PrepareServiceImpl service = createPlannerServiceWithInactivePlanUpdater(schema, CaffeineCacheFactory.INSTANCE, 10000,
Integer.MAX_VALUE, 1000, ver);
String selectQuery = "SELECT * FROM test.t1 WHERE c1 = 1";
await(service.prepareAsync(parse(selectQuery), operationContext().build()));
// catalog version 1
ver.incrementAndGet();
await(service.prepareAsync(parse(selectQuery), operationContext().build()));
Awaitility.await()
.atMost(Duration.ofMillis(10000))
.until(
() -> service.cache.size() == 2
);
assertThat(service.cache.size(), is(2));
service.statisticsChanged(table1.id());
assertThat(service.cache.entrySet().stream().filter(e -> e.getValue().join().needInvalidate()).count(), is(1L));
}
@Test
public void testCacheExpireIfStatisticChanged() throws InterruptedException {
IgniteTable table = TestBuilders.table()
.name("T")
.addColumn("C", NativeTypes.INT32)
.distribution(IgniteDistributions.single())
.build();
IgniteSchema schema = new IgniteSchema("TEST", 0, List.of(table));
int expireMillis = 4_000;
PrepareServiceImpl service =
createPlannerServiceWithInactivePlanUpdater(schema, CaffeineCacheFactory.INSTANCE, 10000,
(int) TimeUnit.MILLISECONDS.toSeconds(expireMillis), 1000, null);
String query = "SELECT * FROM test.t WHERE c = 1";
QueryPlan p0 = await(service.prepareAsync(parse(query), operationContext().build()));
// infinitely change statistic
IgniteTestUtils.runAsync(() -> {
while (true) {
service.statisticsChanged(table.id());
Thread.sleep(expireMillis / 10);
}
});
// Expires if not used
TimeUnit.MILLISECONDS.sleep(expireMillis * 2);
QueryPlan p2 = await(service.prepareAsync(parse(query), operationContext().build()));
assertNotSame(p0, p2);
}
@Test
public void planCacheExpiry() {
IgniteTable table = TestBuilders.table()
.name("T")
.addColumn("C", NativeTypes.INT32)
.distribution(IgniteDistributions.single())
.build();
IgniteSchema schema = new IgniteSchema("TEST", 0, List.of(table));
Awaitility.await().timeout(30, TimeUnit.SECONDS).untilAsserted(() -> {
int expireSeconds = 2;
PrepareServiceImpl service =
createPlannerService(schema, CaffeineCacheFactory.INSTANCE, Integer.MAX_VALUE, expireSeconds, 1000);
String query = "SELECT * FROM test.t WHERE c = 1";
QueryPlan p0 = await(service.prepareAsync(parse(query), operationContext().build()));
// Expires if not used
TimeUnit.SECONDS.sleep(expireSeconds * 2);
QueryPlan p2 = await(service.prepareAsync(parse(query), operationContext().build()));
assertNotSame(p0, p2);
// Returns the previous plan
TimeUnit.MILLISECONDS.sleep(500);
QueryPlan p3 = await(service.prepareAsync(parse(query), operationContext().build()));
assertSame(p2, p3);
// Eventually expires
TimeUnit.SECONDS.sleep(expireSeconds * 2);
QueryPlan p4 = await(service.prepareAsync(parse(query), operationContext().build()));
assertNotSame(p4, p3);
});
}
@Test
public void invalidatePlannerCache() {
IgniteSchema schema = new IgniteSchema("PUBLIC", 0, List.of(
TestBuilders.table().name("T1").addColumn("C", NativeTypes.INT32).distribution(IgniteDistributions.single()).build(),
TestBuilders.table().name("T2").addColumn("C", NativeTypes.INT32).distribution(IgniteDistributions.single()).build()
));
Cache<Object, Object> cache = CaffeineCacheFactory.INSTANCE.create(100);
PrepareServiceImpl service = createPlannerService(schema, new DummyCacheFactory(cache), 1000);
await(service.prepareAsync(parse("SELECT * FROM t1"), createContext()));
await(service.prepareAsync(parse("SELECT * FROM t1 WHERE C > 0"), createContext()));
await(service.prepareAsync(parse("SELECT * FROM t2"), createContext()));
assertThat(cache.size(), is(3));
// Invalidate
await(service.invalidateCache(Set.of()));
assertThat(cache.size(), is(0));
}
@Test
public void invalidateQueryPlans() {
IgniteSchema schema = new IgniteSchema("PUBLIC", 0, List.of(
TestBuilders.table().name("T1").addColumn("C", NativeTypes.INT32).distribution(IgniteDistributions.single()).build(),
TestBuilders.table().name("t2").addColumn("C", NativeTypes.INT32).distribution(IgniteDistributions.single()).build()
));
Cache<Object, Object> cache = CaffeineCacheFactory.INSTANCE.create(100);
PrepareServiceImpl service = createPlannerService(schema, new DummyCacheFactory(cache), 1000);
{ // Simple name.
await(service.prepareAsync(parse("SELECT * FROM t1"), createContext()));
await(service.prepareAsync(parse("SELECT * FROM t1 WHERE C > 0"), createContext()));
QueryPlan queryPlan = await(service.prepareAsync(parse("SELECT * FROM \"t2\""), createContext()));
assertThat(cache.size(), is(3));
// Case, when no plan matches.
await(service.invalidateCache(Set.of("t")));
assertThat(cache.size(), is(3));
await(service.invalidateCache(Set.of("t2")));
assertThat(cache.size(), is(3));
// Found and invalidate related plan.
await(service.invalidateCache(Set.of("t1")));
assertThat(cache.size(), is(1));
QueryPlan explainPlan = await(service.prepareAsync(
parse("explain plan for select * from \"t2\""),
createContext()
));
ExplainPlan plan = (ExplainPlan) explainPlan;
assertThat(plan.plan(), sameInstance(queryPlan));
await(service.invalidateCache(Set.of("\"t2\"")));
assertThat(cache.size(), is(0));
}
{ // Qualified name.
await(service.prepareAsync(parse("SELECT * FROM t1"), createContext()));
await(service.prepareAsync(parse("SELECT * FROM t1 WHERE C > 0"), createContext()));
QueryPlan queryPlan = await(service.prepareAsync(parse("SELECT * FROM \"t2\""), createContext()));
assertThat(cache.size(), is(3));
// Case, when no plan matches.
await(service.invalidateCache(Set.of("PUBLIC.t2")));
assertThat(cache.size(), is(3));
await(service.invalidateCache(Set.of("MYSCHEMA.t1")));
assertThat(cache.size(), is(3));
// Found and invalidate related plan.
await(service.invalidateCache(Set.of("PUBLIC.t1")));
assertThat(cache.size(), is(1));
QueryPlan explainPlan = await(service.prepareAsync(
parse("explain plan for select * from \"t2\""),
createContext()
));
ExplainPlan plan = (ExplainPlan) explainPlan;
assertThat(plan.plan(), sameInstance(queryPlan));
await(service.invalidateCache(Set.of("PUBLIC.\"t2\"")));
assertThat(cache.size(), is(0));
}
}
private static Stream<Arguments> parameterTypes() {
int noScale = ColumnMetadata.UNDEFINED_SCALE;
int noPrecision = ColumnMetadata.UNDEFINED_PRECISION;
return Stream.of(
Arguments.of(NativeTypes.BOOLEAN, noPrecision, noScale),
Arguments.of(NativeTypes.INT8, noPrecision, noScale),
Arguments.of(NativeTypes.INT16, noPrecision, noScale),
Arguments.of(NativeTypes.INT32, noPrecision, noScale),
Arguments.of(NativeTypes.INT64, noPrecision, noScale),
Arguments.of(NativeTypes.FLOAT, noPrecision, noScale),
Arguments.of(NativeTypes.DOUBLE, noPrecision, noScale),
Arguments.of(NativeTypes.decimalOf(10, 2),
IgniteSqlValidator.DECIMAL_DYNAMIC_PARAM_PRECISION, IgniteSqlValidator.DECIMAL_DYNAMIC_PARAM_SCALE),
Arguments.of(NativeTypes.stringOf(42), -1, noScale),
Arguments.of(NativeTypes.blobOf(42), -1, noScale),
Arguments.of(NativeTypes.UUID, noPrecision, noScale),
Arguments.of(NativeTypes.DATE, noPrecision, noScale),
Arguments.of(NativeTypes.time(2), IgniteSqlValidator.TEMPORAL_DYNAMIC_PARAM_PRECISION, noScale),
Arguments.of(NativeTypes.datetime(2), IgniteSqlValidator.TEMPORAL_DYNAMIC_PARAM_PRECISION, noScale),
Arguments.of(NativeTypes.timestamp(2), IgniteSqlValidator.TEMPORAL_DYNAMIC_PARAM_PRECISION, noScale)
);
}
private static ParsedResult parse(String query) {
return new ParserServiceImpl().parse(query);
}
private static SqlOperationContext createContext(Object... params) {
return operationContext(params).build();
}
private static SqlOperationContext.Builder operationContext(Object... params) {
return SqlOperationContext.builder()
.queryId(UUID.randomUUID())
.timeZoneId(ZoneId.systemDefault())
.operationTime(new HybridClockImpl().now())
.defaultSchemaName(SqlCommon.DEFAULT_SCHEMA_NAME)
.parameters(params)
.cancel(new QueryCancel());
}
private static IgniteSchema createSchema() {
IgniteTable table = TestBuilders.table()
.name("T")
.addColumn("A", NativeTypes.INT64)
.addColumn("C", NativeTypes.INT32)
.distribution(IgniteDistributions.single())
.build();
return new IgniteSchema("PUBLIC", 0, List.of(table));
}
private static PrepareService createPlannerService() {
return createPlannerService(createSchema());
}
private static PrepareService createPlannerService(IgniteSchema schema, int cacheSize) {
return createPlannerService(schema, CaffeineCacheFactory.INSTANCE, 10000, Integer.MAX_VALUE, cacheSize);
}
private static PrepareService createPlannerService(IgniteSchema schema) {
return createPlannerService(schema, CaffeineCacheFactory.INSTANCE, 10000);
}
private static PrepareServiceImpl createPlannerService(IgniteSchema schemas, CacheFactory cacheFactory, int timeoutMillis) {
return createPlannerService(schemas, cacheFactory, timeoutMillis, Integer.MAX_VALUE, 1000);
}
private static PrepareServiceImpl createPlannerService(
IgniteSchema schemas,
CacheFactory cacheFactory,
int timeoutMillis,
int planExpireSeconds,
int cacheSize
) {
ClockServiceImpl clockService = mock(ClockServiceImpl.class);
when(clockService.currentLong()).thenReturn(new HybridTimestamp(1_000, 500).longValue());
PrepareServiceImpl service = new PrepareServiceImpl("test", cacheSize, cacheFactory,
mock(DdlSqlToCommandConverter.class), timeoutMillis, 2, planExpireSeconds, mock(MetricManagerImpl.class),
new PredefinedSchemaManager(schemas), clockService::currentLong, commonExecutor);
createdServices.add(service);
service.start();
return service;
}
private static PrepareServiceImpl createPlannerService(
IgniteSchema schemas,
CacheFactory cacheFactory,
int timeoutMillis,
int planExpireSeconds,
int cacheSize,
AtomicInteger ver
) {
return createPlannerService(schemas, cacheFactory, timeoutMillis, planExpireSeconds, cacheSize, ver, commonExecutor);
}
private static PrepareServiceImpl createPlannerService(
IgniteSchema schemas,
CacheFactory cacheFactory,
int timeoutMillis,
int planExpireSeconds,
int cacheSize,
@Nullable AtomicInteger ver,
ScheduledExecutorService executor
) {
ClockServiceImpl clockService = mock(ClockServiceImpl.class);
when(clockService.currentLong()).thenReturn(new HybridTimestamp(1_000, 500).longValue());
PrepareServiceImpl service = new PrepareServiceImpl("test", cacheSize, cacheFactory,
mock(DdlSqlToCommandConverter.class), timeoutMillis, 2, planExpireSeconds, mock(MetricManagerImpl.class),
new VersionedSchemaManager(schemas, ver), clockService::currentLong, executor);
createdServices.add(service);
service.start();
return service;
}
private static PrepareServiceImpl createPlannerServiceWithInactivePlanUpdater(
IgniteSchema schemas,
CacheFactory cacheFactory,
int timeoutMillis,
int planExpireSeconds,
int cacheSize,
@Nullable AtomicInteger ver
) {
ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
return createPlannerService(schemas, cacheFactory, timeoutMillis, planExpireSeconds, cacheSize, ver, executor);
}
private static class DummyCacheFactory implements CacheFactory {
private final Cache<Object, Object> cache;
DummyCacheFactory(Cache<Object, Object> cache) {
this.cache = cache;
}
@Override
public <K, V> Cache<K, V> create(int size) {
return (Cache<K, V>) cache;
}
@Override
public <K, V> Cache<K, V> create(int size, StatsCounter statCounter) {
return (Cache<K, V>) cache;
}
@Override
public <K, V> Cache<K, V> create(int size, StatsCounter statCounter, Duration expireAfterAccess) {
return (Cache<K, V>) cache;
}
}
}
|
apache/geode | 35,677 | geode-pulse/src/uiTest/java/org/apache/geode/tools/pulse/tests/ui/PulseBase.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.apache.geode.tools.pulse.tests.ui;
import static org.apache.geode.cache.Region.SEPARATOR;
import static org.apache.geode.tools.pulse.internal.data.PulseConstants.TWO_PLACE_DECIMAL_FORMAT;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.CLUSTER_CLIENTS_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.CLUSTER_FUNCTIONS_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.CLUSTER_GCPAUSES_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.CLUSTER_QUERIESPERSEC_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.CLUSTER_READPERSEC_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.CLUSTER_SUBSCRIPTION_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.CLUSTER_UNIQUECQS_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.CLUSTER_VIEW_GRID_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.CLUSTER_VIEW_LABEL;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.CLUSTER_VIEW_LOCATORS_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.CLUSTER_VIEW_MEMBERS_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.CLUSTER_VIEW_REGIONS_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.CLUSTER_WRITEPERSEC_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_BROWSER_COLOCATED_REGION;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_BROWSER_COLOCATED_REGION_NAME1;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_BROWSER_COLOCATED_REGION_NAME2;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_BROWSER_COLOCATED_REGION_NAME3;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_BROWSER_LABEL;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_BROWSER_REGION1_CHECKBOX;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_BROWSER_REGION2_CHECKBOX;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_BROWSER_REGION3_CHECKBOX;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_BROWSER_REGIONName1;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_BROWSER_REGIONName2;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_BROWSER_REGIONName3;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_DROPDOWN_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_VIEW_EMPTYNODES;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_VIEW_ENTRYCOUNT;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_VIEW_LABEL;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_VIEW_READPERSEC;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_VIEW_USEDMEMORY;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.DATA_VIEW_WRITEPERSEC;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.MEMBER_VIEW_CPUUSAGE_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.MEMBER_VIEW_JVMPAUSES_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.MEMBER_VIEW_LOADAVG_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.MEMBER_VIEW_OFFHEAPFREESIZE_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.MEMBER_VIEW_OFFHEAPUSEDSIZE_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.MEMBER_VIEW_READPERSEC_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.MEMBER_VIEW_REGION_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.MEMBER_VIEW_SOCKETS_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.MEMBER_VIEW_THREAD_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.MEMBER_VIEW_WRITEPERSEC_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.QUERY_STATISTICS_LABEL;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.REDUNDANCY_GRID_ID;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.REGION_NAME_LABEL;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.REGION_PATH_LABEL;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.REGION_PERSISTENCE_LABEL;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.REGION_TYPE_LABEL;
import static org.apache.geode.tools.pulse.tests.ui.PulseTestConstants.SERVER_GROUP_GRID_ID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.text.DecimalFormat;
import java.util.List;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.apache.geode.tools.pulse.tests.JMXProperties;
import org.apache.geode.tools.pulse.tests.PulseTestLocators;
/**
* If you try to run the Pulse UI Tests through your IDE without forking enabled, you will see
* jmxrmi exceptions. This is due to the implementation of org.apache.geode.tools.pulse.tests.Server
*/
public abstract class PulseBase {
public abstract WebDriver getWebDriver();
public abstract String getPulseURL();
@Before
public void setup() {
// Make sure we go to the home page first
searchByXPathAndClick(PulseTestLocators.TopNavigation.clusterViewLinkXpath);
}
protected void searchByLinkAndClick(String linkText) {
WebElement element = By.linkText(linkText).findElement(getWebDriver());
assertNotNull(element);
element.click();
}
protected void searchByIdAndClick(String id) {
WebElement element = getWebDriver().findElement(By.id(id));
assertNotNull(element);
element.click();
}
protected void searchByXPathAndClick(String xpath) {
WebElement element = getWebDriver().findElement(By.xpath(xpath));
assertNotNull(element);
element.click();
}
@Test
public void testClusterLocatorCount() {
String clusterLocators = getWebDriver().findElement(By.id(CLUSTER_VIEW_LOCATORS_ID)).getText();
String totallocators = JMXProperties.getInstance().getProperty("server.S1.locatorCount");
assertEquals(totallocators, clusterLocators);
}
@Test
public void testClusterRegionCount() {
String clusterRegions = getWebDriver().findElement(By.id(CLUSTER_VIEW_REGIONS_ID)).getText();
String totalregions = JMXProperties.getInstance().getProperty("server.S1.totalRegionCount");
assertEquals(totalregions, clusterRegions);
}
@Test
public void testClusterMemberCount() {
String clusterMembers = getWebDriver().findElement(By.id(CLUSTER_VIEW_MEMBERS_ID)).getText();
String totalMembers = JMXProperties.getInstance().getProperty("server.S1.memberCount");
assertEquals(clusterMembers, totalMembers);
}
@Test
public void testClusterNumClient() {
String clusterClients = getWebDriver().findElement(By.id(CLUSTER_CLIENTS_ID)).getText();
String totalclients = JMXProperties.getInstance().getProperty("server.S1.numClients");
assertEquals(totalclients, clusterClients);
}
@Test
public void testClusterNumRunningFunction() {
String clusterFunctions = getWebDriver().findElement(By.id(CLUSTER_FUNCTIONS_ID)).getText();
String totalfunctions =
JMXProperties.getInstance().getProperty("server.S1.numRunningFunctions");
assertEquals(totalfunctions, clusterFunctions);
}
@Test
public void testClusterRegisteredCQCount() {
String clusterUniqueCQs = getWebDriver().findElement(By.id(CLUSTER_UNIQUECQS_ID)).getText();
String totaluniqueCQs = JMXProperties.getInstance().getProperty("server.S1.registeredCQCount");
assertEquals(totaluniqueCQs, clusterUniqueCQs);
}
@Test
public void testClusterNumSubscriptions() {
String clusterSubscriptions =
getWebDriver().findElement(By.id(CLUSTER_SUBSCRIPTION_ID)).getText();
String totalSubscriptions =
JMXProperties.getInstance().getProperty("server.S1.numSubscriptions");
assertEquals(totalSubscriptions, clusterSubscriptions);
}
@Test
public void testClusterJVMPausesWidget() {
String clusterJVMPauses = getWebDriver().findElement(By.id(CLUSTER_GCPAUSES_ID)).getText();
String totalgcpauses = JMXProperties.getInstance().getProperty("server.S1.jvmPauses");
assertEquals(totalgcpauses, clusterJVMPauses);
}
@Test
public void testClusterAverageWritesWidget() {
String clusterWritePerSec = getWebDriver().findElement(By.id(CLUSTER_WRITEPERSEC_ID)).getText();
String totalwritepersec = JMXProperties.getInstance().getProperty("server.S1.averageWrites");
assertEquals(totalwritepersec, clusterWritePerSec);
}
@Test
public void testClusterAverageReadsWidget() {
String clusterReadPerSec = getWebDriver().findElement(By.id(CLUSTER_READPERSEC_ID)).getText();
String totalreadpersec = JMXProperties.getInstance().getProperty("server.S1.averageReads");
assertEquals(totalreadpersec, clusterReadPerSec);
}
@Test
public void testClusterQuerRequestRateWidget() {
String clusterQueriesPerSec =
getWebDriver().findElement(By.id(CLUSTER_QUERIESPERSEC_ID)).getText();
String totalqueriespersec =
JMXProperties.getInstance().getProperty("server.S1.queryRequestRate");
assertEquals(totalqueriespersec, clusterQueriesPerSec);
}
@Test
public void testClusterGridViewMemberID() {
searchByIdAndClick("default_grid_button");
List<WebElement> elements =
getWebDriver().findElements(By.xpath("//table[@id='memberList']/tbody/tr"));
for (int memberCount = 1; memberCount < elements.size(); memberCount++) {
String memberId = getWebDriver()
.findElement(By.xpath("//table[@id='memberList']/tbody/tr[" + (memberCount + 1) + "]/td"))
.getText();
String propertMemeberId =
JMXProperties.getInstance().getProperty("member.M" + memberCount + ".id");
assertEquals(memberId, propertMemeberId);
}
}
@Test
public void testClusterGridViewMemberName() {
searchByIdAndClick("default_grid_button");
List<WebElement> elements =
getWebDriver().findElements(By.xpath("//table[@id='memberList']/tbody/tr"));
for (int memberNameCount = 1; memberNameCount < elements.size(); memberNameCount++) {
String gridMemberName = getWebDriver()
.findElement(
By.xpath("//table[@id='memberList']/tbody/tr[" + (memberNameCount + 1) + "]/td[2]"))
.getText();
String memberName =
JMXProperties.getInstance().getProperty("member.M" + memberNameCount + ".member");
assertEquals(gridMemberName, memberName);
}
}
@Test
public void testClusterGridViewMemberHost() {
searchByIdAndClick("default_grid_button");
List<WebElement> elements =
getWebDriver().findElements(By.xpath("//table[@id='memberList']/tbody/tr"));
for (int memberHostCount = 1; memberHostCount < elements.size(); memberHostCount++) {
String MemberHost = getWebDriver()
.findElement(
By.xpath("//table[@id='memberList']/tbody/tr[" + (memberHostCount + 1) + "]/td[3]"))
.getText();
String gridMemberHost =
JMXProperties.getInstance().getProperty("member.M" + memberHostCount + ".host");
assertEquals(gridMemberHost, MemberHost);
}
}
@Test
public void testClusterGridViewHeapUsage() {
searchByIdAndClick("default_grid_button");
for (int i = 1; i <= 3; i++) {
Float HeapUsage = Float.parseFloat(getWebDriver()
.findElement(By.xpath("//table[@id='memberList']/tbody/tr[" + (i + 1) + "]/td[5]"))
.getText());
Float gridHeapUsagestring =
Float.parseFloat(JMXProperties.getInstance().getProperty("member.M" + i + ".UsedMemory"));
assertEquals(gridHeapUsagestring, HeapUsage);
}
}
@Test
public void testClusterGridViewCPUUsage() {
searchByIdAndClick("default_grid_button");
for (int i = 1; i <= 3; i++) {
String CPUUsage = getWebDriver()
.findElement(By.xpath("//table[@id='memberList']/tbody/tr[" + (i + 1) + "]/td[6]"))
.getText();
String gridCPUUsage = JMXProperties.getInstance().getProperty("member.M" + i + ".cpuUsage");
gridCPUUsage = gridCPUUsage.trim();
assertEquals(gridCPUUsage, CPUUsage);
}
}
public void testRgraphWidget() {
searchByIdAndClick("default_rgraph_button");
searchByIdAndClick("h1");
searchByIdAndClick("M1");
}
@Test
@Ignore("ElementNotVisible with phantomJS")
public void testMemberTotalRegionCount() {
testRgraphWidget();
String RegionCount = getWebDriver().findElement(By.id(MEMBER_VIEW_REGION_ID)).getText();
String memberRegionCount =
JMXProperties.getInstance().getProperty("member.M1.totalRegionCount");
assertEquals(memberRegionCount, RegionCount);
}
@Test
public void testMemberNumThread() {
searchByIdAndClick("default_grid_button");
searchByIdAndClick("M1&M1");
String ThreadCount = getWebDriver().findElement(By.id(MEMBER_VIEW_THREAD_ID)).getText();
String memberThreadCount = JMXProperties.getInstance().getProperty("member.M1.numThreads");
assertEquals(memberThreadCount, ThreadCount);
}
@Test
public void testMemberTotalFileDescriptorOpen() {
searchByIdAndClick("default_grid_button");
searchByIdAndClick("M1&M1");
String SocketCount = getWebDriver().findElement(By.id(MEMBER_VIEW_SOCKETS_ID)).getText();
String memberSocketCount =
JMXProperties.getInstance().getProperty("member.M1.totalFileDescriptorOpen");
assertEquals(memberSocketCount, SocketCount);
}
@Test
public void testMemberLoadAverage() {
searchByIdAndClick("default_grid_button");
searchByIdAndClick("M1&M1");
String LoadAvg = getWebDriver().findElement(By.id(MEMBER_VIEW_LOADAVG_ID)).getText();
String memberLoadAvg = JMXProperties.getInstance().getProperty("member.M1.loadAverage");
assertEquals(TWO_PLACE_DECIMAL_FORMAT.format(Double.valueOf(memberLoadAvg)), LoadAvg);
}
@Ignore("WIP") // May be useful in near future
@Test
public void testOffHeapFreeSize() {
String OffHeapFreeSizeString =
getWebDriver().findElement(By.id(MEMBER_VIEW_OFFHEAPFREESIZE_ID)).getText();
String OffHeapFreeSizetemp = OffHeapFreeSizeString.replaceAll("[a-zA-Z]", "");
float OffHeapFreeSize = Float.parseFloat(OffHeapFreeSizetemp);
float memberOffHeapFreeSize =
Float.parseFloat(JMXProperties.getInstance().getProperty("member.M1.OffHeapFreeSize"));
if (memberOffHeapFreeSize < 1048576) {
memberOffHeapFreeSize = memberOffHeapFreeSize / 1024;
} else if (memberOffHeapFreeSize < 1073741824) {
memberOffHeapFreeSize = memberOffHeapFreeSize / 1024 / 1024;
} else {
memberOffHeapFreeSize = memberOffHeapFreeSize / 1024 / 1024 / 1024;
}
memberOffHeapFreeSize =
Float.parseFloat(new DecimalFormat("##.##").format(memberOffHeapFreeSize));
assertEquals(memberOffHeapFreeSize, OffHeapFreeSize, 0);
}
@Ignore("WIP") // May be useful in near future
@Test
public void testOffHeapUsedSize() {
String OffHeapUsedSizeString =
getWebDriver().findElement(By.id(MEMBER_VIEW_OFFHEAPUSEDSIZE_ID)).getText();
String OffHeapUsedSizetemp = OffHeapUsedSizeString.replaceAll("[a-zA-Z]", "");
float OffHeapUsedSize = Float.parseFloat(OffHeapUsedSizetemp);
float memberOffHeapUsedSize =
Float.parseFloat(JMXProperties.getInstance().getProperty("member.M1.OffHeapUsedSize"));
if (memberOffHeapUsedSize < 1048576) {
memberOffHeapUsedSize = memberOffHeapUsedSize / 1024;
} else if (memberOffHeapUsedSize < 1073741824) {
memberOffHeapUsedSize = memberOffHeapUsedSize / 1024 / 1024;
} else {
memberOffHeapUsedSize = memberOffHeapUsedSize / 1024 / 1024 / 1024;
}
memberOffHeapUsedSize =
Float.parseFloat(new DecimalFormat("##.##").format(memberOffHeapUsedSize));
assertEquals(memberOffHeapUsedSize, OffHeapUsedSize, 0);
}
@Test
public void testMemberJVMPauses() {
searchByIdAndClick("default_grid_button");
searchByIdAndClick("M1&M1");
String JVMPauses = getWebDriver().findElement(By.id(MEMBER_VIEW_JVMPAUSES_ID)).getText();
String memberGcPausesAvg = JMXProperties.getInstance().getProperty("member.M1.JVMPauses");
assertEquals(memberGcPausesAvg, JVMPauses);
}
@Test
public void testMemberCPUUsage() {
searchByIdAndClick("default_grid_button");
searchByIdAndClick("M1&M1");
String CPUUsagevalue = getWebDriver().findElement(By.id(MEMBER_VIEW_CPUUSAGE_ID)).getText();
String memberCPUUsage = JMXProperties.getInstance().getProperty("member.M1.cpuUsage");
assertEquals(memberCPUUsage, CPUUsagevalue);
}
@Test // difference between UI and properties file
public void testMemberAverageReads() {
searchByIdAndClick("default_grid_button");
searchByIdAndClick("M1&M1");
float ReadPerSec =
Float.parseFloat(getWebDriver().findElement(By.id(MEMBER_VIEW_READPERSEC_ID)).getText());
float memberReadPerSec =
Float.parseFloat(JMXProperties.getInstance().getProperty("member.M1.averageReads"));
memberReadPerSec = Float.parseFloat(new DecimalFormat("##.##").format(memberReadPerSec));
assertEquals(memberReadPerSec, ReadPerSec, 0.001);
}
@Test
@Ignore("ElementNotVisible with phantomJS")
public void testMemberAverageWrites() {
testRgraphWidget();
String WritePerSec = getWebDriver().findElement(By.id(MEMBER_VIEW_WRITEPERSEC_ID)).getText();
String memberWritePerSec = JMXProperties.getInstance().getProperty("member.M1.averageWrites");
assertEquals(memberWritePerSec, WritePerSec);
}
@Test
@Ignore("ElementNotVisible with phantomJS")
public void testMemberGridViewData() {
testRgraphWidget();
searchByXPathAndClick(PulseTestLocators.MemberDetailsView.gridButtonXpath);
// get the number of rows on the grid
String MemberRegionName = getWebDriver()
.findElement(By.xpath("//table[@id='memberRegionsList']/tbody/tr[2]/td[1]")).getText();
String memberRegionName = JMXProperties.getInstance().getProperty("region.R1.name");
assertEquals(memberRegionName, MemberRegionName);
String MemberRegionType = getWebDriver()
.findElement(By.xpath("//table[@id='memberRegionsList']/tbody/tr[2]/td[2]")).getText();
String memberRegionType = JMXProperties.getInstance().getProperty("region.R1.regionType");
assertEquals(memberRegionType, MemberRegionType);
String MemberRegionEntryCount = getWebDriver()
.findElement(By.xpath("//table[@id='memberRegionsList']/tbody/tr[2]/td[3]")).getText();
String memberRegionEntryCount =
JMXProperties.getInstance().getProperty("regionOnMember./R1.M1.entryCount");
assertEquals(memberRegionEntryCount, MemberRegionEntryCount);
}
@Test
public void testDropDownList() {
searchByIdAndClick("default_grid_button");
searchByIdAndClick("M1&M1");
searchByIdAndClick("memberName");
searchByLinkAndClick("M3");
searchByIdAndClick("memberName");
searchByLinkAndClick("M2");
}
@Ignore("WIP")
@Test
public void testDataViewRegionName() throws InterruptedException {
searchByLinkAndClick(DATA_VIEW_LABEL);
Thread.sleep(7000);
searchByIdAndClick("default_grid_button");
String regionName = getWebDriver().findElement(By.id(REGION_NAME_LABEL)).getText();
String dataviewregionname = JMXProperties.getInstance().getProperty("region.R1.name");
assertEquals(dataviewregionname, regionName);
}
@Ignore("WIP")
@Test
public void testDataViewRegionPath() {
String regionPath = getWebDriver().findElement(By.id(REGION_PATH_LABEL)).getText();
String dataviewregionpath = JMXProperties.getInstance().getProperty("region.R1.fullPath");
assertEquals(dataviewregionpath, regionPath);
}
@Ignore("WIP")
@Test
public void testDataViewRegionType() {
String regionType = getWebDriver().findElement(By.id(REGION_TYPE_LABEL)).getText();
String dataviewregiontype = JMXProperties.getInstance().getProperty("region.R1.regionType");
assertEquals(dataviewregiontype, regionType);
}
@Ignore("WIP")
@Test
public void testDataViewEmptyNodes() {
String regionEmptyNodes = getWebDriver().findElement(By.id(DATA_VIEW_EMPTYNODES)).getText();
String dataviewEmptyNodes = JMXProperties.getInstance().getProperty("region.R1.emptyNodes");
assertEquals(dataviewEmptyNodes, regionEmptyNodes);
}
@Ignore("WIP")
@Test
public void testDataViewSystemRegionEntryCount() {
String regionEntryCount = getWebDriver().findElement(By.id(DATA_VIEW_ENTRYCOUNT)).getText();
String dataviewEntryCount =
JMXProperties.getInstance().getProperty("region.R1.systemRegionEntryCount");
assertEquals(dataviewEntryCount, regionEntryCount);
}
@Ignore("WIP")
@Test
public void testDataViewPersistentEnabled() {
String regionPersistence =
getWebDriver().findElement(By.id(REGION_PERSISTENCE_LABEL)).getText();
String dataviewregionpersistence =
JMXProperties.getInstance().getProperty("region.R1.persistentEnabled");
assertEquals(dataviewregionpersistence, regionPersistence);
}
@Ignore("WIP")
@Test
public void testDataViewDiskWritesRate() {
String regionWrites = getWebDriver().findElement(By.id(DATA_VIEW_WRITEPERSEC)).getText();
String dataviewRegionWrites =
JMXProperties.getInstance().getProperty("region.R1.diskWritesRate");
assertEquals(dataviewRegionWrites, regionWrites);
}
@Ignore("WIP")
@Test
public void testDataViewDiskReadsRate() {
String regionReads = getWebDriver().findElement(By.id(DATA_VIEW_READPERSEC)).getText();
String dataviewRegionReads = JMXProperties.getInstance().getProperty("region.R1.diskReadsRate");
assertEquals(dataviewRegionReads, regionReads);
}
@Ignore("WIP")
@Test
public void testDataViewDiskUsage() {
String regionMemoryUsed = getWebDriver().findElement(By.id(DATA_VIEW_USEDMEMORY)).getText();
String dataviewMemoryUsed = JMXProperties.getInstance().getProperty("region.R1.diskUsage");
assertEquals(dataviewMemoryUsed, regionMemoryUsed);
searchByLinkAndClick(QUERY_STATISTICS_LABEL);
}
@Ignore("WIP")
@Test
public void testDataViewGridValue() {
String DataViewRegionName =
getWebDriver().findElement(By.xpath("//*[id('6')/x:td[1]]")).getText();
String dataViewRegionName = JMXProperties.getInstance().getProperty("region.R1.name");
assertEquals(dataViewRegionName, DataViewRegionName);
String DataViewRegionType =
getWebDriver().findElement(By.xpath("//*[id('6')/x:td[2]")).getText();
String dataViewRegionType = JMXProperties.getInstance().getProperty("region.R2.regionType");
assertEquals(dataViewRegionType, DataViewRegionType);
String DataViewEntryCount =
getWebDriver().findElement(By.xpath("//*[id('6')/x:td[3]")).getText();
String dataViewEntryCount =
JMXProperties.getInstance().getProperty("region.R2.systemRegionEntryCount");
assertEquals(dataViewEntryCount, DataViewEntryCount);
String DataViewEntrySize =
getWebDriver().findElement(By.xpath("//*[id('6')/x:td[4]")).getText();
String dataViewEntrySize = JMXProperties.getInstance().getProperty("region.R2.entrySize");
assertEquals(dataViewEntrySize, DataViewEntrySize);
}
public void loadDataBrowserpage() {
searchByLinkAndClick(DATA_BROWSER_LABEL);
// Thread.sleep(7000);
}
@Test
public void testDataBrowserRegionName() {
loadDataBrowserpage();
String DataBrowserRegionName1 =
getWebDriver().findElement(By.id(DATA_BROWSER_REGIONName1)).getText();
String databrowserRegionNametemp1 = JMXProperties.getInstance().getProperty("region.R1.name");
String databrowserRegionName1 =
databrowserRegionNametemp1.replaceAll("[" + SEPARATOR + "]", "");
assertEquals(databrowserRegionName1, DataBrowserRegionName1);
String DataBrowserRegionName2 =
getWebDriver().findElement(By.id(DATA_BROWSER_REGIONName2)).getText();
String databrowserRegionNametemp2 = JMXProperties.getInstance().getProperty("region.R2.name");
String databrowserRegionName2 =
databrowserRegionNametemp2.replaceAll("[" + SEPARATOR + "]", "");
assertEquals(databrowserRegionName2, DataBrowserRegionName2);
String DataBrowserRegionName3 =
getWebDriver().findElement(By.id(DATA_BROWSER_REGIONName3)).getText();
String databrowserRegionNametemp3 = JMXProperties.getInstance().getProperty("region.R3.name");
String databrowserRegionName3 =
databrowserRegionNametemp3.replaceAll("[" + SEPARATOR + "]", "");
assertEquals(databrowserRegionName3, DataBrowserRegionName3);
}
@Test
public void testDataBrowserRegionMembersVerificaition() {
loadDataBrowserpage();
searchByIdAndClick(DATA_BROWSER_REGION1_CHECKBOX);
String DataBrowserMember1Name1 =
getWebDriver().findElement(By.xpath("//label[@for='Member0']")).getText();
String DataBrowserMember1Name2 =
getWebDriver().findElement(By.xpath("//label[@for='Member1']")).getText();
String DataBrowserMember1Name3 =
getWebDriver().findElement(By.xpath("//label[@for='Member2']")).getText();
String databrowserMember1Names = JMXProperties.getInstance().getProperty("region.R1.members");
String databrowserMember1Names1 = databrowserMember1Names.substring(0, 2);
assertEquals(databrowserMember1Names1, DataBrowserMember1Name1);
String databrowserMember1Names2 = databrowserMember1Names.substring(3, 5);
assertEquals(databrowserMember1Names2, DataBrowserMember1Name2);
String databrowserMember1Names3 = databrowserMember1Names.substring(6, 8);
assertEquals(databrowserMember1Names3, DataBrowserMember1Name3);
searchByIdAndClick(DATA_BROWSER_REGION1_CHECKBOX);
searchByIdAndClick(DATA_BROWSER_REGION2_CHECKBOX);
String DataBrowserMember2Name1 =
getWebDriver().findElement(By.xpath("//label[@for='Member0']")).getText();
String DataBrowserMember2Name2 =
getWebDriver().findElement(By.xpath("//label[@for='Member1']")).getText();
String databrowserMember2Names = JMXProperties.getInstance().getProperty("region.R2.members");
String databrowserMember2Names1 = databrowserMember2Names.substring(0, 2);
assertEquals(databrowserMember2Names1, DataBrowserMember2Name1);
String databrowserMember2Names2 = databrowserMember2Names.substring(3, 5);
assertEquals(databrowserMember2Names2, DataBrowserMember2Name2);
searchByIdAndClick(DATA_BROWSER_REGION2_CHECKBOX);
searchByIdAndClick(DATA_BROWSER_REGION3_CHECKBOX);
String DataBrowserMember3Name1 =
getWebDriver().findElement(By.xpath("//label[@for='Member0']")).getText();
String DataBrowserMember3Name2 =
getWebDriver().findElement(By.xpath("//label[@for='Member1']")).getText();
String databrowserMember3Names = JMXProperties.getInstance().getProperty("region.R3.members");
String databrowserMember3Names1 = databrowserMember3Names.substring(0, 2);
assertEquals(databrowserMember3Names1, DataBrowserMember3Name1);
String databrowserMember3Names2 = databrowserMember3Names.substring(3, 5);
assertEquals(databrowserMember3Names2, DataBrowserMember3Name2);
searchByIdAndClick(DATA_BROWSER_REGION3_CHECKBOX);
}
@Test
public void testDataBrowserColocatedRegions() {
loadDataBrowserpage();
String databrowserMemberNames1 = JMXProperties.getInstance().getProperty("region.R1.members");
String databrowserMemberNames2 = JMXProperties.getInstance().getProperty("region.R2.members");
String databrowserMemberNames3 = JMXProperties.getInstance().getProperty("region.R3.members");
if ((databrowserMemberNames1.matches(databrowserMemberNames2 + "(.*)"))) {
if ((databrowserMemberNames1.matches(databrowserMemberNames3 + "(.*)"))) {
if ((databrowserMemberNames2.matches(databrowserMemberNames3 + "(.*)"))) {
System.out.println("R1, R2 and R3 are colocated regions");
}
}
}
searchByIdAndClick(DATA_BROWSER_REGION1_CHECKBOX);
searchByLinkAndClick(DATA_BROWSER_COLOCATED_REGION);
String DataBrowserColocatedRegion1 =
getWebDriver().findElement(By.id(DATA_BROWSER_COLOCATED_REGION_NAME1)).getText();
String DataBrowserColocatedRegion2 =
getWebDriver().findElement(By.id(DATA_BROWSER_COLOCATED_REGION_NAME2)).getText();
String DataBrowserColocatedRegion3 =
getWebDriver().findElement(By.id(DATA_BROWSER_COLOCATED_REGION_NAME3)).getText();
String databrowserColocatedRegiontemp1 =
JMXProperties.getInstance().getProperty("region.R1.name");
String databrowserColocatedRegion1 =
databrowserColocatedRegiontemp1.replaceAll("[" + SEPARATOR + "]", "");
String databrowserColocatedRegiontemp2 =
JMXProperties.getInstance().getProperty("region.R2.name");
String databrowserColocatedRegion2 =
databrowserColocatedRegiontemp2.replaceAll("[" + SEPARATOR + "]", "");
String databrowserColocatedRegiontemp3 =
JMXProperties.getInstance().getProperty("region.R3.name");
String databrowserColocatedRegion3 =
databrowserColocatedRegiontemp3.replaceAll("[" + SEPARATOR + "]", "");
assertEquals(databrowserColocatedRegion1, DataBrowserColocatedRegion1);
assertEquals(databrowserColocatedRegion2, DataBrowserColocatedRegion2);
assertEquals(databrowserColocatedRegion3, DataBrowserColocatedRegion3);
}
public void testTreeMapPopUpData(String S1, String gridIcon) {
for (int i = 1; i <= 3; i++) {
searchByLinkAndClick(CLUSTER_VIEW_LABEL);
if (gridIcon.equals(SERVER_GROUP_GRID_ID)) {
WebElement ServerGroupRadio =
getWebDriver().findElement(By.xpath("//label[@for='radio-servergroups']"));
ServerGroupRadio.click();
}
if (gridIcon.equals(REDUNDANCY_GRID_ID)) {
WebElement ServerGroupRadio =
getWebDriver().findElement(By.xpath("//label[@for='radio-redundancyzones']"));
ServerGroupRadio.click();
}
searchByIdAndClick(gridIcon);
WebElement TreeMapMember =
getWebDriver().findElement(By.xpath("//div[@id='" + S1 + "M" + (i) + "']/div"));
Actions builder = new Actions(getWebDriver());
builder.clickAndHold(TreeMapMember).perform();
int j = 1;
String CPUUsageM1temp = getWebDriver()
.findElement(By.xpath("//div[@id='_tooltip']/div/div/div[2]/div/div[2]/div")).getText();
String CPUUsageM1 = CPUUsageM1temp.replaceAll("[%]", "");
String cpuUsageM1 = JMXProperties.getInstance().getProperty("member.M" + (i) + ".cpuUsage");
assertEquals(cpuUsageM1, CPUUsageM1);
String MemoryUsageM1temp = getWebDriver()
.findElement(
By.xpath("//div[@id='_tooltip']/div/div/div[2]/div[" + (j + 1) + "]/div[2]/div"))
.getText();
String MemoryUsageM1 = MemoryUsageM1temp.replaceAll("MB", "");
String memoryUsageM1 =
JMXProperties.getInstance().getProperty("member.M" + (i) + ".UsedMemory");
assertEquals(memoryUsageM1, MemoryUsageM1);
String LoadAvgM1 = getWebDriver()
.findElement(
By.xpath("//div[@id='_tooltip']/div/div/div[2]/div[" + (j + 2) + "]/div[2]/div"))
.getText();
String loadAvgM1 = JMXProperties.getInstance().getProperty("member.M" + (i) + ".loadAverage");
assertEquals(TWO_PLACE_DECIMAL_FORMAT.format(Double.valueOf(loadAvgM1)), LoadAvgM1);
String ThreadsM1 = getWebDriver()
.findElement(
By.xpath("//div[@id='_tooltip']/div/div/div[2]/div[" + (j + 3) + "]/div[2]/div"))
.getText();
String threadsM1 = JMXProperties.getInstance().getProperty("member.M" + (i) + ".numThreads");
assertEquals(threadsM1, ThreadsM1);
String SocketsM1 = getWebDriver()
.findElement(
By.xpath("//div[@id='_tooltip']/div/div/div[2]/div[" + (j + 4) + "]/div[2]/div"))
.getText();
String socketsM1 =
JMXProperties.getInstance().getProperty("member.M" + (i) + ".totalFileDescriptorOpen");
assertEquals(socketsM1, SocketsM1);
builder.moveToElement(TreeMapMember).release().perform();
}
}
@Test
public void testTopologyPopUpData() {
testTreeMapPopUpData("", CLUSTER_VIEW_GRID_ID);
}
@Test
public void testServerGroupTreeMapPopUpData() {
testTreeMapPopUpData("SG1(!)", SERVER_GROUP_GRID_ID);
}
@Test
public void testDataViewTreeMapPopUpData() {
searchByLinkAndClick(CLUSTER_VIEW_LABEL);
searchByLinkAndClick(DATA_DROPDOWN_ID);
WebElement TreeMapMember = getWebDriver().findElement(By.id("GraphTreeMapClusterData-canvas"));
Actions builder = new Actions(getWebDriver());
builder.clickAndHold(TreeMapMember).perform();
String RegionType = getWebDriver()
.findElement(By.xpath("//div[@id='_tooltip']/div/div/div[2]/div/div[2]/div")).getText();
String regionType = JMXProperties.getInstance().getProperty("region.R2.regionType");
assertEquals(regionType, RegionType);
String EntryCount = getWebDriver()
.findElement(By.xpath("//div[@id='_tooltip']/div/div/div[2]/div[2]/div[2]/div")).getText();
String entryCount = JMXProperties.getInstance().getProperty("region.R2.systemRegionEntryCount");
assertEquals(entryCount, EntryCount);
String EntrySizetemp = getWebDriver()
.findElement(By.xpath("//div[@id='_tooltip']/div/div/div[2]/div[3]/div[2]/div")).getText();
float EntrySize = Float.parseFloat(EntrySizetemp);
float entrySize =
Float.parseFloat(JMXProperties.getInstance().getProperty("region.R2.entrySize"));
entrySize = entrySize / 1024 / 1024;
entrySize = Float.parseFloat(new DecimalFormat("##.####").format(entrySize));
assertEquals(entrySize, EntrySize, 0.001);
builder.moveToElement(TreeMapMember).release().perform();
}
@Test
public void testRegionViewTreeMapPopUpData() {
searchByLinkAndClick(CLUSTER_VIEW_LABEL);
searchByLinkAndClick(DATA_DROPDOWN_ID);
WebElement TreeMapMember = getWebDriver().findElement(By.id("GraphTreeMapClusterData-canvas"));
TreeMapMember.click();
}
@Test
public void userCanGetToPulseDetails() {
getWebDriver().get(getPulseURL() + "pulseVersion");
assertTrue(getWebDriver().getPageSource().contains("sourceRevision"));
}
}
|
googleapis/google-cloud-java | 35,665 | java-maps-routeoptimization/proto-google-maps-routeoptimization-v1/src/main/java/com/google/maps/routeoptimization/v1/DistanceLimit.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/maps/routeoptimization/v1/route_optimization_service.proto
// Protobuf Java Version: 3.25.8
package com.google.maps.routeoptimization.v1;
/**
*
*
* <pre>
* A limit defining a maximum distance which can be traveled. It can be either
* hard or soft.
*
* If a soft limit is defined, both `soft_max_meters` and
* `cost_per_kilometer_above_soft_max` must be defined and be nonnegative.
* </pre>
*
* Protobuf type {@code google.maps.routeoptimization.v1.DistanceLimit}
*/
public final class DistanceLimit extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.maps.routeoptimization.v1.DistanceLimit)
DistanceLimitOrBuilder {
private static final long serialVersionUID = 0L;
// Use DistanceLimit.newBuilder() to construct.
private DistanceLimit(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DistanceLimit() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new DistanceLimit();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.maps.routeoptimization.v1.RouteOptimizationServiceProto
.internal_static_google_maps_routeoptimization_v1_DistanceLimit_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.maps.routeoptimization.v1.RouteOptimizationServiceProto
.internal_static_google_maps_routeoptimization_v1_DistanceLimit_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.maps.routeoptimization.v1.DistanceLimit.class,
com.google.maps.routeoptimization.v1.DistanceLimit.Builder.class);
}
private int bitField0_;
public static final int MAX_METERS_FIELD_NUMBER = 1;
private long maxMeters_ = 0L;
/**
*
*
* <pre>
* A hard limit constraining the distance to be at most max_meters. The limit
* must be nonnegative.
* </pre>
*
* <code>optional int64 max_meters = 1;</code>
*
* @return Whether the maxMeters field is set.
*/
@java.lang.Override
public boolean hasMaxMeters() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* A hard limit constraining the distance to be at most max_meters. The limit
* must be nonnegative.
* </pre>
*
* <code>optional int64 max_meters = 1;</code>
*
* @return The maxMeters.
*/
@java.lang.Override
public long getMaxMeters() {
return maxMeters_;
}
public static final int SOFT_MAX_METERS_FIELD_NUMBER = 2;
private long softMaxMeters_ = 0L;
/**
*
*
* <pre>
* A soft limit not enforcing a maximum distance limit, but when violated
* results in a cost which adds up to other costs defined in the model,
* with the same unit.
*
* If defined soft_max_meters must be less than max_meters and must be
* nonnegative.
* </pre>
*
* <code>optional int64 soft_max_meters = 2;</code>
*
* @return Whether the softMaxMeters field is set.
*/
@java.lang.Override
public boolean hasSoftMaxMeters() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* A soft limit not enforcing a maximum distance limit, but when violated
* results in a cost which adds up to other costs defined in the model,
* with the same unit.
*
* If defined soft_max_meters must be less than max_meters and must be
* nonnegative.
* </pre>
*
* <code>optional int64 soft_max_meters = 2;</code>
*
* @return The softMaxMeters.
*/
@java.lang.Override
public long getSoftMaxMeters() {
return softMaxMeters_;
}
public static final int COST_PER_KILOMETER_BELOW_SOFT_MAX_FIELD_NUMBER = 4;
private double costPerKilometerBelowSoftMax_ = 0D;
/**
*
*
* <pre>
* Cost per kilometer incurred, increasing up to `soft_max_meters`, with
* formula:
* ```
* min(distance_meters, soft_max_meters) / 1000.0 *
* cost_per_kilometer_below_soft_max.
* ```
* This cost is not supported in `route_distance_limit`.
* </pre>
*
* <code>optional double cost_per_kilometer_below_soft_max = 4;</code>
*
* @return Whether the costPerKilometerBelowSoftMax field is set.
*/
@java.lang.Override
public boolean hasCostPerKilometerBelowSoftMax() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Cost per kilometer incurred, increasing up to `soft_max_meters`, with
* formula:
* ```
* min(distance_meters, soft_max_meters) / 1000.0 *
* cost_per_kilometer_below_soft_max.
* ```
* This cost is not supported in `route_distance_limit`.
* </pre>
*
* <code>optional double cost_per_kilometer_below_soft_max = 4;</code>
*
* @return The costPerKilometerBelowSoftMax.
*/
@java.lang.Override
public double getCostPerKilometerBelowSoftMax() {
return costPerKilometerBelowSoftMax_;
}
public static final int COST_PER_KILOMETER_ABOVE_SOFT_MAX_FIELD_NUMBER = 3;
private double costPerKilometerAboveSoftMax_ = 0D;
/**
*
*
* <pre>
* Cost per kilometer incurred if distance is above `soft_max_meters` limit.
* The additional cost is 0 if the distance is under the limit, otherwise the
* formula used to compute the cost is the following:
* ```
* (distance_meters - soft_max_meters) / 1000.0 *
* cost_per_kilometer_above_soft_max.
* ```
* The cost must be nonnegative.
* </pre>
*
* <code>optional double cost_per_kilometer_above_soft_max = 3;</code>
*
* @return Whether the costPerKilometerAboveSoftMax field is set.
*/
@java.lang.Override
public boolean hasCostPerKilometerAboveSoftMax() {
return ((bitField0_ & 0x00000008) != 0);
}
/**
*
*
* <pre>
* Cost per kilometer incurred if distance is above `soft_max_meters` limit.
* The additional cost is 0 if the distance is under the limit, otherwise the
* formula used to compute the cost is the following:
* ```
* (distance_meters - soft_max_meters) / 1000.0 *
* cost_per_kilometer_above_soft_max.
* ```
* The cost must be nonnegative.
* </pre>
*
* <code>optional double cost_per_kilometer_above_soft_max = 3;</code>
*
* @return The costPerKilometerAboveSoftMax.
*/
@java.lang.Override
public double getCostPerKilometerAboveSoftMax() {
return costPerKilometerAboveSoftMax_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeInt64(1, maxMeters_);
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeInt64(2, softMaxMeters_);
}
if (((bitField0_ & 0x00000008) != 0)) {
output.writeDouble(3, costPerKilometerAboveSoftMax_);
}
if (((bitField0_ & 0x00000004) != 0)) {
output.writeDouble(4, costPerKilometerBelowSoftMax_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeInt64Size(1, maxMeters_);
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeInt64Size(2, softMaxMeters_);
}
if (((bitField0_ & 0x00000008) != 0)) {
size +=
com.google.protobuf.CodedOutputStream.computeDoubleSize(3, costPerKilometerAboveSoftMax_);
}
if (((bitField0_ & 0x00000004) != 0)) {
size +=
com.google.protobuf.CodedOutputStream.computeDoubleSize(4, costPerKilometerBelowSoftMax_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.maps.routeoptimization.v1.DistanceLimit)) {
return super.equals(obj);
}
com.google.maps.routeoptimization.v1.DistanceLimit other =
(com.google.maps.routeoptimization.v1.DistanceLimit) obj;
if (hasMaxMeters() != other.hasMaxMeters()) return false;
if (hasMaxMeters()) {
if (getMaxMeters() != other.getMaxMeters()) return false;
}
if (hasSoftMaxMeters() != other.hasSoftMaxMeters()) return false;
if (hasSoftMaxMeters()) {
if (getSoftMaxMeters() != other.getSoftMaxMeters()) return false;
}
if (hasCostPerKilometerBelowSoftMax() != other.hasCostPerKilometerBelowSoftMax()) return false;
if (hasCostPerKilometerBelowSoftMax()) {
if (java.lang.Double.doubleToLongBits(getCostPerKilometerBelowSoftMax())
!= java.lang.Double.doubleToLongBits(other.getCostPerKilometerBelowSoftMax()))
return false;
}
if (hasCostPerKilometerAboveSoftMax() != other.hasCostPerKilometerAboveSoftMax()) return false;
if (hasCostPerKilometerAboveSoftMax()) {
if (java.lang.Double.doubleToLongBits(getCostPerKilometerAboveSoftMax())
!= java.lang.Double.doubleToLongBits(other.getCostPerKilometerAboveSoftMax()))
return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasMaxMeters()) {
hash = (37 * hash) + MAX_METERS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getMaxMeters());
}
if (hasSoftMaxMeters()) {
hash = (37 * hash) + SOFT_MAX_METERS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getSoftMaxMeters());
}
if (hasCostPerKilometerBelowSoftMax()) {
hash = (37 * hash) + COST_PER_KILOMETER_BELOW_SOFT_MAX_FIELD_NUMBER;
hash =
(53 * hash)
+ com.google.protobuf.Internal.hashLong(
java.lang.Double.doubleToLongBits(getCostPerKilometerBelowSoftMax()));
}
if (hasCostPerKilometerAboveSoftMax()) {
hash = (37 * hash) + COST_PER_KILOMETER_ABOVE_SOFT_MAX_FIELD_NUMBER;
hash =
(53 * hash)
+ com.google.protobuf.Internal.hashLong(
java.lang.Double.doubleToLongBits(getCostPerKilometerAboveSoftMax()));
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.maps.routeoptimization.v1.DistanceLimit parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.maps.routeoptimization.v1.DistanceLimit parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.maps.routeoptimization.v1.DistanceLimit parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.maps.routeoptimization.v1.DistanceLimit parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.maps.routeoptimization.v1.DistanceLimit parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.maps.routeoptimization.v1.DistanceLimit parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.maps.routeoptimization.v1.DistanceLimit parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.maps.routeoptimization.v1.DistanceLimit parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.maps.routeoptimization.v1.DistanceLimit parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.maps.routeoptimization.v1.DistanceLimit parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.maps.routeoptimization.v1.DistanceLimit parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.maps.routeoptimization.v1.DistanceLimit parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.maps.routeoptimization.v1.DistanceLimit prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A limit defining a maximum distance which can be traveled. It can be either
* hard or soft.
*
* If a soft limit is defined, both `soft_max_meters` and
* `cost_per_kilometer_above_soft_max` must be defined and be nonnegative.
* </pre>
*
* Protobuf type {@code google.maps.routeoptimization.v1.DistanceLimit}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.maps.routeoptimization.v1.DistanceLimit)
com.google.maps.routeoptimization.v1.DistanceLimitOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.maps.routeoptimization.v1.RouteOptimizationServiceProto
.internal_static_google_maps_routeoptimization_v1_DistanceLimit_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.maps.routeoptimization.v1.RouteOptimizationServiceProto
.internal_static_google_maps_routeoptimization_v1_DistanceLimit_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.maps.routeoptimization.v1.DistanceLimit.class,
com.google.maps.routeoptimization.v1.DistanceLimit.Builder.class);
}
// Construct using com.google.maps.routeoptimization.v1.DistanceLimit.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
maxMeters_ = 0L;
softMaxMeters_ = 0L;
costPerKilometerBelowSoftMax_ = 0D;
costPerKilometerAboveSoftMax_ = 0D;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.maps.routeoptimization.v1.RouteOptimizationServiceProto
.internal_static_google_maps_routeoptimization_v1_DistanceLimit_descriptor;
}
@java.lang.Override
public com.google.maps.routeoptimization.v1.DistanceLimit getDefaultInstanceForType() {
return com.google.maps.routeoptimization.v1.DistanceLimit.getDefaultInstance();
}
@java.lang.Override
public com.google.maps.routeoptimization.v1.DistanceLimit build() {
com.google.maps.routeoptimization.v1.DistanceLimit result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.maps.routeoptimization.v1.DistanceLimit buildPartial() {
com.google.maps.routeoptimization.v1.DistanceLimit result =
new com.google.maps.routeoptimization.v1.DistanceLimit(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.maps.routeoptimization.v1.DistanceLimit result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.maxMeters_ = maxMeters_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.softMaxMeters_ = softMaxMeters_;
to_bitField0_ |= 0x00000002;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.costPerKilometerBelowSoftMax_ = costPerKilometerBelowSoftMax_;
to_bitField0_ |= 0x00000004;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.costPerKilometerAboveSoftMax_ = costPerKilometerAboveSoftMax_;
to_bitField0_ |= 0x00000008;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.maps.routeoptimization.v1.DistanceLimit) {
return mergeFrom((com.google.maps.routeoptimization.v1.DistanceLimit) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.maps.routeoptimization.v1.DistanceLimit other) {
if (other == com.google.maps.routeoptimization.v1.DistanceLimit.getDefaultInstance())
return this;
if (other.hasMaxMeters()) {
setMaxMeters(other.getMaxMeters());
}
if (other.hasSoftMaxMeters()) {
setSoftMaxMeters(other.getSoftMaxMeters());
}
if (other.hasCostPerKilometerBelowSoftMax()) {
setCostPerKilometerBelowSoftMax(other.getCostPerKilometerBelowSoftMax());
}
if (other.hasCostPerKilometerAboveSoftMax()) {
setCostPerKilometerAboveSoftMax(other.getCostPerKilometerAboveSoftMax());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 8:
{
maxMeters_ = input.readInt64();
bitField0_ |= 0x00000001;
break;
} // case 8
case 16:
{
softMaxMeters_ = input.readInt64();
bitField0_ |= 0x00000002;
break;
} // case 16
case 25:
{
costPerKilometerAboveSoftMax_ = input.readDouble();
bitField0_ |= 0x00000008;
break;
} // case 25
case 33:
{
costPerKilometerBelowSoftMax_ = input.readDouble();
bitField0_ |= 0x00000004;
break;
} // case 33
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private long maxMeters_;
/**
*
*
* <pre>
* A hard limit constraining the distance to be at most max_meters. The limit
* must be nonnegative.
* </pre>
*
* <code>optional int64 max_meters = 1;</code>
*
* @return Whether the maxMeters field is set.
*/
@java.lang.Override
public boolean hasMaxMeters() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* A hard limit constraining the distance to be at most max_meters. The limit
* must be nonnegative.
* </pre>
*
* <code>optional int64 max_meters = 1;</code>
*
* @return The maxMeters.
*/
@java.lang.Override
public long getMaxMeters() {
return maxMeters_;
}
/**
*
*
* <pre>
* A hard limit constraining the distance to be at most max_meters. The limit
* must be nonnegative.
* </pre>
*
* <code>optional int64 max_meters = 1;</code>
*
* @param value The maxMeters to set.
* @return This builder for chaining.
*/
public Builder setMaxMeters(long value) {
maxMeters_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* A hard limit constraining the distance to be at most max_meters. The limit
* must be nonnegative.
* </pre>
*
* <code>optional int64 max_meters = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearMaxMeters() {
bitField0_ = (bitField0_ & ~0x00000001);
maxMeters_ = 0L;
onChanged();
return this;
}
private long softMaxMeters_;
/**
*
*
* <pre>
* A soft limit not enforcing a maximum distance limit, but when violated
* results in a cost which adds up to other costs defined in the model,
* with the same unit.
*
* If defined soft_max_meters must be less than max_meters and must be
* nonnegative.
* </pre>
*
* <code>optional int64 soft_max_meters = 2;</code>
*
* @return Whether the softMaxMeters field is set.
*/
@java.lang.Override
public boolean hasSoftMaxMeters() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* A soft limit not enforcing a maximum distance limit, but when violated
* results in a cost which adds up to other costs defined in the model,
* with the same unit.
*
* If defined soft_max_meters must be less than max_meters and must be
* nonnegative.
* </pre>
*
* <code>optional int64 soft_max_meters = 2;</code>
*
* @return The softMaxMeters.
*/
@java.lang.Override
public long getSoftMaxMeters() {
return softMaxMeters_;
}
/**
*
*
* <pre>
* A soft limit not enforcing a maximum distance limit, but when violated
* results in a cost which adds up to other costs defined in the model,
* with the same unit.
*
* If defined soft_max_meters must be less than max_meters and must be
* nonnegative.
* </pre>
*
* <code>optional int64 soft_max_meters = 2;</code>
*
* @param value The softMaxMeters to set.
* @return This builder for chaining.
*/
public Builder setSoftMaxMeters(long value) {
softMaxMeters_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A soft limit not enforcing a maximum distance limit, but when violated
* results in a cost which adds up to other costs defined in the model,
* with the same unit.
*
* If defined soft_max_meters must be less than max_meters and must be
* nonnegative.
* </pre>
*
* <code>optional int64 soft_max_meters = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearSoftMaxMeters() {
bitField0_ = (bitField0_ & ~0x00000002);
softMaxMeters_ = 0L;
onChanged();
return this;
}
private double costPerKilometerBelowSoftMax_;
/**
*
*
* <pre>
* Cost per kilometer incurred, increasing up to `soft_max_meters`, with
* formula:
* ```
* min(distance_meters, soft_max_meters) / 1000.0 *
* cost_per_kilometer_below_soft_max.
* ```
* This cost is not supported in `route_distance_limit`.
* </pre>
*
* <code>optional double cost_per_kilometer_below_soft_max = 4;</code>
*
* @return Whether the costPerKilometerBelowSoftMax field is set.
*/
@java.lang.Override
public boolean hasCostPerKilometerBelowSoftMax() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Cost per kilometer incurred, increasing up to `soft_max_meters`, with
* formula:
* ```
* min(distance_meters, soft_max_meters) / 1000.0 *
* cost_per_kilometer_below_soft_max.
* ```
* This cost is not supported in `route_distance_limit`.
* </pre>
*
* <code>optional double cost_per_kilometer_below_soft_max = 4;</code>
*
* @return The costPerKilometerBelowSoftMax.
*/
@java.lang.Override
public double getCostPerKilometerBelowSoftMax() {
return costPerKilometerBelowSoftMax_;
}
/**
*
*
* <pre>
* Cost per kilometer incurred, increasing up to `soft_max_meters`, with
* formula:
* ```
* min(distance_meters, soft_max_meters) / 1000.0 *
* cost_per_kilometer_below_soft_max.
* ```
* This cost is not supported in `route_distance_limit`.
* </pre>
*
* <code>optional double cost_per_kilometer_below_soft_max = 4;</code>
*
* @param value The costPerKilometerBelowSoftMax to set.
* @return This builder for chaining.
*/
public Builder setCostPerKilometerBelowSoftMax(double value) {
costPerKilometerBelowSoftMax_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Cost per kilometer incurred, increasing up to `soft_max_meters`, with
* formula:
* ```
* min(distance_meters, soft_max_meters) / 1000.0 *
* cost_per_kilometer_below_soft_max.
* ```
* This cost is not supported in `route_distance_limit`.
* </pre>
*
* <code>optional double cost_per_kilometer_below_soft_max = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearCostPerKilometerBelowSoftMax() {
bitField0_ = (bitField0_ & ~0x00000004);
costPerKilometerBelowSoftMax_ = 0D;
onChanged();
return this;
}
private double costPerKilometerAboveSoftMax_;
/**
*
*
* <pre>
* Cost per kilometer incurred if distance is above `soft_max_meters` limit.
* The additional cost is 0 if the distance is under the limit, otherwise the
* formula used to compute the cost is the following:
* ```
* (distance_meters - soft_max_meters) / 1000.0 *
* cost_per_kilometer_above_soft_max.
* ```
* The cost must be nonnegative.
* </pre>
*
* <code>optional double cost_per_kilometer_above_soft_max = 3;</code>
*
* @return Whether the costPerKilometerAboveSoftMax field is set.
*/
@java.lang.Override
public boolean hasCostPerKilometerAboveSoftMax() {
return ((bitField0_ & 0x00000008) != 0);
}
/**
*
*
* <pre>
* Cost per kilometer incurred if distance is above `soft_max_meters` limit.
* The additional cost is 0 if the distance is under the limit, otherwise the
* formula used to compute the cost is the following:
* ```
* (distance_meters - soft_max_meters) / 1000.0 *
* cost_per_kilometer_above_soft_max.
* ```
* The cost must be nonnegative.
* </pre>
*
* <code>optional double cost_per_kilometer_above_soft_max = 3;</code>
*
* @return The costPerKilometerAboveSoftMax.
*/
@java.lang.Override
public double getCostPerKilometerAboveSoftMax() {
return costPerKilometerAboveSoftMax_;
}
/**
*
*
* <pre>
* Cost per kilometer incurred if distance is above `soft_max_meters` limit.
* The additional cost is 0 if the distance is under the limit, otherwise the
* formula used to compute the cost is the following:
* ```
* (distance_meters - soft_max_meters) / 1000.0 *
* cost_per_kilometer_above_soft_max.
* ```
* The cost must be nonnegative.
* </pre>
*
* <code>optional double cost_per_kilometer_above_soft_max = 3;</code>
*
* @param value The costPerKilometerAboveSoftMax to set.
* @return This builder for chaining.
*/
public Builder setCostPerKilometerAboveSoftMax(double value) {
costPerKilometerAboveSoftMax_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Cost per kilometer incurred if distance is above `soft_max_meters` limit.
* The additional cost is 0 if the distance is under the limit, otherwise the
* formula used to compute the cost is the following:
* ```
* (distance_meters - soft_max_meters) / 1000.0 *
* cost_per_kilometer_above_soft_max.
* ```
* The cost must be nonnegative.
* </pre>
*
* <code>optional double cost_per_kilometer_above_soft_max = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearCostPerKilometerAboveSoftMax() {
bitField0_ = (bitField0_ & ~0x00000008);
costPerKilometerAboveSoftMax_ = 0D;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.maps.routeoptimization.v1.DistanceLimit)
}
// @@protoc_insertion_point(class_scope:google.maps.routeoptimization.v1.DistanceLimit)
private static final com.google.maps.routeoptimization.v1.DistanceLimit DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.maps.routeoptimization.v1.DistanceLimit();
}
public static com.google.maps.routeoptimization.v1.DistanceLimit getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DistanceLimit> PARSER =
new com.google.protobuf.AbstractParser<DistanceLimit>() {
@java.lang.Override
public DistanceLimit parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<DistanceLimit> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DistanceLimit> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.maps.routeoptimization.v1.DistanceLimit getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,690 | java-service-usage/proto-google-cloud-service-usage-v1beta1/src/main/java/com/google/api/serviceusage/v1beta1/GetServiceIdentityResponse.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/serviceusage/v1beta1/serviceusage.proto
// Protobuf Java Version: 3.25.8
package com.google.api.serviceusage.v1beta1;
/**
*
*
* <pre>
* Response message for getting service identity.
* </pre>
*
* Protobuf type {@code google.api.serviceusage.v1beta1.GetServiceIdentityResponse}
*/
public final class GetServiceIdentityResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.api.serviceusage.v1beta1.GetServiceIdentityResponse)
GetServiceIdentityResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetServiceIdentityResponse.newBuilder() to construct.
private GetServiceIdentityResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetServiceIdentityResponse() {
state_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GetServiceIdentityResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.api.serviceusage.v1beta1.ServiceUsageProto
.internal_static_google_api_serviceusage_v1beta1_GetServiceIdentityResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.serviceusage.v1beta1.ServiceUsageProto
.internal_static_google_api_serviceusage_v1beta1_GetServiceIdentityResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.class,
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.Builder.class);
}
/**
*
*
* <pre>
* Enum for service identity state.
* </pre>
*
* Protobuf enum {@code google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState}
*/
public enum IdentityState implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* Default service identity state. This value is used if the state is
* omitted.
* </pre>
*
* <code>IDENTITY_STATE_UNSPECIFIED = 0;</code>
*/
IDENTITY_STATE_UNSPECIFIED(0),
/**
*
*
* <pre>
* Service identity has been created and can be used.
* </pre>
*
* <code>ACTIVE = 1;</code>
*/
ACTIVE(1),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* Default service identity state. This value is used if the state is
* omitted.
* </pre>
*
* <code>IDENTITY_STATE_UNSPECIFIED = 0;</code>
*/
public static final int IDENTITY_STATE_UNSPECIFIED_VALUE = 0;
/**
*
*
* <pre>
* Service identity has been created and can be used.
* </pre>
*
* <code>ACTIVE = 1;</code>
*/
public static final int ACTIVE_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 IdentityState 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 IdentityState forNumber(int value) {
switch (value) {
case 0:
return IDENTITY_STATE_UNSPECIFIED;
case 1:
return ACTIVE;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<IdentityState> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<IdentityState> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<IdentityState>() {
public IdentityState findValueByNumber(int number) {
return IdentityState.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.serviceusage.v1beta1.GetServiceIdentityResponse.getDescriptor()
.getEnumTypes()
.get(0);
}
private static final IdentityState[] VALUES = values();
public static IdentityState 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 IdentityState(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState)
}
private int bitField0_;
public static final int IDENTITY_FIELD_NUMBER = 1;
private com.google.api.serviceusage.v1beta1.ServiceIdentity identity_;
/**
*
*
* <pre>
* Service identity that service producer can use to access consumer
* resources. If exists is true, it contains email and unique_id. If exists is
* false, it contains pre-constructed email and empty unique_id.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.ServiceIdentity identity = 1;</code>
*
* @return Whether the identity field is set.
*/
@java.lang.Override
public boolean hasIdentity() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Service identity that service producer can use to access consumer
* resources. If exists is true, it contains email and unique_id. If exists is
* false, it contains pre-constructed email and empty unique_id.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.ServiceIdentity identity = 1;</code>
*
* @return The identity.
*/
@java.lang.Override
public com.google.api.serviceusage.v1beta1.ServiceIdentity getIdentity() {
return identity_ == null
? com.google.api.serviceusage.v1beta1.ServiceIdentity.getDefaultInstance()
: identity_;
}
/**
*
*
* <pre>
* Service identity that service producer can use to access consumer
* resources. If exists is true, it contains email and unique_id. If exists is
* false, it contains pre-constructed email and empty unique_id.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.ServiceIdentity identity = 1;</code>
*/
@java.lang.Override
public com.google.api.serviceusage.v1beta1.ServiceIdentityOrBuilder getIdentityOrBuilder() {
return identity_ == null
? com.google.api.serviceusage.v1beta1.ServiceIdentity.getDefaultInstance()
: identity_;
}
public static final int STATE_FIELD_NUMBER = 2;
private int state_ = 0;
/**
*
*
* <pre>
* Service identity state.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState state = 2;
* </code>
*
* @return The enum numeric value on the wire for state.
*/
@java.lang.Override
public int getStateValue() {
return state_;
}
/**
*
*
* <pre>
* Service identity state.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState state = 2;
* </code>
*
* @return The state.
*/
@java.lang.Override
public com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState getState() {
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState result =
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState.forNumber(
state_);
return result == null
? com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState.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 (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getIdentity());
}
if (state_
!= com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState
.IDENTITY_STATE_UNSPECIFIED
.getNumber()) {
output.writeEnum(2, state_);
}
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, getIdentity());
}
if (state_
!= com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState
.IDENTITY_STATE_UNSPECIFIED
.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, state_);
}
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.serviceusage.v1beta1.GetServiceIdentityResponse)) {
return super.equals(obj);
}
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse other =
(com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse) obj;
if (hasIdentity() != other.hasIdentity()) return false;
if (hasIdentity()) {
if (!getIdentity().equals(other.getIdentity())) return false;
}
if (state_ != other.state_) 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 (hasIdentity()) {
hash = (37 * hash) + IDENTITY_FIELD_NUMBER;
hash = (53 * hash) + getIdentity().hashCode();
}
hash = (37 * hash) + STATE_FIELD_NUMBER;
hash = (53 * hash) + state_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse 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.serviceusage.v1beta1.GetServiceIdentityResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse 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.serviceusage.v1beta1.GetServiceIdentityResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse 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.serviceusage.v1beta1.GetServiceIdentityResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse 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.serviceusage.v1beta1.GetServiceIdentityResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse 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.serviceusage.v1beta1.GetServiceIdentityResponse 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 getting service identity.
* </pre>
*
* Protobuf type {@code google.api.serviceusage.v1beta1.GetServiceIdentityResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.api.serviceusage.v1beta1.GetServiceIdentityResponse)
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.api.serviceusage.v1beta1.ServiceUsageProto
.internal_static_google_api_serviceusage_v1beta1_GetServiceIdentityResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.serviceusage.v1beta1.ServiceUsageProto
.internal_static_google_api_serviceusage_v1beta1_GetServiceIdentityResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.class,
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.Builder.class);
}
// Construct using com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getIdentityFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
identity_ = null;
if (identityBuilder_ != null) {
identityBuilder_.dispose();
identityBuilder_ = null;
}
state_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.api.serviceusage.v1beta1.ServiceUsageProto
.internal_static_google_api_serviceusage_v1beta1_GetServiceIdentityResponse_descriptor;
}
@java.lang.Override
public com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse
getDefaultInstanceForType() {
return com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse build() {
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse buildPartial() {
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse result =
new com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.identity_ = identityBuilder_ == null ? identity_ : identityBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.state_ = state_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse) {
return mergeFrom((com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse other) {
if (other
== com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.getDefaultInstance())
return this;
if (other.hasIdentity()) {
mergeIdentity(other.getIdentity());
}
if (other.state_ != 0) {
setStateValue(other.getStateValue());
}
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(getIdentityFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
state_ = input.readEnum();
bitField0_ |= 0x00000002;
break;
} // case 16
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.api.serviceusage.v1beta1.ServiceIdentity identity_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.api.serviceusage.v1beta1.ServiceIdentity,
com.google.api.serviceusage.v1beta1.ServiceIdentity.Builder,
com.google.api.serviceusage.v1beta1.ServiceIdentityOrBuilder>
identityBuilder_;
/**
*
*
* <pre>
* Service identity that service producer can use to access consumer
* resources. If exists is true, it contains email and unique_id. If exists is
* false, it contains pre-constructed email and empty unique_id.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.ServiceIdentity identity = 1;</code>
*
* @return Whether the identity field is set.
*/
public boolean hasIdentity() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Service identity that service producer can use to access consumer
* resources. If exists is true, it contains email and unique_id. If exists is
* false, it contains pre-constructed email and empty unique_id.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.ServiceIdentity identity = 1;</code>
*
* @return The identity.
*/
public com.google.api.serviceusage.v1beta1.ServiceIdentity getIdentity() {
if (identityBuilder_ == null) {
return identity_ == null
? com.google.api.serviceusage.v1beta1.ServiceIdentity.getDefaultInstance()
: identity_;
} else {
return identityBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Service identity that service producer can use to access consumer
* resources. If exists is true, it contains email and unique_id. If exists is
* false, it contains pre-constructed email and empty unique_id.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.ServiceIdentity identity = 1;</code>
*/
public Builder setIdentity(com.google.api.serviceusage.v1beta1.ServiceIdentity value) {
if (identityBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
identity_ = value;
} else {
identityBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Service identity that service producer can use to access consumer
* resources. If exists is true, it contains email and unique_id. If exists is
* false, it contains pre-constructed email and empty unique_id.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.ServiceIdentity identity = 1;</code>
*/
public Builder setIdentity(
com.google.api.serviceusage.v1beta1.ServiceIdentity.Builder builderForValue) {
if (identityBuilder_ == null) {
identity_ = builderForValue.build();
} else {
identityBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Service identity that service producer can use to access consumer
* resources. If exists is true, it contains email and unique_id. If exists is
* false, it contains pre-constructed email and empty unique_id.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.ServiceIdentity identity = 1;</code>
*/
public Builder mergeIdentity(com.google.api.serviceusage.v1beta1.ServiceIdentity value) {
if (identityBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& identity_ != null
&& identity_
!= com.google.api.serviceusage.v1beta1.ServiceIdentity.getDefaultInstance()) {
getIdentityBuilder().mergeFrom(value);
} else {
identity_ = value;
}
} else {
identityBuilder_.mergeFrom(value);
}
if (identity_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Service identity that service producer can use to access consumer
* resources. If exists is true, it contains email and unique_id. If exists is
* false, it contains pre-constructed email and empty unique_id.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.ServiceIdentity identity = 1;</code>
*/
public Builder clearIdentity() {
bitField0_ = (bitField0_ & ~0x00000001);
identity_ = null;
if (identityBuilder_ != null) {
identityBuilder_.dispose();
identityBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Service identity that service producer can use to access consumer
* resources. If exists is true, it contains email and unique_id. If exists is
* false, it contains pre-constructed email and empty unique_id.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.ServiceIdentity identity = 1;</code>
*/
public com.google.api.serviceusage.v1beta1.ServiceIdentity.Builder getIdentityBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getIdentityFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Service identity that service producer can use to access consumer
* resources. If exists is true, it contains email and unique_id. If exists is
* false, it contains pre-constructed email and empty unique_id.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.ServiceIdentity identity = 1;</code>
*/
public com.google.api.serviceusage.v1beta1.ServiceIdentityOrBuilder getIdentityOrBuilder() {
if (identityBuilder_ != null) {
return identityBuilder_.getMessageOrBuilder();
} else {
return identity_ == null
? com.google.api.serviceusage.v1beta1.ServiceIdentity.getDefaultInstance()
: identity_;
}
}
/**
*
*
* <pre>
* Service identity that service producer can use to access consumer
* resources. If exists is true, it contains email and unique_id. If exists is
* false, it contains pre-constructed email and empty unique_id.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.ServiceIdentity identity = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.api.serviceusage.v1beta1.ServiceIdentity,
com.google.api.serviceusage.v1beta1.ServiceIdentity.Builder,
com.google.api.serviceusage.v1beta1.ServiceIdentityOrBuilder>
getIdentityFieldBuilder() {
if (identityBuilder_ == null) {
identityBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.api.serviceusage.v1beta1.ServiceIdentity,
com.google.api.serviceusage.v1beta1.ServiceIdentity.Builder,
com.google.api.serviceusage.v1beta1.ServiceIdentityOrBuilder>(
getIdentity(), getParentForChildren(), isClean());
identity_ = null;
}
return identityBuilder_;
}
private int state_ = 0;
/**
*
*
* <pre>
* Service identity state.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState state = 2;
* </code>
*
* @return The enum numeric value on the wire for state.
*/
@java.lang.Override
public int getStateValue() {
return state_;
}
/**
*
*
* <pre>
* Service identity state.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState state = 2;
* </code>
*
* @param value The enum numeric value on the wire for state to set.
* @return This builder for chaining.
*/
public Builder setStateValue(int value) {
state_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Service identity state.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState state = 2;
* </code>
*
* @return The state.
*/
@java.lang.Override
public com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState getState() {
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState result =
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState.forNumber(
state_);
return result == null
? com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState
.UNRECOGNIZED
: result;
}
/**
*
*
* <pre>
* Service identity state.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState state = 2;
* </code>
*
* @param value The state to set.
* @return This builder for chaining.
*/
public Builder setState(
com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
state_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Service identity state.
* </pre>
*
* <code>.google.api.serviceusage.v1beta1.GetServiceIdentityResponse.IdentityState state = 2;
* </code>
*
* @return This builder for chaining.
*/
public Builder clearState() {
bitField0_ = (bitField0_ & ~0x00000002);
state_ = 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.serviceusage.v1beta1.GetServiceIdentityResponse)
}
// @@protoc_insertion_point(class_scope:google.api.serviceusage.v1beta1.GetServiceIdentityResponse)
private static final com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse();
}
public static com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetServiceIdentityResponse> PARSER =
new com.google.protobuf.AbstractParser<GetServiceIdentityResponse>() {
@java.lang.Override
public GetServiceIdentityResponse 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<GetServiceIdentityResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetServiceIdentityResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.api.serviceusage.v1beta1.GetServiceIdentityResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,723 | java-admanager/proto-ad-manager-v1/src/main/java/com/google/ads/admanager/v1/DeviceCategoryTargeting.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/admanager/v1/targeting.proto
// Protobuf Java Version: 3.25.8
package com.google.ads.admanager.v1;
/**
*
*
* <pre>
* Represents a list of targeted and excluded device categories.
* </pre>
*
* Protobuf type {@code google.ads.admanager.v1.DeviceCategoryTargeting}
*/
public final class DeviceCategoryTargeting extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.ads.admanager.v1.DeviceCategoryTargeting)
DeviceCategoryTargetingOrBuilder {
private static final long serialVersionUID = 0L;
// Use DeviceCategoryTargeting.newBuilder() to construct.
private DeviceCategoryTargeting(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DeviceCategoryTargeting() {
targetedCategories_ = com.google.protobuf.LazyStringArrayList.emptyList();
excludedCategories_ = com.google.protobuf.LazyStringArrayList.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new DeviceCategoryTargeting();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.ads.admanager.v1.TargetingProto
.internal_static_google_ads_admanager_v1_DeviceCategoryTargeting_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.admanager.v1.TargetingProto
.internal_static_google_ads_admanager_v1_DeviceCategoryTargeting_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.admanager.v1.DeviceCategoryTargeting.class,
com.google.ads.admanager.v1.DeviceCategoryTargeting.Builder.class);
}
public static final int TARGETED_CATEGORIES_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList targetedCategories_ =
com.google.protobuf.LazyStringArrayList.emptyList();
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be
* targeted/included.
* </pre>
*
* <code>
* repeated string targeted_categories = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return A list containing the targetedCategories.
*/
public com.google.protobuf.ProtocolStringList getTargetedCategoriesList() {
return targetedCategories_;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be
* targeted/included.
* </pre>
*
* <code>
* repeated string targeted_categories = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The count of targetedCategories.
*/
public int getTargetedCategoriesCount() {
return targetedCategories_.size();
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be
* targeted/included.
* </pre>
*
* <code>
* repeated string targeted_categories = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index of the element to return.
* @return The targetedCategories at the given index.
*/
public java.lang.String getTargetedCategories(int index) {
return targetedCategories_.get(index);
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be
* targeted/included.
* </pre>
*
* <code>
* repeated string targeted_categories = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index of the value to return.
* @return The bytes of the targetedCategories at the given index.
*/
public com.google.protobuf.ByteString getTargetedCategoriesBytes(int index) {
return targetedCategories_.getByteString(index);
}
public static final int EXCLUDED_CATEGORIES_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList excludedCategories_ =
com.google.protobuf.LazyStringArrayList.emptyList();
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be excluded.
* </pre>
*
* <code>
* repeated string excluded_categories = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return A list containing the excludedCategories.
*/
public com.google.protobuf.ProtocolStringList getExcludedCategoriesList() {
return excludedCategories_;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be excluded.
* </pre>
*
* <code>
* repeated string excluded_categories = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The count of excludedCategories.
*/
public int getExcludedCategoriesCount() {
return excludedCategories_.size();
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be excluded.
* </pre>
*
* <code>
* repeated string excluded_categories = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index of the element to return.
* @return The excludedCategories at the given index.
*/
public java.lang.String getExcludedCategories(int index) {
return excludedCategories_.get(index);
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be excluded.
* </pre>
*
* <code>
* repeated string excluded_categories = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index of the value to return.
* @return The bytes of the excludedCategories at the given index.
*/
public com.google.protobuf.ByteString getExcludedCategoriesBytes(int index) {
return excludedCategories_.getByteString(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < targetedCategories_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, targetedCategories_.getRaw(i));
}
for (int i = 0; i < excludedCategories_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, excludedCategories_.getRaw(i));
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
{
int dataSize = 0;
for (int i = 0; i < targetedCategories_.size(); i++) {
dataSize += computeStringSizeNoTag(targetedCategories_.getRaw(i));
}
size += dataSize;
size += 1 * getTargetedCategoriesList().size();
}
{
int dataSize = 0;
for (int i = 0; i < excludedCategories_.size(); i++) {
dataSize += computeStringSizeNoTag(excludedCategories_.getRaw(i));
}
size += dataSize;
size += 1 * getExcludedCategoriesList().size();
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.admanager.v1.DeviceCategoryTargeting)) {
return super.equals(obj);
}
com.google.ads.admanager.v1.DeviceCategoryTargeting other =
(com.google.ads.admanager.v1.DeviceCategoryTargeting) obj;
if (!getTargetedCategoriesList().equals(other.getTargetedCategoriesList())) return false;
if (!getExcludedCategoriesList().equals(other.getExcludedCategoriesList())) 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 (getTargetedCategoriesCount() > 0) {
hash = (37 * hash) + TARGETED_CATEGORIES_FIELD_NUMBER;
hash = (53 * hash) + getTargetedCategoriesList().hashCode();
}
if (getExcludedCategoriesCount() > 0) {
hash = (37 * hash) + EXCLUDED_CATEGORIES_FIELD_NUMBER;
hash = (53 * hash) + getExcludedCategoriesList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.admanager.v1.DeviceCategoryTargeting parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.admanager.v1.DeviceCategoryTargeting 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.DeviceCategoryTargeting parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.admanager.v1.DeviceCategoryTargeting 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.DeviceCategoryTargeting parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.admanager.v1.DeviceCategoryTargeting 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.DeviceCategoryTargeting parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.ads.admanager.v1.DeviceCategoryTargeting 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.DeviceCategoryTargeting parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.admanager.v1.DeviceCategoryTargeting 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.DeviceCategoryTargeting 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.DeviceCategoryTargeting 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.DeviceCategoryTargeting prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Represents a list of targeted and excluded device categories.
* </pre>
*
* Protobuf type {@code google.ads.admanager.v1.DeviceCategoryTargeting}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.ads.admanager.v1.DeviceCategoryTargeting)
com.google.ads.admanager.v1.DeviceCategoryTargetingOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.ads.admanager.v1.TargetingProto
.internal_static_google_ads_admanager_v1_DeviceCategoryTargeting_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.admanager.v1.TargetingProto
.internal_static_google_ads_admanager_v1_DeviceCategoryTargeting_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.admanager.v1.DeviceCategoryTargeting.class,
com.google.ads.admanager.v1.DeviceCategoryTargeting.Builder.class);
}
// Construct using com.google.ads.admanager.v1.DeviceCategoryTargeting.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
targetedCategories_ = com.google.protobuf.LazyStringArrayList.emptyList();
excludedCategories_ = com.google.protobuf.LazyStringArrayList.emptyList();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.ads.admanager.v1.TargetingProto
.internal_static_google_ads_admanager_v1_DeviceCategoryTargeting_descriptor;
}
@java.lang.Override
public com.google.ads.admanager.v1.DeviceCategoryTargeting getDefaultInstanceForType() {
return com.google.ads.admanager.v1.DeviceCategoryTargeting.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.admanager.v1.DeviceCategoryTargeting build() {
com.google.ads.admanager.v1.DeviceCategoryTargeting result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.admanager.v1.DeviceCategoryTargeting buildPartial() {
com.google.ads.admanager.v1.DeviceCategoryTargeting result =
new com.google.ads.admanager.v1.DeviceCategoryTargeting(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.admanager.v1.DeviceCategoryTargeting result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
targetedCategories_.makeImmutable();
result.targetedCategories_ = targetedCategories_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
excludedCategories_.makeImmutable();
result.excludedCategories_ = excludedCategories_;
}
}
@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.DeviceCategoryTargeting) {
return mergeFrom((com.google.ads.admanager.v1.DeviceCategoryTargeting) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.admanager.v1.DeviceCategoryTargeting other) {
if (other == com.google.ads.admanager.v1.DeviceCategoryTargeting.getDefaultInstance())
return this;
if (!other.targetedCategories_.isEmpty()) {
if (targetedCategories_.isEmpty()) {
targetedCategories_ = other.targetedCategories_;
bitField0_ |= 0x00000001;
} else {
ensureTargetedCategoriesIsMutable();
targetedCategories_.addAll(other.targetedCategories_);
}
onChanged();
}
if (!other.excludedCategories_.isEmpty()) {
if (excludedCategories_.isEmpty()) {
excludedCategories_ = other.excludedCategories_;
bitField0_ |= 0x00000002;
} else {
ensureExcludedCategoriesIsMutable();
excludedCategories_.addAll(other.excludedCategories_);
}
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 26:
{
java.lang.String s = input.readStringRequireUtf8();
ensureTargetedCategoriesIsMutable();
targetedCategories_.add(s);
break;
} // case 26
case 34:
{
java.lang.String s = input.readStringRequireUtf8();
ensureExcludedCategoriesIsMutable();
excludedCategories_.add(s);
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.protobuf.LazyStringArrayList targetedCategories_ =
com.google.protobuf.LazyStringArrayList.emptyList();
private void ensureTargetedCategoriesIsMutable() {
if (!targetedCategories_.isModifiable()) {
targetedCategories_ = new com.google.protobuf.LazyStringArrayList(targetedCategories_);
}
bitField0_ |= 0x00000001;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be
* targeted/included.
* </pre>
*
* <code>
* repeated string targeted_categories = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return A list containing the targetedCategories.
*/
public com.google.protobuf.ProtocolStringList getTargetedCategoriesList() {
targetedCategories_.makeImmutable();
return targetedCategories_;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be
* targeted/included.
* </pre>
*
* <code>
* repeated string targeted_categories = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The count of targetedCategories.
*/
public int getTargetedCategoriesCount() {
return targetedCategories_.size();
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be
* targeted/included.
* </pre>
*
* <code>
* repeated string targeted_categories = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index of the element to return.
* @return The targetedCategories at the given index.
*/
public java.lang.String getTargetedCategories(int index) {
return targetedCategories_.get(index);
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be
* targeted/included.
* </pre>
*
* <code>
* repeated string targeted_categories = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index of the value to return.
* @return The bytes of the targetedCategories at the given index.
*/
public com.google.protobuf.ByteString getTargetedCategoriesBytes(int index) {
return targetedCategories_.getByteString(index);
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be
* targeted/included.
* </pre>
*
* <code>
* repeated string targeted_categories = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index to set the value at.
* @param value The targetedCategories to set.
* @return This builder for chaining.
*/
public Builder setTargetedCategories(int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureTargetedCategoriesIsMutable();
targetedCategories_.set(index, value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be
* targeted/included.
* </pre>
*
* <code>
* repeated string targeted_categories = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The targetedCategories to add.
* @return This builder for chaining.
*/
public Builder addTargetedCategories(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureTargetedCategoriesIsMutable();
targetedCategories_.add(value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be
* targeted/included.
* </pre>
*
* <code>
* repeated string targeted_categories = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param values The targetedCategories to add.
* @return This builder for chaining.
*/
public Builder addAllTargetedCategories(java.lang.Iterable<java.lang.String> values) {
ensureTargetedCategoriesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, targetedCategories_);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be
* targeted/included.
* </pre>
*
* <code>
* repeated string targeted_categories = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearTargetedCategories() {
targetedCategories_ = com.google.protobuf.LazyStringArrayList.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be
* targeted/included.
* </pre>
*
* <code>
* repeated string targeted_categories = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes of the targetedCategories to add.
* @return This builder for chaining.
*/
public Builder addTargetedCategoriesBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureTargetedCategoriesIsMutable();
targetedCategories_.add(value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.protobuf.LazyStringArrayList excludedCategories_ =
com.google.protobuf.LazyStringArrayList.emptyList();
private void ensureExcludedCategoriesIsMutable() {
if (!excludedCategories_.isModifiable()) {
excludedCategories_ = new com.google.protobuf.LazyStringArrayList(excludedCategories_);
}
bitField0_ |= 0x00000002;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be excluded.
* </pre>
*
* <code>
* repeated string excluded_categories = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return A list containing the excludedCategories.
*/
public com.google.protobuf.ProtocolStringList getExcludedCategoriesList() {
excludedCategories_.makeImmutable();
return excludedCategories_;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be excluded.
* </pre>
*
* <code>
* repeated string excluded_categories = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The count of excludedCategories.
*/
public int getExcludedCategoriesCount() {
return excludedCategories_.size();
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be excluded.
* </pre>
*
* <code>
* repeated string excluded_categories = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index of the element to return.
* @return The excludedCategories at the given index.
*/
public java.lang.String getExcludedCategories(int index) {
return excludedCategories_.get(index);
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be excluded.
* </pre>
*
* <code>
* repeated string excluded_categories = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index of the value to return.
* @return The bytes of the excludedCategories at the given index.
*/
public com.google.protobuf.ByteString getExcludedCategoriesBytes(int index) {
return excludedCategories_.getByteString(index);
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be excluded.
* </pre>
*
* <code>
* repeated string excluded_categories = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index to set the value at.
* @param value The excludedCategories to set.
* @return This builder for chaining.
*/
public Builder setExcludedCategories(int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureExcludedCategoriesIsMutable();
excludedCategories_.set(index, value);
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be excluded.
* </pre>
*
* <code>
* repeated string excluded_categories = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The excludedCategories to add.
* @return This builder for chaining.
*/
public Builder addExcludedCategories(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureExcludedCategoriesIsMutable();
excludedCategories_.add(value);
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be excluded.
* </pre>
*
* <code>
* repeated string excluded_categories = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param values The excludedCategories to add.
* @return This builder for chaining.
*/
public Builder addAllExcludedCategories(java.lang.Iterable<java.lang.String> values) {
ensureExcludedCategoriesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, excludedCategories_);
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be excluded.
* </pre>
*
* <code>
* repeated string excluded_categories = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearExcludedCategories() {
excludedCategories_ = com.google.protobuf.LazyStringArrayList.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A list of device category resource names that should be excluded.
* </pre>
*
* <code>
* repeated string excluded_categories = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes of the excludedCategories to add.
* @return This builder for chaining.
*/
public Builder addExcludedCategoriesBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureExcludedCategoriesIsMutable();
excludedCategories_.add(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.ads.admanager.v1.DeviceCategoryTargeting)
}
// @@protoc_insertion_point(class_scope:google.ads.admanager.v1.DeviceCategoryTargeting)
private static final com.google.ads.admanager.v1.DeviceCategoryTargeting DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.admanager.v1.DeviceCategoryTargeting();
}
public static com.google.ads.admanager.v1.DeviceCategoryTargeting getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DeviceCategoryTargeting> PARSER =
new com.google.protobuf.AbstractParser<DeviceCategoryTargeting>() {
@java.lang.Override
public DeviceCategoryTargeting 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<DeviceCategoryTargeting> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DeviceCategoryTargeting> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.admanager.v1.DeviceCategoryTargeting getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/commons-text | 35,613 | src/main/java/org/apache/commons/text/WordUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.text;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
/**
* Operations on Strings that contain words.
*
* <p>
* This class tries to handle {@code null} input gracefully. An exception will not be thrown for a
* {@code null} input. Each method documents its behavior in more detail.
* </p>
*
* @since 1.1
*/
public class WordUtils {
/**
* Abbreviates the words nicely.
*
* <p>
* This method searches for the first space after the lower limit and abbreviates
* the String there. It will also append any String passed as a parameter
* to the end of the String. The upper limit can be specified to forcibly
* abbreviate a String.
* </p>
*
* @param str the string to be abbreviated. If null is passed, null is returned.
* If the empty String is passed, the empty string is returned.
* @param lower the lower limit; negative value is treated as zero.
* @param upper the upper limit; specify -1 if no limit is desired.
* The upper limit cannot be lower than the lower limit.
* @param appendToEnd String to be appended to the end of the abbreviated string.
* This is appended ONLY if the string was indeed abbreviated.
* The append does not count towards the lower or upper limits.
* @return The abbreviated String.
*
* <pre>
* WordUtils.abbreviate("Now is the time for all good men", 0, 40, null)); = "Now"
* WordUtils.abbreviate("Now is the time for all good men", 10, 40, null)); = "Now is the"
* WordUtils.abbreviate("Now is the time for all good men", 20, 40, null)); = "Now is the time for all"
* WordUtils.abbreviate("Now is the time for all good men", 0, 40, "")); = "Now"
* WordUtils.abbreviate("Now is the time for all good men", 10, 40, "")); = "Now is the"
* WordUtils.abbreviate("Now is the time for all good men", 20, 40, "")); = "Now is the time for all"
* WordUtils.abbreviate("Now is the time for all good men", 0, 40, " ...")); = "Now ..."
* WordUtils.abbreviate("Now is the time for all good men", 10, 40, " ...")); = "Now is the ..."
* WordUtils.abbreviate("Now is the time for all good men", 20, 40, " ...")); = "Now is the time for all ..."
* WordUtils.abbreviate("Now is the time for all good men", 0, -1, "")); = "Now"
* WordUtils.abbreviate("Now is the time for all good men", 10, -1, "")); = "Now is the"
* WordUtils.abbreviate("Now is the time for all good men", 20, -1, "")); = "Now is the time for all"
* WordUtils.abbreviate("Now is the time for all good men", 50, -1, "")); = "Now is the time for all good men"
* WordUtils.abbreviate("Now is the time for all good men", 1000, -1, "")); = "Now is the time for all good men"
* WordUtils.abbreviate("Now is the time for all good men", 9, -10, null)); = IllegalArgumentException
* WordUtils.abbreviate("Now is the time for all good men", 10, 5, null)); = IllegalArgumentException
* </pre>
*/
public static String abbreviate(final String str, int lower, int upper, final String appendToEnd) {
Validate.isTrue(upper >= -1, "upper value cannot be less than -1");
Validate.isTrue(upper >= lower || upper == -1, "upper value is less than lower value");
if (StringUtils.isEmpty(str)) {
return str;
}
// if the lower value is greater than the length of the string,
// set to the length of the string
if (lower > str.length()) {
lower = str.length();
}
// if the upper value is -1 (i.e. no limit) or is greater
// than the length of the string, set to the length of the string
if (upper == -1 || upper > str.length()) {
upper = str.length();
}
final StringBuilder result = new StringBuilder();
final int index = StringUtils.indexOf(str, " ", lower);
if (index == -1) {
result.append(str, 0, upper);
// only if abbreviation has occurred do we append the appendToEnd value
if (upper != str.length()) {
result.append(StringUtils.defaultString(appendToEnd));
}
} else {
result.append(str, 0, Math.min(index, upper));
result.append(StringUtils.defaultString(appendToEnd));
}
return result.toString();
}
/**
* Capitalizes all the whitespace separated words in a String.
* Only the first character of each word is changed. To convert the
* rest of each word to lowercase at the same time,
* use {@link #capitalizeFully(String)}.
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
* A {@code null} input String returns {@code null}.
* Capitalization uses the Unicode title case, normally equivalent to
* upper case.</p>
*
* <pre>
* WordUtils.capitalize(null) = null
* WordUtils.capitalize("") = ""
* WordUtils.capitalize("i am FINE") = "I Am FINE"
* </pre>
*
* @param str the String to capitalize, may be null
* @return capitalized String, {@code null} if null String input
* @see #uncapitalize(String)
* @see #capitalizeFully(String)
*/
public static String capitalize(final String str) {
return capitalize(str, null);
}
/**
* Capitalizes all the delimiter separated words in a String.
* Only the first character of each word is changed. To convert the
* rest of each word to lowercase at the same time,
* use {@link #capitalizeFully(String, char[])}.
*
* <p>The delimiters represent a set of characters understood to separate words.
* The first string character and the first non-delimiter character after a
* delimiter will be capitalized.</p>
*
* <p>A {@code null} input String returns {@code null}.
* Capitalization uses the Unicode title case, normally equivalent to
* upper case.</p>
*
* <pre>
* WordUtils.capitalize(null, *) = null
* WordUtils.capitalize("", *) = ""
* WordUtils.capitalize(*, new char[0]) = *
* WordUtils.capitalize("i am fine", null) = "I Am Fine"
* WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"
* WordUtils.capitalize("i am fine", new char[]{}) = "I am fine"
* </pre>
*
* @param str the String to capitalize, may be null
* @param delimiters set of characters to determine capitalization, null means whitespace
* @return capitalized String, {@code null} if null String input
* @see #uncapitalize(String)
* @see #capitalizeFully(String)
*/
public static String capitalize(final String str, final char... delimiters) {
if (StringUtils.isEmpty(str)) {
return str;
}
final Predicate<Integer> isDelimiter = generateIsDelimiterFunction(delimiters);
final int strLen = str.length();
final int[] newCodePoints = new int[strLen];
int outOffset = 0;
boolean capitalizeNext = true;
for (int index = 0; index < strLen;) {
final int codePoint = str.codePointAt(index);
if (isDelimiter.test(codePoint)) {
capitalizeNext = true;
newCodePoints[outOffset++] = codePoint;
index += Character.charCount(codePoint);
} else if (capitalizeNext) {
final int titleCaseCodePoint = Character.toTitleCase(codePoint);
newCodePoints[outOffset++] = titleCaseCodePoint;
index += Character.charCount(titleCaseCodePoint);
capitalizeNext = false;
} else {
newCodePoints[outOffset++] = codePoint;
index += Character.charCount(codePoint);
}
}
return new String(newCodePoints, 0, outOffset);
}
/**
* Converts all the whitespace separated words in a String into capitalized words,
* that is each word is made up of a titlecase character and then a series of
* lowercase characters.
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
* A {@code null} input String returns {@code null}.
* Capitalization uses the Unicode title case, normally equivalent to
* upper case.</p>
*
* <pre>
* WordUtils.capitalizeFully(null) = null
* WordUtils.capitalizeFully("") = ""
* WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
* </pre>
*
* @param str the String to capitalize, may be null
* @return capitalized String, {@code null} if null String input
*/
public static String capitalizeFully(final String str) {
return capitalizeFully(str, null);
}
/**
* Converts all the delimiter separated words in a String into capitalized words,
* that is each word is made up of a titlecase character and then a series of
* lowercase characters.
*
* <p>The delimiters represent a set of characters understood to separate words.
* The first string character and the first non-delimiter character after a
* delimiter will be capitalized.</p>
*
* <p>A {@code null} input String returns {@code null}.
* Capitalization uses the Unicode title case, normally equivalent to
* upper case.</p>
*
* <pre>
* WordUtils.capitalizeFully(null, *) = null
* WordUtils.capitalizeFully("", *) = ""
* WordUtils.capitalizeFully(*, null) = *
* WordUtils.capitalizeFully(*, new char[0]) = *
* WordUtils.capitalizeFully("i aM.fine", {'.'}) = "I am.Fine"
* </pre>
*
* @param str the String to capitalize, may be null
* @param delimiters set of characters to determine capitalization, null means whitespace
* @return capitalized String, {@code null} if null String input
*/
public static String capitalizeFully(String str, final char... delimiters) {
if (StringUtils.isEmpty(str)) {
return str;
}
str = str.toLowerCase();
return capitalize(str, delimiters);
}
/**
* Checks if the String contains all words in the given array.
*
* <p>
* A {@code null} String will return {@code false}. A {@code null}, zero
* length search array or if one element of array is null will return {@code false}.
* </p>
*
* <pre>
* WordUtils.containsAllWords(null, *) = false
* WordUtils.containsAllWords("", *) = false
* WordUtils.containsAllWords(*, null) = false
* WordUtils.containsAllWords(*, []) = false
* WordUtils.containsAllWords("abcd", "ab", "cd") = false
* WordUtils.containsAllWords("abc def", "def", "abc") = true
* </pre>
*
* @param word The CharSequence to check, may be null
* @param words The array of String words to search for, may be null
* @return {@code true} if all search words are found, {@code false} otherwise
*/
public static boolean containsAllWords(final CharSequence word, final CharSequence... words) {
if (StringUtils.isEmpty(word) || ArrayUtils.isEmpty(words)) {
return false;
}
for (final CharSequence w : words) {
if (StringUtils.isBlank(w)) {
return false;
}
final Pattern p = Pattern.compile(".*\\b" + Pattern.quote(w.toString()) + "\\b.*");
if (!p.matcher(word).matches()) {
return false;
}
}
return true;
}
/**
* Given the array of delimiters supplied; returns a function determining whether a character code point is a delimiter.
* The function provides O(1) lookup time.
* Whitespace is defined by {@link Character#isWhitespace(char)} and is used as the defaultvalue if delimiters is null.
*
* @param delimiters set of characters to determine delimiters, null means whitespace
* @return Predicate<Integer> taking a code point value as an argument and returning true if a delimiter.
*/
private static Predicate<Integer> generateIsDelimiterFunction(final char[] delimiters) {
final Predicate<Integer> isDelimiter;
if (delimiters == null || delimiters.length == 0) {
isDelimiter = delimiters == null ? Character::isWhitespace : c -> false;
} else {
final Set<Integer> delimiterSet = new HashSet<>();
for (int index = 0; index < delimiters.length; index++) {
delimiterSet.add(Character.codePointAt(delimiters, index));
}
isDelimiter = delimiterSet::contains;
}
return isDelimiter;
}
/**
* Extracts the initial characters from each word in the String.
*
* <p>All first characters after whitespace are returned as a new string.
* Their case is not changed.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
* A {@code null} input String returns {@code null}.</p>
*
* <pre>
* WordUtils.initials(null) = null
* WordUtils.initials("") = ""
* WordUtils.initials("Ben John Lee") = "BJL"
* WordUtils.initials("Ben J.Lee") = "BJ"
* </pre>
*
* @param str the String to get initials from, may be null
* @return String of initial letters, {@code null} if null String input
* @see #initials(String,char[])
*/
public static String initials(final String str) {
return initials(str, null);
}
/**
* Extracts the initial characters from each word in the String.
*
* <p>All first characters after the defined delimiters are returned as a new string.
* Their case is not changed.</p>
*
* <p>If the delimiters array is null, then Whitespace is used.
* Whitespace is defined by {@link Character#isWhitespace(char)}.
* A {@code null} input String returns {@code null}.
* An empty delimiter array returns an empty String.</p>
*
* <pre>
* WordUtils.initials(null, *) = null
* WordUtils.initials("", *) = ""
* WordUtils.initials("Ben John Lee", null) = "BJL"
* WordUtils.initials("Ben J.Lee", null) = "BJ"
* WordUtils.initials("Ben J.Lee", [' ','.']) = "BJL"
* WordUtils.initials(*, new char[0]) = ""
* </pre>
*
* @param str the String to get initials from, may be null
* @param delimiters set of characters to determine words, null means whitespace
* @return String of initial characters, {@code null} if null String input
* @see #initials(String)
*/
public static String initials(final String str, final char... delimiters) {
if (StringUtils.isEmpty(str)) {
return str;
}
if (delimiters != null && delimiters.length == 0) {
return StringUtils.EMPTY;
}
final Predicate<Integer> isDelimiter = generateIsDelimiterFunction(delimiters);
final int strLen = str.length();
final int[] newCodePoints = new int[strLen / 2 + 1];
int count = 0;
boolean lastWasGap = true;
for (int i = 0; i < strLen;) {
final int codePoint = str.codePointAt(i);
if (isDelimiter.test(codePoint)) {
lastWasGap = true;
} else if (lastWasGap) {
newCodePoints[count++] = codePoint;
lastWasGap = false;
}
i += Character.charCount(codePoint);
}
return new String(newCodePoints, 0, count);
}
/**
* Is the character a delimiter.
*
* @param ch the character to check
* @param delimiters the delimiters
* @return true if it is a delimiter
* @deprecated as of 1.2 and will be removed in 2.0
*/
@Deprecated
public static boolean isDelimiter(final char ch, final char[] delimiters) {
if (delimiters == null) {
return Character.isWhitespace(ch);
}
for (final char delimiter : delimiters) {
if (ch == delimiter) {
return true;
}
}
return false;
}
/**
* Is the codePoint a delimiter.
*
* @param codePoint the codePint to check
* @param delimiters the delimiters
* @return true if it is a delimiter
* @deprecated as of 1.2 and will be removed in 2.0
*/
@Deprecated
public static boolean isDelimiter(final int codePoint, final char[] delimiters) {
if (delimiters == null) {
return Character.isWhitespace(codePoint);
}
for (int index = 0; index < delimiters.length; index++) {
final int delimiterCodePoint = Character.codePointAt(delimiters, index);
if (delimiterCodePoint == codePoint) {
return true;
}
}
return false;
}
/**
* Swaps the case of a String using a word based algorithm.
*
* <ul>
* <li>Upper case character converts to Lower case</li>
* <li>Title case character converts to Lower case</li>
* <li>Lower case character after Whitespace or at start converts to Title case</li>
* <li>Other Lower case character converts to Upper case</li>
* </ul>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
* A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.swapCase(null) = null
* StringUtils.swapCase("") = ""
* StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
* </pre>
*
* @param str the String to swap case, may be null
* @return The changed String, {@code null} if null String input
*/
public static String swapCase(final String str) {
if (StringUtils.isEmpty(str)) {
return str;
}
final int strLen = str.length();
final int[] newCodePoints = new int[strLen];
int outOffset = 0;
boolean whitespace = true;
for (int index = 0; index < strLen;) {
final int oldCodepoint = str.codePointAt(index);
final int newCodePoint;
if (Character.isUpperCase(oldCodepoint) || Character.isTitleCase(oldCodepoint)) {
newCodePoint = Character.toLowerCase(oldCodepoint);
whitespace = false;
} else if (Character.isLowerCase(oldCodepoint)) {
if (whitespace) {
newCodePoint = Character.toTitleCase(oldCodepoint);
whitespace = false;
} else {
newCodePoint = Character.toUpperCase(oldCodepoint);
}
} else {
whitespace = Character.isWhitespace(oldCodepoint);
newCodePoint = oldCodepoint;
}
newCodePoints[outOffset++] = newCodePoint;
index += Character.charCount(newCodePoint);
}
return new String(newCodePoints, 0, outOffset);
}
/**
* Uncapitalizes all the whitespace separated words in a String.
* Only the first character of each word is changed.
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
* A {@code null} input String returns {@code null}.</p>
*
* <pre>
* WordUtils.uncapitalize(null) = null
* WordUtils.uncapitalize("") = ""
* WordUtils.uncapitalize("I Am FINE") = "i am fINE"
* </pre>
*
* @param str the String to uncapitalize, may be null
* @return uncapitalized String, {@code null} if null String input
* @see #capitalize(String)
*/
public static String uncapitalize(final String str) {
return uncapitalize(str, null);
}
/**
* Uncapitalizes all the whitespace separated words in a String.
* Only the first character of each word is changed.
*
* <p>The delimiters represent a set of characters understood to separate words.
* The first string character and the first non-delimiter character after a
* delimiter will be uncapitalized.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
* A {@code null} input String returns {@code null}.</p>
*
* <pre>
* WordUtils.uncapitalize(null, *) = null
* WordUtils.uncapitalize("", *) = ""
* WordUtils.uncapitalize(*, null) = *
* WordUtils.uncapitalize(*, new char[0]) = *
* WordUtils.uncapitalize("I AM.FINE", {'.'}) = "i AM.fINE"
* WordUtils.uncapitalize("I am fine", new char[]{}) = "i am fine"
* </pre>
*
* @param str the String to uncapitalize, may be null
* @param delimiters set of characters to determine uncapitalization, null means whitespace
* @return uncapitalized String, {@code null} if null String input
* @see #capitalize(String)
*/
public static String uncapitalize(final String str, final char... delimiters) {
if (StringUtils.isEmpty(str)) {
return str;
}
final Predicate<Integer> isDelimiter = generateIsDelimiterFunction(delimiters);
final int strLen = str.length();
final int[] newCodePoints = new int[strLen];
int outOffset = 0;
boolean uncapitalizeNext = true;
for (int index = 0; index < strLen;) {
final int codePoint = str.codePointAt(index);
if (isDelimiter.test(codePoint)) {
uncapitalizeNext = true;
newCodePoints[outOffset++] = codePoint;
index += Character.charCount(codePoint);
} else if (uncapitalizeNext) {
final int titleCaseCodePoint = Character.toLowerCase(codePoint);
newCodePoints[outOffset++] = titleCaseCodePoint;
index += Character.charCount(titleCaseCodePoint);
uncapitalizeNext = false;
} else {
newCodePoints[outOffset++] = codePoint;
index += Character.charCount(codePoint);
}
}
return new String(newCodePoints, 0, outOffset);
}
/**
* Wraps a single line of text, identifying words by {@code ' '}.
*
* <p>New lines will be separated by the system property line separator.
* Very long words, such as URLs will <em>not</em> be wrapped.</p>
*
* <p>Leading spaces on a new line are stripped.
* Trailing spaces are not stripped.</p>
*
* <table border="1">
* <caption>Examples</caption>
* <tr>
* <th>input</th>
* <th>wrapLength</th>
* <th>result</th>
* </tr>
* <tr>
* <td>null</td>
* <td>*</td>
* <td>null</td>
* </tr>
* <tr>
* <td>""</td>
* <td>*</td>
* <td>""</td>
* </tr>
* <tr>
* <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
* <td>20</td>
* <td>"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."</td>
* </tr>
* <tr>
* <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
* <td>20</td>
* <td>"Click here to jump\nto the commons\nwebsite -\nhttps://commons.apache.org"</td>
* </tr>
* <tr>
* <td>"Click here, https://commons.apache.org, to jump to the commons website"</td>
* <td>20</td>
* <td>"Click here,\nhttps://commons.apache.org,\nto jump to the\ncommons website"</td>
* </tr>
* </table>
*
* (assuming that '\n' is the systems line separator)
*
* @param str the String to be word wrapped, may be null
* @param wrapLength the column to wrap the words at, less than 1 is treated as 1
* @return a line with newlines inserted, {@code null} if null input
*/
public static String wrap(final String str, final int wrapLength) {
return wrap(str, wrapLength, null, false);
}
/**
* Wraps a single line of text, identifying words by {@code ' '}.
*
* <p>Leading spaces on a new line are stripped.
* Trailing spaces are not stripped.</p>
*
* <table border="1">
* <caption>Examples</caption>
* <tr>
* <th>input</th>
* <th>wrapLength</th>
* <th>newLineString</th>
* <th>wrapLongWords</th>
* <th>result</th>
* </tr>
* <tr>
* <td>null</td>
* <td>*</td>
* <td>*</td>
* <td>true/false</td>
* <td>null</td>
* </tr>
* <tr>
* <td>""</td>
* <td>*</td>
* <td>*</td>
* <td>true/false</td>
* <td>""</td>
* </tr>
* <tr>
* <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
* <td>20</td>
* <td>"\n"</td>
* <td>true/false</td>
* <td>"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."</td>
* </tr>
* <tr>
* <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
* <td>20</td>
* <td>"<br />"</td>
* <td>true/false</td>
* <td>"Here is one line of<br />text that is going<
* br />to be wrapped after<br />20 columns."</td>
* </tr>
* <tr>
* <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
* <td>20</td>
* <td>null</td>
* <td>true/false</td>
* <td>"Here is one line of" + systemNewLine + "text that is going"
* + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."</td>
* </tr>
* <tr>
* <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
* <td>20</td>
* <td>"\n"</td>
* <td>false</td>
* <td>"Click here to jump\nto the commons\nwebsite -\nhttps://commons.apache.org"</td>
* </tr>
* <tr>
* <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
* <td>20</td>
* <td>"\n"</td>
* <td>true</td>
* <td>"Click here to jump\nto the commons\nwebsite -\nhttps://commons.apach\ne.org"</td>
* </tr>
* </table>
*
* @param str the String to be word wrapped, may be null
* @param wrapLength the column to wrap the words at, less than 1 is treated as 1
* @param newLineStr the string to insert for a new line,
* {@code null} uses the system property line separator
* @param wrapLongWords true if long words (such as URLs) should be wrapped
* @return a line with newlines inserted, {@code null} if null input
*/
public static String wrap(final String str,
final int wrapLength,
final String newLineStr,
final boolean wrapLongWords) {
return wrap(str, wrapLength, newLineStr, wrapLongWords, " ");
}
/**
* Wraps a single line of text, identifying words by {@code wrapOn}.
*
* <p>Leading spaces on a new line are stripped.
* Trailing spaces are not stripped.</p>
*
* <table border="1">
* <caption>Examples</caption>
* <tr>
* <th>input</th>
* <th>wrapLength</th>
* <th>newLineString</th>
* <th>wrapLongWords</th>
* <th>wrapOn</th>
* <th>result</th>
* </tr>
* <tr>
* <td>null</td>
* <td>*</td>
* <td>*</td>
* <td>true/false</td>
* <td>*</td>
* <td>null</td>
* </tr>
* <tr>
* <td>""</td>
* <td>*</td>
* <td>*</td>
* <td>true/false</td>
* <td>*</td>
* <td>""</td>
* </tr>
* <tr>
* <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
* <td>20</td>
* <td>"\n"</td>
* <td>true/false</td>
* <td>" "</td>
* <td>"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."</td>
* </tr>
* <tr>
* <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
* <td>20</td>
* <td>"<br />"</td>
* <td>true/false</td>
* <td>" "</td>
* <td>"Here is one line of<br />text that is going<br />
* to be wrapped after<br />20 columns."</td>
* </tr>
* <tr>
* <td>"Here is one line of text that is going to be wrapped after 20 columns."</td>
* <td>20</td>
* <td>null</td>
* <td>true/false</td>
* <td>" "</td>
* <td>"Here is one line of" + systemNewLine + "text that is going"
* + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."</td>
* </tr>
* <tr>
* <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
* <td>20</td>
* <td>"\n"</td>
* <td>false</td>
* <td>" "</td>
* <td>"Click here to jump\nto the commons\nwebsite -\nhttps://commons.apache.org"</td>
* </tr>
* <tr>
* <td>"Click here to jump to the commons website - https://commons.apache.org"</td>
* <td>20</td>
* <td>"\n"</td>
* <td>true</td>
* <td>" "</td>
* <td>"Click here to jump\nto the commons\nwebsite -\nhttps://commons.apach\ne.org"</td>
* </tr>
* <tr>
* <td>"flammable/inflammable"</td>
* <td>20</td>
* <td>"\n"</td>
* <td>true</td>
* <td>"/"</td>
* <td>"flammable\ninflammable"</td>
* </tr>
* </table>
* @param str the String to be word wrapped, may be null
* @param wrapLength the column to wrap the words at, less than 1 is treated as 1
* @param newLineStr the string to insert for a new line,
* {@code null} uses the system property line separator
* @param wrapLongWords true if long words (such as URLs) should be wrapped
* @param wrapOn regex expression to be used as a breakable characters,
* if blank string is provided a space character will be used
* @return a line with newlines inserted, {@code null} if null input
*/
public static String wrap(final String str,
int wrapLength,
String newLineStr,
final boolean wrapLongWords,
String wrapOn) {
if (str == null) {
return null;
}
if (newLineStr == null) {
newLineStr = System.lineSeparator();
}
if (wrapLength < 1) {
wrapLength = 1;
}
if (StringUtils.isBlank(wrapOn)) {
wrapOn = " ";
}
final Pattern patternToWrapOn = Pattern.compile(wrapOn);
final int inputLineLength = str.length();
int offset = 0;
final StringBuilder wrappedLine = new StringBuilder(inputLineLength + 32);
int matcherSize = -1;
while (offset < inputLineLength) {
int spaceToWrapAt = -1;
Matcher matcher = patternToWrapOn.matcher(str.substring(offset,
Math.min((int) Math.min(Integer.MAX_VALUE, offset + wrapLength + 1L), inputLineLength)));
if (matcher.find()) {
if (matcher.start() == 0) {
matcherSize = matcher.end();
if (matcherSize != 0) {
offset += matcher.end();
continue;
}
offset += 1;
}
spaceToWrapAt = matcher.start() + offset;
}
// only last line without leading spaces is left
if (inputLineLength - offset <= wrapLength) {
break;
}
while (matcher.find()) {
spaceToWrapAt = matcher.start() + offset;
}
if (spaceToWrapAt >= offset) {
// normal case
wrappedLine.append(str, offset, spaceToWrapAt);
wrappedLine.append(newLineStr);
offset = spaceToWrapAt + 1;
} else // really long word or URL
if (wrapLongWords) {
if (matcherSize == 0) {
offset--;
}
// wrap really long word one line at a time
wrappedLine.append(str, offset, wrapLength + offset);
wrappedLine.append(newLineStr);
offset += wrapLength;
matcherSize = -1;
} else {
// do not wrap really long word, just extend beyond limit
matcher = patternToWrapOn.matcher(str.substring(offset + wrapLength));
if (matcher.find()) {
matcherSize = matcher.end() - matcher.start();
spaceToWrapAt = matcher.start() + offset + wrapLength;
}
if (spaceToWrapAt >= 0) {
if (matcherSize == 0 && offset != 0) {
offset--;
}
wrappedLine.append(str, offset, spaceToWrapAt);
wrappedLine.append(newLineStr);
offset = spaceToWrapAt + 1;
} else {
if (matcherSize == 0 && offset != 0) {
offset--;
}
wrappedLine.append(str, offset, str.length());
offset = inputLineLength;
matcherSize = -1;
}
}
}
if (matcherSize == 0 && offset < inputLineLength) {
offset--;
}
// Whatever is left in line is short enough to just pass through
wrappedLine.append(str, offset, str.length());
return wrappedLine.toString();
}
/**
* {@code WordUtils} instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* {@code WordUtils.wrap("foo bar", 20);}.
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public WordUtils() {
}
}
|
apache/ignite-3 | 36,094 | modules/sql-engine/src/test/java/org/apache/ignite/internal/sql/engine/planner/datatypes/DateTimeCaseTypeCoercionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.sql.engine.planner.datatypes;
import static org.apache.ignite.internal.lang.IgniteStringFormatter.format;
import java.util.List;
import java.util.stream.Stream;
import org.apache.calcite.rex.RexNode;
import org.apache.ignite.internal.sql.engine.planner.datatypes.utils.DatetimePair;
import org.apache.ignite.internal.sql.engine.planner.datatypes.utils.TypePair;
import org.apache.ignite.internal.sql.engine.planner.datatypes.utils.Types;
import org.apache.ignite.internal.sql.engine.schema.IgniteSchema;
import org.apache.ignite.internal.sql.engine.util.SqlTestUtils;
import org.apache.ignite.internal.type.NativeTypes;
import org.hamcrest.Matcher;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
/**
* A set of tests to verify behavior of type coercion for CASE operator, when operands belong to DATETIME types.
*
* <p>This tests aim to help to understand in which cases implicit cast will be added to which operand.
*/
public class DateTimeCaseTypeCoercionTest extends BaseTypeCoercionTest {
private static final IgniteSchema SCHEMA = createSchemaWithTwoColumnTable(NativeTypes.STRING, NativeTypes.STRING);
/** CASE operands from columns. */
@ParameterizedTest
@MethodSource("caseArgs")
public void caseColumnsTypeCoercion(
TypePair typePair,
Matcher<RexNode> firstOperandMatcher,
Matcher<RexNode> secondOperandMatcher
) throws Exception {
IgniteSchema schema = createSchemaWithTwoColumnTable(typePair.first(), typePair.second());
assertPlan("SELECT CASE WHEN RAND_UUID() != RAND_UUID() THEN c1 ELSE c2 END FROM t", schema,
operandCaseMatcher(firstOperandMatcher, secondOperandMatcher)::matches, List.of());
}
private static Stream<Arguments> caseArgs() {
return Stream.of(
forTypePair(DatetimePair.DATE_DATE)
.firstOpBeSame()
.secondOpBeSame(),
// TIME 0
forTypePair(DatetimePair.TIME_0_TIME_0)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIME_0_TIME_3)
.firstOpMatches(castTo(Types.TIME_3))
.secondOpBeSame(),
forTypePair(DatetimePair.TIME_0_TIME_6)
.firstOpMatches(castTo(Types.TIME_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIME_0_TIME_9)
.firstOpMatches(castTo(Types.TIME_9))
.secondOpBeSame(),
// TIME 3
forTypePair(DatetimePair.TIME_3_TIME_3)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIME_3_TIME_6)
.firstOpMatches(castTo(Types.TIME_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIME_3_TIME_9)
.firstOpMatches(castTo(Types.TIME_9))
.secondOpBeSame(),
// TIME 6
forTypePair(DatetimePair.TIME_6_TIME_6)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIME_6_TIME_9)
.firstOpMatches(castTo(Types.TIME_9))
.secondOpBeSame(),
// TIME 9
forTypePair(DatetimePair.TIME_9_TIME_9)
.firstOpBeSame()
.secondOpBeSame(),
// TIMESTAMP 0
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_0)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_3)
.firstOpMatches(castTo(Types.TIMESTAMP_3))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_6)
.firstOpMatches(castTo(Types.TIMESTAMP_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_WLTZ_0)
.firstOpBeSame()
.secondOpMatches(castTo(Types.TIMESTAMP_0)),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_WLTZ_3)
.firstOpMatches(castTo(Types.TIMESTAMP_3))
.secondOpMatches(castTo(Types.TIMESTAMP_3)),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_WLTZ_6)
.firstOpMatches(castTo(Types.TIMESTAMP_6))
.secondOpMatches(castTo(Types.TIMESTAMP_6)),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_WLTZ_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpMatches(castTo(Types.TIMESTAMP_9)),
// TIMESTAMP 3
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_3)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_6)
.firstOpMatches(castTo(Types.TIMESTAMP_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_WLTZ_3)
.firstOpBeSame()
.secondOpMatches(castTo(Types.TIMESTAMP_3)),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_WLTZ_6)
.firstOpMatches(castTo(Types.TIMESTAMP_6))
.secondOpMatches(castTo(Types.TIMESTAMP_6)),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_WLTZ_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpMatches(castTo(Types.TIMESTAMP_9)),
// TIMESTAMP 6
forTypePair(DatetimePair.TIMESTAMP_6_TIMESTAMP_6)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_6_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_6_TIMESTAMP_WLTZ_6)
.firstOpBeSame()
.secondOpMatches(castTo(Types.TIMESTAMP_6)),
forTypePair(DatetimePair.TIMESTAMP_6_TIMESTAMP_WLTZ_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpMatches(castTo(Types.TIMESTAMP_9)),
// TIMESTAMP 9
forTypePair(DatetimePair.TIMESTAMP_9_TIMESTAMP_9)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_9_TIMESTAMP_WLTZ_9)
.firstOpBeSame()
.secondOpMatches(castTo(Types.TIMESTAMP_9)),
// TIMESTAMP LTZ 0
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_WLTZ_0)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_WLTZ_3)
.firstOpMatches(castTo(Types.TIMESTAMP_WLTZ_3))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_WLTZ_6)
.firstOpMatches(castTo(Types.TIMESTAMP_WLTZ_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_WLTZ_9)
.firstOpMatches(castTo(Types.TIMESTAMP_WLTZ_9))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_0)
.firstOpMatches(castTo(Types.TIMESTAMP_0))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_3)
.firstOpMatches(castTo(Types.TIMESTAMP_3))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_6)
.firstOpMatches(castTo(Types.TIMESTAMP_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpBeSame(),
// TIMESTAMP LTZ 3
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_WLTZ_3)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_WLTZ_6)
.firstOpMatches(castTo(Types.TIMESTAMP_WLTZ_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_WLTZ_9)
.firstOpMatches(castTo(Types.TIMESTAMP_WLTZ_9))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_3)
.firstOpMatches(castTo(Types.TIMESTAMP_3))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_6)
.firstOpMatches(castTo(Types.TIMESTAMP_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpBeSame(),
// TIMESTAMP LTZ 6
forTypePair(DatetimePair.TIMESTAMP_WLTZ_6_TIMESTAMP_WLTZ_6)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_6_TIMESTAMP_WLTZ_9)
.firstOpMatches(castTo(Types.TIMESTAMP_WLTZ_9))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_6_TIMESTAMP_6)
.firstOpMatches(castTo(Types.TIMESTAMP_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_6_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpBeSame(),
// TIMESTAMP LTZ 9
forTypePair(DatetimePair.TIMESTAMP_WLTZ_9_TIMESTAMP_WLTZ_9)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_9_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpBeSame()
);
}
/** CASE operands from dynamic params. */
@ParameterizedTest
@MethodSource("dynamicLiteralArgs")
public void caseWithDynamicParamsCoercion(
TypePair typePair,
Matcher<RexNode> firstOperandMatcher,
Matcher<RexNode> secondOperandMatcher
) throws Exception {
List<Object> params = List.of(
SqlTestUtils.generateValueByType(typePair.first()),
SqlTestUtils.generateValueByType(typePair.second())
);
assertPlan("SELECT CASE WHEN RAND_UUID() != RAND_UUID() THEN ? ELSE ? END FROM t", SCHEMA,
operandCaseMatcher(firstOperandMatcher, secondOperandMatcher)::matches, params);
}
private static Stream<Arguments> dynamicLiteralArgs() {
return Stream.of(
forTypePair(DatetimePair.DATE_DATE)
.firstOpBeSame()
.secondOpBeSame(),
// TIME 0
forTypePair(DatetimePair.TIME_0_TIME_0)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM)),
forTypePair(DatetimePair.TIME_0_TIME_3)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM)),
forTypePair(DatetimePair.TIME_0_TIME_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM)),
forTypePair(DatetimePair.TIME_0_TIME_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM)),
// TIME 3
forTypePair(DatetimePair.TIME_3_TIME_3)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM)),
forTypePair(DatetimePair.TIME_3_TIME_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM)),
forTypePair(DatetimePair.TIME_3_TIME_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM)),
// TIME 6
forTypePair(DatetimePair.TIME_6_TIME_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM)),
forTypePair(DatetimePair.TIME_6_TIME_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_DYN_PARAM))
.secondOpBeSame(),
// TIME 9
forTypePair(DatetimePair.TIME_9_TIME_9)
.firstOpBeSame()
.secondOpBeSame(),
// TIMESTAMP 0
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_0)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_3)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_WLTZ_0)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_WLTZ_3)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_WLTZ_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM)),
// TIMESTAMP 3
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_3)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_WLTZ_3)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_WLTZ_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM)),
// TIMESTAMP 6
forTypePair(DatetimePair.TIMESTAMP_6_TIMESTAMP_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_6_TIMESTAMP_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_6_TIMESTAMP_WLTZ_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_6_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM)),
// TIMESTAMP 9
forTypePair(DatetimePair.TIMESTAMP_9_TIMESTAMP_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_9_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM)),
// TIMESTAMP LTZ 0
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_WLTZ_0)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_WLTZ_3)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_WLTZ_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_0)
.firstOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_3)
.firstOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_6)
.firstOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
// TIMESTAMP LTZ 3
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_WLTZ_3)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_WLTZ_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_3)
.firstOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_6)
.firstOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
// TIMESTAMP LTZ 6
forTypePair(DatetimePair.TIMESTAMP_WLTZ_6_TIMESTAMP_WLTZ_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_6_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_6_TIMESTAMP_6)
.firstOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_6_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM)),
// TIMESTAMP LTZ 9
forTypePair(DatetimePair.TIMESTAMP_WLTZ_9_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_DYN_PARAM)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_9_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_DYN_PARAM))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_DYN_PARAM))
);
}
/** CASE operands from literals. */
@ParameterizedTest
@MethodSource("literalArgs")
public void caseWithLiteralsCoercion(
TypePair typePair,
Matcher<RexNode> firstOperandMatcher,
Matcher<RexNode> secondOperandMatcher
) throws Exception {
List<Object> params = List.of(
generateLiteralWithNoRepetition(typePair.first()), generateLiteralWithNoRepetition(typePair.second())
);
assertPlan(format("SELECT CASE WHEN RAND_UUID() != RAND_UUID() THEN {} ELSE {} END FROM t", params.get(0), params.get(1)),
SCHEMA, operandCaseMatcher(firstOperandMatcher, secondOperandMatcher)::matches, List.of());
}
private static Stream<Arguments> literalArgs() {
return Stream.of(
forTypePair(DatetimePair.DATE_DATE)
.firstOpBeSame()
.secondOpBeSame(),
// TIME 0
forTypePair(DatetimePair.TIME_0_TIME_0)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIME_0_TIME_3)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_3))
.secondOpBeSame(),
forTypePair(DatetimePair.TIME_0_TIME_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIME_0_TIME_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_9))
.secondOpBeSame(),
// TIME 3
forTypePair(DatetimePair.TIME_3_TIME_3)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIME_3_TIME_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIME_3_TIME_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_9))
.secondOpBeSame(),
// TIME 6
forTypePair(DatetimePair.TIME_6_TIME_6)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIME_6_TIME_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_9))
.secondOpBeSame(),
// TIME 9
forTypePair(DatetimePair.TIME_9_TIME_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIME_9))
.secondOpMatches(ofTypeWithoutCast(Types.TIME_9)),
// TIMESTAMP 0
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_0)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_3)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_3))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_9))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_WLTZ_0)
.firstOpBeSame()
.secondOpMatches(castTo(Types.TIMESTAMP_0)),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_WLTZ_3)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_3))
.secondOpMatches(castTo(Types.TIMESTAMP_3)),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_WLTZ_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_6))
.secondOpMatches(castTo(Types.TIMESTAMP_6)),
forTypePair(DatetimePair.TIMESTAMP_0_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_9))
.secondOpMatches(castTo(Types.TIMESTAMP_9)),
// TIMESTAMP 3
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_3)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_9))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_WLTZ_3)
.firstOpBeSame()
.secondOpMatches(castTo(Types.TIMESTAMP_3)),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_WLTZ_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_6))
.secondOpMatches(castTo(Types.TIMESTAMP_6)),
forTypePair(DatetimePair.TIMESTAMP_3_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_9))
.secondOpMatches(castTo(Types.TIMESTAMP_9)),
// TIMESTAMP 6
forTypePair(DatetimePair.TIMESTAMP_6_TIMESTAMP_6)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_6_TIMESTAMP_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_9))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_9)),
forTypePair(DatetimePair.TIMESTAMP_6_TIMESTAMP_WLTZ_6)
.firstOpBeSame()
.secondOpMatches(castTo(Types.TIMESTAMP_6)),
forTypePair(DatetimePair.TIMESTAMP_6_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_9))
.secondOpMatches(castTo(Types.TIMESTAMP_9)),
// TIMESTAMP 9
forTypePair(DatetimePair.TIMESTAMP_9_TIMESTAMP_9)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_9_TIMESTAMP_WLTZ_9)
.firstOpBeSame()
.secondOpMatches(castTo(Types.TIMESTAMP_9)),
// TIMESTAMP LTZ 0
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_WLTZ_0)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_WLTZ_3)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_3))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_WLTZ_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_9))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_0)
.firstOpMatches(castTo(Types.TIMESTAMP_0))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_3)
.firstOpMatches(castTo(Types.TIMESTAMP_3))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_6)
.firstOpMatches(castTo(Types.TIMESTAMP_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_0_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpBeSame(),
// TIMESTAMP LTZ 3
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_WLTZ_3)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_WLTZ_6)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_9))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_3)
.firstOpMatches(castTo(Types.TIMESTAMP_3))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_6)
.firstOpMatches(castTo(Types.TIMESTAMP_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_3_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpBeSame(),
// TIMESTAMP LTZ 6
forTypePair(DatetimePair.TIMESTAMP_WLTZ_6_TIMESTAMP_WLTZ_6)
.firstOpBeSame()
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_6_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_9))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_6_TIMESTAMP_6)
.firstOpMatches(castTo(Types.TIMESTAMP_6))
.secondOpBeSame(),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_6_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpBeSame(),
// TIMESTAMP LTZ 9
forTypePair(DatetimePair.TIMESTAMP_WLTZ_9_TIMESTAMP_WLTZ_9)
.firstOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_9))
.secondOpMatches(ofTypeWithoutCast(Types.TIMESTAMP_WLTZ_9)),
forTypePair(DatetimePair.TIMESTAMP_WLTZ_9_TIMESTAMP_9)
.firstOpMatches(castTo(Types.TIMESTAMP_9))
.secondOpBeSame()
);
}
/**
* This test ensures that all test cases don't miss any type pair from {@link DatetimePair}.
*/
@Test
void argsIncludesAllTypePairs() {
checkIncludesAllTypePairs(caseArgs(), DatetimePair.class);
checkIncludesAllTypePairs(dynamicLiteralArgs(), DatetimePair.class);
checkIncludesAllTypePairs(literalArgs(), DatetimePair.class);
}
}
|
googleapis/google-cloud-java | 35,611 | java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/GetRuleRegionSecurityPolicyRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* A request message for RegionSecurityPolicies.GetRule. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest}
*/
public final class GetRuleRegionSecurityPolicyRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest)
GetRuleRegionSecurityPolicyRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetRuleRegionSecurityPolicyRequest.newBuilder() to construct.
private GetRuleRegionSecurityPolicyRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetRuleRegionSecurityPolicyRequest() {
project_ = "";
region_ = "";
securityPolicy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GetRuleRegionSecurityPolicyRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetRuleRegionSecurityPolicyRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetRuleRegionSecurityPolicyRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest.class,
com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest.Builder.class);
}
private int bitField0_;
public static final int PRIORITY_FIELD_NUMBER = 445151652;
private int priority_ = 0;
/**
*
*
* <pre>
* The priority of the rule to get from the security policy.
* </pre>
*
* <code>optional int32 priority = 445151652;</code>
*
* @return Whether the priority field is set.
*/
@java.lang.Override
public boolean hasPriority() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The priority of the rule to get from the security policy.
* </pre>
*
* <code>optional int32 priority = 445151652;</code>
*
* @return The priority.
*/
@java.lang.Override
public int getPriority() {
return priority_;
}
public static final int PROJECT_FIELD_NUMBER = 227560217;
@SuppressWarnings("serial")
private volatile java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The project.
*/
@java.lang.Override
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for project.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int REGION_FIELD_NUMBER = 138946292;
@SuppressWarnings("serial")
private volatile java.lang.Object region_ = "";
/**
*
*
* <pre>
* Name of the region scoping this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The region.
*/
@java.lang.Override
public java.lang.String getRegion() {
java.lang.Object ref = region_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
region_ = s;
return s;
}
}
/**
*
*
* <pre>
* Name of the region scoping this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for region.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRegionBytes() {
java.lang.Object ref = region_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
region_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SECURITY_POLICY_FIELD_NUMBER = 171082513;
@SuppressWarnings("serial")
private volatile java.lang.Object securityPolicy_ = "";
/**
*
*
* <pre>
* Name of the security policy to which the queried rule belongs.
* </pre>
*
* <code>string security_policy = 171082513 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The securityPolicy.
*/
@java.lang.Override
public java.lang.String getSecurityPolicy() {
java.lang.Object ref = securityPolicy_;
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();
securityPolicy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Name of the security policy to which the queried rule belongs.
* </pre>
*
* <code>string security_policy = 171082513 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for securityPolicy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getSecurityPolicyBytes() {
java.lang.Object ref = securityPolicy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
securityPolicy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(region_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 138946292, region_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(securityPolicy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 171082513, securityPolicy_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeInt32(445151652, priority_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(region_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(138946292, region_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(securityPolicy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(171082513, securityPolicy_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(445151652, priority_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest other =
(com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest) obj;
if (hasPriority() != other.hasPriority()) return false;
if (hasPriority()) {
if (getPriority() != other.getPriority()) return false;
}
if (!getProject().equals(other.getProject())) return false;
if (!getRegion().equals(other.getRegion())) return false;
if (!getSecurityPolicy().equals(other.getSecurityPolicy())) 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 (hasPriority()) {
hash = (37 * hash) + PRIORITY_FIELD_NUMBER;
hash = (53 * hash) + getPriority();
}
hash = (37 * hash) + PROJECT_FIELD_NUMBER;
hash = (53 * hash) + getProject().hashCode();
hash = (37 * hash) + REGION_FIELD_NUMBER;
hash = (53 * hash) + getRegion().hashCode();
hash = (37 * hash) + SECURITY_POLICY_FIELD_NUMBER;
hash = (53 * hash) + getSecurityPolicy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A request message for RegionSecurityPolicies.GetRule. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest)
com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetRuleRegionSecurityPolicyRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetRuleRegionSecurityPolicyRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest.class,
com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest.Builder.class);
}
// Construct using com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
priority_ = 0;
project_ = "";
region_ = "";
securityPolicy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetRuleRegionSecurityPolicyRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest
getDefaultInstanceForType() {
return com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest build() {
com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest buildPartial() {
com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest result =
new com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.priority_ = priority_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.project_ = project_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.region_ = region_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.securityPolicy_ = securityPolicy_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest) {
return mergeFrom((com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest other) {
if (other
== com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest.getDefaultInstance())
return this;
if (other.hasPriority()) {
setPriority(other.getPriority());
}
if (!other.getProject().isEmpty()) {
project_ = other.project_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getRegion().isEmpty()) {
region_ = other.region_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getSecurityPolicy().isEmpty()) {
securityPolicy_ = other.securityPolicy_;
bitField0_ |= 0x00000008;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 1111570338:
{
region_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 1111570338
case 1368660106:
{
securityPolicy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 1368660106
case 1820481738:
{
project_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 1820481738
case -733754080:
{
priority_ = input.readInt32();
bitField0_ |= 0x00000001;
break;
} // case -733754080
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 priority_;
/**
*
*
* <pre>
* The priority of the rule to get from the security policy.
* </pre>
*
* <code>optional int32 priority = 445151652;</code>
*
* @return Whether the priority field is set.
*/
@java.lang.Override
public boolean hasPriority() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The priority of the rule to get from the security policy.
* </pre>
*
* <code>optional int32 priority = 445151652;</code>
*
* @return The priority.
*/
@java.lang.Override
public int getPriority() {
return priority_;
}
/**
*
*
* <pre>
* The priority of the rule to get from the security policy.
* </pre>
*
* <code>optional int32 priority = 445151652;</code>
*
* @param value The priority to set.
* @return This builder for chaining.
*/
public Builder setPriority(int value) {
priority_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The priority of the rule to get from the security policy.
* </pre>
*
* <code>optional int32 priority = 445151652;</code>
*
* @return This builder for chaining.
*/
public Builder clearPriority() {
bitField0_ = (bitField0_ & ~0x00000001);
priority_ = 0;
onChanged();
return this;
}
private java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The project.
*/
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for project.
*/
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The project to set.
* @return This builder for chaining.
*/
public Builder setProject(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearProject() {
project_ = getDefaultInstance().getProject();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for project to set.
* @return This builder for chaining.
*/
public Builder setProjectBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object region_ = "";
/**
*
*
* <pre>
* Name of the region scoping this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The region.
*/
public java.lang.String getRegion() {
java.lang.Object ref = region_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
region_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Name of the region scoping this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for region.
*/
public com.google.protobuf.ByteString getRegionBytes() {
java.lang.Object ref = region_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
region_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Name of the region scoping this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The region to set.
* @return This builder for chaining.
*/
public Builder setRegion(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
region_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the region scoping this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearRegion() {
region_ = getDefaultInstance().getRegion();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the region scoping this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for region to set.
* @return This builder for chaining.
*/
public Builder setRegionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
region_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object securityPolicy_ = "";
/**
*
*
* <pre>
* Name of the security policy to which the queried rule belongs.
* </pre>
*
* <code>string security_policy = 171082513 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The securityPolicy.
*/
public java.lang.String getSecurityPolicy() {
java.lang.Object ref = securityPolicy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
securityPolicy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Name of the security policy to which the queried rule belongs.
* </pre>
*
* <code>string security_policy = 171082513 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for securityPolicy.
*/
public com.google.protobuf.ByteString getSecurityPolicyBytes() {
java.lang.Object ref = securityPolicy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
securityPolicy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Name of the security policy to which the queried rule belongs.
* </pre>
*
* <code>string security_policy = 171082513 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The securityPolicy to set.
* @return This builder for chaining.
*/
public Builder setSecurityPolicy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
securityPolicy_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the security policy to which the queried rule belongs.
* </pre>
*
* <code>string security_policy = 171082513 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearSecurityPolicy() {
securityPolicy_ = getDefaultInstance().getSecurityPolicy();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the security policy to which the queried rule belongs.
* </pre>
*
* <code>string security_policy = 171082513 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for securityPolicy to set.
* @return This builder for chaining.
*/
public Builder setSecurityPolicyBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
securityPolicy_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest)
private static final com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest();
}
public static com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetRuleRegionSecurityPolicyRequest> PARSER =
new com.google.protobuf.AbstractParser<GetRuleRegionSecurityPolicyRequest>() {
@java.lang.Override
public GetRuleRegionSecurityPolicyRequest 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<GetRuleRegionSecurityPolicyRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetRuleRegionSecurityPolicyRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.GetRuleRegionSecurityPolicyRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/geode | 35,535 | geode-core/src/distributedTest/java/org/apache/geode/disttx/DistTXDebugDUnitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.disttx;
import static org.apache.geode.test.dunit.Assert.assertEquals;
import static org.apache.geode.test.dunit.Assert.assertNotNull;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import org.junit.Test;
import org.apache.geode.DataSerializable;
import org.apache.geode.DataSerializer;
import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.CacheException;
import org.apache.geode.cache.CacheTransactionManager;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.EntryOperation;
import org.apache.geode.cache.PartitionAttributes;
import org.apache.geode.cache.PartitionAttributesFactory;
import org.apache.geode.cache.PartitionResolver;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.Scope;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.internal.cache.control.InternalResourceManager;
import org.apache.geode.internal.cache.execute.CustomerIDPartitionResolver;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.Invoke;
import org.apache.geode.test.dunit.LogWriterUtils;
import org.apache.geode.test.dunit.SerializableCallable;
import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
/**
* TODO: reenable this test and fix it when work on Dist TX resumes -- it fails with no members to
* host buckets
*/
public class DistTXDebugDUnitTest extends JUnit4CacheTestCase {
protected VM accessor = null;
protected VM dataStore1 = null;
protected VM dataStore2 = null;
private VM dataStore3 = null;
@Override
public final void postSetUp() throws Exception {
Host host = Host.getHost(0);
dataStore1 = host.getVM(0);
dataStore2 = host.getVM(1);
dataStore3 = host.getVM(2);
accessor = host.getVM(3);
postSetUpDistTXDebugDUnitTest();
}
protected void postSetUpDistTXDebugDUnitTest() throws Exception {}
@Override
public final void postTearDownCacheTestCase() throws Exception {
Invoke.invokeInEveryVM(new SerializableRunnable() {
@Override
public void run() {
InternalResourceManager.setResourceObserver(null);
}
});
InternalResourceManager.setResourceObserver(null);
}
private void createCacheInVm() {
getCache();
}
protected void createCacheInAllVms() {
dataStore1.invoke(this::createCacheInVm);
dataStore2.invoke(this::createCacheInVm);
dataStore3.invoke(this::createCacheInVm);
accessor.invoke(this::createCacheInVm);
}
public static void createPR(String partitionedRegionName, Integer redundancy,
Integer localMaxMemory, Integer totalNumBuckets, Object colocatedWith,
Boolean isPartitionResolver) {
createPR(partitionedRegionName, redundancy, localMaxMemory, totalNumBuckets, colocatedWith,
isPartitionResolver, Boolean.TRUE/* Concurrency checks; By default is false */);
}
public static void createPR(String partitionedRegionName, Integer redundancy,
Integer localMaxMemory, Integer totalNumBuckets, Object colocatedWith,
Boolean isPartitionResolver, Boolean concurrencyChecks) {
PartitionAttributesFactory<String, String> paf = new PartitionAttributesFactory();
paf.setRedundantCopies(redundancy);
if (localMaxMemory != null) {
paf.setLocalMaxMemory(localMaxMemory);
}
if (totalNumBuckets != null) {
paf.setTotalNumBuckets(totalNumBuckets);
}
if (colocatedWith != null) {
paf.setColocatedWith((String) colocatedWith);
}
if (isPartitionResolver) {
paf.setPartitionResolver(new CustomerIDPartitionResolver("CustomerIDPartitionResolver"));
}
PartitionAttributes<String, String> prAttr = paf.create();
AttributesFactory<String, String> attr = new AttributesFactory();
attr.setPartitionAttributes(prAttr);
attr.setConcurrencyChecksEnabled(concurrencyChecks);
assertNotNull(basicGetCache());
Region<String, String> pr = basicGetCache().createRegion(partitionedRegionName, attr.create());
assertNotNull(pr);
LogWriterUtils.getLogWriter().info(
"Partitioned Region " + partitionedRegionName + " created Successfully :" + pr);
}
protected void createPartitionedRegion(Object[] attributes) {
dataStore1.invoke(DistTXDebugDUnitTest.class, "createPR", attributes);
dataStore2.invoke(DistTXDebugDUnitTest.class, "createPR", attributes);
dataStore3.invoke(DistTXDebugDUnitTest.class, "createPR", attributes);
// make Local max memory = o for accessor
attributes[2] = 0;
accessor.invoke(DistTXDebugDUnitTest.class, "createPR", attributes);
}
public static void destroyPR(String partitionedRegionName) {
// assertNotNull(basicGetCache());
// Region pr = basicGetCache().getRegion(partitionedRegionName);
assertNotNull(basicGetCache());
Region pr = basicGetCache().getRegion(partitionedRegionName);
assertNotNull(pr);
LogWriterUtils.getLogWriter().info("Destroying Partitioned Region " + partitionedRegionName);
pr.destroyRegion();
}
public static void createRR(String replicatedRegionName, boolean empty) {
AttributesFactory af = new AttributesFactory();
af.setScope(Scope.DISTRIBUTED_ACK);
if (empty) {
af.setDataPolicy(DataPolicy.EMPTY);
} else {
af.setDataPolicy(DataPolicy.REPLICATE);
}
// Region rr = basicGetCache().createRegion(replicatedRegionName,
// af.create());
Region rr = basicGetCache().createRegion(replicatedRegionName, af.create());
assertNotNull(rr);
LogWriterUtils.getLogWriter().info(
"Replicated Region " + replicatedRegionName + " created Successfully :" + rr);
}
protected void createReplicatedRegion(Object[] attributes) {
dataStore1.invoke(DistTXDebugDUnitTest.class, "createRR", attributes);
dataStore2.invoke(DistTXDebugDUnitTest.class, "createRR", attributes);
dataStore3.invoke(DistTXDebugDUnitTest.class, "createRR", attributes);
// DataPolicy.EMPTY for accessor
attributes[1] = Boolean.TRUE;
accessor.invoke(DistTXDebugDUnitTest.class, "createRR", attributes);
}
@Test
public void testTXPR() throws Exception {
createCacheInAllVms();
Object[] prAttrs = new Object[] {"pregion1", 1, null, 3, null, Boolean.FALSE, Boolean.FALSE};
createPartitionedRegion(prAttrs);
SerializableCallable TxOps = new SerializableCallable("TxOps") {
@Override
public Object call() throws CacheException {
// PartitionedRegion pr1 = (PartitionedRegion)
// basicGetCache().getRegion(
// "pregion1");
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
// put some data (non tx ops)
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.put");
pr1.put(dummy, "1_entry__" + i);
}
// put in tx and commit
// CacheTransactionManager ctx = basicGetCache()
// .getCacheTransactionManager();
CacheTransactionManager ctx = basicGetCache().getCacheTransactionManager();
ctx.setDistributed(true);
ctx.begin();
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.put in tx 1");
pr1.put(dummy, "2_entry__" + i);
}
ctx.commit();
// verify the data
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.get");
assertEquals("2_entry__" + i, pr1.get(dummy));
}
// put data in tx and rollback
ctx.begin();
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.put in tx 2");
pr1.put(dummy, "3_entry__" + i);
}
ctx.rollback();
// verify the data
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.get");
assertEquals("2_entry__" + i, pr1.get(dummy));
}
// destroy data in tx and commit
ctx.begin();
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.destroy in tx 3");
pr1.destroy(dummy);
}
ctx.commit();
// verify the data
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.get");
assertEquals(null, pr1.get(dummy));
}
// verify data size on all replicas
SerializableCallable verifySize = new SerializableCallable("getOps") {
@Override
public Object call() throws CacheException {
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
LogWriterUtils.getLogWriter()
.info(" calling pr.getLocalSize " + pr1.getLocalSizeForTest());
assertEquals(0, pr1.getLocalSizeForTest());
return null;
}
};
dataStore1.invoke(verifySize);
dataStore2.invoke(verifySize);
dataStore3.invoke(verifySize);
return null;
}
};
accessor.invoke(TxOps);
accessor.invoke(() -> DistTXDebugDUnitTest.destroyPR("pregion1"));
}
@Test
public void testTXDestroy_invalidate() throws Exception {
createCacheInAllVms();
Object[] prAttrs = new Object[] {"pregion1", 1, null, 3, null, Boolean.FALSE, Boolean.FALSE};
createPartitionedRegion(prAttrs);
Object[] rrAttrs = new Object[] {"rregion1", Boolean.FALSE};
createReplicatedRegion(rrAttrs);
SerializableCallable TxOps = new SerializableCallable("TxOps") {
@Override
public Object call() throws CacheException {
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
Region rr1 = basicGetCache().getRegion("rregion1");
// put some data (non tx ops)
for (int i = 1; i <= 6; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling non-tx put");
pr1.put(dummy, "1_entry__" + i);
rr1.put(dummy, "1_entry__" + i);
}
CacheTransactionManager ctx = basicGetCache().getCacheTransactionManager();
ctx.setDistributed(true);
// destroy data in tx and commit
ctx.begin();
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr1.destroy in tx key=" + dummy);
pr1.destroy(dummy);
LogWriterUtils.getLogWriter().info(" calling rr1.destroy in tx key=" + i);
rr1.destroy(dummy);
}
for (int i = 4; i <= 6; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr1.invalidate in tx key=" + dummy);
pr1.invalidate(dummy);
LogWriterUtils.getLogWriter().info(" calling rr1.invalidate in tx key=" + i);
rr1.invalidate(dummy);
}
ctx.commit();
// verify the data
for (int i = 1; i <= 6; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr1.get");
assertEquals(null, pr1.get(dummy));
LogWriterUtils.getLogWriter().info(" calling rr1.get");
assertEquals(null, rr1.get(i));
}
return null;
}
};
accessor.invoke(TxOps);
// verify data size on all replicas
SerializableCallable verifySize = new SerializableCallable("getOps") {
@Override
public Object call() throws CacheException {
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
Region rr1 = basicGetCache().getRegion("rregion1");
LogWriterUtils.getLogWriter()
.info(" calling pr1.getLocalSize " + pr1.getLocalSizeForTest());
assertEquals(2, pr1.getLocalSizeForTest());
LogWriterUtils.getLogWriter().info(" calling rr1.size " + rr1.size());
assertEquals(3, rr1.size());
return null;
}
};
dataStore1.invoke(verifySize);
dataStore2.invoke(verifySize);
dataStore3.invoke(verifySize);
accessor.invoke(() -> DistTXDebugDUnitTest.destroyPR("pregion1"));
}
@Test
public void testTXPR_RR() throws Exception {
createCacheInAllVms();
Object[] prAttrs = new Object[] {"pregion1", 1, null, 3, null, Boolean.FALSE, Boolean.FALSE};
createPartitionedRegion(prAttrs);
Object[] rrAttrs = new Object[] {"rregion1", Boolean.FALSE};
createReplicatedRegion(rrAttrs);
SerializableCallable TxOps = new SerializableCallable("TxOps") {
@Override
public Object call() throws CacheException {
// PartitionedRegion pr1 = (PartitionedRegion)
// basicGetCache().getRegion(
// "pregion1");
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
// Region rr1 = basicGetCache().getRegion("rregion1");
Region rr1 = basicGetCache().getRegion("rregion1");
// put some data (non tx ops)
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.put non-tx PR1_entry__" + i);
pr1.put(dummy, "PR1_entry__" + i);
LogWriterUtils.getLogWriter().info(" calling rr.put non-tx RR1_entry__" + i);
rr1.put(i, "RR1_entry__" + i);
}
// put in tx and commit
// CacheTransactionManager ctx = basicGetCache()
// .getCacheTransactionManager();
CacheTransactionManager ctx = basicGetCache().getCacheTransactionManager();
ctx.setDistributed(true);
ctx.begin();
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.put in tx PR2_entry__" + i);
pr1.put(dummy, "PR2_entry__" + i);
LogWriterUtils.getLogWriter().info(" calling rr.put in tx RR2_entry__" + i);
rr1.put(i, "RR2_entry__" + i);
}
ctx.commit();
// verify the data
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.get PR2_entry__" + i);
assertEquals("PR2_entry__" + i, pr1.get(dummy));
LogWriterUtils.getLogWriter().info(" calling rr.get RR2_entry__" + i);
assertEquals("RR2_entry__" + i, rr1.get(i));
}
return null;
}
};
accessor.invoke(TxOps);
// verify data size on all replicas
SerializableCallable verifySize = new SerializableCallable("getOps") {
@Override
public Object call() throws CacheException {
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
LogWriterUtils.getLogWriter().info(" calling pr.getLocalSize " + pr1.getLocalSizeForTest());
assertEquals(2, pr1.getLocalSizeForTest());
Region rr1 = basicGetCache().getRegion("rregion1");
LogWriterUtils.getLogWriter().info(" calling rr.getLocalSize " + rr1.size());
assertEquals(3, rr1.size());
return null;
}
};
dataStore1.invoke(verifySize);
dataStore2.invoke(verifySize);
dataStore3.invoke(verifySize);
accessor.invoke(() -> DistTXDebugDUnitTest.destroyPR("pregion1"));
}
@Test
public void testTXPR2() throws Exception {
createCacheInAllVms();
Object[] prAttrs = new Object[] {"pregion1", 1, null, 3, null, Boolean.FALSE, Boolean.FALSE};
createPartitionedRegion(prAttrs);
SerializableCallable TxOps = new SerializableCallable("TxOps") {
@Override
public Object call() throws CacheException {
// PartitionedRegion pr1 = (PartitionedRegion)
// basicGetCache().getRegion(
// "pregion1");
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
// put in tx and commit
// CacheTransactionManager ctx = basicGetCache()
// .getCacheTransactionManager();
CacheTransactionManager ctx = basicGetCache().getCacheTransactionManager();
ctx.setDistributed(true);
ctx.begin();
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.put in tx 1");
pr1.put(dummy, "2_entry__" + i);
}
ctx.commit();
// verify the data
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.get " + pr1.get(dummy));
assertEquals("2_entry__" + i, pr1.get(dummy));
}
return null;
}
};
accessor.invoke(TxOps);
SerializableCallable TxGetOps = new SerializableCallable("TxGetOps") {
@Override
public Object call() throws CacheException {
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
CacheTransactionManager ctx = basicGetCache().getCacheTransactionManager();
LogWriterUtils.getLogWriter().info(" calling pr.getLocalSize " + pr1.getLocalSizeForTest());
assertEquals(2, pr1.getLocalSizeForTest());
return null;
}
};
dataStore1.invoke(TxGetOps);
dataStore2.invoke(TxGetOps);
dataStore3.invoke(TxGetOps);
SerializableCallable TxRollbackOps = new SerializableCallable("TxOps") {
@Override
public Object call() throws CacheException {
// PartitionedRegion pr1 = (PartitionedRegion)
// basicGetCache().getRegion(
// "pregion1");
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
// put in tx and commit
// CacheTransactionManager ctx = basicGetCache()
// .getCacheTransactionManager();
CacheTransactionManager ctx = basicGetCache().getCacheTransactionManager();
ctx.setDistributed(true);
ctx.begin();
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.put in tx for rollback no_entry__" + i);
pr1.put(dummy, "no_entry__" + i);
}
ctx.rollback();
// verify the data
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.get after rollback " + pr1.get(dummy));
assertEquals("2_entry__" + i, pr1.get(dummy));
}
return null;
}
};
accessor.invoke(TxRollbackOps);
accessor.invoke(() -> DistTXDebugDUnitTest.destroyPR("pregion1"));
}
@Test
public void testTXPRRR2_create() throws Exception {
createCacheInAllVms();
Object[] prAttrs = new Object[] {"pregion1", 1, null, 3, null, Boolean.FALSE, Boolean.FALSE};
createPartitionedRegion(prAttrs);
Object[] rrAttrs = new Object[] {"rregion1", Boolean.FALSE};
createReplicatedRegion(rrAttrs);
SerializableCallable TxOps = new SerializableCallable("TxOps") {
@Override
public Object call() throws CacheException {
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
Region rr1 = basicGetCache().getRegion("rregion1");
CacheTransactionManager ctx = basicGetCache().getCacheTransactionManager();
ctx.setDistributed(true);
ctx.begin();
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.create in tx 1");
pr1.create(dummy, "2_entry__" + i);
LogWriterUtils.getLogWriter().info(" calling rr.create " + "2_entry__" + i);
rr1.create(i, "2_entry__" + i);
}
ctx.commit();
// verify the data
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.get " + pr1.get(dummy));
assertEquals("2_entry__" + i, pr1.get(dummy));
LogWriterUtils.getLogWriter().info(" calling rr.get " + rr1.get(i));
assertEquals("2_entry__" + i, rr1.get(i));
}
return null;
}
};
accessor.invoke(TxOps);
// verify data size on all replicas
SerializableCallable verifySize = new SerializableCallable("getOps") {
@Override
public Object call() throws CacheException {
Region rr1 = basicGetCache().getRegion("rregion1");
LogWriterUtils.getLogWriter().info(" calling rr.getLocalSize " + rr1.size());
assertEquals(3, rr1.size());
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
LogWriterUtils.getLogWriter().info(" calling pr.getLocalSize " + pr1.getLocalSizeForTest());
assertEquals(2, pr1.getLocalSizeForTest());
return null;
}
};
dataStore1.invoke(verifySize);
dataStore2.invoke(verifySize);
dataStore3.invoke(verifySize);
}
@Test
public void testTXPRRR2_putall() throws Exception {
createCacheInAllVms();
Object[] prAttrs = new Object[] {"pregion1", 1, null, 3, null, Boolean.FALSE, Boolean.FALSE};
createPartitionedRegion(prAttrs);
Object[] rrAttrs = new Object[] {"rregion1", Boolean.FALSE};
createReplicatedRegion(rrAttrs);
SerializableCallable TxOps = new SerializableCallable("TxOps") {
@Override
public Object call() throws CacheException {
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
Region rr1 = basicGetCache().getRegion("rregion1");
CacheTransactionManager ctx = basicGetCache().getCacheTransactionManager();
ctx.setDistributed(true);
ctx.begin();
HashMap<DummyKeyBasedRoutingResolver, String> phm =
new HashMap<>();
HashMap<Integer, String> rhm = new HashMap<>();
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
phm.put(dummy, "2_entry__" + i);
rhm.put(i, "2_entry__" + i);
}
pr1.putAll(phm);
rr1.putAll(rhm);
ctx.commit();
// verify the data
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.get " + pr1.get(dummy));
assertEquals("2_entry__" + i, pr1.get(dummy));
LogWriterUtils.getLogWriter().info(" calling rr.get " + rr1.get(i));
assertEquals("2_entry__" + i, rr1.get(i));
}
return null;
}
};
accessor.invoke(TxOps);
// verify data size on all replicas
SerializableCallable verifySize = new SerializableCallable("getOps") {
@Override
public Object call() throws CacheException {
Region rr1 = basicGetCache().getRegion("rregion1");
LogWriterUtils.getLogWriter().info(" calling rr.getLocalSize " + rr1.size());
assertEquals(3, rr1.size());
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
LogWriterUtils.getLogWriter().info(" calling pr.getLocalSize " + pr1.getLocalSizeForTest());
assertEquals(2, pr1.getLocalSizeForTest());
return null;
}
};
dataStore1.invoke(verifySize);
dataStore2.invoke(verifySize);
dataStore3.invoke(verifySize);
// accessor.invoke(TxOps);
}
@Test
public void testTXPR_putall() throws Exception {
createCacheInAllVms();
Object[] prAttrs = new Object[] {"pregion1", 1, null, 3, null, Boolean.FALSE, Boolean.FALSE};
createPartitionedRegion(prAttrs);
SerializableCallable TxOps = new SerializableCallable("TxOps") {
@Override
public Object call() throws CacheException {
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
CacheTransactionManager ctx = basicGetCache().getCacheTransactionManager();
ctx.setDistributed(true);
ctx.begin();
HashMap<DummyKeyBasedRoutingResolver, String> phm =
new HashMap<>();
HashMap<Integer, String> rhm = new HashMap<>();
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
phm.put(dummy, "2_entry__" + i);
}
pr1.putAll(phm);
ctx.commit();
// verify the data
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.get " + pr1.get(dummy));
assertEquals("2_entry__" + i, pr1.get(dummy));
}
return null;
}
};
// dataStore1.invoke(TxOps);
accessor.invoke(TxOps);
// verify data size on all replicas
SerializableCallable verifySize = new SerializableCallable("getOps") {
@Override
public Object call() throws CacheException {
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
LogWriterUtils.getLogWriter().info(" calling pr.getLocalSize " + pr1.getLocalSizeForTest());
assertEquals(2, pr1.getLocalSizeForTest());
return null;
}
};
dataStore1.invoke(verifySize);
dataStore2.invoke(verifySize);
dataStore3.invoke(verifySize);
// accessor.invoke(TxOps);
}
@Test
public void testTXRR_removeAll() throws Exception {
performRR_removeAllTest(false);
}
@Test
public void testTXRR_removeAll_dataNodeAsCoordinator() throws Exception {
performRR_removeAllTest(true);
}
/**
* @param dataNodeAsCoordinator TODO
*
*/
private void performRR_removeAllTest(boolean dataNodeAsCoordinator) {
createCacheInAllVms();
Object[] rrAttrs = new Object[] {"rregion1", Boolean.FALSE};
createReplicatedRegion(rrAttrs);
SerializableCallable TxOps = new SerializableCallable("TxOps") {
@Override
public Object call() throws CacheException {
Region rr1 = basicGetCache().getRegion("rregion1");
// put some data
HashMap<Integer, String> rhm = new HashMap<>();
for (int i = 1; i <= 3; i++) {
rhm.put(i, "2_entry__" + i);
}
rr1.putAll(rhm);
CacheTransactionManager ctx = basicGetCache().getCacheTransactionManager();
ctx.setDistributed(true);
ctx.begin();
rr1.removeAll(rhm.keySet());
ctx.commit();
// verify the data
for (int i = 1; i <= 3; i++) {
LogWriterUtils.getLogWriter().info(" calling rr.get " + rr1.get(i));
assertEquals(null, rr1.get(i));
}
return null;
}
};
if (dataNodeAsCoordinator) {
dataStore1.invoke(TxOps);
} else {
accessor.invoke(TxOps);
}
// verify data size on all replicas
SerializableCallable verifySize = new SerializableCallable("getOps") {
@Override
public Object call() throws CacheException {
Region rr1 = basicGetCache().getRegion("rregion1");
LogWriterUtils.getLogWriter().info(" calling rr.getLocalSize " + rr1.size());
assertEquals(0, rr1.size());
return null;
}
};
dataStore1.invoke(verifySize);
dataStore2.invoke(verifySize);
dataStore3.invoke(verifySize);
// accessor.invoke(TxOps);
}
@Test
public void testTXPR_removeAll() throws Exception {
createCacheInAllVms();
Object[] prAttrs = new Object[] {"pregion1", 1, null, 3, null, Boolean.FALSE, Boolean.FALSE};
createPartitionedRegion(prAttrs);
SerializableCallable TxOps = new SerializableCallable("TxOps") {
@Override
public Object call() throws CacheException {
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
HashMap<DummyKeyBasedRoutingResolver, String> phm =
new HashMap<>();
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
phm.put(dummy, "2_entry__" + i);
}
pr1.putAll(phm);
CacheTransactionManager ctx = basicGetCache().getCacheTransactionManager();
ctx.setDistributed(true);
ctx.begin();
pr1.removeAll(phm.keySet());
ctx.commit();
// verify the data
for (int i = 1; i <= 3; i++) {
DummyKeyBasedRoutingResolver dummy = new DummyKeyBasedRoutingResolver(i);
LogWriterUtils.getLogWriter().info(" calling pr.get " + pr1.get(dummy));
assertEquals(null, pr1.get(dummy));
}
return null;
}
};
accessor.invoke(TxOps);
// verify data size on all replicas
SerializableCallable verifySize = new SerializableCallable("getOps") {
@Override
public Object call() throws CacheException {
PartitionedRegion pr1 = (PartitionedRegion) basicGetCache().getRegion("pregion1");
LogWriterUtils.getLogWriter().info(" calling pr.getLocalSize " + pr1.getLocalSizeForTest());
assertEquals(0, pr1.getLocalSizeForTest());
return null;
}
};
dataStore1.invoke(verifySize);
dataStore2.invoke(verifySize);
dataStore3.invoke(verifySize);
// accessor.invoke(TxOps);
}
public void performTXRRtestOps(boolean makeDatNodeAsCoordinator) {
createCacheInAllVms();
Object[] prAttrs = new Object[] {"pregion1", 1, null, 3, null, Boolean.FALSE, Boolean.FALSE};
createPartitionedRegion(prAttrs);
Object[] rrAttrs = new Object[] {"rregion1", Boolean.FALSE};
createReplicatedRegion(rrAttrs);
SerializableCallable TxOps = new SerializableCallable("TxOps") {
@Override
public Object call() throws CacheException {
Region rr1 = basicGetCache().getRegion("rregion1");
CacheTransactionManager ctx = basicGetCache().getCacheTransactionManager();
ctx.setDistributed(true);
ctx.begin();
for (int i = 1; i <= 3; i++) {
LogWriterUtils.getLogWriter().info(" calling rr.put " + "2_entry__" + i);
rr1.put(i, "2_entry__" + i);
}
ctx.commit();
// verify the data
for (int i = 1; i <= 3; i++) {
LogWriterUtils.getLogWriter().info(" calling rr.get " + rr1.get(i));
assertEquals("2_entry__" + i, rr1.get(i));
}
return null;
}
};
if (makeDatNodeAsCoordinator) {
dataStore1.invoke(TxOps);
} else {
accessor.invoke(TxOps);
}
// verify data size on all replicas
SerializableCallable verifySize = new SerializableCallable("getOps") {
@Override
public Object call() throws CacheException {
Region rr1 = basicGetCache().getRegion("rregion1");
LogWriterUtils.getLogWriter().info(" calling rr.getLocalSize " + rr1.size());
assertEquals(3, rr1.size());
return null;
}
};
dataStore1.invoke(verifySize);
dataStore2.invoke(verifySize);
dataStore3.invoke(verifySize);
SerializableCallable TxRollbackOps = new SerializableCallable("TxOps") {
@Override
public Object call() throws CacheException {
Region rr1 = basicGetCache().getRegion("rregion1");
CacheTransactionManager ctx = basicGetCache().getCacheTransactionManager();
ctx.setDistributed(true);
ctx.begin();
for (int i = 1; i <= 3; i++) {
LogWriterUtils.getLogWriter().info(" calling rr.put for rollback no_entry__" + i);
rr1.put(i, "no_entry__" + i);
}
ctx.rollback();
// verify the data
for (int i = 1; i <= 3; i++) {
LogWriterUtils.getLogWriter()
.info(" calling rr.get after rollback " + rr1.get(i));
assertEquals("2_entry__" + i, rr1.get(i));
}
return null;
}
};
if (makeDatNodeAsCoordinator) {
dataStore1.invoke(TxRollbackOps);
} else {
accessor.invoke(TxRollbackOps);
}
}
@Test
public void testTXRR2() throws Exception {
performTXRRtestOps(false); // actual test
}
@Test
public void testTXRR2_dataNodeAsCoordinator() throws Exception {
performTXRRtestOps(true);
}
private static class DummyKeyBasedRoutingResolver implements PartitionResolver, DataSerializable {
Integer dummyID;
public DummyKeyBasedRoutingResolver() {}
public DummyKeyBasedRoutingResolver(int id) {
dummyID = id;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
@Override
public Serializable getRoutingObject(EntryOperation opDetails) {
return (Serializable) opDetails.getKey();
}
@Override
public void close() {
// TODO Auto-generated method stub
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
dummyID = DataSerializer.readInteger(in);
}
@Override
public void toData(DataOutput out) throws IOException {
DataSerializer.writeInteger(dummyID, out);
}
@Override
public int hashCode() {
int i = dummyID;
return i;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof DummyKeyBasedRoutingResolver)) {
return false;
}
DummyKeyBasedRoutingResolver otherDummyID = (DummyKeyBasedRoutingResolver) o;
return (otherDummyID.dummyID.equals(dummyID));
}
}
}
|
googleapis/google-cloud-java | 35,675 | java-contact-center-insights/proto-google-cloud-contact-center-insights-v1/src/main/java/com/google/cloud/contactcenterinsights/v1/UpdateAnalysisRuleRequest.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/contactcenterinsights/v1/contact_center_insights.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.contactcenterinsights.v1;
/**
*
*
* <pre>
* The request to update a analysis rule.
* </pre>
*
* Protobuf type {@code google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest}
*/
public final class UpdateAnalysisRuleRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest)
UpdateAnalysisRuleRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateAnalysisRuleRequest.newBuilder() to construct.
private UpdateAnalysisRuleRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateAnalysisRuleRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateAnalysisRuleRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_UpdateAnalysisRuleRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_UpdateAnalysisRuleRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest.class,
com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest.Builder.class);
}
private int bitField0_;
public static final int ANALYSIS_RULE_FIELD_NUMBER = 1;
private com.google.cloud.contactcenterinsights.v1.AnalysisRule analysisRule_;
/**
*
*
* <pre>
* Required. The new analysis rule.
* </pre>
*
* <code>
* .google.cloud.contactcenterinsights.v1.AnalysisRule analysis_rule = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the analysisRule field is set.
*/
@java.lang.Override
public boolean hasAnalysisRule() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The new analysis rule.
* </pre>
*
* <code>
* .google.cloud.contactcenterinsights.v1.AnalysisRule analysis_rule = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The analysisRule.
*/
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.AnalysisRule getAnalysisRule() {
return analysisRule_ == null
? com.google.cloud.contactcenterinsights.v1.AnalysisRule.getDefaultInstance()
: analysisRule_;
}
/**
*
*
* <pre>
* Required. The new analysis rule.
* </pre>
*
* <code>
* .google.cloud.contactcenterinsights.v1.AnalysisRule analysis_rule = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.AnalysisRuleOrBuilder
getAnalysisRuleOrBuilder() {
return analysisRule_ == null
? com.google.cloud.contactcenterinsights.v1.AnalysisRule.getDefaultInstance()
: analysisRule_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Optional. The list of fields to be updated.
* If the update_mask is not provided, the update will be applied to all
* fields.
* </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. The list of fields to be updated.
* If the update_mask is not provided, the update will be applied to all
* fields.
* </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. The list of fields to be updated.
* If the update_mask is not provided, the update will be applied to all
* fields.
* </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, getAnalysisRule());
}
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, getAnalysisRule());
}
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.contactcenterinsights.v1.UpdateAnalysisRuleRequest)) {
return super.equals(obj);
}
com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest other =
(com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest) obj;
if (hasAnalysisRule() != other.hasAnalysisRule()) return false;
if (hasAnalysisRule()) {
if (!getAnalysisRule().equals(other.getAnalysisRule())) 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 (hasAnalysisRule()) {
hash = (37 * hash) + ANALYSIS_RULE_FIELD_NUMBER;
hash = (53 * hash) + getAnalysisRule().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.contactcenterinsights.v1.UpdateAnalysisRuleRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest 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.contactcenterinsights.v1.UpdateAnalysisRuleRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest 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.contactcenterinsights.v1.UpdateAnalysisRuleRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest 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.contactcenterinsights.v1.UpdateAnalysisRuleRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest
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.contactcenterinsights.v1.UpdateAnalysisRuleRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest 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.contactcenterinsights.v1.UpdateAnalysisRuleRequest 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 to update a analysis rule.
* </pre>
*
* Protobuf type {@code google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest)
com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_UpdateAnalysisRuleRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_UpdateAnalysisRuleRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest.class,
com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest.Builder.class);
}
// Construct using
// com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getAnalysisRuleFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
analysisRule_ = null;
if (analysisRuleBuilder_ != null) {
analysisRuleBuilder_.dispose();
analysisRuleBuilder_ = 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.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_UpdateAnalysisRuleRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest
getDefaultInstanceForType() {
return com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest build() {
com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest buildPartial() {
com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest result =
new com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.analysisRule_ =
analysisRuleBuilder_ == null ? analysisRule_ : analysisRuleBuilder_.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.contactcenterinsights.v1.UpdateAnalysisRuleRequest) {
return mergeFrom(
(com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest other) {
if (other
== com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest
.getDefaultInstance()) return this;
if (other.hasAnalysisRule()) {
mergeAnalysisRule(other.getAnalysisRule());
}
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(getAnalysisRuleFieldBuilder().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.contactcenterinsights.v1.AnalysisRule analysisRule_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.contactcenterinsights.v1.AnalysisRule,
com.google.cloud.contactcenterinsights.v1.AnalysisRule.Builder,
com.google.cloud.contactcenterinsights.v1.AnalysisRuleOrBuilder>
analysisRuleBuilder_;
/**
*
*
* <pre>
* Required. The new analysis rule.
* </pre>
*
* <code>
* .google.cloud.contactcenterinsights.v1.AnalysisRule analysis_rule = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the analysisRule field is set.
*/
public boolean hasAnalysisRule() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The new analysis rule.
* </pre>
*
* <code>
* .google.cloud.contactcenterinsights.v1.AnalysisRule analysis_rule = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The analysisRule.
*/
public com.google.cloud.contactcenterinsights.v1.AnalysisRule getAnalysisRule() {
if (analysisRuleBuilder_ == null) {
return analysisRule_ == null
? com.google.cloud.contactcenterinsights.v1.AnalysisRule.getDefaultInstance()
: analysisRule_;
} else {
return analysisRuleBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The new analysis rule.
* </pre>
*
* <code>
* .google.cloud.contactcenterinsights.v1.AnalysisRule analysis_rule = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setAnalysisRule(com.google.cloud.contactcenterinsights.v1.AnalysisRule value) {
if (analysisRuleBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
analysisRule_ = value;
} else {
analysisRuleBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The new analysis rule.
* </pre>
*
* <code>
* .google.cloud.contactcenterinsights.v1.AnalysisRule analysis_rule = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setAnalysisRule(
com.google.cloud.contactcenterinsights.v1.AnalysisRule.Builder builderForValue) {
if (analysisRuleBuilder_ == null) {
analysisRule_ = builderForValue.build();
} else {
analysisRuleBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The new analysis rule.
* </pre>
*
* <code>
* .google.cloud.contactcenterinsights.v1.AnalysisRule analysis_rule = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeAnalysisRule(com.google.cloud.contactcenterinsights.v1.AnalysisRule value) {
if (analysisRuleBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& analysisRule_ != null
&& analysisRule_
!= com.google.cloud.contactcenterinsights.v1.AnalysisRule.getDefaultInstance()) {
getAnalysisRuleBuilder().mergeFrom(value);
} else {
analysisRule_ = value;
}
} else {
analysisRuleBuilder_.mergeFrom(value);
}
if (analysisRule_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The new analysis rule.
* </pre>
*
* <code>
* .google.cloud.contactcenterinsights.v1.AnalysisRule analysis_rule = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearAnalysisRule() {
bitField0_ = (bitField0_ & ~0x00000001);
analysisRule_ = null;
if (analysisRuleBuilder_ != null) {
analysisRuleBuilder_.dispose();
analysisRuleBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The new analysis rule.
* </pre>
*
* <code>
* .google.cloud.contactcenterinsights.v1.AnalysisRule analysis_rule = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.contactcenterinsights.v1.AnalysisRule.Builder getAnalysisRuleBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getAnalysisRuleFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The new analysis rule.
* </pre>
*
* <code>
* .google.cloud.contactcenterinsights.v1.AnalysisRule analysis_rule = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.contactcenterinsights.v1.AnalysisRuleOrBuilder
getAnalysisRuleOrBuilder() {
if (analysisRuleBuilder_ != null) {
return analysisRuleBuilder_.getMessageOrBuilder();
} else {
return analysisRule_ == null
? com.google.cloud.contactcenterinsights.v1.AnalysisRule.getDefaultInstance()
: analysisRule_;
}
}
/**
*
*
* <pre>
* Required. The new analysis rule.
* </pre>
*
* <code>
* .google.cloud.contactcenterinsights.v1.AnalysisRule analysis_rule = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.contactcenterinsights.v1.AnalysisRule,
com.google.cloud.contactcenterinsights.v1.AnalysisRule.Builder,
com.google.cloud.contactcenterinsights.v1.AnalysisRuleOrBuilder>
getAnalysisRuleFieldBuilder() {
if (analysisRuleBuilder_ == null) {
analysisRuleBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.contactcenterinsights.v1.AnalysisRule,
com.google.cloud.contactcenterinsights.v1.AnalysisRule.Builder,
com.google.cloud.contactcenterinsights.v1.AnalysisRuleOrBuilder>(
getAnalysisRule(), getParentForChildren(), isClean());
analysisRule_ = null;
}
return analysisRuleBuilder_;
}
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. The list of fields to be updated.
* If the update_mask is not provided, the update will be applied to all
* fields.
* </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. The list of fields to be updated.
* If the update_mask is not provided, the update will be applied to all
* fields.
* </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. The list of fields to be updated.
* If the update_mask is not provided, the update will be applied to all
* fields.
* </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. The list of fields to be updated.
* If the update_mask is not provided, the update will be applied to all
* fields.
* </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. The list of fields to be updated.
* If the update_mask is not provided, the update will be applied to all
* fields.
* </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. The list of fields to be updated.
* If the update_mask is not provided, the update will be applied to all
* fields.
* </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. The list of fields to be updated.
* If the update_mask is not provided, the update will be applied to all
* fields.
* </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. The list of fields to be updated.
* If the update_mask is not provided, the update will be applied to all
* fields.
* </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. The list of fields to be updated.
* If the update_mask is not provided, the update will be applied to all
* fields.
* </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.contactcenterinsights.v1.UpdateAnalysisRuleRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest)
private static final com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest();
}
public static com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateAnalysisRuleRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateAnalysisRuleRequest>() {
@java.lang.Override
public UpdateAnalysisRuleRequest 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<UpdateAnalysisRuleRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateAnalysisRuleRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.UpdateAnalysisRuleRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,926 | java-compute/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/HealthChecksStubSettings.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.HealthChecksClient.AggregatedListPagedResponse;
import static com.google.cloud.compute.v1.HealthChecksClient.ListPagedResponse;
import com.google.api.core.ApiFunction;
import com.google.api.core.ApiFuture;
import com.google.api.core.ObsoleteApi;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.HttpJsonTransportChannel;
import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider;
import com.google.api.gax.httpjson.ProtoOperationTransformers;
import com.google.api.gax.longrunning.OperationSnapshot;
import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiCallContext;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.PageContext;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.PagedListDescriptor;
import com.google.api.gax.rpc.PagedListResponseFactory;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.compute.v1.AggregatedListHealthChecksRequest;
import com.google.cloud.compute.v1.DeleteHealthCheckRequest;
import com.google.cloud.compute.v1.GetHealthCheckRequest;
import com.google.cloud.compute.v1.HealthCheck;
import com.google.cloud.compute.v1.HealthCheckList;
import com.google.cloud.compute.v1.HealthChecksAggregatedList;
import com.google.cloud.compute.v1.HealthChecksScopedList;
import com.google.cloud.compute.v1.InsertHealthCheckRequest;
import com.google.cloud.compute.v1.ListHealthChecksRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.PatchHealthCheckRequest;
import com.google.cloud.compute.v1.UpdateHealthCheckRequest;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link HealthChecksStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (compute.googleapis.com) and default port (443) are used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the
* [RetrySettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.retrying.RetrySettings)
* of get:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* HealthChecksStubSettings.Builder healthChecksSettingsBuilder =
* HealthChecksStubSettings.newBuilder();
* healthChecksSettingsBuilder
* .getSettings()
* .setRetrySettings(
* healthChecksSettingsBuilder
* .getSettings()
* .getRetrySettings()
* .toBuilder()
* .setInitialRetryDelayDuration(Duration.ofSeconds(1))
* .setInitialRpcTimeoutDuration(Duration.ofSeconds(5))
* .setMaxAttempts(5)
* .setMaxRetryDelayDuration(Duration.ofSeconds(30))
* .setMaxRpcTimeoutDuration(Duration.ofSeconds(60))
* .setRetryDelayMultiplier(1.3)
* .setRpcTimeoutMultiplier(1.5)
* .setTotalTimeoutDuration(Duration.ofSeconds(300))
* .build());
* HealthChecksStubSettings healthChecksSettings = healthChecksSettingsBuilder.build();
* }</pre>
*
* Please refer to the [Client Side Retry
* Guide](https://github.com/googleapis/google-cloud-java/blob/main/docs/client_retries.md) for
* additional support in setting retries.
*
* <p>To configure the RetrySettings of a Long Running Operation method, create an
* OperationTimedPollAlgorithm object and update the RPC's polling algorithm. For example, to
* configure the RetrySettings for delete:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* HealthChecksStubSettings.Builder healthChecksSettingsBuilder =
* HealthChecksStubSettings.newBuilder();
* TimedRetryAlgorithm timedRetryAlgorithm =
* OperationalTimedPollAlgorithm.create(
* RetrySettings.newBuilder()
* .setInitialRetryDelayDuration(Duration.ofMillis(500))
* .setRetryDelayMultiplier(1.5)
* .setMaxRetryDelayDuration(Duration.ofMillis(5000))
* .setTotalTimeoutDuration(Duration.ofHours(24))
* .build());
* healthChecksSettingsBuilder
* .createClusterOperationSettings()
* .setPollingAlgorithm(timedRetryAlgorithm)
* .build();
* }</pre>
*/
@Generated("by gapic-generator-java")
public class HealthChecksStubSettings extends StubSettings<HealthChecksStubSettings> {
/** The default scopes of the service. */
private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
ImmutableList.<String>builder()
.add("https://www.googleapis.com/auth/compute")
.add("https://www.googleapis.com/auth/cloud-platform")
.build();
private final PagedCallSettings<
AggregatedListHealthChecksRequest,
HealthChecksAggregatedList,
AggregatedListPagedResponse>
aggregatedListSettings;
private final UnaryCallSettings<DeleteHealthCheckRequest, Operation> deleteSettings;
private final OperationCallSettings<DeleteHealthCheckRequest, Operation, Operation>
deleteOperationSettings;
private final UnaryCallSettings<GetHealthCheckRequest, HealthCheck> getSettings;
private final UnaryCallSettings<InsertHealthCheckRequest, Operation> insertSettings;
private final OperationCallSettings<InsertHealthCheckRequest, Operation, Operation>
insertOperationSettings;
private final PagedCallSettings<ListHealthChecksRequest, HealthCheckList, ListPagedResponse>
listSettings;
private final UnaryCallSettings<PatchHealthCheckRequest, Operation> patchSettings;
private final OperationCallSettings<PatchHealthCheckRequest, Operation, Operation>
patchOperationSettings;
private final UnaryCallSettings<UpdateHealthCheckRequest, Operation> updateSettings;
private final OperationCallSettings<UpdateHealthCheckRequest, Operation, Operation>
updateOperationSettings;
private static final PagedListDescriptor<
AggregatedListHealthChecksRequest,
HealthChecksAggregatedList,
Map.Entry<String, HealthChecksScopedList>>
AGGREGATED_LIST_PAGE_STR_DESC =
new PagedListDescriptor<
AggregatedListHealthChecksRequest,
HealthChecksAggregatedList,
Map.Entry<String, HealthChecksScopedList>>() {
@Override
public String emptyToken() {
return "";
}
@Override
public AggregatedListHealthChecksRequest injectToken(
AggregatedListHealthChecksRequest payload, String token) {
return AggregatedListHealthChecksRequest.newBuilder(payload)
.setPageToken(token)
.build();
}
@Override
public AggregatedListHealthChecksRequest injectPageSize(
AggregatedListHealthChecksRequest payload, int pageSize) {
return AggregatedListHealthChecksRequest.newBuilder(payload)
.setMaxResults(pageSize)
.build();
}
@Override
public Integer extractPageSize(AggregatedListHealthChecksRequest payload) {
return payload.getMaxResults();
}
@Override
public String extractNextToken(HealthChecksAggregatedList payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<Map.Entry<String, HealthChecksScopedList>> extractResources(
HealthChecksAggregatedList payload) {
return payload.getItemsMap().entrySet();
}
};
private static final PagedListDescriptor<ListHealthChecksRequest, HealthCheckList, HealthCheck>
LIST_PAGE_STR_DESC =
new PagedListDescriptor<ListHealthChecksRequest, HealthCheckList, HealthCheck>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListHealthChecksRequest injectToken(
ListHealthChecksRequest payload, String token) {
return ListHealthChecksRequest.newBuilder(payload).setPageToken(token).build();
}
@Override
public ListHealthChecksRequest injectPageSize(
ListHealthChecksRequest payload, int pageSize) {
return ListHealthChecksRequest.newBuilder(payload).setMaxResults(pageSize).build();
}
@Override
public Integer extractPageSize(ListHealthChecksRequest payload) {
return payload.getMaxResults();
}
@Override
public String extractNextToken(HealthCheckList payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<HealthCheck> extractResources(HealthCheckList payload) {
return payload.getItemsList();
}
};
private static final PagedListResponseFactory<
AggregatedListHealthChecksRequest,
HealthChecksAggregatedList,
AggregatedListPagedResponse>
AGGREGATED_LIST_PAGE_STR_FACT =
new PagedListResponseFactory<
AggregatedListHealthChecksRequest,
HealthChecksAggregatedList,
AggregatedListPagedResponse>() {
@Override
public ApiFuture<AggregatedListPagedResponse> getFuturePagedResponse(
UnaryCallable<AggregatedListHealthChecksRequest, HealthChecksAggregatedList>
callable,
AggregatedListHealthChecksRequest request,
ApiCallContext context,
ApiFuture<HealthChecksAggregatedList> futureResponse) {
PageContext<
AggregatedListHealthChecksRequest,
HealthChecksAggregatedList,
Map.Entry<String, HealthChecksScopedList>>
pageContext =
PageContext.create(callable, AGGREGATED_LIST_PAGE_STR_DESC, request, context);
return AggregatedListPagedResponse.createAsync(pageContext, futureResponse);
}
};
private static final PagedListResponseFactory<
ListHealthChecksRequest, HealthCheckList, ListPagedResponse>
LIST_PAGE_STR_FACT =
new PagedListResponseFactory<
ListHealthChecksRequest, HealthCheckList, ListPagedResponse>() {
@Override
public ApiFuture<ListPagedResponse> getFuturePagedResponse(
UnaryCallable<ListHealthChecksRequest, HealthCheckList> callable,
ListHealthChecksRequest request,
ApiCallContext context,
ApiFuture<HealthCheckList> futureResponse) {
PageContext<ListHealthChecksRequest, HealthCheckList, HealthCheck> pageContext =
PageContext.create(callable, LIST_PAGE_STR_DESC, request, context);
return ListPagedResponse.createAsync(pageContext, futureResponse);
}
};
/** Returns the object with the settings used for calls to aggregatedList. */
public PagedCallSettings<
AggregatedListHealthChecksRequest,
HealthChecksAggregatedList,
AggregatedListPagedResponse>
aggregatedListSettings() {
return aggregatedListSettings;
}
/** Returns the object with the settings used for calls to delete. */
public UnaryCallSettings<DeleteHealthCheckRequest, Operation> deleteSettings() {
return deleteSettings;
}
/** Returns the object with the settings used for calls to delete. */
public OperationCallSettings<DeleteHealthCheckRequest, Operation, Operation>
deleteOperationSettings() {
return deleteOperationSettings;
}
/** Returns the object with the settings used for calls to get. */
public UnaryCallSettings<GetHealthCheckRequest, HealthCheck> getSettings() {
return getSettings;
}
/** Returns the object with the settings used for calls to insert. */
public UnaryCallSettings<InsertHealthCheckRequest, Operation> insertSettings() {
return insertSettings;
}
/** Returns the object with the settings used for calls to insert. */
public OperationCallSettings<InsertHealthCheckRequest, Operation, Operation>
insertOperationSettings() {
return insertOperationSettings;
}
/** Returns the object with the settings used for calls to list. */
public PagedCallSettings<ListHealthChecksRequest, HealthCheckList, ListPagedResponse>
listSettings() {
return listSettings;
}
/** Returns the object with the settings used for calls to patch. */
public UnaryCallSettings<PatchHealthCheckRequest, Operation> patchSettings() {
return patchSettings;
}
/** Returns the object with the settings used for calls to patch. */
public OperationCallSettings<PatchHealthCheckRequest, Operation, Operation>
patchOperationSettings() {
return patchOperationSettings;
}
/** Returns the object with the settings used for calls to update. */
public UnaryCallSettings<UpdateHealthCheckRequest, Operation> updateSettings() {
return updateSettings;
}
/** Returns the object with the settings used for calls to update. */
public OperationCallSettings<UpdateHealthCheckRequest, Operation, Operation>
updateOperationSettings() {
return updateOperationSettings;
}
public HealthChecksStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(HttpJsonTransportChannel.getHttpJsonTransportName())) {
return HttpJsonHealthChecksStub.create(this);
}
throw new UnsupportedOperationException(
String.format(
"Transport not supported: %s", getTransportChannelProvider().getTransportName()));
}
/** Returns the default service name. */
@Override
public String getServiceName() {
return "compute";
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return InstantiatingExecutorProvider.newBuilder();
}
/** Returns the default service endpoint. */
@ObsoleteApi("Use getEndpoint() instead")
public static String getDefaultEndpoint() {
return "compute.googleapis.com:443";
}
/** Returns the default mTLS service endpoint. */
public static String getDefaultMtlsEndpoint() {
return "compute.mtls.googleapis.com:443";
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return DEFAULT_SERVICE_SCOPES;
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return GoogleCredentialsProvider.newBuilder()
.setScopesToApply(DEFAULT_SERVICE_SCOPES)
.setUseJwtAccessWithScope(true);
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingHttpJsonChannelProvider.Builder
defaultHttpJsonTransportProviderBuilder() {
return InstantiatingHttpJsonChannelProvider.newBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return defaultHttpJsonTransportProviderBuilder().build();
}
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic", GaxProperties.getLibraryVersion(HealthChecksStubSettings.class))
.setTransportToken(
GaxHttpJsonProperties.getHttpJsonTokenName(),
GaxHttpJsonProperties.getHttpJsonVersion());
}
/** Returns a new builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected HealthChecksStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
aggregatedListSettings = settingsBuilder.aggregatedListSettings().build();
deleteSettings = settingsBuilder.deleteSettings().build();
deleteOperationSettings = settingsBuilder.deleteOperationSettings().build();
getSettings = settingsBuilder.getSettings().build();
insertSettings = settingsBuilder.insertSettings().build();
insertOperationSettings = settingsBuilder.insertOperationSettings().build();
listSettings = settingsBuilder.listSettings().build();
patchSettings = settingsBuilder.patchSettings().build();
patchOperationSettings = settingsBuilder.patchOperationSettings().build();
updateSettings = settingsBuilder.updateSettings().build();
updateOperationSettings = settingsBuilder.updateOperationSettings().build();
}
/** Builder for HealthChecksStubSettings. */
public static class Builder extends StubSettings.Builder<HealthChecksStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final PagedCallSettings.Builder<
AggregatedListHealthChecksRequest,
HealthChecksAggregatedList,
AggregatedListPagedResponse>
aggregatedListSettings;
private final UnaryCallSettings.Builder<DeleteHealthCheckRequest, Operation> deleteSettings;
private final OperationCallSettings.Builder<DeleteHealthCheckRequest, Operation, Operation>
deleteOperationSettings;
private final UnaryCallSettings.Builder<GetHealthCheckRequest, HealthCheck> getSettings;
private final UnaryCallSettings.Builder<InsertHealthCheckRequest, Operation> insertSettings;
private final OperationCallSettings.Builder<InsertHealthCheckRequest, Operation, Operation>
insertOperationSettings;
private final PagedCallSettings.Builder<
ListHealthChecksRequest, HealthCheckList, ListPagedResponse>
listSettings;
private final UnaryCallSettings.Builder<PatchHealthCheckRequest, Operation> patchSettings;
private final OperationCallSettings.Builder<PatchHealthCheckRequest, Operation, Operation>
patchOperationSettings;
private final UnaryCallSettings.Builder<UpdateHealthCheckRequest, Operation> updateSettings;
private final OperationCallSettings.Builder<UpdateHealthCheckRequest, Operation, Operation>
updateOperationSettings;
private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
RETRYABLE_CODE_DEFINITIONS;
static {
ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions =
ImmutableMap.builder();
definitions.put(
"retry_policy_0_codes",
ImmutableSet.copyOf(
Lists.<StatusCode.Code>newArrayList(
StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.UNAVAILABLE)));
definitions.put(
"no_retry_1_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
RetrySettings settings = null;
settings =
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(100L))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelayDuration(Duration.ofMillis(60000L))
.setInitialRpcTimeoutDuration(Duration.ofMillis(600000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(600000L))
.setTotalTimeoutDuration(Duration.ofMillis(600000L))
.build();
definitions.put("retry_policy_0_params", settings);
settings =
RetrySettings.newBuilder()
.setInitialRpcTimeoutDuration(Duration.ofMillis(600000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(600000L))
.setTotalTimeoutDuration(Duration.ofMillis(600000L))
.build();
definitions.put("no_retry_1_params", settings);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
protected Builder() {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(clientContext);
aggregatedListSettings = PagedCallSettings.newBuilder(AGGREGATED_LIST_PAGE_STR_FACT);
deleteSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
deleteOperationSettings = OperationCallSettings.newBuilder();
getSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
insertSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
insertOperationSettings = OperationCallSettings.newBuilder();
listSettings = PagedCallSettings.newBuilder(LIST_PAGE_STR_FACT);
patchSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
patchOperationSettings = OperationCallSettings.newBuilder();
updateSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
updateOperationSettings = OperationCallSettings.newBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
aggregatedListSettings,
deleteSettings,
getSettings,
insertSettings,
listSettings,
patchSettings,
updateSettings);
initDefaults(this);
}
protected Builder(HealthChecksStubSettings settings) {
super(settings);
aggregatedListSettings = settings.aggregatedListSettings.toBuilder();
deleteSettings = settings.deleteSettings.toBuilder();
deleteOperationSettings = settings.deleteOperationSettings.toBuilder();
getSettings = settings.getSettings.toBuilder();
insertSettings = settings.insertSettings.toBuilder();
insertOperationSettings = settings.insertOperationSettings.toBuilder();
listSettings = settings.listSettings.toBuilder();
patchSettings = settings.patchSettings.toBuilder();
patchOperationSettings = settings.patchOperationSettings.toBuilder();
updateSettings = settings.updateSettings.toBuilder();
updateOperationSettings = settings.updateOperationSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
aggregatedListSettings,
deleteSettings,
getSettings,
insertSettings,
listSettings,
patchSettings,
updateSettings);
}
private static Builder createDefault() {
Builder builder = new Builder(((ClientContext) null));
builder.setTransportChannelProvider(defaultTransportChannelProvider());
builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build());
builder.setMtlsEndpoint(getDefaultMtlsEndpoint());
builder.setSwitchToMtlsEndpointAllowed(true);
return initDefaults(builder);
}
private static Builder initDefaults(Builder builder) {
builder
.aggregatedListSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.deleteSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.getSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.insertSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.listSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.patchSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.updateSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.deleteOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<DeleteHealthCheckRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Operation.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(Operation.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(500L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(20000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(600000L))
.build()));
builder
.insertOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<InsertHealthCheckRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Operation.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(Operation.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(500L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(20000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(600000L))
.build()));
builder
.patchOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<PatchHealthCheckRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Operation.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(Operation.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(500L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(20000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(600000L))
.build()));
builder
.updateOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<UpdateHealthCheckRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Operation.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(Operation.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(500L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(20000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(600000L))
.build()));
return builder;
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);
return this;
}
public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() {
return unaryMethodSettingsBuilders;
}
/** Returns the builder for the settings used for calls to aggregatedList. */
public PagedCallSettings.Builder<
AggregatedListHealthChecksRequest,
HealthChecksAggregatedList,
AggregatedListPagedResponse>
aggregatedListSettings() {
return aggregatedListSettings;
}
/** Returns the builder for the settings used for calls to delete. */
public UnaryCallSettings.Builder<DeleteHealthCheckRequest, Operation> deleteSettings() {
return deleteSettings;
}
/** Returns the builder for the settings used for calls to delete. */
public OperationCallSettings.Builder<DeleteHealthCheckRequest, Operation, Operation>
deleteOperationSettings() {
return deleteOperationSettings;
}
/** Returns the builder for the settings used for calls to get. */
public UnaryCallSettings.Builder<GetHealthCheckRequest, HealthCheck> getSettings() {
return getSettings;
}
/** Returns the builder for the settings used for calls to insert. */
public UnaryCallSettings.Builder<InsertHealthCheckRequest, Operation> insertSettings() {
return insertSettings;
}
/** Returns the builder for the settings used for calls to insert. */
public OperationCallSettings.Builder<InsertHealthCheckRequest, Operation, Operation>
insertOperationSettings() {
return insertOperationSettings;
}
/** Returns the builder for the settings used for calls to list. */
public PagedCallSettings.Builder<ListHealthChecksRequest, HealthCheckList, ListPagedResponse>
listSettings() {
return listSettings;
}
/** Returns the builder for the settings used for calls to patch. */
public UnaryCallSettings.Builder<PatchHealthCheckRequest, Operation> patchSettings() {
return patchSettings;
}
/** Returns the builder for the settings used for calls to patch. */
public OperationCallSettings.Builder<PatchHealthCheckRequest, Operation, Operation>
patchOperationSettings() {
return patchOperationSettings;
}
/** Returns the builder for the settings used for calls to update. */
public UnaryCallSettings.Builder<UpdateHealthCheckRequest, Operation> updateSettings() {
return updateSettings;
}
/** Returns the builder for the settings used for calls to update. */
public OperationCallSettings.Builder<UpdateHealthCheckRequest, Operation, Operation>
updateOperationSettings() {
return updateOperationSettings;
}
@Override
public HealthChecksStubSettings build() throws IOException {
return new HealthChecksStubSettings(this);
}
}
}
|
googleapis/google-cloud-java | 35,576 | java-retail/google-cloud-retail/src/test/java/com/google/cloud/retail/v2/CatalogServiceClientHttpJsonTest.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.retail.v2;
import static com.google.cloud.retail.v2.CatalogServiceClient.ListCatalogsPagedResponse;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.testing.MockHttpService;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.ApiExceptionFactory;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.testing.FakeStatusCode;
import com.google.cloud.retail.v2.stub.HttpJsonCatalogServiceStub;
import com.google.common.collect.Lists;
import com.google.protobuf.Empty;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Timestamp;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Generated;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@Generated("by gapic-generator-java")
public class CatalogServiceClientHttpJsonTest {
private static MockHttpService mockService;
private static CatalogServiceClient client;
@BeforeClass
public static void startStaticServer() throws IOException {
mockService =
new MockHttpService(
HttpJsonCatalogServiceStub.getMethodDescriptors(),
CatalogServiceSettings.getDefaultEndpoint());
CatalogServiceSettings settings =
CatalogServiceSettings.newHttpJsonBuilder()
.setTransportChannelProvider(
CatalogServiceSettings.defaultHttpJsonTransportProviderBuilder()
.setHttpTransport(mockService)
.build())
.setCredentialsProvider(NoCredentialsProvider.create())
.build();
client = CatalogServiceClient.create(settings);
}
@AfterClass
public static void stopServer() {
client.close();
}
@Before
public void setUp() {}
@After
public void tearDown() throws Exception {
mockService.reset();
}
@Test
public void listCatalogsTest() throws Exception {
Catalog responsesElement = Catalog.newBuilder().build();
ListCatalogsResponse expectedResponse =
ListCatalogsResponse.newBuilder()
.setNextPageToken("")
.addAllCatalogs(Arrays.asList(responsesElement))
.build();
mockService.addResponse(expectedResponse);
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
ListCatalogsPagedResponse pagedListResponse = client.listCatalogs(parent);
List<Catalog> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getCatalogsList().get(0), resources.get(0));
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void listCatalogsExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
client.listCatalogs(parent);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listCatalogsTest2() throws Exception {
Catalog responsesElement = Catalog.newBuilder().build();
ListCatalogsResponse expectedResponse =
ListCatalogsResponse.newBuilder()
.setNextPageToken("")
.addAllCatalogs(Arrays.asList(responsesElement))
.build();
mockService.addResponse(expectedResponse);
String parent = "projects/project-5833/locations/location-5833";
ListCatalogsPagedResponse pagedListResponse = client.listCatalogs(parent);
List<Catalog> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getCatalogsList().get(0), resources.get(0));
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void listCatalogsExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String parent = "projects/project-5833/locations/location-5833";
client.listCatalogs(parent);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void updateCatalogTest() throws Exception {
Catalog expectedResponse =
Catalog.newBuilder()
.setName(CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setDisplayName("displayName1714148973")
.setProductLevelConfig(ProductLevelConfig.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
Catalog catalog =
Catalog.newBuilder()
.setName(CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setDisplayName("displayName1714148973")
.setProductLevelConfig(ProductLevelConfig.newBuilder().build())
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
Catalog actualResponse = client.updateCatalog(catalog, updateMask);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void updateCatalogExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
Catalog catalog =
Catalog.newBuilder()
.setName(CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setDisplayName("displayName1714148973")
.setProductLevelConfig(ProductLevelConfig.newBuilder().build())
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
client.updateCatalog(catalog, updateMask);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void setDefaultBranchTest() throws Exception {
Empty expectedResponse = Empty.newBuilder().build();
mockService.addResponse(expectedResponse);
CatalogName catalog = CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]");
client.setDefaultBranch(catalog);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void setDefaultBranchExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
CatalogName catalog = CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]");
client.setDefaultBranch(catalog);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void setDefaultBranchTest2() throws Exception {
Empty expectedResponse = Empty.newBuilder().build();
mockService.addResponse(expectedResponse);
String catalog = "projects/project-6372/locations/location-6372/catalogs/catalog-6372";
client.setDefaultBranch(catalog);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void setDefaultBranchExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String catalog = "projects/project-6372/locations/location-6372/catalogs/catalog-6372";
client.setDefaultBranch(catalog);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getDefaultBranchTest() throws Exception {
GetDefaultBranchResponse expectedResponse =
GetDefaultBranchResponse.newBuilder()
.setBranch(BranchName.of("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]").toString())
.setSetTime(Timestamp.newBuilder().build())
.setNote("note3387378")
.build();
mockService.addResponse(expectedResponse);
CatalogName catalog = CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]");
GetDefaultBranchResponse actualResponse = client.getDefaultBranch(catalog);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void getDefaultBranchExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
CatalogName catalog = CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]");
client.getDefaultBranch(catalog);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getDefaultBranchTest2() throws Exception {
GetDefaultBranchResponse expectedResponse =
GetDefaultBranchResponse.newBuilder()
.setBranch(BranchName.of("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]").toString())
.setSetTime(Timestamp.newBuilder().build())
.setNote("note3387378")
.build();
mockService.addResponse(expectedResponse);
String catalog = "projects/project-6372/locations/location-6372/catalogs/catalog-6372";
GetDefaultBranchResponse actualResponse = client.getDefaultBranch(catalog);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void getDefaultBranchExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String catalog = "projects/project-6372/locations/location-6372/catalogs/catalog-6372";
client.getDefaultBranch(catalog);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getCompletionConfigTest() throws Exception {
CompletionConfig expectedResponse =
CompletionConfig.newBuilder()
.setName(CompletionConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setMatchingOrder("matchingOrder-1366761135")
.setMaxSuggestions(618824852)
.setMinPrefixLength(96853510)
.setAutoLearning(true)
.setSuggestionsInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastSuggestionsImportOperation("lastSuggestionsImportOperation-245829751")
.setDenylistInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastDenylistImportOperation("lastDenylistImportOperation1262341570")
.setAllowlistInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastAllowlistImportOperation("lastAllowlistImportOperation1624716689")
.build();
mockService.addResponse(expectedResponse);
CompletionConfigName name = CompletionConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]");
CompletionConfig actualResponse = client.getCompletionConfig(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void getCompletionConfigExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
CompletionConfigName name = CompletionConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]");
client.getCompletionConfig(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getCompletionConfigTest2() throws Exception {
CompletionConfig expectedResponse =
CompletionConfig.newBuilder()
.setName(CompletionConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setMatchingOrder("matchingOrder-1366761135")
.setMaxSuggestions(618824852)
.setMinPrefixLength(96853510)
.setAutoLearning(true)
.setSuggestionsInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastSuggestionsImportOperation("lastSuggestionsImportOperation-245829751")
.setDenylistInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastDenylistImportOperation("lastDenylistImportOperation1262341570")
.setAllowlistInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastAllowlistImportOperation("lastAllowlistImportOperation1624716689")
.build();
mockService.addResponse(expectedResponse);
String name =
"projects/project-6627/locations/location-6627/catalogs/catalog-6627/completionConfig";
CompletionConfig actualResponse = client.getCompletionConfig(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void getCompletionConfigExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String name =
"projects/project-6627/locations/location-6627/catalogs/catalog-6627/completionConfig";
client.getCompletionConfig(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void updateCompletionConfigTest() throws Exception {
CompletionConfig expectedResponse =
CompletionConfig.newBuilder()
.setName(CompletionConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setMatchingOrder("matchingOrder-1366761135")
.setMaxSuggestions(618824852)
.setMinPrefixLength(96853510)
.setAutoLearning(true)
.setSuggestionsInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastSuggestionsImportOperation("lastSuggestionsImportOperation-245829751")
.setDenylistInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastDenylistImportOperation("lastDenylistImportOperation1262341570")
.setAllowlistInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastAllowlistImportOperation("lastAllowlistImportOperation1624716689")
.build();
mockService.addResponse(expectedResponse);
CompletionConfig completionConfig =
CompletionConfig.newBuilder()
.setName(CompletionConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setMatchingOrder("matchingOrder-1366761135")
.setMaxSuggestions(618824852)
.setMinPrefixLength(96853510)
.setAutoLearning(true)
.setSuggestionsInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastSuggestionsImportOperation("lastSuggestionsImportOperation-245829751")
.setDenylistInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastDenylistImportOperation("lastDenylistImportOperation1262341570")
.setAllowlistInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastAllowlistImportOperation("lastAllowlistImportOperation1624716689")
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
CompletionConfig actualResponse = client.updateCompletionConfig(completionConfig, updateMask);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void updateCompletionConfigExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
CompletionConfig completionConfig =
CompletionConfig.newBuilder()
.setName(CompletionConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setMatchingOrder("matchingOrder-1366761135")
.setMaxSuggestions(618824852)
.setMinPrefixLength(96853510)
.setAutoLearning(true)
.setSuggestionsInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastSuggestionsImportOperation("lastSuggestionsImportOperation-245829751")
.setDenylistInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastDenylistImportOperation("lastDenylistImportOperation1262341570")
.setAllowlistInputConfig(CompletionDataInputConfig.newBuilder().build())
.setLastAllowlistImportOperation("lastAllowlistImportOperation1624716689")
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
client.updateCompletionConfig(completionConfig, updateMask);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getAttributesConfigTest() throws Exception {
AttributesConfig expectedResponse =
AttributesConfig.newBuilder()
.setName(AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.putAllCatalogAttributes(new HashMap<String, CatalogAttribute>())
.setAttributeConfigLevel(AttributeConfigLevel.forNumber(0))
.build();
mockService.addResponse(expectedResponse);
AttributesConfigName name = AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]");
AttributesConfig actualResponse = client.getAttributesConfig(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void getAttributesConfigExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
AttributesConfigName name = AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]");
client.getAttributesConfig(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getAttributesConfigTest2() throws Exception {
AttributesConfig expectedResponse =
AttributesConfig.newBuilder()
.setName(AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.putAllCatalogAttributes(new HashMap<String, CatalogAttribute>())
.setAttributeConfigLevel(AttributeConfigLevel.forNumber(0))
.build();
mockService.addResponse(expectedResponse);
String name =
"projects/project-9790/locations/location-9790/catalogs/catalog-9790/attributesConfig";
AttributesConfig actualResponse = client.getAttributesConfig(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void getAttributesConfigExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String name =
"projects/project-9790/locations/location-9790/catalogs/catalog-9790/attributesConfig";
client.getAttributesConfig(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void updateAttributesConfigTest() throws Exception {
AttributesConfig expectedResponse =
AttributesConfig.newBuilder()
.setName(AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.putAllCatalogAttributes(new HashMap<String, CatalogAttribute>())
.setAttributeConfigLevel(AttributeConfigLevel.forNumber(0))
.build();
mockService.addResponse(expectedResponse);
AttributesConfig attributesConfig =
AttributesConfig.newBuilder()
.setName(AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.putAllCatalogAttributes(new HashMap<String, CatalogAttribute>())
.setAttributeConfigLevel(AttributeConfigLevel.forNumber(0))
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
AttributesConfig actualResponse = client.updateAttributesConfig(attributesConfig, updateMask);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void updateAttributesConfigExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
AttributesConfig attributesConfig =
AttributesConfig.newBuilder()
.setName(AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.putAllCatalogAttributes(new HashMap<String, CatalogAttribute>())
.setAttributeConfigLevel(AttributeConfigLevel.forNumber(0))
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
client.updateAttributesConfig(attributesConfig, updateMask);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void addCatalogAttributeTest() throws Exception {
AttributesConfig expectedResponse =
AttributesConfig.newBuilder()
.setName(AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.putAllCatalogAttributes(new HashMap<String, CatalogAttribute>())
.setAttributeConfigLevel(AttributeConfigLevel.forNumber(0))
.build();
mockService.addResponse(expectedResponse);
AddCatalogAttributeRequest request =
AddCatalogAttributeRequest.newBuilder()
.setAttributesConfig(
AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setCatalogAttribute(CatalogAttribute.newBuilder().build())
.build();
AttributesConfig actualResponse = client.addCatalogAttribute(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void addCatalogAttributeExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
AddCatalogAttributeRequest request =
AddCatalogAttributeRequest.newBuilder()
.setAttributesConfig(
AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setCatalogAttribute(CatalogAttribute.newBuilder().build())
.build();
client.addCatalogAttribute(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void removeCatalogAttributeTest() throws Exception {
AttributesConfig expectedResponse =
AttributesConfig.newBuilder()
.setName(AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.putAllCatalogAttributes(new HashMap<String, CatalogAttribute>())
.setAttributeConfigLevel(AttributeConfigLevel.forNumber(0))
.build();
mockService.addResponse(expectedResponse);
RemoveCatalogAttributeRequest request =
RemoveCatalogAttributeRequest.newBuilder()
.setAttributesConfig(
AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setKey("key106079")
.build();
AttributesConfig actualResponse = client.removeCatalogAttribute(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void removeCatalogAttributeExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
RemoveCatalogAttributeRequest request =
RemoveCatalogAttributeRequest.newBuilder()
.setAttributesConfig(
AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setKey("key106079")
.build();
client.removeCatalogAttribute(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void replaceCatalogAttributeTest() throws Exception {
AttributesConfig expectedResponse =
AttributesConfig.newBuilder()
.setName(AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.putAllCatalogAttributes(new HashMap<String, CatalogAttribute>())
.setAttributeConfigLevel(AttributeConfigLevel.forNumber(0))
.build();
mockService.addResponse(expectedResponse);
ReplaceCatalogAttributeRequest request =
ReplaceCatalogAttributeRequest.newBuilder()
.setAttributesConfig(
AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setCatalogAttribute(CatalogAttribute.newBuilder().build())
.setUpdateMask(FieldMask.newBuilder().build())
.build();
AttributesConfig actualResponse = client.replaceCatalogAttribute(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void replaceCatalogAttributeExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
ReplaceCatalogAttributeRequest request =
ReplaceCatalogAttributeRequest.newBuilder()
.setAttributesConfig(
AttributesConfigName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString())
.setCatalogAttribute(CatalogAttribute.newBuilder().build())
.setUpdateMask(FieldMask.newBuilder().build())
.build();
client.replaceCatalogAttribute(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
}
|
apache/drill | 35,972 | contrib/format-maprdb/src/main/java/org/apache/drill/exec/store/mapr/db/json/JsonTableGroupScan.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.store.mapr.db.json;
import static org.apache.drill.exec.planner.index.Statistics.ROWCOUNT_HUGE;
import static org.apache.drill.exec.planner.index.Statistics.ROWCOUNT_UNKNOWN;
import static org.apache.drill.exec.planner.index.Statistics.AVG_ROWSIZE_UNKNOWN;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.mapr.db.impl.ConditionImpl;
import com.mapr.db.impl.ConditionNode.RowkeyRange;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rex.RexNode;
import org.apache.drill.common.exceptions.DrillRuntimeException;
import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.common.expression.FieldReference;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.exec.physical.base.GroupScan;
import org.apache.drill.exec.physical.base.IndexGroupScan;
import org.apache.drill.exec.physical.base.PhysicalOperator;
import org.apache.drill.exec.physical.base.ScanStats;
import org.apache.drill.exec.physical.base.ScanStats.GroupScanProperty;
import org.apache.drill.exec.record.metadata.TupleMetadata;
import org.apache.drill.exec.store.AbstractStoragePlugin;
import org.apache.drill.exec.planner.index.IndexDescriptor;
import org.apache.drill.exec.planner.index.MapRDBIndexDescriptor;
import org.apache.drill.exec.planner.index.MapRDBStatisticsPayload;
import org.apache.drill.exec.planner.index.Statistics;
import org.apache.drill.exec.planner.index.MapRDBStatistics;
import org.apache.drill.exec.planner.cost.PluginCost;
import org.apache.drill.exec.planner.physical.PartitionFunction;
import org.apache.drill.exec.planner.physical.PrelUtil;
import org.apache.drill.exec.store.StoragePluginRegistry;
import org.apache.drill.exec.store.dfs.FileSystemConfig;
import org.apache.drill.exec.store.dfs.FileSystemPlugin;
import org.apache.drill.exec.store.mapr.PluginConstants;
import org.apache.drill.exec.store.mapr.db.MapRDBFormatPlugin;
import org.apache.drill.exec.store.mapr.db.MapRDBFormatPluginConfig;
import org.apache.drill.exec.store.mapr.db.MapRDBGroupScan;
import org.apache.drill.exec.store.mapr.db.MapRDBSubScan;
import org.apache.drill.exec.store.mapr.db.MapRDBSubScanSpec;
import org.apache.drill.exec.store.mapr.db.MapRDBTableStats;
import org.apache.drill.exec.store.mapr.db.TabletFragmentInfo;
import org.apache.drill.exec.util.Utilities;
import org.apache.drill.exec.metastore.store.FileSystemMetadataProviderManager;
import org.apache.drill.exec.metastore.MetadataProviderManager;
import org.apache.drill.metastore.metadata.TableMetadataProvider;
import org.ojai.store.QueryCondition;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Preconditions;
import com.mapr.db.MetaTable;
import com.mapr.db.Table;
import com.mapr.db.impl.TabletInfoImpl;
import com.mapr.db.index.IndexDesc;
import com.mapr.db.scan.ScanRange;
@JsonTypeName("maprdb-json-scan")
public class JsonTableGroupScan extends MapRDBGroupScan implements IndexGroupScan {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(JsonTableGroupScan.class);
public static final int STAR_COLS = 100;
public static final String TABLE_JSON = "json";
/*
* The <forcedRowCountMap> maintains a mapping of <RexNode, Rowcount>. These RowCounts take precedence over
* anything computed using <MapRDBStatistics> stats. Currently, it is used for picking index plans with the
* index_selectivity_factor. We forcibly set the full table rows as HUGE <Statistics.ROWCOUNT_HUGE> in this
* map when the selectivity of the index is lower than index_selectivity_factor. During costing, the table
* rowCount is returned as HUGE instead of the correct <stats> rowcount. This results in the planner choosing
* the cheaper index plans!
* NOTE: Full table rowCounts are specified with the NULL condition. e.g. forcedRowCountMap<NULL, 1000>
*/
protected Map<RexNode, Double> forcedRowCountMap;
/*
* This stores the statistics associated with this GroupScan. Please note that the stats must be initialized
* before using it to compute filter row counts based on query conditions.
*/
protected MapRDBStatistics stats;
protected JsonScanSpec scanSpec;
protected double fullTableRowCount;
protected double fullTableEstimatedSize;
/**
* need only read maxRecordsToRead records.
*/
protected int maxRecordsToRead = -1;
/**
* Forced parallelization width
*/
protected int parallelizationWidth = -1;
@JsonCreator
public JsonTableGroupScan(@JsonProperty("userName") final String userName,
@JsonProperty("scanSpec") JsonScanSpec scanSpec,
@JsonProperty("storage") FileSystemConfig storagePluginConfig,
@JsonProperty("format") MapRDBFormatPluginConfig formatPluginConfig,
@JsonProperty("columns") List<SchemaPath> columns,
@JsonProperty("schema") TupleMetadata schema,
@JacksonInject StoragePluginRegistry pluginRegistry) throws ExecutionSetupException {
this(userName, pluginRegistry.resolve(storagePluginConfig, AbstractStoragePlugin.class),
pluginRegistry.resolveFormat(storagePluginConfig, formatPluginConfig, MapRDBFormatPlugin.class),
scanSpec, columns, new MapRDBStatistics(), FileSystemMetadataProviderManager.getMetadataProviderForSchema(schema));
}
public JsonTableGroupScan(String userName, AbstractStoragePlugin storagePlugin,
MapRDBFormatPlugin formatPlugin, JsonScanSpec scanSpec, List<SchemaPath> columns,
MetadataProviderManager metadataProviderManager) {
this(userName, storagePlugin, formatPlugin, scanSpec, columns,
new MapRDBStatistics(), FileSystemMetadataProviderManager.getMetadataProvider(metadataProviderManager));
}
public JsonTableGroupScan(String userName, AbstractStoragePlugin storagePlugin,
MapRDBFormatPlugin formatPlugin, JsonScanSpec scanSpec, List<SchemaPath> columns,
MapRDBStatistics stats, TableMetadataProvider metadataProvider) {
super(storagePlugin, formatPlugin, columns, userName, metadataProvider);
this.scanSpec = scanSpec;
this.stats = stats;
this.forcedRowCountMap = new HashMap<>();
init();
}
/**
* Private constructor, used for cloning.
* @param that The HBaseGroupScan to clone
*/
protected JsonTableGroupScan(JsonTableGroupScan that) {
super(that);
this.scanSpec = that.scanSpec;
this.endpointFragmentMapping = that.endpointFragmentMapping;
this.stats = that.stats;
this.fullTableRowCount = that.fullTableRowCount;
this.fullTableEstimatedSize = that.fullTableEstimatedSize;
this.forcedRowCountMap = that.forcedRowCountMap;
this.maxRecordsToRead = that.maxRecordsToRead;
this.parallelizationWidth = that.parallelizationWidth;
init();
}
@Override
public GroupScan clone(List<SchemaPath> columns) {
JsonTableGroupScan newScan = new JsonTableGroupScan(this);
newScan.columns = columns;
return newScan;
}
public GroupScan clone(JsonScanSpec scanSpec) {
JsonTableGroupScan newScan = new JsonTableGroupScan(this);
newScan.scanSpec = scanSpec;
newScan.resetRegionsToScan(); // resetting will force recalculation
return newScan;
}
private void init() {
try {
// Get the fullTableRowCount only once i.e. if not already obtained before.
if (fullTableRowCount == 0) {
final Table t = this.formatPlugin.getJsonTableCache().getTable(
scanSpec.getTableName(), scanSpec.getIndexDesc(), getUserName());
final MetaTable metaTable = t.getMetaTable();
// For condition null, we get full table stats.
com.mapr.db.scan.ScanStats stats = metaTable.getScanStats();
fullTableRowCount = stats.getEstimatedNumRows();
fullTableEstimatedSize = stats.getEstimatedSize();
// MapRDB client can return invalid rowCount i.e. 0, especially right after table
// creation. It takes 15 minutes before table stats are obtained and cached in client.
// If we get 0 rowCount, fallback to getting rowCount using old admin API.
if (fullTableRowCount == 0) {
PluginCost pluginCostModel = formatPlugin.getPluginCostModel();
final int avgColumnSize = pluginCostModel.getAverageColumnSize(this);
final int numColumns = (columns == null || columns.isEmpty() || Utilities.isStarQuery(columns)) ? STAR_COLS : columns.size();
MapRDBTableStats tableStats = new MapRDBTableStats(formatPlugin.getFsConf(), scanSpec.getTableName());
fullTableRowCount = tableStats.getNumRows();
fullTableEstimatedSize = fullTableRowCount * numColumns * avgColumnSize;
}
}
} catch (Exception e) {
throw new DrillRuntimeException("Error getting region info for table: " +
scanSpec.getTableName() + (scanSpec.getIndexDesc() == null ? "" : (", index: " + scanSpec.getIndexName())), e);
}
}
@Override
protected NavigableMap<TabletFragmentInfo, String> getRegionsToScan() {
return getRegionsToScan(formatPlugin.getScanRangeSizeMB());
}
protected NavigableMap<TabletFragmentInfo, String> getRegionsToScan(int scanRangeSizeMB) {
// If regionsToScan already computed, just return.
double estimatedRowCount = ROWCOUNT_UNKNOWN;
if (doNotAccessRegionsToScan == null) {
final Table t = this.formatPlugin.getJsonTableCache().getTable(
scanSpec.getTableName(), scanSpec.getIndexDesc(), getUserName());
final MetaTable metaTable = t.getMetaTable();
QueryCondition scanSpecCondition = scanSpec.getCondition();
List<ScanRange> scanRanges = (scanSpecCondition == null)
? metaTable.getScanRanges(scanRangeSizeMB)
: metaTable.getScanRanges(scanSpecCondition, scanRangeSizeMB);
logger.debug("getRegionsToScan() with scanSpec {}: table={}, index={}, condition={}, sizeMB={}, #ScanRanges={}",
System.identityHashCode(scanSpec), scanSpec.getTableName(), scanSpec.getIndexName(),
scanSpec.getCondition() == null ? "null" : scanSpec.getCondition(), scanRangeSizeMB,
scanRanges == null ? "null" : scanRanges.size());
final TreeMap<TabletFragmentInfo, String> regionsToScan = new TreeMap<>();
if (isIndexScan()) {
String idxIdentifier = stats.buildUniqueIndexIdentifier(scanSpec.getIndexDesc().getPrimaryTablePath(),
scanSpec.getIndexDesc().getIndexName());
if (stats.isStatsAvailable()) {
estimatedRowCount = stats.getRowCount(scanSpec.getCondition(), idxIdentifier);
}
} else {
if (stats.isStatsAvailable()) {
estimatedRowCount = stats.getRowCount(scanSpec.getCondition(), null);
}
}
// If limit pushdown has occurred - factor it in the rowcount
if (this.maxRecordsToRead > 0) {
estimatedRowCount = Math.min(estimatedRowCount, this.maxRecordsToRead);
}
// If the estimated row count > 0 then scan ranges must be > 0
Preconditions.checkState(estimatedRowCount == ROWCOUNT_UNKNOWN
|| estimatedRowCount == 0 || (scanRanges != null && scanRanges.size() > 0),
String.format("#Scan ranges should be greater than 0 since estimated rowcount=[%f]", estimatedRowCount));
if (scanRanges != null && scanRanges.size() > 0) {
// set the start-row of the scanspec as the start-row of the first scan range
ScanRange firstRange = scanRanges.get(0);
QueryCondition firstCondition = firstRange.getCondition();
byte[] firstStartRow = ((ConditionImpl) firstCondition).getRowkeyRanges().get(0).getStartRow();
scanSpec.setStartRow(firstStartRow);
// set the stop-row of ScanSpec as the stop-row of the last scan range
ScanRange lastRange = scanRanges.get(scanRanges.size() - 1);
QueryCondition lastCondition = lastRange.getCondition();
List<RowkeyRange> rowkeyRanges = ((ConditionImpl) lastCondition).getRowkeyRanges();
byte[] lastStopRow = rowkeyRanges.get(rowkeyRanges.size() - 1).getStopRow();
scanSpec.setStopRow(lastStopRow);
for (ScanRange range : scanRanges) {
TabletInfoImpl tabletInfoImpl = (TabletInfoImpl) range;
regionsToScan.put(new TabletFragmentInfo(tabletInfoImpl), range.getLocations()[0]);
}
}
setRegionsToScan(regionsToScan);
}
return doNotAccessRegionsToScan;
}
@Override
protected MapRDBSubScanSpec getSubScanSpec(final TabletFragmentInfo tfi) {
// XXX/TODO check filter/Condition
final JsonScanSpec spec = scanSpec;
final String serverHostName = getRegionsToScan().get(tfi);
QueryCondition condition = tfi.getTabletInfoImpl().getCondition();
byte[] startRow = condition == null ? null : ((ConditionImpl) condition).getRowkeyRanges().get(0).getStartRow();
byte[] stopRow = condition == null ? null : ((ConditionImpl) condition).getRowkeyRanges().get(0).getStopRow();
JsonSubScanSpec subScanSpec = new JsonSubScanSpec(
spec.getTableName(),
spec.getIndexDesc(),
serverHostName,
tfi.getTabletInfoImpl().getCondition(),
spec.getCondition(),
startRow,
stopRow,
getUserName());
return subScanSpec;
}
@Override
public MapRDBSubScan getSpecificScan(int minorFragmentId) {
assert minorFragmentId < endpointFragmentMapping.size() : String.format(
"Mappings length [%d] should be greater than minor fragment id [%d] but it isn't.", endpointFragmentMapping.size(),
minorFragmentId);
return new MapRDBSubScan(getUserName(), formatPlugin, endpointFragmentMapping.get(minorFragmentId), columns, maxRecordsToRead, TABLE_JSON, getSchema());
}
@Override
public ScanStats getScanStats() {
if (isIndexScan()) {
return indexScanStats();
}
return fullTableScanStats();
}
private ScanStats fullTableScanStats() {
PluginCost pluginCostModel = formatPlugin.getPluginCostModel();
final int avgColumnSize = pluginCostModel.getAverageColumnSize(this);
final int numColumns = (columns == null || columns.isEmpty()) ? STAR_COLS : columns.size();
// index will be NULL for FTS
double rowCount = stats.getRowCount(scanSpec.getCondition(), null);
// rowcount based on _id predicate. If NO _id predicate present in condition, then the
// rowcount should be same as totalRowCount. Equality b/w the two rowcounts should not be
// construed as NO _id predicate since stats are approximate.
double leadingRowCount = stats.getLeadingRowCount(scanSpec.getCondition(), null);
double avgRowSize = stats.getAvgRowSize(null, true);
double totalRowCount = stats.getRowCount(null, null);
logger.debug("GroupScan {} with stats {}: rowCount={}, condition={}, totalRowCount={}, fullTableRowCount={}",
System.identityHashCode(this), System.identityHashCode(stats), rowCount,
scanSpec.getCondition() == null ? "null" : scanSpec.getCondition(),
totalRowCount, fullTableRowCount);
// If UNKNOWN, or DB stats sync issues(manifests as 0 rows) use defaults.
if (rowCount == ROWCOUNT_UNKNOWN || rowCount == 0) {
rowCount = (scanSpec.getSerializedFilter() != null ? .5 : 1) * fullTableRowCount;
}
// If limit pushdown has occurred - factor it in the rowcount
if (this.maxRecordsToRead > 0) {
rowCount = Math.min(rowCount, this.maxRecordsToRead);
}
if (totalRowCount == ROWCOUNT_UNKNOWN || totalRowCount == 0) {
logger.debug("did not get valid totalRowCount, will take this: {}", fullTableRowCount);
totalRowCount = fullTableRowCount;
}
if (avgRowSize == AVG_ROWSIZE_UNKNOWN || avgRowSize == 0) {
avgRowSize = fullTableEstimatedSize/fullTableRowCount;
}
double totalBlocks = getNumOfBlocks(totalRowCount, fullTableEstimatedSize, avgRowSize, pluginCostModel);
double numBlocks = Math.min(totalBlocks, getNumOfBlocks(leadingRowCount, fullTableEstimatedSize, avgRowSize, pluginCostModel));
double diskCost = numBlocks * pluginCostModel.getSequentialBlockReadCost(this);
/*
* Table scan cost made INFINITE in order to pick index plans. Use the MAX possible rowCount for
* costing purposes.
* NOTE: Full table rowCounts are specified with the NULL condition.
* e.g. forcedRowCountMap<NULL, 1000>
*/
if (forcedRowCountMap.get(null) != null && //Forced full table rowcount and it is HUGE
forcedRowCountMap.get(null) == ROWCOUNT_HUGE ) {
rowCount = ROWCOUNT_HUGE;
diskCost = ROWCOUNT_HUGE;
}
logger.debug("JsonGroupScan:{} rowCount:{}, avgRowSize:{}, blocks:{}, totalBlocks:{}, diskCost:{}",
this.getOperatorId(), rowCount, avgRowSize, numBlocks, totalBlocks, diskCost);
return new ScanStats(GroupScanProperty.NO_EXACT_ROW_COUNT, rowCount, 1, diskCost);
}
private double getNumOfBlocks(double rowCount, double sizeFromDisk,
double avgRowSize, PluginCost pluginCostModel) {
if (rowCount == ROWCOUNT_UNKNOWN || rowCount == 0) {
return Math.ceil(sizeFromDisk / pluginCostModel.getBlockSize(this));
} else {
return Math.ceil(rowCount * avgRowSize / pluginCostModel.getBlockSize(this));
}
}
private ScanStats indexScanStats() {
if (!this.getIndexHint().equals("") &&
this.getIndexHint().equals(getIndexDesc().getIndexName())) {
logger.debug("JsonIndexGroupScan:{} forcing index {} by making tiny cost", this, this.getIndexHint());
return new ScanStats(GroupScanProperty.NO_EXACT_ROW_COUNT, 1,1, 0);
}
int totalColNum = STAR_COLS;
PluginCost pluginCostModel = formatPlugin.getPluginCostModel();
final int avgColumnSize = pluginCostModel.getAverageColumnSize(this);
boolean filterPushed = (scanSpec.getSerializedFilter() != null);
if (scanSpec != null && scanSpec.getIndexDesc() != null) {
totalColNum = scanSpec.getIndexDesc().getIncludedFields().size()
+ scanSpec.getIndexDesc().getIndexedFields().size() + 1;
}
int numColumns = (columns == null || columns.isEmpty()) ? totalColNum: columns.size();
String idxIdentifier = stats.buildUniqueIndexIdentifier(scanSpec.getIndexDesc().getPrimaryTablePath(),
scanSpec.getIndexDesc().getIndexName());
double rowCount = stats.getRowCount(scanSpec.getCondition(), idxIdentifier);
// rowcount based on index leading columns predicate.
double leadingRowCount = stats.getLeadingRowCount(scanSpec.getCondition(), idxIdentifier);
double avgRowSize = stats.getAvgRowSize(idxIdentifier, false);
// If UNKNOWN, use defaults
if (rowCount == ROWCOUNT_UNKNOWN || rowCount == 0) {
rowCount = (filterPushed ? 0.0005f : 0.001f) * fullTableRowCount / scanSpec.getIndexDesc().getIndexedFields().size();
}
// If limit pushdown has occurred - factor it in the rowcount
if (this.maxRecordsToRead > 0) {
rowCount = Math.min(rowCount, this.maxRecordsToRead);
}
if (leadingRowCount == ROWCOUNT_UNKNOWN || leadingRowCount == 0) {
leadingRowCount = rowCount;
}
if (avgRowSize == AVG_ROWSIZE_UNKNOWN || avgRowSize == 0) {
avgRowSize = avgColumnSize * numColumns;
}
double rowsFromDisk = leadingRowCount;
if (!filterPushed) {
// both start and stop rows are empty, indicating this is a full scan so
// use the total rows for calculating disk i/o
rowsFromDisk = fullTableRowCount;
}
double totalBlocks = Math.ceil((avgRowSize * fullTableRowCount)/pluginCostModel.getBlockSize(this));
double numBlocks = Math.ceil(((avgRowSize * rowsFromDisk)/pluginCostModel.getBlockSize(this)));
numBlocks = Math.min(totalBlocks, numBlocks);
double diskCost = numBlocks * pluginCostModel.getSequentialBlockReadCost(this);
logger.debug("index_plan_info: JsonIndexGroupScan:{} - indexName:{}: rowCount:{}, avgRowSize:{}, blocks:{}, totalBlocks:{}, rowsFromDisk {}, diskCost:{}",
System.identityHashCode(this), scanSpec.getIndexDesc().getIndexName(), rowCount, avgRowSize, numBlocks, totalBlocks, rowsFromDisk, diskCost);
return new ScanStats(GroupScanProperty.NO_EXACT_ROW_COUNT, rowCount, 1, diskCost);
}
@Override
@JsonIgnore
public PhysicalOperator getNewWithChildren(List<PhysicalOperator> children) {
Preconditions.checkArgument(children.isEmpty());
return new JsonTableGroupScan(this);
}
@Override
@JsonIgnore
public String getTableName() {
return scanSpec.getTableName();
}
public IndexDesc getIndexDesc() {
return scanSpec.getIndexDesc();
}
public boolean isDisablePushdown() {
return !formatPluginConfig.isEnablePushdown();
}
@Override
@JsonIgnore
public boolean canPushdownProjects(List<SchemaPath> columns) {
return formatPluginConfig.isEnablePushdown();
}
@Override
public String toString() {
return "JsonTableGroupScan [ScanSpec=" + scanSpec + ", columns=" + columns
+ (maxRecordsToRead > 0 ? ", limit=" + maxRecordsToRead : "")
+ (getMaxParallelizationWidth() > 0 ? ", maxwidth=" + getMaxParallelizationWidth() : "") + "]";
}
public JsonScanSpec getScanSpec() {
return scanSpec;
}
@Override
public boolean supportsSecondaryIndex() {
return true;
}
@Override
@JsonIgnore
public boolean isIndexScan() {
return scanSpec != null && scanSpec.isSecondaryIndex();
}
@Override
public boolean supportsRestrictedScan() {
return true;
}
@Override
public RestrictedJsonTableGroupScan getRestrictedScan(List<SchemaPath> columns) {
RestrictedJsonTableGroupScan newScan = new RestrictedJsonTableGroupScan(this.getUserName(),
(FileSystemPlugin) this.getStoragePlugin(),
this.getFormatPlugin(),
this.getScanSpec(),
this.getColumns(),
this.getStatistics(),
this.getSchema());
newScan.columns = columns;
return newScan;
}
/**
* Get the estimated average rowsize. DO NOT call this API directly.
* Call the stats API instead which modifies the counts based on preference options.
* @param index to use for generating the estimate
* @return row count post filtering
*/
public MapRDBStatisticsPayload getAverageRowSizeStats(IndexDescriptor index) {
IndexDesc indexDesc = null;
double avgRowSize = AVG_ROWSIZE_UNKNOWN;
if (index != null) {
indexDesc = (IndexDesc)((MapRDBIndexDescriptor)index).getOriginalDesc();
}
// If no index is specified, get it from the primary table
if (indexDesc == null && scanSpec.isSecondaryIndex()) {
throw new UnsupportedOperationException("getAverageRowSizeStats should be invoked on primary table");
}
// Get the index table or primary table and use the DB API to get the estimated number of rows. For size estimates,
// we assume that all the columns would be read from the disk.
final Table table = this.formatPlugin.getJsonTableCache().getTable(scanSpec.getTableName(), indexDesc, getUserName());
if (table != null) {
final MetaTable metaTable = table.getMetaTable();
if (metaTable != null) {
avgRowSize = metaTable.getAverageRowSize();
}
}
logger.debug("index_plan_info: getEstimatedRowCount obtained from DB Client for {}: indexName: {}, indexInfo: {}, " +
"avgRowSize: {}, estimatedSize {}", this, (indexDesc == null ? "null" : indexDesc.getIndexName()),
(indexDesc == null ? "null" : indexDesc.getIndexInfo()), avgRowSize, fullTableEstimatedSize);
return new MapRDBStatisticsPayload(ROWCOUNT_UNKNOWN, ROWCOUNT_UNKNOWN, avgRowSize);
}
/**
* Get the estimated statistics after applying the {@link RexNode} condition. DO NOT call this API directly.
* Call the stats API instead which modifies the counts based on preference options.
* @param condition filter to apply
* @param index to use for generating the estimate
* @param scanRel the current scan rel
* @return row count post filtering
*/
public MapRDBStatisticsPayload getFirstKeyEstimatedStats(QueryCondition condition, IndexDescriptor index, RelNode scanRel) {
IndexDesc indexDesc = null;
if (index != null) {
indexDesc = (IndexDesc)((MapRDBIndexDescriptor)index).getOriginalDesc();
}
return getFirstKeyEstimatedStatsInternal(condition, indexDesc, scanRel);
}
/**
* Get the estimated statistics after applying the {@link QueryCondition} condition
* @param condition filter to apply
* @param index to use for generating the estimate
* @param scanRel the current scan rel
* @return {@link MapRDBStatisticsPayload} statistics
*/
private MapRDBStatisticsPayload getFirstKeyEstimatedStatsInternal(QueryCondition condition, IndexDesc index, RelNode scanRel) {
// If no index is specified, get it from the primary table
if (index == null && scanSpec.isSecondaryIndex()) {
// If stats not cached get it from the table.
// table = MapRDB.getTable(scanSpec.getPrimaryTablePath());
throw new UnsupportedOperationException("getFirstKeyEstimatedStats should be invoked on primary table");
}
// Get the index table or primary table and use the DB API to get the estimated number of rows. For size estimates,
// we assume that all the columns would be read from the disk.
final Table table = this.formatPlugin.getJsonTableCache().getTable(scanSpec.getTableName(), index, getUserName());
if (table != null) {
// Factor reflecting confidence in the DB estimates. If a table has few tablets, the tablet-level stats
// might be off. The decay scalingFactor will reduce estimates when one tablet represents a significant percentage
// of the entire table.
double scalingFactor = 1.0;
boolean isFullScan = false;
final MetaTable metaTable = table.getMetaTable();
com.mapr.db.scan.ScanStats stats = (condition == null)
? metaTable.getScanStats() : metaTable.getScanStats(condition);
if (index == null && condition != null) {
// Given table condition might not be on leading column. Check if the rowcount matches full table rows.
// In that case no leading key present or does not prune enough. Treat it like so.
com.mapr.db.scan.ScanStats noConditionPTabStats = metaTable.getScanStats();
if (stats.getEstimatedNumRows() == noConditionPTabStats.getEstimatedNumRows()) {
isFullScan = true;
}
}
// Use the scalingFactor only when a condition filters out rows from the table. If no condition is present, all rows
// should be selected. So the scalingFactor should not reduce the returned rows
if (condition != null && !isFullScan) {
double forcedScalingFactor = PrelUtil.getSettings(scanRel.getCluster()).getIndexStatsRowCountScalingFactor();
// Accuracy is defined as 1 - Error where Error = # Boundary Tablets (2) / # Total Matching Tablets.
// For 2 or less matching tablets, the error is assumed to be 50%. The Sqrt gives the decaying scalingFactor
if (stats.getTabletCount() > 2) {
double accuracy = 1.0 - (2.0/stats.getTabletCount());
scalingFactor = Math.min(1.0, 1.0 / Math.sqrt(1.0 / accuracy));
} else {
scalingFactor = 0.5;
}
if (forcedScalingFactor < 1.0
&& metaTable.getScanStats().getTabletCount() < PluginConstants.JSON_TABLE_NUM_TABLETS_PER_INDEX_DEFAULT) {
// User forced confidence scalingFactor for small tables (assumed as less than 32 tablets (~512 MB))
scalingFactor = forcedScalingFactor;
}
}
logger.info("index_plan_info: getEstimatedRowCount obtained from DB Client for {}: indexName: {}, indexInfo: {}, " +
"condition: {} rowCount: {}, avgRowSize: {}, estimatedSize {}, tabletCount {}, totalTabletCount {}, " +
"scalingFactor {}",
this, (index == null ? "null" : index.getIndexName()), (index == null ? "null" : index.getIndexInfo()),
(condition == null ? "null" : condition.toString()), stats.getEstimatedNumRows(),
(stats.getEstimatedNumRows() == 0 ? 0 : stats.getEstimatedSize()/stats.getEstimatedNumRows()),
stats.getEstimatedSize(), stats.getTabletCount(), metaTable.getScanStats().getTabletCount(), scalingFactor);
return new MapRDBStatisticsPayload(scalingFactor * stats.getEstimatedNumRows(), scalingFactor * stats.getEstimatedNumRows(),
((stats.getEstimatedNumRows() == 0 ? 0 : (double)stats.getEstimatedSize()/stats.getEstimatedNumRows())));
} else {
logger.info("index_plan_info: getEstimatedRowCount: {} indexName: {}, indexInfo: {}, " +
"condition: {} rowCount: UNKNOWN, avgRowSize: UNKNOWN", this, (index == null ? "null" : index.getIndexName()),
(index == null ? "null" : index.getIndexInfo()), (condition == null ? "null" : condition.toString()));
return new MapRDBStatisticsPayload(ROWCOUNT_UNKNOWN, ROWCOUNT_UNKNOWN, AVG_ROWSIZE_UNKNOWN);
}
}
/**
* Set the row count resulting from applying the {@link RexNode} condition. Forced row counts will take
* precedence over stats row counts
* @param condition filter to apply
* @param count row count
* @param capRowCount row count limit
*/
@Override
@JsonIgnore
public void setRowCount(RexNode condition, double count, double capRowCount) {
forcedRowCountMap.put(condition, count);
}
@Override
public void setStatistics(Statistics statistics) {
assert statistics instanceof MapRDBStatistics : String.format(
"Passed unexpected statistics instance. Expects MAPR-DB Statistics instance");
this.stats = ((MapRDBStatistics) statistics);
}
/**
* Get the row count after applying the {@link RexNode} condition
* @param condition filter to apply
* @param scanRel the current scan rel
* @return row count post filtering
*/
@Override
@JsonIgnore
public double getRowCount(RexNode condition, RelNode scanRel) {
// Do not use statistics if row count is forced. Forced rowcounts take precedence over stats
double rowcount;
if (forcedRowCountMap.get(condition) != null) {
return forcedRowCountMap.get(condition);
}
if (scanSpec.getIndexDesc() != null) {
String idxIdentifier = stats.buildUniqueIndexIdentifier(scanSpec.getIndexDesc().getPrimaryTablePath(),
scanSpec.getIndexName());
rowcount = stats.getRowCount(condition, idxIdentifier, scanRel);
} else {
rowcount = stats.getRowCount(condition, null, scanRel);
}
// Stats might NOT have the full rows (e.g. table is newly populated and DB stats APIs return it after
// 15 mins). Use the table rows as populated using the (expensive but accurate) Hbase API if needed.
if (condition == null && (rowcount == 0 || rowcount == ROWCOUNT_UNKNOWN)) {
rowcount = fullTableRowCount;
logger.debug("getRowCount: Stats not available yet! Use Admin APIs full table rowcount {}",
fullTableRowCount);
}
return rowcount;
}
@Override
public boolean isDistributed() {
// getMaxParallelizationWidth gets information about all regions to scan and is expensive.
// This option is meant to be used only for unit tests.
boolean useNumRegions = storagePlugin.getContext().getConfig().getBoolean(PluginConstants.JSON_TABLE_USE_NUM_REGIONS_FOR_DISTRIBUTION_PLANNING);
double fullTableSize;
if (useNumRegions) {
return getMaxParallelizationWidth() > 1;
}
// This function gets called multiple times during planning. To avoid performance
// bottleneck, estimate degree of parallelization using stats instead of actually getting information
// about all regions.
double rowCount, rowSize;
double scanRangeSize = storagePlugin.getContext().getConfig().getInt(PluginConstants.JSON_TABLE_SCAN_SIZE_MB) * 1024 * 1024;
if (scanSpec.getIndexDesc() != null) {
String idxIdentifier = stats.buildUniqueIndexIdentifier(scanSpec.getIndexDesc().getPrimaryTablePath(), scanSpec.getIndexName());
rowCount = stats.getRowCount(scanSpec.getCondition(), idxIdentifier);
rowSize = stats.getAvgRowSize(idxIdentifier, false);
} else {
rowCount = stats.getRowCount(scanSpec.getCondition(), null);
rowSize = stats.getAvgRowSize(null, false);
}
if (rowCount == ROWCOUNT_UNKNOWN || rowCount == 0 ||
rowSize == AVG_ROWSIZE_UNKNOWN || rowSize == 0) {
fullTableSize = (scanSpec.getSerializedFilter() != null ? .5 : 1) * this.fullTableEstimatedSize;
} else {
fullTableSize = rowCount * rowSize;
}
return (long) fullTableSize / scanRangeSize > 1;
}
@Override
public MapRDBStatistics getStatistics() {
return stats;
}
@Override
@JsonIgnore
public void setColumns(List<SchemaPath> columns) {
this.columns = columns;
}
@Override
@JsonIgnore
public List<SchemaPath> getColumns() {
return columns;
}
@Override
@JsonIgnore
public PartitionFunction getRangePartitionFunction(List<FieldReference> refList) {
return new JsonTableRangePartitionFunction(refList, scanSpec.getTableName(), this.getUserName(), this.getFormatPlugin());
}
/**
* Convert a given {@link LogicalExpression} condition into a {@link QueryCondition} condition
* @param condition expressed as a {@link LogicalExpression}
* @return {@link QueryCondition} condition equivalent to the given expression
*/
@JsonIgnore
public QueryCondition convertToQueryCondition(LogicalExpression condition) {
final JsonConditionBuilder jsonConditionBuilder = new JsonConditionBuilder(this, condition);
final JsonScanSpec newScanSpec = jsonConditionBuilder.parseTree();
if (newScanSpec != null) {
return newScanSpec.getCondition();
} else {
return null;
}
}
/**
* Checks if Json table reader supports limit push down.
*
* @return true if limit push down is supported, false otherwise
*/
@Override
public boolean supportsLimitPushdown() {
if (maxRecordsToRead < 0) {
return true;
}
return false; // limit is already pushed. No more pushdown of limit
}
@Override
public GroupScan applyLimit(int maxRecords) {
maxRecordsToRead = Math.max(maxRecords, 1);
return this;
}
@Override
public int getMaxParallelizationWidth() {
if (this.parallelizationWidth > 0) {
return this.parallelizationWidth;
}
return super.getMaxParallelizationWidth();
}
@Override
public void setParallelizationWidth(int width) {
if (width > 0) {
this.parallelizationWidth = width;
logger.debug("Forced parallelization width = {}", width);
}
}
}
|
googleapis/google-cloud-java | 35,740 | java-asset/proto-google-cloud-asset-v1/src/main/java/com/google/cloud/asset/v1/UpdateFeedRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/asset/v1/asset_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.asset.v1;
/**
*
*
* <pre>
* Update asset feed request.
* </pre>
*
* Protobuf type {@code google.cloud.asset.v1.UpdateFeedRequest}
*/
public final class UpdateFeedRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.asset.v1.UpdateFeedRequest)
UpdateFeedRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateFeedRequest.newBuilder() to construct.
private UpdateFeedRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateFeedRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateFeedRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.asset.v1.AssetServiceProto
.internal_static_google_cloud_asset_v1_UpdateFeedRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.asset.v1.AssetServiceProto
.internal_static_google_cloud_asset_v1_UpdateFeedRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.asset.v1.UpdateFeedRequest.class,
com.google.cloud.asset.v1.UpdateFeedRequest.Builder.class);
}
private int bitField0_;
public static final int FEED_FIELD_NUMBER = 1;
private com.google.cloud.asset.v1.Feed feed_;
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return Whether the feed field is set.
*/
@java.lang.Override
public boolean hasFeed() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The feed.
*/
@java.lang.Override
public com.google.cloud.asset.v1.Feed getFeed() {
return feed_ == null ? com.google.cloud.asset.v1.Feed.getDefaultInstance() : feed_;
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.cloud.asset.v1.FeedOrBuilder getFeedOrBuilder() {
return feed_ == null ? com.google.cloud.asset.v1.Feed.getDefaultInstance() : feed_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Required. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getFeed());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getUpdateMask());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getFeed());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.asset.v1.UpdateFeedRequest)) {
return super.equals(obj);
}
com.google.cloud.asset.v1.UpdateFeedRequest other =
(com.google.cloud.asset.v1.UpdateFeedRequest) obj;
if (hasFeed() != other.hasFeed()) return false;
if (hasFeed()) {
if (!getFeed().equals(other.getFeed())) return false;
}
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasFeed()) {
hash = (37 * hash) + FEED_FIELD_NUMBER;
hash = (53 * hash) + getFeed().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.asset.v1.UpdateFeedRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.asset.v1.UpdateFeedRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.asset.v1.UpdateFeedRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.asset.v1.UpdateFeedRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.asset.v1.UpdateFeedRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.asset.v1.UpdateFeedRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.asset.v1.UpdateFeedRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.asset.v1.UpdateFeedRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.asset.v1.UpdateFeedRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.asset.v1.UpdateFeedRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.asset.v1.UpdateFeedRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.asset.v1.UpdateFeedRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.asset.v1.UpdateFeedRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Update asset feed request.
* </pre>
*
* Protobuf type {@code google.cloud.asset.v1.UpdateFeedRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.asset.v1.UpdateFeedRequest)
com.google.cloud.asset.v1.UpdateFeedRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.asset.v1.AssetServiceProto
.internal_static_google_cloud_asset_v1_UpdateFeedRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.asset.v1.AssetServiceProto
.internal_static_google_cloud_asset_v1_UpdateFeedRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.asset.v1.UpdateFeedRequest.class,
com.google.cloud.asset.v1.UpdateFeedRequest.Builder.class);
}
// Construct using com.google.cloud.asset.v1.UpdateFeedRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getFeedFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
feed_ = null;
if (feedBuilder_ != null) {
feedBuilder_.dispose();
feedBuilder_ = null;
}
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.asset.v1.AssetServiceProto
.internal_static_google_cloud_asset_v1_UpdateFeedRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.asset.v1.UpdateFeedRequest getDefaultInstanceForType() {
return com.google.cloud.asset.v1.UpdateFeedRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.asset.v1.UpdateFeedRequest build() {
com.google.cloud.asset.v1.UpdateFeedRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.asset.v1.UpdateFeedRequest buildPartial() {
com.google.cloud.asset.v1.UpdateFeedRequest result =
new com.google.cloud.asset.v1.UpdateFeedRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.asset.v1.UpdateFeedRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.feed_ = feedBuilder_ == null ? feed_ : feedBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.asset.v1.UpdateFeedRequest) {
return mergeFrom((com.google.cloud.asset.v1.UpdateFeedRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.asset.v1.UpdateFeedRequest other) {
if (other == com.google.cloud.asset.v1.UpdateFeedRequest.getDefaultInstance()) return this;
if (other.hasFeed()) {
mergeFeed(other.getFeed());
}
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(getFeedFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.asset.v1.Feed feed_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.asset.v1.Feed,
com.google.cloud.asset.v1.Feed.Builder,
com.google.cloud.asset.v1.FeedOrBuilder>
feedBuilder_;
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return Whether the feed field is set.
*/
public boolean hasFeed() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The feed.
*/
public com.google.cloud.asset.v1.Feed getFeed() {
if (feedBuilder_ == null) {
return feed_ == null ? com.google.cloud.asset.v1.Feed.getDefaultInstance() : feed_;
} else {
return feedBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setFeed(com.google.cloud.asset.v1.Feed value) {
if (feedBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
feed_ = value;
} else {
feedBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setFeed(com.google.cloud.asset.v1.Feed.Builder builderForValue) {
if (feedBuilder_ == null) {
feed_ = builderForValue.build();
} else {
feedBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder mergeFeed(com.google.cloud.asset.v1.Feed value) {
if (feedBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& feed_ != null
&& feed_ != com.google.cloud.asset.v1.Feed.getDefaultInstance()) {
getFeedBuilder().mergeFrom(value);
} else {
feed_ = value;
}
} else {
feedBuilder_.mergeFrom(value);
}
if (feed_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearFeed() {
bitField0_ = (bitField0_ & ~0x00000001);
feed_ = null;
if (feedBuilder_ != null) {
feedBuilder_.dispose();
feedBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.cloud.asset.v1.Feed.Builder getFeedBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getFeedFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.cloud.asset.v1.FeedOrBuilder getFeedOrBuilder() {
if (feedBuilder_ != null) {
return feedBuilder_.getMessageOrBuilder();
} else {
return feed_ == null ? com.google.cloud.asset.v1.Feed.getDefaultInstance() : feed_;
}
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.asset.v1.Feed,
com.google.cloud.asset.v1.Feed.Builder,
com.google.cloud.asset.v1.FeedOrBuilder>
getFeedFieldBuilder() {
if (feedBuilder_ == null) {
feedBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.asset.v1.Feed,
com.google.cloud.asset.v1.Feed.Builder,
com.google.cloud.asset.v1.FeedOrBuilder>(
getFeed(), getParentForChildren(), isClean());
feed_ = null;
}
return feedBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* Required. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Required. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.asset.v1.UpdateFeedRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.asset.v1.UpdateFeedRequest)
private static final com.google.cloud.asset.v1.UpdateFeedRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.asset.v1.UpdateFeedRequest();
}
public static com.google.cloud.asset.v1.UpdateFeedRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateFeedRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateFeedRequest>() {
@java.lang.Override
public UpdateFeedRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<UpdateFeedRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateFeedRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.asset.v1.UpdateFeedRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-api-java-client-services | 35,913 | clients/google-api-services-fcm/v1/2.0.0/com/google/api/services/fcm/v1/model/AndroidNotification.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.fcm.v1.model;
/**
* Notification to send to android devices.
*
* <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 Firebase Cloud Messaging 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 AndroidNotification extends com.google.api.client.json.GenericJson {
/**
* The notification's body text. If present, it will override
* google.firebase.fcm.v1.Notification.body.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String body;
/**
* Variable string values to be used in place of the format specifiers in body_loc_key to use to
* localize the body text to the user's current localization. See [Formatting and
* Styling](https://goo.gl/MalYE3) for more information.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> bodyLocArgs;
/**
* The key to the body string in the app's string resources to use to localize the body text to
* the user's current localization. See [String Resources](https://goo.gl/NdFZGI) for more
* information.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String bodyLocKey;
/**
* If set, display notifications delivered to the device will be handled by the app instead of the
* proxy.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean bypassProxyNotification;
/**
* The [notification's channel
* id](https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels) (new
* in Android O). The app must create a channel with this channel ID before any notification with
* this channel ID is received. If you don't send this channel ID in the request, or if the
* channel ID provided has not yet been created by the app, FCM uses the channel ID specified in
* the app manifest.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String channelId;
/**
* The action associated with a user click on the notification. If specified, an activity with a
* matching intent filter is launched when a user clicks on the notification.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String clickAction;
/**
* The notification's icon color, expressed in #rrggbb format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String color;
/**
* If set to true, use the Android framework's default LED light settings for the notification.
* Default values are specified in [config.xml](https://android.googlesource.com/platform/framewor
* ks/base/+/master/core/res/res/values/config.xml). If `default_light_settings` is set to true
* and `light_settings` is also set, the user-specified `light_settings` is used instead of the
* default value.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean defaultLightSettings;
/**
* If set to true, use the Android framework's default sound for the notification. Default values
* are specified in [config.xml](https://android.googlesource.com/platform/frameworks/base/+/maste
* r/core/res/res/values/config.xml).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean defaultSound;
/**
* If set to true, use the Android framework's default vibrate pattern for the notification.
* Default values are specified in [config.xml](https://android.googlesource.com/platform/framewor
* ks/base/+/master/core/res/res/values/config.xml). If `default_vibrate_timings` is set to true
* and `vibrate_timings` is also set, the default value is used instead of the user-specified
* `vibrate_timings`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean defaultVibrateTimings;
/**
* Set the time that the event in the notification occurred. Notifications in the panel are sorted
* by this time. A point in time is represented using
* [protobuf.Timestamp](https://developers.google.com/protocol-
* buffers/docs/reference/java/com/google/protobuf/Timestamp).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String eventTime;
/**
* The notification's icon. Sets the notification icon to myicon for drawable resource myicon. If
* you don't send this key in the request, FCM displays the launcher icon specified in your app
* manifest.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String icon;
/**
* Contains the URL of an image that is going to be displayed in a notification. If present, it
* will override google.firebase.fcm.v1.Notification.image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String image;
/**
* Settings to control the notification's LED blinking rate and color if LED is available on the
* device. The total blinking time is controlled by the OS.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LightSettings lightSettings;
/**
* Set whether or not this notification is relevant only to the current device. Some notifications
* can be bridged to other devices for remote display, such as a Wear OS watch. This hint can be
* set to recommend this notification not be bridged. See [Wear OS
* guides](https://developer.android.com/training/wearables/notifications/bridger#existing-method-
* of-preventing-bridging)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean localOnly;
/**
* Sets the number of items this notification represents. May be displayed as a badge count for
* launchers that support badging.See [Notification
* Badge](https://developer.android.com/training/notify-user/badges). For example, this might be
* useful if you're using just one notification to represent multiple new messages but you want
* the count here to represent the number of total new messages. If zero or unspecified, systems
* that support badging use the default, which is to increment a number displayed on the long-
* press menu each time a new notification arrives.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer notificationCount;
/**
* Set the relative priority for this notification. Priority is an indication of how much of the
* user's attention should be consumed by this notification. Low-priority notifications may be
* hidden from the user in certain situations, while the user might be interrupted for a higher-
* priority notification. The effect of setting the same priorities may differ slightly on
* different platforms. Note this priority differs from `AndroidMessagePriority`. This priority is
* processed by the client after the message has been delivered, whereas [AndroidMessagePriority](
* https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidmessagepriority
* ) is an FCM concept that controls when the message is delivered.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String notificationPriority;
/**
* Setting to control when a notification may be proxied.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String proxy;
/**
* The sound to play when the device receives the notification. Supports "default" or the filename
* of a sound resource bundled in the app. Sound files must reside in /res/raw/.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sound;
/**
* When set to false or unset, the notification is automatically dismissed when the user clicks it
* in the panel. When set to true, the notification persists even when the user clicks it.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sticky;
/**
* Identifier used to replace existing notifications in the notification drawer. If not specified,
* each request creates a new notification. If specified and a notification with the same tag is
* already being shown, the new notification replaces the existing one in the notification drawer.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String tag;
/**
* Sets the "ticker" text, which is sent to accessibility services. Prior to API level 21
* (`Lollipop`), sets the text that is displayed in the status bar when the notification first
* arrives.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String ticker;
/**
* The notification's title. If present, it will override
* google.firebase.fcm.v1.Notification.title.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String title;
/**
* Variable string values to be used in place of the format specifiers in title_loc_key to use to
* localize the title text to the user's current localization. See [Formatting and
* Styling](https://goo.gl/MalYE3) for more information.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> titleLocArgs;
/**
* The key to the title string in the app's string resources to use to localize the title text to
* the user's current localization. See [String Resources](https://goo.gl/NdFZGI) for more
* information.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String titleLocKey;
/**
* Set the vibration pattern to use. Pass in an array of
* [protobuf.Duration](https://developers.google.com/protocol-
* buffers/docs/reference/google.protobuf#google.protobuf.Duration) to turn on or off the
* vibrator. The first value indicates the `Duration` to wait before turning the vibrator on. The
* next value indicates the `Duration` to keep the vibrator on. Subsequent values alternate
* between `Duration` to turn the vibrator off and to turn the vibrator on. If `vibrate_timings`
* is set and `default_vibrate_timings` is set to `true`, the default value is used instead of the
* user-specified `vibrate_timings`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<String> vibrateTimings;
/**
* Set the [Notification.visibility](https://developer.android.com/reference/android/app/Notificat
* ion.html#visibility) of the notification.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String visibility;
/**
* The notification's body text. If present, it will override
* google.firebase.fcm.v1.Notification.body.
* @return value or {@code null} for none
*/
public java.lang.String getBody() {
return body;
}
/**
* The notification's body text. If present, it will override
* google.firebase.fcm.v1.Notification.body.
* @param body body or {@code null} for none
*/
public AndroidNotification setBody(java.lang.String body) {
this.body = body;
return this;
}
/**
* Variable string values to be used in place of the format specifiers in body_loc_key to use to
* localize the body text to the user's current localization. See [Formatting and
* Styling](https://goo.gl/MalYE3) for more information.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getBodyLocArgs() {
return bodyLocArgs;
}
/**
* Variable string values to be used in place of the format specifiers in body_loc_key to use to
* localize the body text to the user's current localization. See [Formatting and
* Styling](https://goo.gl/MalYE3) for more information.
* @param bodyLocArgs bodyLocArgs or {@code null} for none
*/
public AndroidNotification setBodyLocArgs(java.util.List<java.lang.String> bodyLocArgs) {
this.bodyLocArgs = bodyLocArgs;
return this;
}
/**
* The key to the body string in the app's string resources to use to localize the body text to
* the user's current localization. See [String Resources](https://goo.gl/NdFZGI) for more
* information.
* @return value or {@code null} for none
*/
public java.lang.String getBodyLocKey() {
return bodyLocKey;
}
/**
* The key to the body string in the app's string resources to use to localize the body text to
* the user's current localization. See [String Resources](https://goo.gl/NdFZGI) for more
* information.
* @param bodyLocKey bodyLocKey or {@code null} for none
*/
public AndroidNotification setBodyLocKey(java.lang.String bodyLocKey) {
this.bodyLocKey = bodyLocKey;
return this;
}
/**
* If set, display notifications delivered to the device will be handled by the app instead of the
* proxy.
* @return value or {@code null} for none
*/
public java.lang.Boolean getBypassProxyNotification() {
return bypassProxyNotification;
}
/**
* If set, display notifications delivered to the device will be handled by the app instead of the
* proxy.
* @param bypassProxyNotification bypassProxyNotification or {@code null} for none
*/
public AndroidNotification setBypassProxyNotification(java.lang.Boolean bypassProxyNotification) {
this.bypassProxyNotification = bypassProxyNotification;
return this;
}
/**
* The [notification's channel
* id](https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels) (new
* in Android O). The app must create a channel with this channel ID before any notification with
* this channel ID is received. If you don't send this channel ID in the request, or if the
* channel ID provided has not yet been created by the app, FCM uses the channel ID specified in
* the app manifest.
* @return value or {@code null} for none
*/
public java.lang.String getChannelId() {
return channelId;
}
/**
* The [notification's channel
* id](https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels) (new
* in Android O). The app must create a channel with this channel ID before any notification with
* this channel ID is received. If you don't send this channel ID in the request, or if the
* channel ID provided has not yet been created by the app, FCM uses the channel ID specified in
* the app manifest.
* @param channelId channelId or {@code null} for none
*/
public AndroidNotification setChannelId(java.lang.String channelId) {
this.channelId = channelId;
return this;
}
/**
* The action associated with a user click on the notification. If specified, an activity with a
* matching intent filter is launched when a user clicks on the notification.
* @return value or {@code null} for none
*/
public java.lang.String getClickAction() {
return clickAction;
}
/**
* The action associated with a user click on the notification. If specified, an activity with a
* matching intent filter is launched when a user clicks on the notification.
* @param clickAction clickAction or {@code null} for none
*/
public AndroidNotification setClickAction(java.lang.String clickAction) {
this.clickAction = clickAction;
return this;
}
/**
* The notification's icon color, expressed in #rrggbb format.
* @return value or {@code null} for none
*/
public java.lang.String getColor() {
return color;
}
/**
* The notification's icon color, expressed in #rrggbb format.
* @param color color or {@code null} for none
*/
public AndroidNotification setColor(java.lang.String color) {
this.color = color;
return this;
}
/**
* If set to true, use the Android framework's default LED light settings for the notification.
* Default values are specified in [config.xml](https://android.googlesource.com/platform/framewor
* ks/base/+/master/core/res/res/values/config.xml). If `default_light_settings` is set to true
* and `light_settings` is also set, the user-specified `light_settings` is used instead of the
* default value.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDefaultLightSettings() {
return defaultLightSettings;
}
/**
* If set to true, use the Android framework's default LED light settings for the notification.
* Default values are specified in [config.xml](https://android.googlesource.com/platform/framewor
* ks/base/+/master/core/res/res/values/config.xml). If `default_light_settings` is set to true
* and `light_settings` is also set, the user-specified `light_settings` is used instead of the
* default value.
* @param defaultLightSettings defaultLightSettings or {@code null} for none
*/
public AndroidNotification setDefaultLightSettings(java.lang.Boolean defaultLightSettings) {
this.defaultLightSettings = defaultLightSettings;
return this;
}
/**
* If set to true, use the Android framework's default sound for the notification. Default values
* are specified in [config.xml](https://android.googlesource.com/platform/frameworks/base/+/maste
* r/core/res/res/values/config.xml).
* @return value or {@code null} for none
*/
public java.lang.Boolean getDefaultSound() {
return defaultSound;
}
/**
* If set to true, use the Android framework's default sound for the notification. Default values
* are specified in [config.xml](https://android.googlesource.com/platform/frameworks/base/+/maste
* r/core/res/res/values/config.xml).
* @param defaultSound defaultSound or {@code null} for none
*/
public AndroidNotification setDefaultSound(java.lang.Boolean defaultSound) {
this.defaultSound = defaultSound;
return this;
}
/**
* If set to true, use the Android framework's default vibrate pattern for the notification.
* Default values are specified in [config.xml](https://android.googlesource.com/platform/framewor
* ks/base/+/master/core/res/res/values/config.xml). If `default_vibrate_timings` is set to true
* and `vibrate_timings` is also set, the default value is used instead of the user-specified
* `vibrate_timings`.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDefaultVibrateTimings() {
return defaultVibrateTimings;
}
/**
* If set to true, use the Android framework's default vibrate pattern for the notification.
* Default values are specified in [config.xml](https://android.googlesource.com/platform/framewor
* ks/base/+/master/core/res/res/values/config.xml). If `default_vibrate_timings` is set to true
* and `vibrate_timings` is also set, the default value is used instead of the user-specified
* `vibrate_timings`.
* @param defaultVibrateTimings defaultVibrateTimings or {@code null} for none
*/
public AndroidNotification setDefaultVibrateTimings(java.lang.Boolean defaultVibrateTimings) {
this.defaultVibrateTimings = defaultVibrateTimings;
return this;
}
/**
* Set the time that the event in the notification occurred. Notifications in the panel are sorted
* by this time. A point in time is represented using
* [protobuf.Timestamp](https://developers.google.com/protocol-
* buffers/docs/reference/java/com/google/protobuf/Timestamp).
* @return value or {@code null} for none
*/
public String getEventTime() {
return eventTime;
}
/**
* Set the time that the event in the notification occurred. Notifications in the panel are sorted
* by this time. A point in time is represented using
* [protobuf.Timestamp](https://developers.google.com/protocol-
* buffers/docs/reference/java/com/google/protobuf/Timestamp).
* @param eventTime eventTime or {@code null} for none
*/
public AndroidNotification setEventTime(String eventTime) {
this.eventTime = eventTime;
return this;
}
/**
* The notification's icon. Sets the notification icon to myicon for drawable resource myicon. If
* you don't send this key in the request, FCM displays the launcher icon specified in your app
* manifest.
* @return value or {@code null} for none
*/
public java.lang.String getIcon() {
return icon;
}
/**
* The notification's icon. Sets the notification icon to myicon for drawable resource myicon. If
* you don't send this key in the request, FCM displays the launcher icon specified in your app
* manifest.
* @param icon icon or {@code null} for none
*/
public AndroidNotification setIcon(java.lang.String icon) {
this.icon = icon;
return this;
}
/**
* Contains the URL of an image that is going to be displayed in a notification. If present, it
* will override google.firebase.fcm.v1.Notification.image.
* @return value or {@code null} for none
*/
public java.lang.String getImage() {
return image;
}
/**
* Contains the URL of an image that is going to be displayed in a notification. If present, it
* will override google.firebase.fcm.v1.Notification.image.
* @param image image or {@code null} for none
*/
public AndroidNotification setImage(java.lang.String image) {
this.image = image;
return this;
}
/**
* Settings to control the notification's LED blinking rate and color if LED is available on the
* device. The total blinking time is controlled by the OS.
* @return value or {@code null} for none
*/
public LightSettings getLightSettings() {
return lightSettings;
}
/**
* Settings to control the notification's LED blinking rate and color if LED is available on the
* device. The total blinking time is controlled by the OS.
* @param lightSettings lightSettings or {@code null} for none
*/
public AndroidNotification setLightSettings(LightSettings lightSettings) {
this.lightSettings = lightSettings;
return this;
}
/**
* Set whether or not this notification is relevant only to the current device. Some notifications
* can be bridged to other devices for remote display, such as a Wear OS watch. This hint can be
* set to recommend this notification not be bridged. See [Wear OS
* guides](https://developer.android.com/training/wearables/notifications/bridger#existing-method-
* of-preventing-bridging)
* @return value or {@code null} for none
*/
public java.lang.Boolean getLocalOnly() {
return localOnly;
}
/**
* Set whether or not this notification is relevant only to the current device. Some notifications
* can be bridged to other devices for remote display, such as a Wear OS watch. This hint can be
* set to recommend this notification not be bridged. See [Wear OS
* guides](https://developer.android.com/training/wearables/notifications/bridger#existing-method-
* of-preventing-bridging)
* @param localOnly localOnly or {@code null} for none
*/
public AndroidNotification setLocalOnly(java.lang.Boolean localOnly) {
this.localOnly = localOnly;
return this;
}
/**
* Sets the number of items this notification represents. May be displayed as a badge count for
* launchers that support badging.See [Notification
* Badge](https://developer.android.com/training/notify-user/badges). For example, this might be
* useful if you're using just one notification to represent multiple new messages but you want
* the count here to represent the number of total new messages. If zero or unspecified, systems
* that support badging use the default, which is to increment a number displayed on the long-
* press menu each time a new notification arrives.
* @return value or {@code null} for none
*/
public java.lang.Integer getNotificationCount() {
return notificationCount;
}
/**
* Sets the number of items this notification represents. May be displayed as a badge count for
* launchers that support badging.See [Notification
* Badge](https://developer.android.com/training/notify-user/badges). For example, this might be
* useful if you're using just one notification to represent multiple new messages but you want
* the count here to represent the number of total new messages. If zero or unspecified, systems
* that support badging use the default, which is to increment a number displayed on the long-
* press menu each time a new notification arrives.
* @param notificationCount notificationCount or {@code null} for none
*/
public AndroidNotification setNotificationCount(java.lang.Integer notificationCount) {
this.notificationCount = notificationCount;
return this;
}
/**
* Set the relative priority for this notification. Priority is an indication of how much of the
* user's attention should be consumed by this notification. Low-priority notifications may be
* hidden from the user in certain situations, while the user might be interrupted for a higher-
* priority notification. The effect of setting the same priorities may differ slightly on
* different platforms. Note this priority differs from `AndroidMessagePriority`. This priority is
* processed by the client after the message has been delivered, whereas [AndroidMessagePriority](
* https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidmessagepriority
* ) is an FCM concept that controls when the message is delivered.
* @return value or {@code null} for none
*/
public java.lang.String getNotificationPriority() {
return notificationPriority;
}
/**
* Set the relative priority for this notification. Priority is an indication of how much of the
* user's attention should be consumed by this notification. Low-priority notifications may be
* hidden from the user in certain situations, while the user might be interrupted for a higher-
* priority notification. The effect of setting the same priorities may differ slightly on
* different platforms. Note this priority differs from `AndroidMessagePriority`. This priority is
* processed by the client after the message has been delivered, whereas [AndroidMessagePriority](
* https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidmessagepriority
* ) is an FCM concept that controls when the message is delivered.
* @param notificationPriority notificationPriority or {@code null} for none
*/
public AndroidNotification setNotificationPriority(java.lang.String notificationPriority) {
this.notificationPriority = notificationPriority;
return this;
}
/**
* Setting to control when a notification may be proxied.
* @return value or {@code null} for none
*/
public java.lang.String getProxy() {
return proxy;
}
/**
* Setting to control when a notification may be proxied.
* @param proxy proxy or {@code null} for none
*/
public AndroidNotification setProxy(java.lang.String proxy) {
this.proxy = proxy;
return this;
}
/**
* The sound to play when the device receives the notification. Supports "default" or the filename
* of a sound resource bundled in the app. Sound files must reside in /res/raw/.
* @return value or {@code null} for none
*/
public java.lang.String getSound() {
return sound;
}
/**
* The sound to play when the device receives the notification. Supports "default" or the filename
* of a sound resource bundled in the app. Sound files must reside in /res/raw/.
* @param sound sound or {@code null} for none
*/
public AndroidNotification setSound(java.lang.String sound) {
this.sound = sound;
return this;
}
/**
* When set to false or unset, the notification is automatically dismissed when the user clicks it
* in the panel. When set to true, the notification persists even when the user clicks it.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSticky() {
return sticky;
}
/**
* When set to false or unset, the notification is automatically dismissed when the user clicks it
* in the panel. When set to true, the notification persists even when the user clicks it.
* @param sticky sticky or {@code null} for none
*/
public AndroidNotification setSticky(java.lang.Boolean sticky) {
this.sticky = sticky;
return this;
}
/**
* Identifier used to replace existing notifications in the notification drawer. If not specified,
* each request creates a new notification. If specified and a notification with the same tag is
* already being shown, the new notification replaces the existing one in the notification drawer.
* @return value or {@code null} for none
*/
public java.lang.String getTag() {
return tag;
}
/**
* Identifier used to replace existing notifications in the notification drawer. If not specified,
* each request creates a new notification. If specified and a notification with the same tag is
* already being shown, the new notification replaces the existing one in the notification drawer.
* @param tag tag or {@code null} for none
*/
public AndroidNotification setTag(java.lang.String tag) {
this.tag = tag;
return this;
}
/**
* Sets the "ticker" text, which is sent to accessibility services. Prior to API level 21
* (`Lollipop`), sets the text that is displayed in the status bar when the notification first
* arrives.
* @return value or {@code null} for none
*/
public java.lang.String getTicker() {
return ticker;
}
/**
* Sets the "ticker" text, which is sent to accessibility services. Prior to API level 21
* (`Lollipop`), sets the text that is displayed in the status bar when the notification first
* arrives.
* @param ticker ticker or {@code null} for none
*/
public AndroidNotification setTicker(java.lang.String ticker) {
this.ticker = ticker;
return this;
}
/**
* The notification's title. If present, it will override
* google.firebase.fcm.v1.Notification.title.
* @return value or {@code null} for none
*/
public java.lang.String getTitle() {
return title;
}
/**
* The notification's title. If present, it will override
* google.firebase.fcm.v1.Notification.title.
* @param title title or {@code null} for none
*/
public AndroidNotification setTitle(java.lang.String title) {
this.title = title;
return this;
}
/**
* Variable string values to be used in place of the format specifiers in title_loc_key to use to
* localize the title text to the user's current localization. See [Formatting and
* Styling](https://goo.gl/MalYE3) for more information.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTitleLocArgs() {
return titleLocArgs;
}
/**
* Variable string values to be used in place of the format specifiers in title_loc_key to use to
* localize the title text to the user's current localization. See [Formatting and
* Styling](https://goo.gl/MalYE3) for more information.
* @param titleLocArgs titleLocArgs or {@code null} for none
*/
public AndroidNotification setTitleLocArgs(java.util.List<java.lang.String> titleLocArgs) {
this.titleLocArgs = titleLocArgs;
return this;
}
/**
* The key to the title string in the app's string resources to use to localize the title text to
* the user's current localization. See [String Resources](https://goo.gl/NdFZGI) for more
* information.
* @return value or {@code null} for none
*/
public java.lang.String getTitleLocKey() {
return titleLocKey;
}
/**
* The key to the title string in the app's string resources to use to localize the title text to
* the user's current localization. See [String Resources](https://goo.gl/NdFZGI) for more
* information.
* @param titleLocKey titleLocKey or {@code null} for none
*/
public AndroidNotification setTitleLocKey(java.lang.String titleLocKey) {
this.titleLocKey = titleLocKey;
return this;
}
/**
* Set the vibration pattern to use. Pass in an array of
* [protobuf.Duration](https://developers.google.com/protocol-
* buffers/docs/reference/google.protobuf#google.protobuf.Duration) to turn on or off the
* vibrator. The first value indicates the `Duration` to wait before turning the vibrator on. The
* next value indicates the `Duration` to keep the vibrator on. Subsequent values alternate
* between `Duration` to turn the vibrator off and to turn the vibrator on. If `vibrate_timings`
* is set and `default_vibrate_timings` is set to `true`, the default value is used instead of the
* user-specified `vibrate_timings`.
* @return value or {@code null} for none
*/
public java.util.List<String> getVibrateTimings() {
return vibrateTimings;
}
/**
* Set the vibration pattern to use. Pass in an array of
* [protobuf.Duration](https://developers.google.com/protocol-
* buffers/docs/reference/google.protobuf#google.protobuf.Duration) to turn on or off the
* vibrator. The first value indicates the `Duration` to wait before turning the vibrator on. The
* next value indicates the `Duration` to keep the vibrator on. Subsequent values alternate
* between `Duration` to turn the vibrator off and to turn the vibrator on. If `vibrate_timings`
* is set and `default_vibrate_timings` is set to `true`, the default value is used instead of the
* user-specified `vibrate_timings`.
* @param vibrateTimings vibrateTimings or {@code null} for none
*/
public AndroidNotification setVibrateTimings(java.util.List<String> vibrateTimings) {
this.vibrateTimings = vibrateTimings;
return this;
}
/**
* Set the [Notification.visibility](https://developer.android.com/reference/android/app/Notificat
* ion.html#visibility) of the notification.
* @return value or {@code null} for none
*/
public java.lang.String getVisibility() {
return visibility;
}
/**
* Set the [Notification.visibility](https://developer.android.com/reference/android/app/Notificat
* ion.html#visibility) of the notification.
* @param visibility visibility or {@code null} for none
*/
public AndroidNotification setVisibility(java.lang.String visibility) {
this.visibility = visibility;
return this;
}
@Override
public AndroidNotification set(String fieldName, Object value) {
return (AndroidNotification) super.set(fieldName, value);
}
@Override
public AndroidNotification clone() {
return (AndroidNotification) super.clone();
}
}
|
googleads/googleads-java-lib | 35,853 | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202411/ContentServiceSoapBindingStub.java | // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* ContentServiceSoapBindingStub.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4.1-SNAPSHOT Mar 20, 2024 (11:59:10 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202411;
public class ContentServiceSoapBindingStub extends org.apache.axis.client.Stub implements com.google.api.ads.admanager.axis.v202411.ContentServiceInterface {
private java.util.Vector cachedSerClasses = new java.util.Vector();
private java.util.Vector cachedSerQNames = new java.util.Vector();
private java.util.Vector cachedSerFactories = new java.util.Vector();
private java.util.Vector cachedDeserFactories = new java.util.Vector();
static org.apache.axis.description.OperationDesc [] _operations;
static {
_operations = new org.apache.axis.description.OperationDesc[1];
_initOperationDesc1();
}
private static void _initOperationDesc1(){
org.apache.axis.description.OperationDesc oper;
org.apache.axis.description.ParameterDesc param;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("getContentByStatement");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "statement"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "Statement"), com.google.api.ads.admanager.axis.v202411.Statement.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ContentPage"));
oper.setReturnClass(com.google.api.ads.admanager.axis.v202411.ContentPage.class);
oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "rval"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ApiExceptionFault"),
"com.google.api.ads.admanager.axis.v202411.ApiException",
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ApiException"),
true
));
_operations[0] = oper;
}
public ContentServiceSoapBindingStub() throws org.apache.axis.AxisFault {
this(null);
}
public ContentServiceSoapBindingStub(java.net.URL endpointURL, javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
this(service);
super.cachedEndpoint = endpointURL;
}
public ContentServiceSoapBindingStub(javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
if (service == null) {
super.service = new org.apache.axis.client.Service();
} else {
super.service = service;
}
((org.apache.axis.client.Service)super.service).setTypeMappingVersion("1.2");
java.lang.Class cls;
javax.xml.namespace.QName qName;
javax.xml.namespace.QName qName2;
java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class;
java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class;
java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class;
java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class;
java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class;
java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class;
java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class;
java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class;
java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class;
java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class;
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ApiError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.ApiError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ApiException");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.ApiException.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ApiVersionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.ApiVersionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ApiVersionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.ApiVersionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ApplicationException");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.ApplicationException.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "AuthenticationError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.AuthenticationError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "AuthenticationError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.AuthenticationErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "BooleanValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.BooleanValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "CmsContent");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.CmsContent.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "CollectionSizeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.CollectionSizeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "CollectionSizeError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.CollectionSizeErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "CommonError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.CommonError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "CommonError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.CommonErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "Content");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.Content.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ContentPage");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.ContentPage.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ContentStatus");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.ContentStatus.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ContentStatusDefinedBy");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.ContentStatusDefinedBy.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "DaiIngestError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.DaiIngestError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "DaiIngestErrorReason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.DaiIngestErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "DaiIngestStatus");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.DaiIngestStatus.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "Date");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.Date.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "DateTime");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.DateTime.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "DateTimeValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.DateTimeValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "DateValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.DateValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "FeatureError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.FeatureError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "FeatureError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.FeatureErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "FieldPathElement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.FieldPathElement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "InternalApiError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.InternalApiError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "InternalApiError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.InternalApiErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "InvalidUrlError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.InvalidUrlError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "InvalidUrlError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.InvalidUrlErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "NotNullError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.NotNullError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "NotNullError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.NotNullErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "NumberValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.NumberValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ObjectValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.ObjectValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ParseError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.ParseError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ParseError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.ParseErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "PermissionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.PermissionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "PermissionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.PermissionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "PublisherQueryLanguageContextError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.PublisherQueryLanguageContextError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "PublisherQueryLanguageContextError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.PublisherQueryLanguageContextErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "PublisherQueryLanguageSyntaxError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.PublisherQueryLanguageSyntaxError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "PublisherQueryLanguageSyntaxError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.PublisherQueryLanguageSyntaxErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "QuotaError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.QuotaError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "QuotaError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.QuotaErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "RequiredCollectionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.RequiredCollectionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "RequiredCollectionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.RequiredCollectionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "RequiredError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.RequiredError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "RequiredError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.RequiredErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "RequiredNumberError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.RequiredNumberError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "RequiredNumberError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.RequiredNumberErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ServerError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.ServerError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "ServerError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.ServerErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "SetValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.SetValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "SoapRequestHeader");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.SoapRequestHeader.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "SoapResponseHeader");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.SoapResponseHeader.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "Statement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.Statement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "StatementError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.StatementError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "StatementError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.StatementErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "String_ValueMapEntry");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.String_ValueMapEntry.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "StringFormatError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.StringFormatError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "StringFormatError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.StringFormatErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "StringLengthError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.StringLengthError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "StringLengthError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.StringLengthErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "TextValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.TextValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "TypeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.TypeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "Value");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202411.Value.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
}
protected org.apache.axis.client.Call createCall() throws java.rmi.RemoteException {
try {
org.apache.axis.client.Call _call = super._createCall();
if (super.maintainSessionSet) {
_call.setMaintainSession(super.maintainSession);
}
if (super.cachedUsername != null) {
_call.setUsername(super.cachedUsername);
}
if (super.cachedPassword != null) {
_call.setPassword(super.cachedPassword);
}
if (super.cachedEndpoint != null) {
_call.setTargetEndpointAddress(super.cachedEndpoint);
}
if (super.cachedTimeout != null) {
_call.setTimeout(super.cachedTimeout);
}
if (super.cachedPortName != null) {
_call.setPortName(super.cachedPortName);
}
java.util.Enumeration keys = super.cachedProperties.keys();
while (keys.hasMoreElements()) {
java.lang.String key = (java.lang.String) keys.nextElement();
_call.setProperty(key, super.cachedProperties.get(key));
}
// All the type mapping information is registered
// when the first call is made.
// The type mapping information is actually registered in
// the TypeMappingRegistry of the service, which
// is the reason why registration is only needed for the first call.
synchronized (this) {
if (firstCall()) {
// must set encoding style before registering serializers
_call.setEncodingStyle(null);
for (int i = 0; i < cachedSerFactories.size(); ++i) {
java.lang.Class cls = (java.lang.Class) cachedSerClasses.get(i);
javax.xml.namespace.QName qName =
(javax.xml.namespace.QName) cachedSerQNames.get(i);
java.lang.Object x = cachedSerFactories.get(i);
if (x instanceof Class) {
java.lang.Class sf = (java.lang.Class)
cachedSerFactories.get(i);
java.lang.Class df = (java.lang.Class)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}
else if (x instanceof javax.xml.rpc.encoding.SerializerFactory) {
org.apache.axis.encoding.SerializerFactory sf = (org.apache.axis.encoding.SerializerFactory)
cachedSerFactories.get(i);
org.apache.axis.encoding.DeserializerFactory df = (org.apache.axis.encoding.DeserializerFactory)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}
}
}
}
return _call;
}
catch (java.lang.Throwable _t) {
throw new org.apache.axis.AxisFault("Failure trying to get the Call object", _t);
}
}
public com.google.api.ads.admanager.axis.v202411.ContentPage getContentByStatement(com.google.api.ads.admanager.axis.v202411.Statement statement) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202411.ApiException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[0]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "getContentByStatement"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {statement});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.google.api.ads.admanager.axis.v202411.ContentPage) _resp;
} catch (java.lang.Exception _exception) {
return (com.google.api.ads.admanager.axis.v202411.ContentPage) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.admanager.axis.v202411.ContentPage.class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
if (axisFaultException.detail != null) {
if (axisFaultException.detail instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException) axisFaultException.detail;
}
if (axisFaultException.detail instanceof com.google.api.ads.admanager.axis.v202411.ApiException) {
throw (com.google.api.ads.admanager.axis.v202411.ApiException) axisFaultException.detail;
}
}
throw axisFaultException;
}
}
}
|
googleads/googleads-java-lib | 35,853 | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202502/ContentServiceSoapBindingStub.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
//
// 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.
/**
* ContentServiceSoapBindingStub.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4.1-SNAPSHOT Mar 20, 2024 (11:59:10 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202502;
public class ContentServiceSoapBindingStub extends org.apache.axis.client.Stub implements com.google.api.ads.admanager.axis.v202502.ContentServiceInterface {
private java.util.Vector cachedSerClasses = new java.util.Vector();
private java.util.Vector cachedSerQNames = new java.util.Vector();
private java.util.Vector cachedSerFactories = new java.util.Vector();
private java.util.Vector cachedDeserFactories = new java.util.Vector();
static org.apache.axis.description.OperationDesc [] _operations;
static {
_operations = new org.apache.axis.description.OperationDesc[1];
_initOperationDesc1();
}
private static void _initOperationDesc1(){
org.apache.axis.description.OperationDesc oper;
org.apache.axis.description.ParameterDesc param;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("getContentByStatement");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "statement"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "Statement"), com.google.api.ads.admanager.axis.v202502.Statement.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ContentPage"));
oper.setReturnClass(com.google.api.ads.admanager.axis.v202502.ContentPage.class);
oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "rval"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ApiExceptionFault"),
"com.google.api.ads.admanager.axis.v202502.ApiException",
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ApiException"),
true
));
_operations[0] = oper;
}
public ContentServiceSoapBindingStub() throws org.apache.axis.AxisFault {
this(null);
}
public ContentServiceSoapBindingStub(java.net.URL endpointURL, javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
this(service);
super.cachedEndpoint = endpointURL;
}
public ContentServiceSoapBindingStub(javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
if (service == null) {
super.service = new org.apache.axis.client.Service();
} else {
super.service = service;
}
((org.apache.axis.client.Service)super.service).setTypeMappingVersion("1.2");
java.lang.Class cls;
javax.xml.namespace.QName qName;
javax.xml.namespace.QName qName2;
java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class;
java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class;
java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class;
java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class;
java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class;
java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class;
java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class;
java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class;
java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class;
java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class;
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ApiError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.ApiError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ApiException");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.ApiException.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ApiVersionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.ApiVersionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ApiVersionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.ApiVersionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ApplicationException");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.ApplicationException.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "AuthenticationError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.AuthenticationError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "AuthenticationError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.AuthenticationErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "BooleanValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.BooleanValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "CmsContent");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.CmsContent.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "CollectionSizeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.CollectionSizeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "CollectionSizeError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.CollectionSizeErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "CommonError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.CommonError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "CommonError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.CommonErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "Content");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.Content.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ContentPage");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.ContentPage.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ContentStatus");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.ContentStatus.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ContentStatusDefinedBy");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.ContentStatusDefinedBy.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "DaiIngestError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.DaiIngestError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "DaiIngestErrorReason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.DaiIngestErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "DaiIngestStatus");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.DaiIngestStatus.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "Date");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.Date.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "DateTime");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.DateTime.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "DateTimeValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.DateTimeValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "DateValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.DateValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "FeatureError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.FeatureError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "FeatureError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.FeatureErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "FieldPathElement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.FieldPathElement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "InternalApiError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.InternalApiError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "InternalApiError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.InternalApiErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "InvalidUrlError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.InvalidUrlError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "InvalidUrlError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.InvalidUrlErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "NotNullError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.NotNullError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "NotNullError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.NotNullErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "NumberValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.NumberValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ObjectValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.ObjectValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ParseError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.ParseError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ParseError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.ParseErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "PermissionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.PermissionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "PermissionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.PermissionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "PublisherQueryLanguageContextError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.PublisherQueryLanguageContextError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "PublisherQueryLanguageContextError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.PublisherQueryLanguageContextErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "PublisherQueryLanguageSyntaxError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.PublisherQueryLanguageSyntaxError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "PublisherQueryLanguageSyntaxError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.PublisherQueryLanguageSyntaxErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "QuotaError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.QuotaError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "QuotaError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.QuotaErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "RequiredCollectionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.RequiredCollectionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "RequiredCollectionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.RequiredCollectionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "RequiredError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.RequiredError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "RequiredError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.RequiredErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "RequiredNumberError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.RequiredNumberError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "RequiredNumberError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.RequiredNumberErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ServerError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.ServerError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "ServerError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.ServerErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "SetValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.SetValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "SoapRequestHeader");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.SoapRequestHeader.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "SoapResponseHeader");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.SoapResponseHeader.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "Statement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.Statement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "StatementError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.StatementError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "StatementError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.StatementErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "String_ValueMapEntry");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.String_ValueMapEntry.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "StringFormatError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.StringFormatError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "StringFormatError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.StringFormatErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "StringLengthError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.StringLengthError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "StringLengthError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.StringLengthErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "TextValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.TextValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "TypeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.TypeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "Value");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202502.Value.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
}
protected org.apache.axis.client.Call createCall() throws java.rmi.RemoteException {
try {
org.apache.axis.client.Call _call = super._createCall();
if (super.maintainSessionSet) {
_call.setMaintainSession(super.maintainSession);
}
if (super.cachedUsername != null) {
_call.setUsername(super.cachedUsername);
}
if (super.cachedPassword != null) {
_call.setPassword(super.cachedPassword);
}
if (super.cachedEndpoint != null) {
_call.setTargetEndpointAddress(super.cachedEndpoint);
}
if (super.cachedTimeout != null) {
_call.setTimeout(super.cachedTimeout);
}
if (super.cachedPortName != null) {
_call.setPortName(super.cachedPortName);
}
java.util.Enumeration keys = super.cachedProperties.keys();
while (keys.hasMoreElements()) {
java.lang.String key = (java.lang.String) keys.nextElement();
_call.setProperty(key, super.cachedProperties.get(key));
}
// All the type mapping information is registered
// when the first call is made.
// The type mapping information is actually registered in
// the TypeMappingRegistry of the service, which
// is the reason why registration is only needed for the first call.
synchronized (this) {
if (firstCall()) {
// must set encoding style before registering serializers
_call.setEncodingStyle(null);
for (int i = 0; i < cachedSerFactories.size(); ++i) {
java.lang.Class cls = (java.lang.Class) cachedSerClasses.get(i);
javax.xml.namespace.QName qName =
(javax.xml.namespace.QName) cachedSerQNames.get(i);
java.lang.Object x = cachedSerFactories.get(i);
if (x instanceof Class) {
java.lang.Class sf = (java.lang.Class)
cachedSerFactories.get(i);
java.lang.Class df = (java.lang.Class)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}
else if (x instanceof javax.xml.rpc.encoding.SerializerFactory) {
org.apache.axis.encoding.SerializerFactory sf = (org.apache.axis.encoding.SerializerFactory)
cachedSerFactories.get(i);
org.apache.axis.encoding.DeserializerFactory df = (org.apache.axis.encoding.DeserializerFactory)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}
}
}
}
return _call;
}
catch (java.lang.Throwable _t) {
throw new org.apache.axis.AxisFault("Failure trying to get the Call object", _t);
}
}
public com.google.api.ads.admanager.axis.v202502.ContentPage getContentByStatement(com.google.api.ads.admanager.axis.v202502.Statement statement) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202502.ApiException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[0]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "getContentByStatement"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {statement});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.google.api.ads.admanager.axis.v202502.ContentPage) _resp;
} catch (java.lang.Exception _exception) {
return (com.google.api.ads.admanager.axis.v202502.ContentPage) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.admanager.axis.v202502.ContentPage.class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
if (axisFaultException.detail != null) {
if (axisFaultException.detail instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException) axisFaultException.detail;
}
if (axisFaultException.detail instanceof com.google.api.ads.admanager.axis.v202502.ApiException) {
throw (com.google.api.ads.admanager.axis.v202502.ApiException) axisFaultException.detail;
}
}
throw axisFaultException;
}
}
}
|
googleads/googleads-java-lib | 35,853 | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202505/ContentServiceSoapBindingStub.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
//
// 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.
/**
* ContentServiceSoapBindingStub.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4.1-SNAPSHOT Mar 20, 2024 (11:59:10 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202505;
public class ContentServiceSoapBindingStub extends org.apache.axis.client.Stub implements com.google.api.ads.admanager.axis.v202505.ContentServiceInterface {
private java.util.Vector cachedSerClasses = new java.util.Vector();
private java.util.Vector cachedSerQNames = new java.util.Vector();
private java.util.Vector cachedSerFactories = new java.util.Vector();
private java.util.Vector cachedDeserFactories = new java.util.Vector();
static org.apache.axis.description.OperationDesc [] _operations;
static {
_operations = new org.apache.axis.description.OperationDesc[1];
_initOperationDesc1();
}
private static void _initOperationDesc1(){
org.apache.axis.description.OperationDesc oper;
org.apache.axis.description.ParameterDesc param;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("getContentByStatement");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "statement"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "Statement"), com.google.api.ads.admanager.axis.v202505.Statement.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ContentPage"));
oper.setReturnClass(com.google.api.ads.admanager.axis.v202505.ContentPage.class);
oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "rval"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ApiExceptionFault"),
"com.google.api.ads.admanager.axis.v202505.ApiException",
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ApiException"),
true
));
_operations[0] = oper;
}
public ContentServiceSoapBindingStub() throws org.apache.axis.AxisFault {
this(null);
}
public ContentServiceSoapBindingStub(java.net.URL endpointURL, javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
this(service);
super.cachedEndpoint = endpointURL;
}
public ContentServiceSoapBindingStub(javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
if (service == null) {
super.service = new org.apache.axis.client.Service();
} else {
super.service = service;
}
((org.apache.axis.client.Service)super.service).setTypeMappingVersion("1.2");
java.lang.Class cls;
javax.xml.namespace.QName qName;
javax.xml.namespace.QName qName2;
java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class;
java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class;
java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class;
java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class;
java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class;
java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class;
java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class;
java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class;
java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class;
java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class;
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ApiError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.ApiError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ApiException");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.ApiException.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ApiVersionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.ApiVersionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ApiVersionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.ApiVersionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ApplicationException");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.ApplicationException.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "AuthenticationError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.AuthenticationError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "AuthenticationError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.AuthenticationErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "BooleanValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.BooleanValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "CmsContent");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.CmsContent.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "CollectionSizeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.CollectionSizeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "CollectionSizeError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.CollectionSizeErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "CommonError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.CommonError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "CommonError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.CommonErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "Content");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.Content.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ContentPage");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.ContentPage.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ContentStatus");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.ContentStatus.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ContentStatusDefinedBy");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.ContentStatusDefinedBy.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "DaiIngestError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.DaiIngestError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "DaiIngestErrorReason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.DaiIngestErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "DaiIngestStatus");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.DaiIngestStatus.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "Date");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.Date.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "DateTime");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.DateTime.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "DateTimeValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.DateTimeValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "DateValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.DateValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "FeatureError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.FeatureError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "FeatureError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.FeatureErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "FieldPathElement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.FieldPathElement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "InternalApiError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.InternalApiError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "InternalApiError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.InternalApiErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "InvalidUrlError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.InvalidUrlError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "InvalidUrlError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.InvalidUrlErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "NotNullError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.NotNullError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "NotNullError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.NotNullErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "NumberValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.NumberValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ObjectValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.ObjectValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ParseError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.ParseError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ParseError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.ParseErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "PermissionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.PermissionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "PermissionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.PermissionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "PublisherQueryLanguageContextError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.PublisherQueryLanguageContextError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "PublisherQueryLanguageContextError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.PublisherQueryLanguageContextErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "PublisherQueryLanguageSyntaxError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.PublisherQueryLanguageSyntaxError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "PublisherQueryLanguageSyntaxError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.PublisherQueryLanguageSyntaxErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "QuotaError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.QuotaError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "QuotaError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.QuotaErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "RequiredCollectionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.RequiredCollectionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "RequiredCollectionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.RequiredCollectionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "RequiredError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.RequiredError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "RequiredError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.RequiredErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "RequiredNumberError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.RequiredNumberError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "RequiredNumberError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.RequiredNumberErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ServerError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.ServerError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "ServerError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.ServerErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "SetValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.SetValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "SoapRequestHeader");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.SoapRequestHeader.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "SoapResponseHeader");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.SoapResponseHeader.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "Statement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.Statement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "StatementError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.StatementError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "StatementError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.StatementErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "String_ValueMapEntry");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.String_ValueMapEntry.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "StringFormatError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.StringFormatError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "StringFormatError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.StringFormatErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "StringLengthError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.StringLengthError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "StringLengthError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.StringLengthErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "TextValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.TextValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "TypeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.TypeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "Value");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202505.Value.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
}
protected org.apache.axis.client.Call createCall() throws java.rmi.RemoteException {
try {
org.apache.axis.client.Call _call = super._createCall();
if (super.maintainSessionSet) {
_call.setMaintainSession(super.maintainSession);
}
if (super.cachedUsername != null) {
_call.setUsername(super.cachedUsername);
}
if (super.cachedPassword != null) {
_call.setPassword(super.cachedPassword);
}
if (super.cachedEndpoint != null) {
_call.setTargetEndpointAddress(super.cachedEndpoint);
}
if (super.cachedTimeout != null) {
_call.setTimeout(super.cachedTimeout);
}
if (super.cachedPortName != null) {
_call.setPortName(super.cachedPortName);
}
java.util.Enumeration keys = super.cachedProperties.keys();
while (keys.hasMoreElements()) {
java.lang.String key = (java.lang.String) keys.nextElement();
_call.setProperty(key, super.cachedProperties.get(key));
}
// All the type mapping information is registered
// when the first call is made.
// The type mapping information is actually registered in
// the TypeMappingRegistry of the service, which
// is the reason why registration is only needed for the first call.
synchronized (this) {
if (firstCall()) {
// must set encoding style before registering serializers
_call.setEncodingStyle(null);
for (int i = 0; i < cachedSerFactories.size(); ++i) {
java.lang.Class cls = (java.lang.Class) cachedSerClasses.get(i);
javax.xml.namespace.QName qName =
(javax.xml.namespace.QName) cachedSerQNames.get(i);
java.lang.Object x = cachedSerFactories.get(i);
if (x instanceof Class) {
java.lang.Class sf = (java.lang.Class)
cachedSerFactories.get(i);
java.lang.Class df = (java.lang.Class)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}
else if (x instanceof javax.xml.rpc.encoding.SerializerFactory) {
org.apache.axis.encoding.SerializerFactory sf = (org.apache.axis.encoding.SerializerFactory)
cachedSerFactories.get(i);
org.apache.axis.encoding.DeserializerFactory df = (org.apache.axis.encoding.DeserializerFactory)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}
}
}
}
return _call;
}
catch (java.lang.Throwable _t) {
throw new org.apache.axis.AxisFault("Failure trying to get the Call object", _t);
}
}
public com.google.api.ads.admanager.axis.v202505.ContentPage getContentByStatement(com.google.api.ads.admanager.axis.v202505.Statement statement) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202505.ApiException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[0]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "getContentByStatement"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {statement});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.google.api.ads.admanager.axis.v202505.ContentPage) _resp;
} catch (java.lang.Exception _exception) {
return (com.google.api.ads.admanager.axis.v202505.ContentPage) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.admanager.axis.v202505.ContentPage.class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
if (axisFaultException.detail != null) {
if (axisFaultException.detail instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException) axisFaultException.detail;
}
if (axisFaultException.detail instanceof com.google.api.ads.admanager.axis.v202505.ApiException) {
throw (com.google.api.ads.admanager.axis.v202505.ApiException) axisFaultException.detail;
}
}
throw axisFaultException;
}
}
}
|
googleads/googleads-java-lib | 35,853 | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202508/ContentServiceSoapBindingStub.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
//
// 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.
/**
* ContentServiceSoapBindingStub.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4.1-SNAPSHOT Mar 20, 2024 (11:59:10 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202508;
public class ContentServiceSoapBindingStub extends org.apache.axis.client.Stub implements com.google.api.ads.admanager.axis.v202508.ContentServiceInterface {
private java.util.Vector cachedSerClasses = new java.util.Vector();
private java.util.Vector cachedSerQNames = new java.util.Vector();
private java.util.Vector cachedSerFactories = new java.util.Vector();
private java.util.Vector cachedDeserFactories = new java.util.Vector();
static org.apache.axis.description.OperationDesc [] _operations;
static {
_operations = new org.apache.axis.description.OperationDesc[1];
_initOperationDesc1();
}
private static void _initOperationDesc1(){
org.apache.axis.description.OperationDesc oper;
org.apache.axis.description.ParameterDesc param;
oper = new org.apache.axis.description.OperationDesc();
oper.setName("getContentByStatement");
param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "statement"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "Statement"), com.google.api.ads.admanager.axis.v202508.Statement.class, false, false);
param.setOmittable(true);
oper.addParameter(param);
oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ContentPage"));
oper.setReturnClass(com.google.api.ads.admanager.axis.v202508.ContentPage.class);
oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "rval"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ApiExceptionFault"),
"com.google.api.ads.admanager.axis.v202508.ApiException",
new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ApiException"),
true
));
_operations[0] = oper;
}
public ContentServiceSoapBindingStub() throws org.apache.axis.AxisFault {
this(null);
}
public ContentServiceSoapBindingStub(java.net.URL endpointURL, javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
this(service);
super.cachedEndpoint = endpointURL;
}
public ContentServiceSoapBindingStub(javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
if (service == null) {
super.service = new org.apache.axis.client.Service();
} else {
super.service = service;
}
((org.apache.axis.client.Service)super.service).setTypeMappingVersion("1.2");
java.lang.Class cls;
javax.xml.namespace.QName qName;
javax.xml.namespace.QName qName2;
java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class;
java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class;
java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class;
java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class;
java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class;
java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class;
java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class;
java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class;
java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class;
java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class;
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ApiError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.ApiError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ApiException");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.ApiException.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ApiVersionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.ApiVersionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ApiVersionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.ApiVersionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ApplicationException");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.ApplicationException.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "AuthenticationError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.AuthenticationError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "AuthenticationError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.AuthenticationErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "BooleanValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.BooleanValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "CmsContent");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.CmsContent.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "CollectionSizeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.CollectionSizeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "CollectionSizeError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.CollectionSizeErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "CommonError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.CommonError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "CommonError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.CommonErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "Content");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.Content.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ContentPage");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.ContentPage.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ContentStatus");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.ContentStatus.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ContentStatusDefinedBy");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.ContentStatusDefinedBy.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "DaiIngestError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.DaiIngestError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "DaiIngestErrorReason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.DaiIngestErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "DaiIngestStatus");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.DaiIngestStatus.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "Date");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.Date.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "DateTime");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.DateTime.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "DateTimeValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.DateTimeValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "DateValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.DateValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "FeatureError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.FeatureError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "FeatureError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.FeatureErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "FieldPathElement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.FieldPathElement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "InternalApiError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.InternalApiError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "InternalApiError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.InternalApiErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "InvalidUrlError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.InvalidUrlError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "InvalidUrlError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.InvalidUrlErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "NotNullError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.NotNullError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "NotNullError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.NotNullErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "NumberValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.NumberValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ObjectValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.ObjectValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ParseError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.ParseError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ParseError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.ParseErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "PermissionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.PermissionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "PermissionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.PermissionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "PublisherQueryLanguageContextError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.PublisherQueryLanguageContextError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "PublisherQueryLanguageContextError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.PublisherQueryLanguageContextErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "PublisherQueryLanguageSyntaxError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.PublisherQueryLanguageSyntaxError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "PublisherQueryLanguageSyntaxError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.PublisherQueryLanguageSyntaxErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "QuotaError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.QuotaError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "QuotaError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.QuotaErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "RequiredCollectionError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.RequiredCollectionError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "RequiredCollectionError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.RequiredCollectionErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "RequiredError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.RequiredError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "RequiredError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.RequiredErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "RequiredNumberError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.RequiredNumberError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "RequiredNumberError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.RequiredNumberErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ServerError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.ServerError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "ServerError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.ServerErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "SetValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.SetValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "SoapRequestHeader");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.SoapRequestHeader.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "SoapResponseHeader");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.SoapResponseHeader.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "Statement");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.Statement.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "StatementError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.StatementError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "StatementError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.StatementErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "String_ValueMapEntry");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.String_ValueMapEntry.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "StringFormatError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.StringFormatError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "StringFormatError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.StringFormatErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "StringLengthError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.StringLengthError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "StringLengthError.Reason");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.StringLengthErrorReason.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(enumsf);
cachedDeserFactories.add(enumdf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "TextValue");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.TextValue.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "TypeError");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.TypeError.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "Value");
cachedSerQNames.add(qName);
cls = com.google.api.ads.admanager.axis.v202508.Value.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
}
protected org.apache.axis.client.Call createCall() throws java.rmi.RemoteException {
try {
org.apache.axis.client.Call _call = super._createCall();
if (super.maintainSessionSet) {
_call.setMaintainSession(super.maintainSession);
}
if (super.cachedUsername != null) {
_call.setUsername(super.cachedUsername);
}
if (super.cachedPassword != null) {
_call.setPassword(super.cachedPassword);
}
if (super.cachedEndpoint != null) {
_call.setTargetEndpointAddress(super.cachedEndpoint);
}
if (super.cachedTimeout != null) {
_call.setTimeout(super.cachedTimeout);
}
if (super.cachedPortName != null) {
_call.setPortName(super.cachedPortName);
}
java.util.Enumeration keys = super.cachedProperties.keys();
while (keys.hasMoreElements()) {
java.lang.String key = (java.lang.String) keys.nextElement();
_call.setProperty(key, super.cachedProperties.get(key));
}
// All the type mapping information is registered
// when the first call is made.
// The type mapping information is actually registered in
// the TypeMappingRegistry of the service, which
// is the reason why registration is only needed for the first call.
synchronized (this) {
if (firstCall()) {
// must set encoding style before registering serializers
_call.setEncodingStyle(null);
for (int i = 0; i < cachedSerFactories.size(); ++i) {
java.lang.Class cls = (java.lang.Class) cachedSerClasses.get(i);
javax.xml.namespace.QName qName =
(javax.xml.namespace.QName) cachedSerQNames.get(i);
java.lang.Object x = cachedSerFactories.get(i);
if (x instanceof Class) {
java.lang.Class sf = (java.lang.Class)
cachedSerFactories.get(i);
java.lang.Class df = (java.lang.Class)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}
else if (x instanceof javax.xml.rpc.encoding.SerializerFactory) {
org.apache.axis.encoding.SerializerFactory sf = (org.apache.axis.encoding.SerializerFactory)
cachedSerFactories.get(i);
org.apache.axis.encoding.DeserializerFactory df = (org.apache.axis.encoding.DeserializerFactory)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}
}
}
}
return _call;
}
catch (java.lang.Throwable _t) {
throw new org.apache.axis.AxisFault("Failure trying to get the Call object", _t);
}
}
public com.google.api.ads.admanager.axis.v202508.ContentPage getContentByStatement(com.google.api.ads.admanager.axis.v202508.Statement statement) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202508.ApiException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call = createCall();
_call.setOperation(_operations[0]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "getContentByStatement"));
setRequestHeaders(_call);
setAttachments(_call);
try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {statement});
if (_resp instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException)_resp;
}
else {
extractAttachments(_call);
try {
return (com.google.api.ads.admanager.axis.v202508.ContentPage) _resp;
} catch (java.lang.Exception _exception) {
return (com.google.api.ads.admanager.axis.v202508.ContentPage) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.admanager.axis.v202508.ContentPage.class);
}
}
} catch (org.apache.axis.AxisFault axisFaultException) {
if (axisFaultException.detail != null) {
if (axisFaultException.detail instanceof java.rmi.RemoteException) {
throw (java.rmi.RemoteException) axisFaultException.detail;
}
if (axisFaultException.detail instanceof com.google.api.ads.admanager.axis.v202508.ApiException) {
throw (com.google.api.ads.admanager.axis.v202508.ApiException) axisFaultException.detail;
}
}
throw axisFaultException;
}
}
}
|
googleapis/google-cloud-java | 35,941 | java-dialogflow/google-cloud-dialogflow/src/main/java/com/google/cloud/dialogflow/v2/stub/ParticipantsStubSettings.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.dialogflow.v2.stub;
import static com.google.cloud.dialogflow.v2.ParticipantsClient.ListLocationsPagedResponse;
import static com.google.cloud.dialogflow.v2.ParticipantsClient.ListParticipantsPagedResponse;
import com.google.api.core.ApiFunction;
import com.google.api.core.ApiFuture;
import com.google.api.core.BetaApi;
import com.google.api.core.ObsoleteApi;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.GrpcTransportChannel;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.HttpJsonTransportChannel;
import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiCallContext;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.PageContext;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.PagedListDescriptor;
import com.google.api.gax.rpc.PagedListResponseFactory;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.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.dialogflow.v2.AnalyzeContentRequest;
import com.google.cloud.dialogflow.v2.AnalyzeContentResponse;
import com.google.cloud.dialogflow.v2.CreateParticipantRequest;
import com.google.cloud.dialogflow.v2.GetParticipantRequest;
import com.google.cloud.dialogflow.v2.ListParticipantsRequest;
import com.google.cloud.dialogflow.v2.ListParticipantsResponse;
import com.google.cloud.dialogflow.v2.Participant;
import com.google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest;
import com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse;
import com.google.cloud.dialogflow.v2.SuggestArticlesRequest;
import com.google.cloud.dialogflow.v2.SuggestArticlesResponse;
import com.google.cloud.dialogflow.v2.SuggestFaqAnswersRequest;
import com.google.cloud.dialogflow.v2.SuggestFaqAnswersResponse;
import com.google.cloud.dialogflow.v2.SuggestKnowledgeAssistRequest;
import com.google.cloud.dialogflow.v2.SuggestKnowledgeAssistResponse;
import com.google.cloud.dialogflow.v2.SuggestSmartRepliesRequest;
import com.google.cloud.dialogflow.v2.SuggestSmartRepliesResponse;
import com.google.cloud.dialogflow.v2.UpdateParticipantRequest;
import com.google.cloud.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link ParticipantsStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (dialogflow.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 createParticipant:
*
* <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
* ParticipantsStubSettings.Builder participantsSettingsBuilder =
* ParticipantsStubSettings.newBuilder();
* participantsSettingsBuilder
* .createParticipantSettings()
* .setRetrySettings(
* participantsSettingsBuilder
* .createParticipantSettings()
* .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());
* ParticipantsStubSettings participantsSettings = participantsSettingsBuilder.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 ParticipantsStubSettings extends StubSettings<ParticipantsStubSettings> {
/** 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/dialogflow")
.build();
private final UnaryCallSettings<CreateParticipantRequest, Participant> createParticipantSettings;
private final UnaryCallSettings<GetParticipantRequest, Participant> getParticipantSettings;
private final PagedCallSettings<
ListParticipantsRequest, ListParticipantsResponse, ListParticipantsPagedResponse>
listParticipantsSettings;
private final UnaryCallSettings<UpdateParticipantRequest, Participant> updateParticipantSettings;
private final UnaryCallSettings<AnalyzeContentRequest, AnalyzeContentResponse>
analyzeContentSettings;
private final StreamingCallSettings<
StreamingAnalyzeContentRequest, StreamingAnalyzeContentResponse>
streamingAnalyzeContentSettings;
private final UnaryCallSettings<SuggestArticlesRequest, SuggestArticlesResponse>
suggestArticlesSettings;
private final UnaryCallSettings<SuggestFaqAnswersRequest, SuggestFaqAnswersResponse>
suggestFaqAnswersSettings;
private final UnaryCallSettings<SuggestSmartRepliesRequest, SuggestSmartRepliesResponse>
suggestSmartRepliesSettings;
private final UnaryCallSettings<SuggestKnowledgeAssistRequest, SuggestKnowledgeAssistResponse>
suggestKnowledgeAssistSettings;
private final PagedCallSettings<
ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse>
listLocationsSettings;
private final UnaryCallSettings<GetLocationRequest, Location> getLocationSettings;
private static final PagedListDescriptor<
ListParticipantsRequest, ListParticipantsResponse, Participant>
LIST_PARTICIPANTS_PAGE_STR_DESC =
new PagedListDescriptor<
ListParticipantsRequest, ListParticipantsResponse, Participant>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListParticipantsRequest injectToken(
ListParticipantsRequest payload, String token) {
return ListParticipantsRequest.newBuilder(payload).setPageToken(token).build();
}
@Override
public ListParticipantsRequest injectPageSize(
ListParticipantsRequest payload, int pageSize) {
return ListParticipantsRequest.newBuilder(payload).setPageSize(pageSize).build();
}
@Override
public Integer extractPageSize(ListParticipantsRequest payload) {
return payload.getPageSize();
}
@Override
public String extractNextToken(ListParticipantsResponse payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<Participant> extractResources(ListParticipantsResponse payload) {
return payload.getParticipantsList();
}
};
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<
ListParticipantsRequest, ListParticipantsResponse, ListParticipantsPagedResponse>
LIST_PARTICIPANTS_PAGE_STR_FACT =
new PagedListResponseFactory<
ListParticipantsRequest, ListParticipantsResponse, ListParticipantsPagedResponse>() {
@Override
public ApiFuture<ListParticipantsPagedResponse> getFuturePagedResponse(
UnaryCallable<ListParticipantsRequest, ListParticipantsResponse> callable,
ListParticipantsRequest request,
ApiCallContext context,
ApiFuture<ListParticipantsResponse> futureResponse) {
PageContext<ListParticipantsRequest, ListParticipantsResponse, Participant>
pageContext =
PageContext.create(
callable, LIST_PARTICIPANTS_PAGE_STR_DESC, request, context);
return ListParticipantsPagedResponse.createAsync(pageContext, futureResponse);
}
};
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 createParticipant. */
public UnaryCallSettings<CreateParticipantRequest, Participant> createParticipantSettings() {
return createParticipantSettings;
}
/** Returns the object with the settings used for calls to getParticipant. */
public UnaryCallSettings<GetParticipantRequest, Participant> getParticipantSettings() {
return getParticipantSettings;
}
/** Returns the object with the settings used for calls to listParticipants. */
public PagedCallSettings<
ListParticipantsRequest, ListParticipantsResponse, ListParticipantsPagedResponse>
listParticipantsSettings() {
return listParticipantsSettings;
}
/** Returns the object with the settings used for calls to updateParticipant. */
public UnaryCallSettings<UpdateParticipantRequest, Participant> updateParticipantSettings() {
return updateParticipantSettings;
}
/** Returns the object with the settings used for calls to analyzeContent. */
public UnaryCallSettings<AnalyzeContentRequest, AnalyzeContentResponse> analyzeContentSettings() {
return analyzeContentSettings;
}
/** Returns the object with the settings used for calls to streamingAnalyzeContent. */
public StreamingCallSettings<StreamingAnalyzeContentRequest, StreamingAnalyzeContentResponse>
streamingAnalyzeContentSettings() {
return streamingAnalyzeContentSettings;
}
/** Returns the object with the settings used for calls to suggestArticles. */
public UnaryCallSettings<SuggestArticlesRequest, SuggestArticlesResponse>
suggestArticlesSettings() {
return suggestArticlesSettings;
}
/** Returns the object with the settings used for calls to suggestFaqAnswers. */
public UnaryCallSettings<SuggestFaqAnswersRequest, SuggestFaqAnswersResponse>
suggestFaqAnswersSettings() {
return suggestFaqAnswersSettings;
}
/** Returns the object with the settings used for calls to suggestSmartReplies. */
public UnaryCallSettings<SuggestSmartRepliesRequest, SuggestSmartRepliesResponse>
suggestSmartRepliesSettings() {
return suggestSmartRepliesSettings;
}
/** Returns the object with the settings used for calls to suggestKnowledgeAssist. */
public UnaryCallSettings<SuggestKnowledgeAssistRequest, SuggestKnowledgeAssistResponse>
suggestKnowledgeAssistSettings() {
return suggestKnowledgeAssistSettings;
}
/** 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;
}
public ParticipantsStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(GrpcTransportChannel.getGrpcTransportName())) {
return GrpcParticipantsStub.create(this);
}
if (getTransportChannelProvider()
.getTransportName()
.equals(HttpJsonTransportChannel.getHttpJsonTransportName())) {
return HttpJsonParticipantsStub.create(this);
}
throw new UnsupportedOperationException(
String.format(
"Transport not supported: %s", getTransportChannelProvider().getTransportName()));
}
/** Returns the default service name. */
@Override
public String getServiceName() {
return "dialogflow";
}
/** 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 "dialogflow.googleapis.com:443";
}
/** Returns the default mTLS service endpoint. */
public static String getDefaultMtlsEndpoint() {
return "dialogflow.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(ParticipantsStubSettings.class))
.setTransportToken(
GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion());
}
public static ApiClientHeaderProvider.Builder defaultHttpJsonApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic", GaxProperties.getLibraryVersion(ParticipantsStubSettings.class))
.setTransportToken(
GaxHttpJsonProperties.getHttpJsonTokenName(),
GaxHttpJsonProperties.getHttpJsonVersion());
}
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return ParticipantsStubSettings.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 ParticipantsStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
createParticipantSettings = settingsBuilder.createParticipantSettings().build();
getParticipantSettings = settingsBuilder.getParticipantSettings().build();
listParticipantsSettings = settingsBuilder.listParticipantsSettings().build();
updateParticipantSettings = settingsBuilder.updateParticipantSettings().build();
analyzeContentSettings = settingsBuilder.analyzeContentSettings().build();
streamingAnalyzeContentSettings = settingsBuilder.streamingAnalyzeContentSettings().build();
suggestArticlesSettings = settingsBuilder.suggestArticlesSettings().build();
suggestFaqAnswersSettings = settingsBuilder.suggestFaqAnswersSettings().build();
suggestSmartRepliesSettings = settingsBuilder.suggestSmartRepliesSettings().build();
suggestKnowledgeAssistSettings = settingsBuilder.suggestKnowledgeAssistSettings().build();
listLocationsSettings = settingsBuilder.listLocationsSettings().build();
getLocationSettings = settingsBuilder.getLocationSettings().build();
}
/** Builder for ParticipantsStubSettings. */
public static class Builder extends StubSettings.Builder<ParticipantsStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final UnaryCallSettings.Builder<CreateParticipantRequest, Participant>
createParticipantSettings;
private final UnaryCallSettings.Builder<GetParticipantRequest, Participant>
getParticipantSettings;
private final PagedCallSettings.Builder<
ListParticipantsRequest, ListParticipantsResponse, ListParticipantsPagedResponse>
listParticipantsSettings;
private final UnaryCallSettings.Builder<UpdateParticipantRequest, Participant>
updateParticipantSettings;
private final UnaryCallSettings.Builder<AnalyzeContentRequest, AnalyzeContentResponse>
analyzeContentSettings;
private final StreamingCallSettings.Builder<
StreamingAnalyzeContentRequest, StreamingAnalyzeContentResponse>
streamingAnalyzeContentSettings;
private final UnaryCallSettings.Builder<SuggestArticlesRequest, SuggestArticlesResponse>
suggestArticlesSettings;
private final UnaryCallSettings.Builder<SuggestFaqAnswersRequest, SuggestFaqAnswersResponse>
suggestFaqAnswersSettings;
private final UnaryCallSettings.Builder<SuggestSmartRepliesRequest, SuggestSmartRepliesResponse>
suggestSmartRepliesSettings;
private final UnaryCallSettings.Builder<
SuggestKnowledgeAssistRequest, SuggestKnowledgeAssistResponse>
suggestKnowledgeAssistSettings;
private final PagedCallSettings.Builder<
ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse>
listLocationsSettings;
private final UnaryCallSettings.Builder<GetLocationRequest, Location> getLocationSettings;
private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
RETRYABLE_CODE_DEFINITIONS;
static {
ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions =
ImmutableMap.builder();
definitions.put(
"retry_policy_0_codes",
ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList(StatusCode.Code.UNAVAILABLE)));
definitions.put(
"retry_policy_1_codes",
ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList(StatusCode.Code.UNAVAILABLE)));
definitions.put(
"no_retry_2_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
RetrySettings settings = null;
settings =
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(100L))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelayDuration(Duration.ofMillis(60000L))
.setInitialRpcTimeoutDuration(Duration.ofMillis(60000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(60000L))
.setTotalTimeoutDuration(Duration.ofMillis(60000L))
.build();
definitions.put("retry_policy_0_params", settings);
settings =
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(100L))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelayDuration(Duration.ofMillis(60000L))
.setInitialRpcTimeoutDuration(Duration.ofMillis(220000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(220000L))
.setTotalTimeoutDuration(Duration.ofMillis(220000L))
.build();
definitions.put("retry_policy_1_params", settings);
settings =
RetrySettings.newBuilder()
.setInitialRpcTimeoutDuration(Duration.ofMillis(220000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(220000L))
.setTotalTimeoutDuration(Duration.ofMillis(220000L))
.build();
definitions.put("no_retry_2_params", settings);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
protected Builder() {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(clientContext);
createParticipantSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
getParticipantSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
listParticipantsSettings = PagedCallSettings.newBuilder(LIST_PARTICIPANTS_PAGE_STR_FACT);
updateParticipantSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
analyzeContentSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
streamingAnalyzeContentSettings = StreamingCallSettings.newBuilder();
suggestArticlesSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
suggestFaqAnswersSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
suggestSmartRepliesSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
suggestKnowledgeAssistSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
listLocationsSettings = PagedCallSettings.newBuilder(LIST_LOCATIONS_PAGE_STR_FACT);
getLocationSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
createParticipantSettings,
getParticipantSettings,
listParticipantsSettings,
updateParticipantSettings,
analyzeContentSettings,
suggestArticlesSettings,
suggestFaqAnswersSettings,
suggestSmartRepliesSettings,
suggestKnowledgeAssistSettings,
listLocationsSettings,
getLocationSettings);
initDefaults(this);
}
protected Builder(ParticipantsStubSettings settings) {
super(settings);
createParticipantSettings = settings.createParticipantSettings.toBuilder();
getParticipantSettings = settings.getParticipantSettings.toBuilder();
listParticipantsSettings = settings.listParticipantsSettings.toBuilder();
updateParticipantSettings = settings.updateParticipantSettings.toBuilder();
analyzeContentSettings = settings.analyzeContentSettings.toBuilder();
streamingAnalyzeContentSettings = settings.streamingAnalyzeContentSettings.toBuilder();
suggestArticlesSettings = settings.suggestArticlesSettings.toBuilder();
suggestFaqAnswersSettings = settings.suggestFaqAnswersSettings.toBuilder();
suggestSmartRepliesSettings = settings.suggestSmartRepliesSettings.toBuilder();
suggestKnowledgeAssistSettings = settings.suggestKnowledgeAssistSettings.toBuilder();
listLocationsSettings = settings.listLocationsSettings.toBuilder();
getLocationSettings = settings.getLocationSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
createParticipantSettings,
getParticipantSettings,
listParticipantsSettings,
updateParticipantSettings,
analyzeContentSettings,
suggestArticlesSettings,
suggestFaqAnswersSettings,
suggestSmartRepliesSettings,
suggestKnowledgeAssistSettings,
listLocationsSettings,
getLocationSettings);
}
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
.createParticipantSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.getParticipantSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.listParticipantsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.updateParticipantSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.analyzeContentSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params"));
builder
.suggestArticlesSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.suggestFaqAnswersSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.suggestSmartRepliesSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.suggestKnowledgeAssistSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.listLocationsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.getLocationSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
return builder;
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);
return this;
}
public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() {
return unaryMethodSettingsBuilders;
}
/** Returns the builder for the settings used for calls to createParticipant. */
public UnaryCallSettings.Builder<CreateParticipantRequest, Participant>
createParticipantSettings() {
return createParticipantSettings;
}
/** Returns the builder for the settings used for calls to getParticipant. */
public UnaryCallSettings.Builder<GetParticipantRequest, Participant> getParticipantSettings() {
return getParticipantSettings;
}
/** Returns the builder for the settings used for calls to listParticipants. */
public PagedCallSettings.Builder<
ListParticipantsRequest, ListParticipantsResponse, ListParticipantsPagedResponse>
listParticipantsSettings() {
return listParticipantsSettings;
}
/** Returns the builder for the settings used for calls to updateParticipant. */
public UnaryCallSettings.Builder<UpdateParticipantRequest, Participant>
updateParticipantSettings() {
return updateParticipantSettings;
}
/** Returns the builder for the settings used for calls to analyzeContent. */
public UnaryCallSettings.Builder<AnalyzeContentRequest, AnalyzeContentResponse>
analyzeContentSettings() {
return analyzeContentSettings;
}
/** Returns the builder for the settings used for calls to streamingAnalyzeContent. */
public StreamingCallSettings.Builder<
StreamingAnalyzeContentRequest, StreamingAnalyzeContentResponse>
streamingAnalyzeContentSettings() {
return streamingAnalyzeContentSettings;
}
/** Returns the builder for the settings used for calls to suggestArticles. */
public UnaryCallSettings.Builder<SuggestArticlesRequest, SuggestArticlesResponse>
suggestArticlesSettings() {
return suggestArticlesSettings;
}
/** Returns the builder for the settings used for calls to suggestFaqAnswers. */
public UnaryCallSettings.Builder<SuggestFaqAnswersRequest, SuggestFaqAnswersResponse>
suggestFaqAnswersSettings() {
return suggestFaqAnswersSettings;
}
/** Returns the builder for the settings used for calls to suggestSmartReplies. */
public UnaryCallSettings.Builder<SuggestSmartRepliesRequest, SuggestSmartRepliesResponse>
suggestSmartRepliesSettings() {
return suggestSmartRepliesSettings;
}
/** Returns the builder for the settings used for calls to suggestKnowledgeAssist. */
public UnaryCallSettings.Builder<SuggestKnowledgeAssistRequest, SuggestKnowledgeAssistResponse>
suggestKnowledgeAssistSettings() {
return suggestKnowledgeAssistSettings;
}
/** 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;
}
@Override
public ParticipantsStubSettings build() throws IOException {
return new ParticipantsStubSettings(this);
}
}
}
|
google/closure-templates | 35,704 | java/src/com/google/template/soy/jbcsrc/restricted/MethodRefs.java | /*
* Copyright 2023 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.jbcsrc.restricted;
import static com.google.template.soy.jbcsrc.restricted.MethodRef.createNonPure;
import static com.google.template.soy.jbcsrc.restricted.MethodRef.createNonPureConstructor;
import static com.google.template.soy.jbcsrc.restricted.MethodRef.createPure;
import static com.google.template.soy.jbcsrc.restricted.MethodRef.createPureConstructor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.primitives.Ints;
import com.google.common.primitives.UnsignedInts;
import com.google.common.primitives.UnsignedLongs;
import com.google.protobuf.ExtensionLite;
import com.google.protobuf.GeneratedMessage.ExtendableMessage;
import com.google.protobuf.Message;
import com.google.protobuf.ProtocolMessageEnum;
import com.google.template.soy.base.internal.BaseUtils;
import com.google.template.soy.data.Dir;
import com.google.template.soy.data.LoggingAdvisingAppendable;
import com.google.template.soy.data.LoggingAdvisingAppendable.BufferingAppendable;
import com.google.template.soy.data.ProtoFieldInterpreter;
import com.google.template.soy.data.RecordProperty;
import com.google.template.soy.data.SanitizedContent;
import com.google.template.soy.data.SanitizedContent.ContentKind;
import com.google.template.soy.data.SoyProtoValue;
import com.google.template.soy.data.SoyValue;
import com.google.template.soy.data.SoyValueProvider;
import com.google.template.soy.data.SoyVisualElement;
import com.google.template.soy.data.SoyVisualElementData;
import com.google.template.soy.data.TemplateInterface;
import com.google.template.soy.data.TemplateValue;
import com.google.template.soy.data.UnsafeSanitizedContentOrdainer;
import com.google.template.soy.data.internal.DictImpl;
import com.google.template.soy.data.internal.LazyProtoToSoyValueList;
import com.google.template.soy.data.internal.LazyProtoToSoyValueMap;
import com.google.template.soy.data.internal.ListImpl;
import com.google.template.soy.data.internal.ParamStore;
import com.google.template.soy.data.internal.RuntimeMapTypeTracker;
import com.google.template.soy.data.internal.SetImpl;
import com.google.template.soy.data.internal.SoyMapImpl;
import com.google.template.soy.data.internal.SoyRecordImpl;
import com.google.template.soy.data.restricted.BooleanData;
import com.google.template.soy.data.restricted.FloatData;
import com.google.template.soy.data.restricted.GbigintData;
import com.google.template.soy.data.restricted.IntegerData;
import com.google.template.soy.data.restricted.StringData;
import com.google.template.soy.jbcsrc.api.RenderResult;
import com.google.template.soy.jbcsrc.restricted.MethodRef.MethodPureness;
import com.google.template.soy.jbcsrc.runtime.DetachableContentProvider;
import com.google.template.soy.jbcsrc.runtime.JbcSrcRuntime;
import com.google.template.soy.jbcsrc.shared.CompiledTemplate;
import com.google.template.soy.jbcsrc.shared.JbcSrcFunctionValue;
import com.google.template.soy.jbcsrc.shared.RenderContext;
import com.google.template.soy.jbcsrc.shared.StackFrame;
import com.google.template.soy.logging.LoggableElementMetadata;
import com.google.template.soy.msgs.restricted.SoyMsgRawParts;
import com.google.template.soy.shared.internal.SharedRuntime;
import com.google.template.soy.shared.restricted.SoyJavaFunction;
import com.google.template.soy.shared.restricted.SoyJavaPrintDirective;
import com.ibm.icu.util.ULocale;
import java.io.Closeable;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.ToIntFunction;
/** Standard constant MethodRef instances shared throughout the compiler. */
public final class MethodRefs {
public static final MethodRef ARRAY_LIST_ADD =
createNonPure(ArrayList.class, "add", Object.class);
public static final MethodRef BOOLEAN_DATA_FOR_VALUE =
createPure(BooleanData.class, "forValue", boolean.class);
public static final MethodRef BOOLEAN_VALUE = createPure(Boolean.class, "booleanValue").asCheap();
public static final MethodRef BOOLEAN_TO_STRING =
createPure(Boolean.class, "toString", boolean.class).asCheap().asNonJavaNullable();
public static final MethodRef COMPILED_TEMPLATE_RENDER =
createNonPure(
CompiledTemplate.class,
"render",
StackFrame.class,
ParamStore.class,
LoggingAdvisingAppendable.class,
RenderContext.class);
public static final MethodRef DICT_IMPL_FOR_PROVIDER_MAP =
createPure(DictImpl.class, "forProviderMap", Map.class, RuntimeMapTypeTracker.Type.class);
public static final MethodRef MAP_IMPL_FOR_PROVIDER_MAP =
createPure(SoyMapImpl.class, "forProviderMap", Map.class);
public static final MethodRef MAP_IMPL_FOR_PROVIDER_MAP_NO_NULL_KEYS =
createPure(SoyMapImpl.class, "forProviderMapNoNullKeys", Map.class);
public static final MethodRef DOUBLE_TO_STRING =
createPure(BaseUtils.class, "formatDouble", double.class);
public static final MethodRef EQUALS = createPure(Object.class, "equals", Object.class);
public static final MethodRef STRING_COMPARE_TO =
createPure(String.class, "compareTo", String.class);
public static final MethodRef FLOAT_DATA_FOR_VALUE =
createPure(FloatData.class, "forValue", double.class);
public static final MethodRef RENDER_RESULT_ASSERT_DONE =
createPure(RenderResult.class, "assertDone");
public static final MethodRef IMMUTABLE_LIST_BUILDER =
createNonPure(ImmutableList.class, "builder");
public static final MethodRef IMMUTABLE_LIST_BUILDER_ADD =
createNonPure(ImmutableList.Builder.class, "add", Object.class);
public static final MethodRef IMMUTABLE_LIST_BUILDER_ADD_ALL =
createNonPure(ImmutableList.Builder.class, "addAll", Iterable.class);
public static final MethodRef IMMUTABLE_LIST_BUILDER_ADD_ALL_ITERATOR =
createNonPure(ImmutableList.Builder.class, "addAll", Iterator.class);
public static final MethodRef IMMUTABLE_LIST_BUILDER_BUILD =
createNonPure(ImmutableList.Builder.class, "build").asNonJavaNullable();
public static final MethodRef IMMUTABLE_SET_BUILDER =
createNonPure(ImmutableSet.class, "builder");
public static final MethodRef IMMUTABLE_SET_BUILDER_ADD_ALL_ITERATOR =
createNonPure(ImmutableSet.Builder.class, "addAll", Iterator.class);
public static final MethodRef IMMUTABLE_SET_BUILDER_BUILD =
createNonPure(ImmutableSet.Builder.class, "build").asNonJavaNullable();
public static final MethodRef IMMUTABLE_SET_COPY_OF =
createNonPure(ImmutableSet.class, "copyOf", Iterator.class).asNonJavaNullable();
/** a list of all the ImmutableList.of overloads, indexed by arity. */
public static final ImmutableList<MethodRef> IMMUTABLE_LIST_OF;
public static final MethodRef IMMUTABLE_LIST_OF_ARRAY;
public static final MethodRef IMMUTABLE_LIST_COPY_OF_ITERABLE =
createNonPure(ImmutableList.class, "copyOf", Iterable.class).asNonJavaNullable();
/** a list of all the ImmutableList.of overloads, indexed by number of entries. */
public static final ImmutableList<MethodRef> IMMUTABLE_MAP_OF;
public static final MethodRef IMMUTABLE_MAP_BUILDER_WITH_EXPECTED_SIZE =
MethodRef.createNonPure(ImmutableMap.class, "builderWithExpectedSize", int.class);
public static final MethodRef IMMUTABLE_MAP_BUILDER_PUT =
MethodRef.createNonPure(ImmutableMap.Builder.class, "put", Object.class, Object.class);
public static final MethodRef IMMUTABLE_MAP_BUILDER_BUILD_KEEPING_LAST =
MethodRef.createNonPure(ImmutableMap.Builder.class, "buildKeepingLast");
public static final MethodRef IMMUTABLE_MAP_BUILDER_BUILD_OR_THROW =
MethodRef.createNonPure(ImmutableMap.Builder.class, "buildOrThrow");
static {
Map<Integer, MethodRef> immutableListOfMethods = new TreeMap<>();
MethodRef immutableListOfArray = null;
for (java.lang.reflect.Method m : ImmutableList.class.getMethods()) {
if (m.getName().equals("of")) {
Class<?>[] params = m.getParameterTypes();
MethodRef ref = MethodRef.create(m, MethodPureness.PURE).asNonJavaNullable();
if (params.length > 0 && params[params.length - 1].isArray()) {
// skip the one that takes an array in the final position
immutableListOfArray = ref;
continue;
}
int arity = params.length;
if (arity == 0) {
// the zero arg one is 'cheap'
ref = ref.asCheap();
}
immutableListOfMethods.put(arity, ref);
}
}
IMMUTABLE_LIST_OF_ARRAY = immutableListOfArray;
IMMUTABLE_LIST_OF = ImmutableList.copyOf(immutableListOfMethods.values());
Map<Integer, MethodRef> immutableMapOfMethods = new TreeMap<>();
for (java.lang.reflect.Method m : ImmutableMap.class.getMethods()) {
if (m.getName().equals("of")) {
Class<?>[] params = m.getParameterTypes();
MethodRef ref = MethodRef.create(m, MethodPureness.PURE).asNonJavaNullable();
if (params.length > 0 && params[params.length - 1].isArray()) {
// skip the one that takes an array in the final position
immutableListOfArray = ref;
continue;
}
int arity = params.length;
if (arity == 0) {
// the zero arg one is 'cheap'
ref = ref.asCheap();
}
immutableMapOfMethods.put(arity / 2, ref);
}
}
IMMUTABLE_MAP_OF = ImmutableList.copyOf(immutableMapOfMethods.values());
}
public static final MethodRef INTEGER_DATA_FOR_VALUE =
createPure(IntegerData.class, "forValue", long.class);
public static final MethodRef INTS_CHECKED_CAST =
createPure(Ints.class, "checkedCast", long.class).asCheap();
public static final MethodRef MAP_PUT =
createNonPure(Map.class, "put", Object.class, Object.class);
public static final MethodRef LIST_GET = createPure(List.class, "get", int.class).asCheap();
public static final MethodRef LIST_SIZE = createPure(List.class, "size").asCheap();
public static final MethodRef MAP_ENTRY_SET =
createPure(Map.class, "entrySet").asNonJavaNullable();
public static final MethodRef GET_ITERATOR =
createPure(Iterable.class, "iterator").asNonJavaNullable();
public static final MethodRef ITERATOR_NEXT = createNonPure(Iterator.class, "next");
public static final MethodRef ITERATOR_HAS_NEXT = createPure(Iterator.class, "hasNext");
public static final MethodRef MAP_ENTRY_GET_KEY = createPure(Map.Entry.class, "getKey");
public static final MethodRef MAP_ENTRY_GET_VALUE = createPure(Map.Entry.class, "getValue");
public static final MethodRef LIST_IMPL_FOR_PROVIDER_LIST =
createPure(ListImpl.class, "forProviderList", List.class);
public static final MethodRef SET_IMPL_FOR_PROVIDER_SET =
createPureConstructor(SetImpl.class, Set.class);
public static final MethodRef LONG_PARSE_LONG =
createPure(Long.class, "parseLong", String.class).asCheap().asNonJavaNullable();
public static final MethodRef UNSIGNED_LONGS_PARSE_UNSIGNED_LONG =
createPure(UnsignedLongs.class, "parseUnsignedLong", String.class).asCheap();
public static final MethodRef UNSIGNED_LONGS_TO_STRING =
createPure(UnsignedLongs.class, "toString", long.class).asCheap().asNonJavaNullable();
public static final MethodRef UNSIGNED_INTS_SATURATED_CAST =
createPure(UnsignedInts.class, "saturatedCast", long.class).asCheap();
public static final MethodRef UNSIGNED_INTS_TO_LONG =
createPure(UnsignedInts.class, "toLong", int.class).asCheap();
public static final MethodRef LONG_TO_STRING =
createPure(Long.class, "toString", long.class).asNonJavaNullable();
public static final MethodRef NUMBER_DOUBLE_VALUE =
createPure(Number.class, "doubleValue").asCheap();
public static final MethodRef NUMBER_LONG_VALUE = createPure(Number.class, "longValue").asCheap();
public static final MethodRef NUMBER_INT_VALUE = createPure(Number.class, "intValue").asCheap();
public static final MethodRef NUMBER_FLOAT_VALUE =
createPure(Number.class, "floatValue").asCheap();
public static final MethodRef OBJECT_TO_STRING =
createPure(Object.class, "toString").asNonJavaNullable();
public static final MethodRef OBJECTS_EQUALS =
createPure(Objects.class, "equals", Object.class, Object.class);
public static final MethodRef ORDAIN_AS_SAFE =
createPure(
UnsafeSanitizedContentOrdainer.class, "ordainAsSafe", String.class, ContentKind.class);
public static final MethodRef ORDAIN_AS_SAFE_DIR =
createPure(
UnsafeSanitizedContentOrdainer.class,
"ordainAsSafe",
String.class,
ContentKind.class,
Dir.class);
public static final MethodRef PARAM_STORE_SET_FIELD =
createNonPure(ParamStore.class, "setField", RecordProperty.class, SoyValueProvider.class);
public static final MethodRef PARAM_STORE_SET_ALL =
createNonPure(ParamStore.class, "setAll", SoyValue.class);
public static final MethodRef PARAM_STORE_FROM_RECORD =
createPure(ParamStore.class, "fromRecord", SoyValue.class);
public static final MethodRef SOY_PROTO_VALUE_CREATE =
createPure(SoyProtoValue.class, "create", Message.class);
public static final MethodRef RENDER_RESULT_DONE =
createPure(RenderResult.class, "done").asCheap();
public static final MethodRef RENDER_RESULT_IS_DONE =
createPure(RenderResult.class, "isDone").asCheap();
public static final MethodRef RENDER_RESULT_LIMITED =
createPure(RenderResult.class, "limited").asCheap();
public static final MethodRef BUFFER_TEMPLATE =
createNonPure(
JbcSrcRuntime.class,
"bufferTemplate",
CompiledTemplate.class,
boolean.class,
JbcSrcRuntime.BufferedRenderDoneFn.class);
public static final MethodRef RUNTIME_CHECK_RESOLVED_LIST =
createNonPure(JbcSrcRuntime.class, "checkResolved", List.class);
public static final MethodRef RUNTIME_CHECK_RESOLVED_MAP =
createNonPure(JbcSrcRuntime.class, "checkResolved", Map.class);
public static final MethodRef SOY_SERVER_KEY =
createPure(SharedRuntime.class, "soyServerKey", SoyValue.class).asCheap();
public static final MethodRef RUNTIME_RANGE_LOOP_LENGTH =
createPure(JbcSrcRuntime.class, "rangeLoopLength", int.class, int.class, int.class).asCheap();
public static final MethodRef SOY_JAVA_PRINT_DIRECTIVE_APPLY_FOR_JAVA =
createNonPure(SoyJavaPrintDirective.class, "applyForJava", SoyValue.class, List.class);
public static final MethodRef RUNTIME_BIND_TEMPLATE_PARAMS =
createPure(JbcSrcRuntime.class, "bindTemplateParams", TemplateValue.class, ParamStore.class);
public static final MethodRef SOY_JAVA_FUNCTION_COMPUTE_FOR_JAVA =
createNonPure(SoyJavaFunction.class, "computeForJava", List.class);
public static final MethodRef RUNTIME_COERCE_DOUBLE_TO_BOOLEAN =
createPure(JbcSrcRuntime.class, "coerceToBoolean", double.class);
public static final MethodRef RUNTIME_COERCE_STRING_TO_BOOLEAN =
createPure(JbcSrcRuntime.class, "coerceToBoolean", String.class);
public static final MethodRef RUNTIME_EQUAL =
createPure(SharedRuntime.class, "equal", SoyValue.class, SoyValue.class);
public static final MethodRef FUNCTION_BIND =
createNonPure(JbcSrcFunctionValue.class, "bind", ImmutableList.class);
public static final MethodRef FUNCTION_CALL =
createNonPure(JbcSrcFunctionValue.class, "call", ImmutableList.class);
public static final MethodRef FUNCTION_AS_INSTANCE =
createNonPure(JbcSrcFunctionValue.class, "asInstance", Class.class);
public static final MethodRef FUNCTION_WITH_RENDER_CONTEXT =
createNonPure(JbcSrcFunctionValue.class, "withRenderContext", RenderContext.class);
public static final MethodRef SOY_VALUE_IS_TRUTHY_NON_EMPTY =
createPure(SoyValue.class, "isTruthyNonEmpty");
public static final MethodRef SOY_VALUE_HAS_CONTENT = createPure(SoyValue.class, "hasContent");
public static final MethodRef SOY_VALUE_RENDER =
createPure(SoyValue.class, "render", LoggingAdvisingAppendable.class);
public static final MethodRef RUNTIME_TRIPLE_EQUAL =
createPure(SharedRuntime.class, "tripleEqual", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_SWITCH_CASE_EQUAL =
createPure(SharedRuntime.class, "switchCaseEqual", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_COMPARE_BOXED_STRING =
createPure(JbcSrcRuntime.class, "compareBoxedStringToBoxed", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_COMPARE_BOXED_VALUE_TO_BOXED_STRING =
createPure(
JbcSrcRuntime.class, "compareBoxedValueToBoxedString", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_COMPARE_UNBOXED_STRING =
createPure(JbcSrcRuntime.class, "compareUnboxedStringToBoxed", String.class, SoyValue.class);
public static final MethodRef RUNTIME_COMPARE_BOXED_VALUE_TO_UNBOXED_STRING =
createPure(
JbcSrcRuntime.class, "compareBoxedValueToUnboxedString", SoyValue.class, String.class);
public static final MethodRef RUNTIME_GET_FIELD =
createPure(JbcSrcRuntime.class, "getField", SoyValue.class, RecordProperty.class);
public static final MethodRef RUNTIME_GET_FIELD_PROVIDER =
createPure(JbcSrcRuntime.class, "getFieldProvider", SoyValue.class, RecordProperty.class);
public static final MethodRef PARAM_STORE_GET_PARAMETER =
createPure(ParamStore.class, "getParameter", RecordProperty.class);
public static final MethodRef PARAM_STORE_GET_PARAMETER_DEFAULT =
createPure(ParamStore.class, "getParameter", RecordProperty.class, SoyValue.class);
public static final MethodRef SOY_VALUE_PROVIDER_WITH_DEFAULT =
createPure(SoyValueProvider.class, "withDefault", SoyValueProvider.class, SoyValue.class)
.asCheap();
public static final MethodRef RUNTIME_GET_LIST_ITEM =
createPure(JbcSrcRuntime.class, "getSoyListItem", List.class, long.class);
public static final MethodRef RUNTIME_GET_LIST_ITEM_PROVIDER =
createPure(JbcSrcRuntime.class, "getSoyListItemProvider", List.class, long.class);
public static final MethodRef RUNTIME_GET_LIST_STATUS =
createNonPure(JbcSrcRuntime.class, "getListStatus", List.class);
public static final MethodRef RUNTIME_GET_MAP_STATUS =
createNonPure(JbcSrcRuntime.class, "getMapStatus", Map.class);
public static final MethodRef RUNTIME_GET_LEGACY_OBJECT_MAP_ITEM =
createPure(JbcSrcRuntime.class, "getSoyLegacyObjectMapItem", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_GET_LEGACY_OBJECT_MAP_ITEM_PROVIDER =
createPure(
JbcSrcRuntime.class, "getSoyLegacyObjectMapItemProvider", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_GET_MAP_ITEM =
createPure(JbcSrcRuntime.class, "getSoyMapItem", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_GET_MAP_ITEM_PROVIDER =
createPure(JbcSrcRuntime.class, "getSoyMapItemProvider", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_LESS_THAN =
createPure(SharedRuntime.class, "lessThan", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_LESS_THAN_OR_EQUAL =
createPure(SharedRuntime.class, "lessThanOrEqual", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_LOGGER =
createPure(JbcSrcRuntime.class, "logger").asCheap();
public static final MethodRef RUNTIME_DEBUGGER =
createNonPure(JbcSrcRuntime.class, "debugger", String.class, int.class);
public static final MethodRef RUNTIME_MINUS =
createPure(SharedRuntime.class, "minus", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_NEGATIVE =
createPure(SharedRuntime.class, "negative", SoyValue.class);
public static final MethodRef RUNTIME_PLUS =
createPure(SharedRuntime.class, "plus", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_MOD =
createPure(SharedRuntime.class, "mod", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_SHIFT_RIGHT =
createPure(SharedRuntime.class, "shiftRight", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_SHIFT_LEFT =
createPure(SharedRuntime.class, "shiftLeft", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_BITWISE_OR =
createPure(SharedRuntime.class, "bitwiseOr", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_BITWISE_XOR =
createPure(SharedRuntime.class, "bitwiseXor", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_BITWISE_AND =
createPure(SharedRuntime.class, "bitwiseAnd", SoyValue.class, SoyValue.class);
public static final MethodRef CONSTRUCT_MAP_FROM_ITERATOR =
createPure(SharedRuntime.class, "constructMapFromIterator", Iterator.class);
public static final MethodRef RUNTIME_TIMES =
createPure(SharedRuntime.class, "times", SoyValue.class, SoyValue.class);
public static final MethodRef RUNTIME_DIVIDED_BY =
createPure(SharedRuntime.class, "dividedBy", SoyValue.class, SoyValue.class);
public static final MethodRef HANDLE_BASIC_TRANSLATION_AND_ESCAPE_HTML =
createPure(JbcSrcRuntime.class, "handleBasicTranslationAndEscapeHtml", String.class);
public static final MethodRef RUNTIME_STRING_EQUALS_AS_NUMBER =
createPure(JbcSrcRuntime.class, "stringEqualsAsNumber", String.class, double.class);
public static final MethodRef RUNTIME_NUMBER_EQUALS_STRING_AS_NUMBER =
createPure(JbcSrcRuntime.class, "numberEqualsStringAsNumber", double.class, String.class);
public static final MethodRef RUNTIME_EMPTY_TO_UNDEFINED =
createPure(JbcSrcRuntime.class, "emptyToUndefined", SoyValue.class);
public static final MethodRef RUNTIME_UNEXPECTED_STATE_ERROR =
createNonPure(JbcSrcRuntime.class, "unexpectedStateError", StackFrame.class);
public static final MethodRef SOY_VALUE_AS_JAVA_LIST = createPure(SoyValue.class, "asJavaList");
public static final MethodRef SOY_VALUE_AS_JAVA_LIST_OR_NULL =
createPure(SoyValue.class, "asJavaListOrNull");
public static final MethodRef SOY_VALUE_AS_JAVA_ITERATOR =
createPure(SoyValue.class, "javaIterator");
public static final MethodRef SOY_VALUE_AS_JAVA_MAP = createPure(SoyValue.class, "asJavaMap");
public static final MethodRef SOY_VALUE_GET_PROTO =
createPure(SoyValue.class, "getProto").asCheap();
public static final MethodRef SOY_VALUE_GET_PROTO_OR_NULL =
createPure(SoyValue.class, "getProtoOrNull").asCheap();
public static final MethodRef SOY_VALUE_COERCE_TO_BOOLEAN =
createPure(SoyValue.class, "coerceToBoolean").asCheap();
public static final MethodRef SOY_VALUE_BOOLEAN_VALUE =
createPure(SoyValue.class, "booleanValue").asCheap();
public static final MethodRef SOY_VALUE_FLOAT_VALUE =
createPure(SoyValue.class, "floatValue").asCheap();
public static final MethodRef SOY_VALUE_LONG_VALUE =
createPure(SoyValue.class, "longValue").asCheap();
public static final MethodRef SOY_VALUE_ITEM_INDEX_VALUE =
createPure(SoyValue.class, "coerceToIndex").asCheap();
public static final MethodRef SOY_VALUE_INTEGER_VALUE =
createPure(SoyValue.class, "integerValue").asCheap();
public static final MethodRef INT_TO_NUMBER =
createPure(JbcSrcRuntime.class, "intToNumber", SoyValue.class);
public static final MethodRef SOY_VALUE_IS_NULLISH =
createPure(SoyValue.class, "isNullish").asCheap().asNonJavaNullable();
public static final MethodRef SOY_VALUE_IS_NULL =
createPure(SoyValue.class, "isNull").asCheap().asNonJavaNullable();
public static final MethodRef SOY_VALUE_IS_UNDEFINED =
createPure(SoyValue.class, "isUndefined").asCheap().asNonJavaNullable();
public static final MethodRef SOY_VALUE_NULLISH_TO_NULL =
createPure(SoyValue.class, "nullishToNull").asCheap().asNonJavaNullable();
public static final MethodRef SOY_VALUE_NULLISH_TO_UNDEFINED =
createPure(SoyValue.class, "nullishToUndefined").asCheap().asNonJavaNullable();
public static final MethodRef SOY_VALUE_JAVA_NUMBER_VALUE =
createPure(JbcSrcRuntime.class, "javaNumberValue", SoyValue.class);
public static final MethodRef SOY_VALUE_STRING_VALUE =
createPure(SoyValue.class, "stringValue").asCheap();
public static final MethodRef SOY_VALUE_STRING_VALUE_OR_NULL =
createPure(SoyValue.class, "stringValueOrNull").asCheap();
public static final MethodRef SOY_VALUE_COERCE_TO_STRING =
createPure(SoyValue.class, "coerceToString");
public static final MethodRef CHECK_TYPE =
createNonPure(SoyValue.class, "checkNullishType", Class.class);
public static final MethodRef CHECK_INT = createNonPure(SoyValue.class, "checkNullishInt");
public static final MethodRef CHECK_FLOAT = createNonPure(SoyValue.class, "checkNullishFloat");
public static final MethodRef CHECK_NUMBER = createNonPure(SoyValue.class, "checkNullishNumber");
public static final MethodRef CHECK_STRING = createNonPure(SoyValue.class, "checkNullishString");
public static final MethodRef CHECK_FUNCTION =
createNonPure(SoyValue.class, "checkNullishFunction");
public static final MethodRef CHECK_BOOLEAN =
createNonPure(SoyValue.class, "checkNullishBoolean");
public static final MethodRef CHECK_CONTENT_KIND =
createNonPure(SoyValue.class, "checkNullishSanitizedContent", ContentKind.class);
public static final MethodRef CHECK_PROTO =
createNonPure(SoyValue.class, "checkNullishProto", Class.class);
public static final MethodRef IS_PROTO_INSTANCE =
createNonPure(SoyValue.class, "isProtoInstance", Class.class);
public static final MethodRef IS_SANITIZED_CONTENT_KIND =
createNonPure(SoyValue.class, "isSanitizedContentKind", SanitizedContent.ContentKind.class);
public static final MethodRef GET_COMPILED_TEMPLATE_FROM_VALUE =
createPure(JbcSrcRuntime.class, "getCompiledTemplate", TemplateValue.class).asCheap();
public static final MethodRef CREATE_NODE_BUILDER =
createPure(
JbcSrcRuntime.class,
"createNodeBuilder",
CompiledTemplate.class,
StackFrame.class,
ParamStore.class,
RenderContext.class);
public static final MethodRef CREATE_TEMPLATE_VALUE =
createPure(TemplateValue.class, "create", String.class, Object.class);
public static final MethodRef CREATE_TEMPLATE_VALUE_FROM_TEMPLATE =
createPure(TemplateValue.class, "createFromTemplate", TemplateInterface.class);
public static final MethodRef SOY_VALUE_PROVIDER_RENDER_AND_RESOLVE =
createNonPure(SoyValueProvider.class, "renderAndResolve", LoggingAdvisingAppendable.class);
public static final MethodRef SOY_NULLISH_TO_JAVA_NULL =
createNonPure(JbcSrcRuntime.class, "soyNullishToJavaNull", SoyValue.class);
public static final MethodRef SOY_NULL_TO_JAVA_NULL =
createNonPure(JbcSrcRuntime.class, "soyNullToJavaNull", SoyValue.class);
public static final MethodRef SOY_VALUE_PROVIDER_STATUS =
createNonPure(SoyValueProvider.class, "status");
public static final MethodRef SOY_VALUE_PROVIDER_RESOLVE =
createNonPure(SoyValueProvider.class, "resolve");
public static final MethodRef SOY_VALUE_PROVIDER_COERCE_TO_BOOLEAN_PROVIDER =
createNonPure(SoyValueProvider.class, "coerceToBooleanProvider");
public static final MethodRef STRING_CONCAT =
createPure(String.class, "concat", String.class).asNonJavaNullable();
public static final MethodRef STRING_IS_EMPTY = createPure(String.class, "isEmpty");
public static final MethodRef STRING_VALUE_OF =
createPure(String.class, "valueOf", Object.class).asNonJavaNullable();
public static final MethodRef BOX_INTEGER =
createPure(Integer.class, "valueOf", int.class).asNonJavaNullable();
public static final MethodRef BOX_LONG =
createPure(Long.class, "valueOf", long.class).asNonJavaNullable();
public static final MethodRef BOX_DOUBLE =
createPure(Double.class, "valueOf", double.class).asNonJavaNullable();
public static final MethodRef BOX_FLOAT =
createPure(Float.class, "valueOf", float.class).asNonJavaNullable();
public static final MethodRef BOX_BOOLEAN =
createPure(Boolean.class, "valueOf", boolean.class).asNonJavaNullable();
public static final MethodRef CHECK_NOT_NULL =
createNonPure(JbcSrcRuntime.class, "checkExpressionNotNull", Object.class, String.class);
public static final MethodRef IS_SOY_NON_NULLISH =
createPure(JbcSrcRuntime.class, "isNonSoyNullish", SoyValueProvider.class);
public static final MethodRef IS_SOY_NON_NULL =
createPure(JbcSrcRuntime.class, "isNonSoyNull", SoyValueProvider.class);
public static final MethodRef GBIGINT_DATA_FOR_VALUE =
createPure(GbigintData.class, "forValue", BigInteger.class).asCheap();
public static final MethodRef GBIGINT_DATA_FOR_STRING_VALUE =
createPure(GbigintData.class, "forStringValue", String.class).asCheap();
public static final MethodRef GBIGINT_DATA_FOR_LONG_VALUE =
createPure(GbigintData.class, "forValue", long.class).asCheap();
public static final MethodRef GBIGINT_DATA_FOR_UNSIGNED_LONG_VALUE =
createPure(GbigintData.class, "forUnsignedLongValue", long.class).asCheap();
public static final MethodRef STRING_DATA_FOR_VALUE =
createPure(StringData.class, "forValue", String.class).asCheap();
public static final MethodRef LOGGING_ADVISING_APPENDABLE_BUFFERING =
createNonPure(
LoggingAdvisingAppendable.class, "buffering", SanitizedContent.ContentKind.class)
.asCheap();
public static final MethodRef MULTIPLEXING_APPENDABLE =
createNonPure(
DetachableContentProvider.MultiplexingAppendable.class,
"create",
SanitizedContent.ContentKind.class)
.asCheap();
public static final MethodRef BUFFERING_APPENDABLE_GET_AS_STRING_DATA =
createPure(BufferingAppendable.class, "getAsStringData");
public static final MethodRef BUFFERING_APPENDABLE_GET_AS_SANITIZED_CONTENT =
createPure(BufferingAppendable.class, "getAsSanitizedContent");
public static final MethodRef CREATE_LOG_STATEMENT =
createPure(JbcSrcRuntime.class, "createLogStatement", boolean.class, SoyValue.class);
public static final MethodRef CREATE_LOG_STATEMENT_NOT_LOGONLY =
createPure(JbcSrcRuntime.class, "createLogStatement", SoyValue.class);
public static final MethodRef CLOSEABLE_CLOSE = createNonPure(Closeable.class, "close");
public static final MethodRef PROTOCOL_ENUM_GET_NUMBER =
createPure(ProtocolMessageEnum.class, "getNumber").asCheap();
public static final MethodRef SOY_VISUAL_ELEMENT_CREATE =
createPure(SoyVisualElement.class, "create", long.class, String.class);
public static final MethodRef SOY_VISUAL_ELEMENT_CREATE_WITH_METADATA =
createPure(
SoyVisualElement.class,
"create",
long.class,
String.class,
LoggableElementMetadata.class);
public static final MethodRef SOY_VISUAL_ELEMENT_DATA_CREATE_NULL_MESSAGE =
createPure(SoyVisualElementData.class, "create", SoyValue.class);
public static final MethodRef SOY_VISUAL_ELEMENT_DATA_CREATE =
createPure(SoyVisualElementData.class, "create", SoyValue.class, Message.class);
public static final MethodRef LAZY_PROTO_TO_SOY_VALUE_LIST_FOR_LIST =
createPure(LazyProtoToSoyValueList.class, "forList", List.class, ProtoFieldInterpreter.class);
public static final MethodRef LAZY_PROTO_TO_SOY_VALUE_MAP_FOR_MAP =
createPure(
LazyProtoToSoyValueMap.class,
"forMap",
Map.class,
ProtoFieldInterpreter.class,
ProtoFieldInterpreter.class);
public static final MethodRef GET_EXTENSION_LIST =
createPure(
JbcSrcRuntime.class,
"getExtensionList",
ExtendableMessage.class,
ExtensionLite.class,
ProtoFieldInterpreter.class);
public static final MethodRef AS_SWITCHABLE_VALUE_LONG =
createPure(JbcSrcRuntime.class, "asSwitchableValue", long.class, int.class);
public static final MethodRef AS_SWITCHABLE_VALUE_DOUBLE =
createPure(JbcSrcRuntime.class, "asSwitchableValue", double.class, int.class);
public static final MethodRef AS_SWITCHABLE_VALUE_SOY_VALUE =
createPure(JbcSrcRuntime.class, "asSwitchableValue", SoyValue.class, int.class);
public static final MethodRef NEW_SOY_SET = createPureConstructor(SetImpl.class, Iterator.class);
// Constructors
public static final MethodRef ARRAY_LIST = createNonPureConstructor(ArrayList.class);
public static final MethodRef ARRAY_LIST_FROM_LIST =
createNonPureConstructor(ArrayList.class, Collection.class);
public static final MethodRef ARRAY_LIST_SIZE =
createNonPureConstructor(ArrayList.class, int.class);
public static final MethodRef HASH_MAP_CAPACITY =
createNonPureConstructor(HashMap.class, int.class);
public static final MethodRef LINKED_HASH_MAP_CAPACITY =
createNonPureConstructor(LinkedHashMap.class, int.class);
public static final MethodRef PARAM_STORE_AUGMENT =
createPureConstructor(ParamStore.class, ParamStore.class, int.class);
public static final MethodRef PARAM_STORE_SIZE =
createPureConstructor(ParamStore.class, int.class);
public static final MethodRef SOY_RECORD_IMPL =
createPureConstructor(SoyRecordImpl.class, ParamStore.class);
public static final MethodRef MSG_RENDERER =
createPureConstructor(
JbcSrcRuntime.MsgRenderer.class,
SoyMsgRawParts.class,
ToIntFunction.class,
ImmutableList.class,
boolean.class,
ImmutableSetMultimap.class);
public static final MethodRef PLRSEL_MSG_RENDERER =
createPureConstructor(
JbcSrcRuntime.PlrSelMsgRenderer.class,
SoyMsgRawParts.class,
ToIntFunction.class,
ImmutableList.class,
boolean.class,
ULocale.class,
ImmutableSetMultimap.class);
public static final MethodRef ESCAPING_BUFFERED_RENDER_DONE_FN =
createPureConstructor(JbcSrcRuntime.EscapingBufferedRenderDoneFn.class, ImmutableList.class);
public static final MethodRef STACK_FRAME_CREATE_LEAF =
createPure(StackFrame.class, "create", RenderResult.class, int.class);
public static final MethodRef STACK_FRAME_CREATE_NON_LEAF =
createPure(StackFrame.class, "create", StackFrame.class, int.class);
private MethodRefs() {}
}
|
googleapis/google-api-java-client-services | 35,856 | clients/google-api-services-cloudtrace/v1/1.28.0/com/google/api/services/cloudtrace/v1/CloudTrace.java | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.cloudtrace.v1;
/**
* Service definition for CloudTrace (v1).
*
* <p>
* Sends application trace data to Stackdriver Trace for viewing. Trace data is collected for all App Engine applications by default. Trace data from other applications can be provided using this API. This library is used to interact with the Trace API directly. If you are looking to instrument your application for Stackdriver Trace, we recommend using OpenCensus.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://cloud.google.com/trace" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link CloudTraceRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class CloudTrace extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15,
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.15 of google-api-client to run version " +
"1.28.0 of the Stackdriver Trace API library.", com.google.api.client.googleapis.GoogleUtils.VERSION);
}
/**
* The default encoded root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_ROOT_URL = "https://cloudtrace.googleapis.com/";
/**
* The default encoded service path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "";
/**
* The default encoded batch path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.23
*/
public static final String DEFAULT_BATCH_PATH = "batch";
/**
* The default encoded base URL of the service. This is determined when the library is generated
* and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;
/**
* Constructor.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public CloudTrace(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
this(new Builder(transport, jsonFactory, httpRequestInitializer));
}
/**
* @param builder builder
*/
CloudTrace(Builder builder) {
super(builder);
}
@Override
protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException {
super.initialize(httpClientRequest);
}
/**
* An accessor for creating requests from the Projects collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code CloudTrace cloudtrace = new CloudTrace(...);}
* {@code CloudTrace.Projects.List request = cloudtrace.projects().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Projects projects() {
return new Projects();
}
/**
* The "projects" collection of methods.
*/
public class Projects {
/**
* Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you
* send matches that of an existing trace, any fields in the existing trace and its spans are
* overwritten by the provided values, and any new fields provided are merged with the existing
* trace data. If the ID does not match, a new trace is created.
*
* Create a request for the method "projects.patchTraces".
*
* This request holds the parameters needed by the cloudtrace server. After setting any optional
* parameters, call the {@link PatchTraces#execute()} method to invoke the remote operation.
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @param content the {@link com.google.api.services.cloudtrace.v1.model.Traces}
* @return the request
*/
public PatchTraces patchTraces(java.lang.String projectId, com.google.api.services.cloudtrace.v1.model.Traces content) throws java.io.IOException {
PatchTraces result = new PatchTraces(projectId, content);
initialize(result);
return result;
}
public class PatchTraces extends CloudTraceRequest<com.google.api.services.cloudtrace.v1.model.Empty> {
private static final String REST_PATH = "v1/projects/{projectId}/traces";
/**
* Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you
* send matches that of an existing trace, any fields in the existing trace and its spans are
* overwritten by the provided values, and any new fields provided are merged with the existing
* trace data. If the ID does not match, a new trace is created.
*
* Create a request for the method "projects.patchTraces".
*
* This request holds the parameters needed by the the cloudtrace server. After setting any
* optional parameters, call the {@link PatchTraces#execute()} method to invoke the remote
* operation. <p> {@link
* PatchTraces#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @param content the {@link com.google.api.services.cloudtrace.v1.model.Traces}
* @since 1.13
*/
protected PatchTraces(java.lang.String projectId, com.google.api.services.cloudtrace.v1.model.Traces content) {
super(CloudTrace.this, "PATCH", REST_PATH, content, com.google.api.services.cloudtrace.v1.model.Empty.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
}
@Override
public PatchTraces set$Xgafv(java.lang.String $Xgafv) {
return (PatchTraces) super.set$Xgafv($Xgafv);
}
@Override
public PatchTraces setAccessToken(java.lang.String accessToken) {
return (PatchTraces) super.setAccessToken(accessToken);
}
@Override
public PatchTraces setAlt(java.lang.String alt) {
return (PatchTraces) super.setAlt(alt);
}
@Override
public PatchTraces setCallback(java.lang.String callback) {
return (PatchTraces) super.setCallback(callback);
}
@Override
public PatchTraces setFields(java.lang.String fields) {
return (PatchTraces) super.setFields(fields);
}
@Override
public PatchTraces setKey(java.lang.String key) {
return (PatchTraces) super.setKey(key);
}
@Override
public PatchTraces setOauthToken(java.lang.String oauthToken) {
return (PatchTraces) super.setOauthToken(oauthToken);
}
@Override
public PatchTraces setPrettyPrint(java.lang.Boolean prettyPrint) {
return (PatchTraces) super.setPrettyPrint(prettyPrint);
}
@Override
public PatchTraces setQuotaUser(java.lang.String quotaUser) {
return (PatchTraces) super.setQuotaUser(quotaUser);
}
@Override
public PatchTraces setUploadType(java.lang.String uploadType) {
return (PatchTraces) super.setUploadType(uploadType);
}
@Override
public PatchTraces setUploadProtocol(java.lang.String uploadProtocol) {
return (PatchTraces) super.setUploadProtocol(uploadProtocol);
}
/** Required. ID of the Cloud project where the trace data is stored. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. ID of the Cloud project where the trace data is stored.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Required. ID of the Cloud project where the trace data is stored. */
public PatchTraces setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
@Override
public PatchTraces set(String parameterName, Object value) {
return (PatchTraces) super.set(parameterName, value);
}
}
/**
* An accessor for creating requests from the Traces collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code CloudTrace cloudtrace = new CloudTrace(...);}
* {@code CloudTrace.Traces.List request = cloudtrace.traces().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Traces traces() {
return new Traces();
}
/**
* The "traces" collection of methods.
*/
public class Traces {
/**
* Gets a single trace by its ID.
*
* Create a request for the method "traces.get".
*
* This request holds the parameters needed by the cloudtrace server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @param traceId Required. ID of the trace to return.
* @return the request
*/
public Get get(java.lang.String projectId, java.lang.String traceId) throws java.io.IOException {
Get result = new Get(projectId, traceId);
initialize(result);
return result;
}
public class Get extends CloudTraceRequest<com.google.api.services.cloudtrace.v1.model.Trace> {
private static final String REST_PATH = "v1/projects/{projectId}/traces/{traceId}";
/**
* Gets a single trace by its ID.
*
* Create a request for the method "traces.get".
*
* This request holds the parameters needed by the the cloudtrace server. After setting any
* optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p>
* {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @param traceId Required. ID of the trace to return.
* @since 1.13
*/
protected Get(java.lang.String projectId, java.lang.String traceId) {
super(CloudTrace.this, "GET", REST_PATH, null, com.google.api.services.cloudtrace.v1.model.Trace.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.traceId = com.google.api.client.util.Preconditions.checkNotNull(traceId, "Required parameter traceId must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/** Required. ID of the Cloud project where the trace data is stored. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. ID of the Cloud project where the trace data is stored.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Required. ID of the Cloud project where the trace data is stored. */
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/** Required. ID of the trace to return. */
@com.google.api.client.util.Key
private java.lang.String traceId;
/** Required. ID of the trace to return.
*/
public java.lang.String getTraceId() {
return traceId;
}
/** Required. ID of the trace to return. */
public Get setTraceId(java.lang.String traceId) {
this.traceId = traceId;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Returns of a list of traces that match the specified filter conditions.
*
* Create a request for the method "traces.list".
*
* This request holds the parameters needed by the cloudtrace server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @return the request
*/
public List list(java.lang.String projectId) throws java.io.IOException {
List result = new List(projectId);
initialize(result);
return result;
}
public class List extends CloudTraceRequest<com.google.api.services.cloudtrace.v1.model.ListTracesResponse> {
private static final String REST_PATH = "v1/projects/{projectId}/traces";
/**
* Returns of a list of traces that match the specified filter conditions.
*
* Create a request for the method "traces.list".
*
* This request holds the parameters needed by the the cloudtrace server. After setting any
* optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p>
* {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @since 1.13
*/
protected List(java.lang.String projectId) {
super(CloudTrace.this, "GET", REST_PATH, null, com.google.api.services.cloudtrace.v1.model.ListTracesResponse.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@Override
public List setFields(java.lang.String fields) {
return (List) super.setFields(fields);
}
@Override
public List setKey(java.lang.String key) {
return (List) super.setKey(key);
}
@Override
public List setOauthToken(java.lang.String oauthToken) {
return (List) super.setOauthToken(oauthToken);
}
@Override
public List setPrettyPrint(java.lang.Boolean prettyPrint) {
return (List) super.setPrettyPrint(prettyPrint);
}
@Override
public List setQuotaUser(java.lang.String quotaUser) {
return (List) super.setQuotaUser(quotaUser);
}
@Override
public List setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
/** Required. ID of the Cloud project where the trace data is stored. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. ID of the Cloud project where the trace data is stored.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Required. ID of the Cloud project where the trace data is stored. */
public List setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* End of the time interval (inclusive) during which the trace data was collected from the
* application.
*/
@com.google.api.client.util.Key
private String endTime;
/** End of the time interval (inclusive) during which the trace data was collected from the
application.
*/
public String getEndTime() {
return endTime;
}
/**
* End of the time interval (inclusive) during which the trace data was collected from the
* application.
*/
public List setEndTime(String endTime) {
this.endTime = endTime;
return this;
}
/**
* Optional. A filter against labels for the request.
*
* By default, searches use prefix matching. To specify exact match, prepend a plus symbol
* (`+`) to the search term. Multiple terms are ANDed. Syntax:
*
* * `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces where any root span starts with
* `NAME_PREFIX`. * `+root:NAME` or `+NAME`: Return traces where any root span's name is
* exactly `NAME`. * `span:NAME_PREFIX`: Return traces where any span starts with
* `NAME_PREFIX`. * `+span:NAME`: Return traces where any span's name is exactly `NAME`. *
* `latency:DURATION`: Return traces whose overall latency is greater or equal to than
* `DURATION`. Accepted units are nanoseconds (`ns`), milliseconds (`ms`), and seconds
* (`s`). Default is `ms`. For example, `latency:24ms` returns traces whose overall latency
* is greater than or equal to 24 milliseconds. * `label:LABEL_KEY`: Return all traces
* containing the specified label key (exact match, case-sensitive) regardless of the
* key:value pair's value (including empty values). * `LABEL_KEY:VALUE_PREFIX`: Return all
* traces containing the specified label key (exact match, case-sensitive) whose value
* starts with `VALUE_PREFIX`. Both a key and a value must be specified. *
* `+LABEL_KEY:VALUE`: Return all traces containing a key:value pair exactly matching the
* specified text. Both a key and a value must be specified. * `method:VALUE`: Equivalent
* to `/http/method:VALUE`. * `url:VALUE`: Equivalent to `/http/url:VALUE`.
*/
@com.google.api.client.util.Key
private java.lang.String filter;
/** Optional. A filter against labels for the request.
By default, searches use prefix matching. To specify exact match, prepend a plus symbol (`+`) to
the search term. Multiple terms are ANDed. Syntax:
* `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces where any root span starts with
`NAME_PREFIX`. * `+root:NAME` or `+NAME`: Return traces where any root span's name is exactly
`NAME`. * `span:NAME_PREFIX`: Return traces where any span starts with `NAME_PREFIX`. *
`+span:NAME`: Return traces where any span's name is exactly `NAME`. * `latency:DURATION`: Return
traces whose overall latency is greater or equal to than `DURATION`. Accepted units are nanoseconds
(`ns`), milliseconds (`ms`), and seconds (`s`). Default is `ms`. For example, `latency:24ms`
returns traces whose overall latency is greater than or equal to 24 milliseconds. *
`label:LABEL_KEY`: Return all traces containing the specified label key (exact match, case-
sensitive) regardless of the key:value pair's value (including empty values). *
`LABEL_KEY:VALUE_PREFIX`: Return all traces containing the specified label key (exact match, case-
sensitive) whose value starts with `VALUE_PREFIX`. Both a key and a value must be specified. *
`+LABEL_KEY:VALUE`: Return all traces containing a key:value pair exactly matching the specified
text. Both a key and a value must be specified. * `method:VALUE`: Equivalent to
`/http/method:VALUE`. * `url:VALUE`: Equivalent to `/http/url:VALUE`.
*/
public java.lang.String getFilter() {
return filter;
}
/**
* Optional. A filter against labels for the request.
*
* By default, searches use prefix matching. To specify exact match, prepend a plus symbol
* (`+`) to the search term. Multiple terms are ANDed. Syntax:
*
* * `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces where any root span starts with
* `NAME_PREFIX`. * `+root:NAME` or `+NAME`: Return traces where any root span's name is
* exactly `NAME`. * `span:NAME_PREFIX`: Return traces where any span starts with
* `NAME_PREFIX`. * `+span:NAME`: Return traces where any span's name is exactly `NAME`. *
* `latency:DURATION`: Return traces whose overall latency is greater or equal to than
* `DURATION`. Accepted units are nanoseconds (`ns`), milliseconds (`ms`), and seconds
* (`s`). Default is `ms`. For example, `latency:24ms` returns traces whose overall latency
* is greater than or equal to 24 milliseconds. * `label:LABEL_KEY`: Return all traces
* containing the specified label key (exact match, case-sensitive) regardless of the
* key:value pair's value (including empty values). * `LABEL_KEY:VALUE_PREFIX`: Return all
* traces containing the specified label key (exact match, case-sensitive) whose value
* starts with `VALUE_PREFIX`. Both a key and a value must be specified. *
* `+LABEL_KEY:VALUE`: Return all traces containing a key:value pair exactly matching the
* specified text. Both a key and a value must be specified. * `method:VALUE`: Equivalent
* to `/http/method:VALUE`. * `url:VALUE`: Equivalent to `/http/url:VALUE`.
*/
public List setFilter(java.lang.String filter) {
this.filter = filter;
return this;
}
/**
* Optional. Field used to sort the returned traces. Can be one of the following:
*
* * `trace_id` * `name` (`name` field of root span in the trace) * `duration`
* (difference between `end_time` and `start_time` fields of the root span) * `start`
* (`start_time` field of the root span)
*
* Descending order can be specified by appending `desc` to the sort field (for example,
* `name desc`).
*
* Only one sort field is permitted.
*/
@com.google.api.client.util.Key
private java.lang.String orderBy;
/** Optional. Field used to sort the returned traces. Can be one of the following:
* `trace_id` * `name` (`name` field of root span in the trace) * `duration` (difference
between `end_time` and `start_time` fields of the root span) * `start` (`start_time` field of the
root span)
Descending order can be specified by appending `desc` to the sort field (for example, `name desc`).
Only one sort field is permitted.
*/
public java.lang.String getOrderBy() {
return orderBy;
}
/**
* Optional. Field used to sort the returned traces. Can be one of the following:
*
* * `trace_id` * `name` (`name` field of root span in the trace) * `duration`
* (difference between `end_time` and `start_time` fields of the root span) * `start`
* (`start_time` field of the root span)
*
* Descending order can be specified by appending `desc` to the sort field (for example,
* `name desc`).
*
* Only one sort field is permitted.
*/
public List setOrderBy(java.lang.String orderBy) {
this.orderBy = orderBy;
return this;
}
/**
* Optional. Maximum number of traces to return. If not specified or <= 0, the
* implementation selects a reasonable value. The implementation may return fewer traces
* than the requested page size.
*/
@com.google.api.client.util.Key
private java.lang.Integer pageSize;
/** Optional. Maximum number of traces to return. If not specified or <= 0, the implementation selects
a reasonable value. The implementation may return fewer traces than the requested page size.
*/
public java.lang.Integer getPageSize() {
return pageSize;
}
/**
* Optional. Maximum number of traces to return. If not specified or <= 0, the
* implementation selects a reasonable value. The implementation may return fewer traces
* than the requested page size.
*/
public List setPageSize(java.lang.Integer pageSize) {
this.pageSize = pageSize;
return this;
}
/**
* Token identifying the page of results to return. If provided, use the value of the
* `next_page_token` field from a previous request.
*/
@com.google.api.client.util.Key
private java.lang.String pageToken;
/** Token identifying the page of results to return. If provided, use the value of the
`next_page_token` field from a previous request.
*/
public java.lang.String getPageToken() {
return pageToken;
}
/**
* Token identifying the page of results to return. If provided, use the value of the
* `next_page_token` field from a previous request.
*/
public List setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
/**
* Start of the time interval (inclusive) during which the trace data was collected from the
* application.
*/
@com.google.api.client.util.Key
private String startTime;
/** Start of the time interval (inclusive) during which the trace data was collected from the
application.
*/
public String getStartTime() {
return startTime;
}
/**
* Start of the time interval (inclusive) during which the trace data was collected from the
* application.
*/
public List setStartTime(String startTime) {
this.startTime = startTime;
return this;
}
/**
* Optional. Type of data returned for traces in the list. Default is `MINIMAL`.
*/
@com.google.api.client.util.Key
private java.lang.String view;
/** Optional. Type of data returned for traces in the list. Default is `MINIMAL`.
*/
public java.lang.String getView() {
return view;
}
/**
* Optional. Type of data returned for traces in the list. Default is `MINIMAL`.
*/
public List setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
}
}
/**
* Builder for {@link CloudTrace}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
DEFAULT_ROOT_URL,
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link CloudTrace}. */
@Override
public CloudTrace build() {
return new CloudTrace(this);
}
@Override
public Builder setRootUrl(String rootUrl) {
return (Builder) super.setRootUrl(rootUrl);
}
@Override
public Builder setServicePath(String servicePath) {
return (Builder) super.setServicePath(servicePath);
}
@Override
public Builder setBatchPath(String batchPath) {
return (Builder) super.setBatchPath(batchPath);
}
@Override
public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
}
@Override
public Builder setApplicationName(String applicationName) {
return (Builder) super.setApplicationName(applicationName);
}
@Override
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
}
@Override
public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) {
return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks);
}
@Override
public Builder setSuppressAllChecks(boolean suppressAllChecks) {
return (Builder) super.setSuppressAllChecks(suppressAllChecks);
}
/**
* Set the {@link CloudTraceRequestInitializer}.
*
* @since 1.12
*/
public Builder setCloudTraceRequestInitializer(
CloudTraceRequestInitializer cloudtraceRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(cloudtraceRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
|
googleapis/google-api-java-client-services | 35,856 | clients/google-api-services-cloudtrace/v1/1.29.2/com/google/api/services/cloudtrace/v1/CloudTrace.java | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.cloudtrace.v1;
/**
* Service definition for CloudTrace (v1).
*
* <p>
* Sends application trace data to Stackdriver Trace for viewing. Trace data is collected for all App Engine applications by default. Trace data from other applications can be provided using this API. This library is used to interact with the Trace API directly. If you are looking to instrument your application for Stackdriver Trace, we recommend using OpenCensus.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://cloud.google.com/trace" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link CloudTraceRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class CloudTrace extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15,
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.15 of google-api-client to run version " +
"1.29.2 of the Stackdriver Trace API library.", com.google.api.client.googleapis.GoogleUtils.VERSION);
}
/**
* The default encoded root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_ROOT_URL = "https://cloudtrace.googleapis.com/";
/**
* The default encoded service path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "";
/**
* The default encoded batch path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.23
*/
public static final String DEFAULT_BATCH_PATH = "batch";
/**
* The default encoded base URL of the service. This is determined when the library is generated
* and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;
/**
* Constructor.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public CloudTrace(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
this(new Builder(transport, jsonFactory, httpRequestInitializer));
}
/**
* @param builder builder
*/
CloudTrace(Builder builder) {
super(builder);
}
@Override
protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException {
super.initialize(httpClientRequest);
}
/**
* An accessor for creating requests from the Projects collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code CloudTrace cloudtrace = new CloudTrace(...);}
* {@code CloudTrace.Projects.List request = cloudtrace.projects().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Projects projects() {
return new Projects();
}
/**
* The "projects" collection of methods.
*/
public class Projects {
/**
* Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you
* send matches that of an existing trace, any fields in the existing trace and its spans are
* overwritten by the provided values, and any new fields provided are merged with the existing
* trace data. If the ID does not match, a new trace is created.
*
* Create a request for the method "projects.patchTraces".
*
* This request holds the parameters needed by the cloudtrace server. After setting any optional
* parameters, call the {@link PatchTraces#execute()} method to invoke the remote operation.
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @param content the {@link com.google.api.services.cloudtrace.v1.model.Traces}
* @return the request
*/
public PatchTraces patchTraces(java.lang.String projectId, com.google.api.services.cloudtrace.v1.model.Traces content) throws java.io.IOException {
PatchTraces result = new PatchTraces(projectId, content);
initialize(result);
return result;
}
public class PatchTraces extends CloudTraceRequest<com.google.api.services.cloudtrace.v1.model.Empty> {
private static final String REST_PATH = "v1/projects/{projectId}/traces";
/**
* Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you
* send matches that of an existing trace, any fields in the existing trace and its spans are
* overwritten by the provided values, and any new fields provided are merged with the existing
* trace data. If the ID does not match, a new trace is created.
*
* Create a request for the method "projects.patchTraces".
*
* This request holds the parameters needed by the the cloudtrace server. After setting any
* optional parameters, call the {@link PatchTraces#execute()} method to invoke the remote
* operation. <p> {@link
* PatchTraces#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @param content the {@link com.google.api.services.cloudtrace.v1.model.Traces}
* @since 1.13
*/
protected PatchTraces(java.lang.String projectId, com.google.api.services.cloudtrace.v1.model.Traces content) {
super(CloudTrace.this, "PATCH", REST_PATH, content, com.google.api.services.cloudtrace.v1.model.Empty.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
}
@Override
public PatchTraces set$Xgafv(java.lang.String $Xgafv) {
return (PatchTraces) super.set$Xgafv($Xgafv);
}
@Override
public PatchTraces setAccessToken(java.lang.String accessToken) {
return (PatchTraces) super.setAccessToken(accessToken);
}
@Override
public PatchTraces setAlt(java.lang.String alt) {
return (PatchTraces) super.setAlt(alt);
}
@Override
public PatchTraces setCallback(java.lang.String callback) {
return (PatchTraces) super.setCallback(callback);
}
@Override
public PatchTraces setFields(java.lang.String fields) {
return (PatchTraces) super.setFields(fields);
}
@Override
public PatchTraces setKey(java.lang.String key) {
return (PatchTraces) super.setKey(key);
}
@Override
public PatchTraces setOauthToken(java.lang.String oauthToken) {
return (PatchTraces) super.setOauthToken(oauthToken);
}
@Override
public PatchTraces setPrettyPrint(java.lang.Boolean prettyPrint) {
return (PatchTraces) super.setPrettyPrint(prettyPrint);
}
@Override
public PatchTraces setQuotaUser(java.lang.String quotaUser) {
return (PatchTraces) super.setQuotaUser(quotaUser);
}
@Override
public PatchTraces setUploadType(java.lang.String uploadType) {
return (PatchTraces) super.setUploadType(uploadType);
}
@Override
public PatchTraces setUploadProtocol(java.lang.String uploadProtocol) {
return (PatchTraces) super.setUploadProtocol(uploadProtocol);
}
/** Required. ID of the Cloud project where the trace data is stored. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. ID of the Cloud project where the trace data is stored.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Required. ID of the Cloud project where the trace data is stored. */
public PatchTraces setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
@Override
public PatchTraces set(String parameterName, Object value) {
return (PatchTraces) super.set(parameterName, value);
}
}
/**
* An accessor for creating requests from the Traces collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code CloudTrace cloudtrace = new CloudTrace(...);}
* {@code CloudTrace.Traces.List request = cloudtrace.traces().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Traces traces() {
return new Traces();
}
/**
* The "traces" collection of methods.
*/
public class Traces {
/**
* Gets a single trace by its ID.
*
* Create a request for the method "traces.get".
*
* This request holds the parameters needed by the cloudtrace server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @param traceId Required. ID of the trace to return.
* @return the request
*/
public Get get(java.lang.String projectId, java.lang.String traceId) throws java.io.IOException {
Get result = new Get(projectId, traceId);
initialize(result);
return result;
}
public class Get extends CloudTraceRequest<com.google.api.services.cloudtrace.v1.model.Trace> {
private static final String REST_PATH = "v1/projects/{projectId}/traces/{traceId}";
/**
* Gets a single trace by its ID.
*
* Create a request for the method "traces.get".
*
* This request holds the parameters needed by the the cloudtrace server. After setting any
* optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p>
* {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @param traceId Required. ID of the trace to return.
* @since 1.13
*/
protected Get(java.lang.String projectId, java.lang.String traceId) {
super(CloudTrace.this, "GET", REST_PATH, null, com.google.api.services.cloudtrace.v1.model.Trace.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.traceId = com.google.api.client.util.Preconditions.checkNotNull(traceId, "Required parameter traceId must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/** Required. ID of the Cloud project where the trace data is stored. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. ID of the Cloud project where the trace data is stored.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Required. ID of the Cloud project where the trace data is stored. */
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/** Required. ID of the trace to return. */
@com.google.api.client.util.Key
private java.lang.String traceId;
/** Required. ID of the trace to return.
*/
public java.lang.String getTraceId() {
return traceId;
}
/** Required. ID of the trace to return. */
public Get setTraceId(java.lang.String traceId) {
this.traceId = traceId;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Returns of a list of traces that match the specified filter conditions.
*
* Create a request for the method "traces.list".
*
* This request holds the parameters needed by the cloudtrace server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @return the request
*/
public List list(java.lang.String projectId) throws java.io.IOException {
List result = new List(projectId);
initialize(result);
return result;
}
public class List extends CloudTraceRequest<com.google.api.services.cloudtrace.v1.model.ListTracesResponse> {
private static final String REST_PATH = "v1/projects/{projectId}/traces";
/**
* Returns of a list of traces that match the specified filter conditions.
*
* Create a request for the method "traces.list".
*
* This request holds the parameters needed by the the cloudtrace server. After setting any
* optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p>
* {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @since 1.13
*/
protected List(java.lang.String projectId) {
super(CloudTrace.this, "GET", REST_PATH, null, com.google.api.services.cloudtrace.v1.model.ListTracesResponse.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@Override
public List setFields(java.lang.String fields) {
return (List) super.setFields(fields);
}
@Override
public List setKey(java.lang.String key) {
return (List) super.setKey(key);
}
@Override
public List setOauthToken(java.lang.String oauthToken) {
return (List) super.setOauthToken(oauthToken);
}
@Override
public List setPrettyPrint(java.lang.Boolean prettyPrint) {
return (List) super.setPrettyPrint(prettyPrint);
}
@Override
public List setQuotaUser(java.lang.String quotaUser) {
return (List) super.setQuotaUser(quotaUser);
}
@Override
public List setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
/** Required. ID of the Cloud project where the trace data is stored. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. ID of the Cloud project where the trace data is stored.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Required. ID of the Cloud project where the trace data is stored. */
public List setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* End of the time interval (inclusive) during which the trace data was collected from the
* application.
*/
@com.google.api.client.util.Key
private String endTime;
/** End of the time interval (inclusive) during which the trace data was collected from the
application.
*/
public String getEndTime() {
return endTime;
}
/**
* End of the time interval (inclusive) during which the trace data was collected from the
* application.
*/
public List setEndTime(String endTime) {
this.endTime = endTime;
return this;
}
/**
* Optional. A filter against labels for the request.
*
* By default, searches use prefix matching. To specify exact match, prepend a plus symbol
* (`+`) to the search term. Multiple terms are ANDed. Syntax:
*
* * `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces where any root span starts with
* `NAME_PREFIX`. * `+root:NAME` or `+NAME`: Return traces where any root span's name is
* exactly `NAME`. * `span:NAME_PREFIX`: Return traces where any span starts with
* `NAME_PREFIX`. * `+span:NAME`: Return traces where any span's name is exactly `NAME`. *
* `latency:DURATION`: Return traces whose overall latency is greater or equal to than
* `DURATION`. Accepted units are nanoseconds (`ns`), milliseconds (`ms`), and seconds
* (`s`). Default is `ms`. For example, `latency:24ms` returns traces whose overall latency
* is greater than or equal to 24 milliseconds. * `label:LABEL_KEY`: Return all traces
* containing the specified label key (exact match, case-sensitive) regardless of the
* key:value pair's value (including empty values). * `LABEL_KEY:VALUE_PREFIX`: Return all
* traces containing the specified label key (exact match, case-sensitive) whose value
* starts with `VALUE_PREFIX`. Both a key and a value must be specified. *
* `+LABEL_KEY:VALUE`: Return all traces containing a key:value pair exactly matching the
* specified text. Both a key and a value must be specified. * `method:VALUE`: Equivalent
* to `/http/method:VALUE`. * `url:VALUE`: Equivalent to `/http/url:VALUE`.
*/
@com.google.api.client.util.Key
private java.lang.String filter;
/** Optional. A filter against labels for the request.
By default, searches use prefix matching. To specify exact match, prepend a plus symbol (`+`) to
the search term. Multiple terms are ANDed. Syntax:
* `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces where any root span starts with
`NAME_PREFIX`. * `+root:NAME` or `+NAME`: Return traces where any root span's name is exactly
`NAME`. * `span:NAME_PREFIX`: Return traces where any span starts with `NAME_PREFIX`. *
`+span:NAME`: Return traces where any span's name is exactly `NAME`. * `latency:DURATION`: Return
traces whose overall latency is greater or equal to than `DURATION`. Accepted units are nanoseconds
(`ns`), milliseconds (`ms`), and seconds (`s`). Default is `ms`. For example, `latency:24ms`
returns traces whose overall latency is greater than or equal to 24 milliseconds. *
`label:LABEL_KEY`: Return all traces containing the specified label key (exact match, case-
sensitive) regardless of the key:value pair's value (including empty values). *
`LABEL_KEY:VALUE_PREFIX`: Return all traces containing the specified label key (exact match, case-
sensitive) whose value starts with `VALUE_PREFIX`. Both a key and a value must be specified. *
`+LABEL_KEY:VALUE`: Return all traces containing a key:value pair exactly matching the specified
text. Both a key and a value must be specified. * `method:VALUE`: Equivalent to
`/http/method:VALUE`. * `url:VALUE`: Equivalent to `/http/url:VALUE`.
*/
public java.lang.String getFilter() {
return filter;
}
/**
* Optional. A filter against labels for the request.
*
* By default, searches use prefix matching. To specify exact match, prepend a plus symbol
* (`+`) to the search term. Multiple terms are ANDed. Syntax:
*
* * `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces where any root span starts with
* `NAME_PREFIX`. * `+root:NAME` or `+NAME`: Return traces where any root span's name is
* exactly `NAME`. * `span:NAME_PREFIX`: Return traces where any span starts with
* `NAME_PREFIX`. * `+span:NAME`: Return traces where any span's name is exactly `NAME`. *
* `latency:DURATION`: Return traces whose overall latency is greater or equal to than
* `DURATION`. Accepted units are nanoseconds (`ns`), milliseconds (`ms`), and seconds
* (`s`). Default is `ms`. For example, `latency:24ms` returns traces whose overall latency
* is greater than or equal to 24 milliseconds. * `label:LABEL_KEY`: Return all traces
* containing the specified label key (exact match, case-sensitive) regardless of the
* key:value pair's value (including empty values). * `LABEL_KEY:VALUE_PREFIX`: Return all
* traces containing the specified label key (exact match, case-sensitive) whose value
* starts with `VALUE_PREFIX`. Both a key and a value must be specified. *
* `+LABEL_KEY:VALUE`: Return all traces containing a key:value pair exactly matching the
* specified text. Both a key and a value must be specified. * `method:VALUE`: Equivalent
* to `/http/method:VALUE`. * `url:VALUE`: Equivalent to `/http/url:VALUE`.
*/
public List setFilter(java.lang.String filter) {
this.filter = filter;
return this;
}
/**
* Optional. Field used to sort the returned traces. Can be one of the following:
*
* * `trace_id` * `name` (`name` field of root span in the trace) * `duration`
* (difference between `end_time` and `start_time` fields of the root span) * `start`
* (`start_time` field of the root span)
*
* Descending order can be specified by appending `desc` to the sort field (for example,
* `name desc`).
*
* Only one sort field is permitted.
*/
@com.google.api.client.util.Key
private java.lang.String orderBy;
/** Optional. Field used to sort the returned traces. Can be one of the following:
* `trace_id` * `name` (`name` field of root span in the trace) * `duration` (difference
between `end_time` and `start_time` fields of the root span) * `start` (`start_time` field of the
root span)
Descending order can be specified by appending `desc` to the sort field (for example, `name desc`).
Only one sort field is permitted.
*/
public java.lang.String getOrderBy() {
return orderBy;
}
/**
* Optional. Field used to sort the returned traces. Can be one of the following:
*
* * `trace_id` * `name` (`name` field of root span in the trace) * `duration`
* (difference between `end_time` and `start_time` fields of the root span) * `start`
* (`start_time` field of the root span)
*
* Descending order can be specified by appending `desc` to the sort field (for example,
* `name desc`).
*
* Only one sort field is permitted.
*/
public List setOrderBy(java.lang.String orderBy) {
this.orderBy = orderBy;
return this;
}
/**
* Optional. Maximum number of traces to return. If not specified or <= 0, the
* implementation selects a reasonable value. The implementation may return fewer traces
* than the requested page size.
*/
@com.google.api.client.util.Key
private java.lang.Integer pageSize;
/** Optional. Maximum number of traces to return. If not specified or <= 0, the implementation selects
a reasonable value. The implementation may return fewer traces than the requested page size.
*/
public java.lang.Integer getPageSize() {
return pageSize;
}
/**
* Optional. Maximum number of traces to return. If not specified or <= 0, the
* implementation selects a reasonable value. The implementation may return fewer traces
* than the requested page size.
*/
public List setPageSize(java.lang.Integer pageSize) {
this.pageSize = pageSize;
return this;
}
/**
* Token identifying the page of results to return. If provided, use the value of the
* `next_page_token` field from a previous request.
*/
@com.google.api.client.util.Key
private java.lang.String pageToken;
/** Token identifying the page of results to return. If provided, use the value of the
`next_page_token` field from a previous request.
*/
public java.lang.String getPageToken() {
return pageToken;
}
/**
* Token identifying the page of results to return. If provided, use the value of the
* `next_page_token` field from a previous request.
*/
public List setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
/**
* Start of the time interval (inclusive) during which the trace data was collected from the
* application.
*/
@com.google.api.client.util.Key
private String startTime;
/** Start of the time interval (inclusive) during which the trace data was collected from the
application.
*/
public String getStartTime() {
return startTime;
}
/**
* Start of the time interval (inclusive) during which the trace data was collected from the
* application.
*/
public List setStartTime(String startTime) {
this.startTime = startTime;
return this;
}
/**
* Optional. Type of data returned for traces in the list. Default is `MINIMAL`.
*/
@com.google.api.client.util.Key
private java.lang.String view;
/** Optional. Type of data returned for traces in the list. Default is `MINIMAL`.
*/
public java.lang.String getView() {
return view;
}
/**
* Optional. Type of data returned for traces in the list. Default is `MINIMAL`.
*/
public List setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
}
}
/**
* Builder for {@link CloudTrace}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
DEFAULT_ROOT_URL,
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link CloudTrace}. */
@Override
public CloudTrace build() {
return new CloudTrace(this);
}
@Override
public Builder setRootUrl(String rootUrl) {
return (Builder) super.setRootUrl(rootUrl);
}
@Override
public Builder setServicePath(String servicePath) {
return (Builder) super.setServicePath(servicePath);
}
@Override
public Builder setBatchPath(String batchPath) {
return (Builder) super.setBatchPath(batchPath);
}
@Override
public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
}
@Override
public Builder setApplicationName(String applicationName) {
return (Builder) super.setApplicationName(applicationName);
}
@Override
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
}
@Override
public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) {
return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks);
}
@Override
public Builder setSuppressAllChecks(boolean suppressAllChecks) {
return (Builder) super.setSuppressAllChecks(suppressAllChecks);
}
/**
* Set the {@link CloudTraceRequestInitializer}.
*
* @since 1.12
*/
public Builder setCloudTraceRequestInitializer(
CloudTraceRequestInitializer cloudtraceRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(cloudtraceRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
|
googleapis/google-cloud-java | 35,520 | java-billing/proto-google-cloud-billing-v1/src/main/java/com/google/cloud/billing/v1/Service.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/billing/v1/cloud_catalog.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.billing.v1;
/**
*
*
* <pre>
* Encapsulates a single service in Google Cloud Platform.
* </pre>
*
* Protobuf type {@code google.cloud.billing.v1.Service}
*/
public final class Service extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.billing.v1.Service)
ServiceOrBuilder {
private static final long serialVersionUID = 0L;
// Use Service.newBuilder() to construct.
private Service(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Service() {
name_ = "";
serviceId_ = "";
displayName_ = "";
businessEntityName_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new Service();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.billing.v1.CloudCatalogProto
.internal_static_google_cloud_billing_v1_Service_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.billing.v1.CloudCatalogProto
.internal_static_google_cloud_billing_v1_Service_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.billing.v1.Service.class,
com.google.cloud.billing.v1.Service.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object name_ = "";
/**
*
*
* <pre>
* The resource name for the service.
* Example: "services/6F81-5844-456A"
* </pre>
*
* <code>string name = 1;</code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* The resource name for the service.
* Example: "services/6F81-5844-456A"
* </pre>
*
* <code>string name = 1;</code>
*
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SERVICE_ID_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object serviceId_ = "";
/**
*
*
* <pre>
* The identifier for the service.
* Example: "6F81-5844-456A"
* </pre>
*
* <code>string service_id = 2;</code>
*
* @return The serviceId.
*/
@java.lang.Override
public java.lang.String getServiceId() {
java.lang.Object ref = serviceId_;
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();
serviceId_ = s;
return s;
}
}
/**
*
*
* <pre>
* The identifier for the service.
* Example: "6F81-5844-456A"
* </pre>
*
* <code>string service_id = 2;</code>
*
* @return The bytes for serviceId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getServiceIdBytes() {
java.lang.Object ref = serviceId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
serviceId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DISPLAY_NAME_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object displayName_ = "";
/**
*
*
* <pre>
* A human readable display name for this service.
* </pre>
*
* <code>string display_name = 3;</code>
*
* @return The displayName.
*/
@java.lang.Override
public java.lang.String getDisplayName() {
java.lang.Object ref = displayName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
displayName_ = s;
return s;
}
}
/**
*
*
* <pre>
* A human readable display name for this service.
* </pre>
*
* <code>string display_name = 3;</code>
*
* @return The bytes for displayName.
*/
@java.lang.Override
public com.google.protobuf.ByteString getDisplayNameBytes() {
java.lang.Object ref = displayName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
displayName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int BUSINESS_ENTITY_NAME_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object businessEntityName_ = "";
/**
*
*
* <pre>
* The business under which the service is offered.
* Ex. "businessEntities/GCP", "businessEntities/Maps"
* </pre>
*
* <code>string business_entity_name = 4;</code>
*
* @return The businessEntityName.
*/
@java.lang.Override
public java.lang.String getBusinessEntityName() {
java.lang.Object ref = businessEntityName_;
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();
businessEntityName_ = s;
return s;
}
}
/**
*
*
* <pre>
* The business under which the service is offered.
* Ex. "businessEntities/GCP", "businessEntities/Maps"
* </pre>
*
* <code>string business_entity_name = 4;</code>
*
* @return The bytes for businessEntityName.
*/
@java.lang.Override
public com.google.protobuf.ByteString getBusinessEntityNameBytes() {
java.lang.Object ref = businessEntityName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
businessEntityName_ = 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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, serviceId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(displayName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, displayName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(businessEntityName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, businessEntityName_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, serviceId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(displayName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, displayName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(businessEntityName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, businessEntityName_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.billing.v1.Service)) {
return super.equals(obj);
}
com.google.cloud.billing.v1.Service other = (com.google.cloud.billing.v1.Service) obj;
if (!getName().equals(other.getName())) return false;
if (!getServiceId().equals(other.getServiceId())) return false;
if (!getDisplayName().equals(other.getDisplayName())) return false;
if (!getBusinessEntityName().equals(other.getBusinessEntityName())) 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) + SERVICE_ID_FIELD_NUMBER;
hash = (53 * hash) + getServiceId().hashCode();
hash = (37 * hash) + DISPLAY_NAME_FIELD_NUMBER;
hash = (53 * hash) + getDisplayName().hashCode();
hash = (37 * hash) + BUSINESS_ENTITY_NAME_FIELD_NUMBER;
hash = (53 * hash) + getBusinessEntityName().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.billing.v1.Service parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.billing.v1.Service parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.billing.v1.Service parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.billing.v1.Service parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.billing.v1.Service parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.billing.v1.Service parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.billing.v1.Service parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.billing.v1.Service parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.billing.v1.Service parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.billing.v1.Service parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.billing.v1.Service parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.billing.v1.Service parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.billing.v1.Service 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>
* Encapsulates a single service in Google Cloud Platform.
* </pre>
*
* Protobuf type {@code google.cloud.billing.v1.Service}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.billing.v1.Service)
com.google.cloud.billing.v1.ServiceOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.billing.v1.CloudCatalogProto
.internal_static_google_cloud_billing_v1_Service_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.billing.v1.CloudCatalogProto
.internal_static_google_cloud_billing_v1_Service_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.billing.v1.Service.class,
com.google.cloud.billing.v1.Service.Builder.class);
}
// Construct using com.google.cloud.billing.v1.Service.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
name_ = "";
serviceId_ = "";
displayName_ = "";
businessEntityName_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.billing.v1.CloudCatalogProto
.internal_static_google_cloud_billing_v1_Service_descriptor;
}
@java.lang.Override
public com.google.cloud.billing.v1.Service getDefaultInstanceForType() {
return com.google.cloud.billing.v1.Service.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.billing.v1.Service build() {
com.google.cloud.billing.v1.Service result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.billing.v1.Service buildPartial() {
com.google.cloud.billing.v1.Service result = new com.google.cloud.billing.v1.Service(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.billing.v1.Service result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.name_ = name_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.serviceId_ = serviceId_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.displayName_ = displayName_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.businessEntityName_ = businessEntityName_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.billing.v1.Service) {
return mergeFrom((com.google.cloud.billing.v1.Service) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.billing.v1.Service other) {
if (other == com.google.cloud.billing.v1.Service.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getServiceId().isEmpty()) {
serviceId_ = other.serviceId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getDisplayName().isEmpty()) {
displayName_ = other.displayName_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getBusinessEntityName().isEmpty()) {
businessEntityName_ = other.businessEntityName_;
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:
{
name_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
serviceId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
displayName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
businessEntityName_ = 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 name_ = "";
/**
*
*
* <pre>
* The resource name for the service.
* Example: "services/6F81-5844-456A"
* </pre>
*
* <code>string name = 1;</code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The resource name for the service.
* Example: "services/6F81-5844-456A"
* </pre>
*
* <code>string name = 1;</code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The resource name for the service.
* Example: "services/6F81-5844-456A"
* </pre>
*
* <code>string name = 1;</code>
*
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The resource name for the service.
* Example: "services/6F81-5844-456A"
* </pre>
*
* <code>string name = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The resource name for the service.
* Example: "services/6F81-5844-456A"
* </pre>
*
* <code>string name = 1;</code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object serviceId_ = "";
/**
*
*
* <pre>
* The identifier for the service.
* Example: "6F81-5844-456A"
* </pre>
*
* <code>string service_id = 2;</code>
*
* @return The serviceId.
*/
public java.lang.String getServiceId() {
java.lang.Object ref = serviceId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
serviceId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The identifier for the service.
* Example: "6F81-5844-456A"
* </pre>
*
* <code>string service_id = 2;</code>
*
* @return The bytes for serviceId.
*/
public com.google.protobuf.ByteString getServiceIdBytes() {
java.lang.Object ref = serviceId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
serviceId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The identifier for the service.
* Example: "6F81-5844-456A"
* </pre>
*
* <code>string service_id = 2;</code>
*
* @param value The serviceId to set.
* @return This builder for chaining.
*/
public Builder setServiceId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
serviceId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The identifier for the service.
* Example: "6F81-5844-456A"
* </pre>
*
* <code>string service_id = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearServiceId() {
serviceId_ = getDefaultInstance().getServiceId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The identifier for the service.
* Example: "6F81-5844-456A"
* </pre>
*
* <code>string service_id = 2;</code>
*
* @param value The bytes for serviceId to set.
* @return This builder for chaining.
*/
public Builder setServiceIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
serviceId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object displayName_ = "";
/**
*
*
* <pre>
* A human readable display name for this service.
* </pre>
*
* <code>string display_name = 3;</code>
*
* @return The displayName.
*/
public java.lang.String getDisplayName() {
java.lang.Object ref = displayName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
displayName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A human readable display name for this service.
* </pre>
*
* <code>string display_name = 3;</code>
*
* @return The bytes for displayName.
*/
public com.google.protobuf.ByteString getDisplayNameBytes() {
java.lang.Object ref = displayName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
displayName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A human readable display name for this service.
* </pre>
*
* <code>string display_name = 3;</code>
*
* @param value The displayName to set.
* @return This builder for chaining.
*/
public Builder setDisplayName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
displayName_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A human readable display name for this service.
* </pre>
*
* <code>string display_name = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearDisplayName() {
displayName_ = getDefaultInstance().getDisplayName();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A human readable display name for this service.
* </pre>
*
* <code>string display_name = 3;</code>
*
* @param value The bytes for displayName to set.
* @return This builder for chaining.
*/
public Builder setDisplayNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
displayName_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object businessEntityName_ = "";
/**
*
*
* <pre>
* The business under which the service is offered.
* Ex. "businessEntities/GCP", "businessEntities/Maps"
* </pre>
*
* <code>string business_entity_name = 4;</code>
*
* @return The businessEntityName.
*/
public java.lang.String getBusinessEntityName() {
java.lang.Object ref = businessEntityName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
businessEntityName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The business under which the service is offered.
* Ex. "businessEntities/GCP", "businessEntities/Maps"
* </pre>
*
* <code>string business_entity_name = 4;</code>
*
* @return The bytes for businessEntityName.
*/
public com.google.protobuf.ByteString getBusinessEntityNameBytes() {
java.lang.Object ref = businessEntityName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
businessEntityName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The business under which the service is offered.
* Ex. "businessEntities/GCP", "businessEntities/Maps"
* </pre>
*
* <code>string business_entity_name = 4;</code>
*
* @param value The businessEntityName to set.
* @return This builder for chaining.
*/
public Builder setBusinessEntityName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
businessEntityName_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* The business under which the service is offered.
* Ex. "businessEntities/GCP", "businessEntities/Maps"
* </pre>
*
* <code>string business_entity_name = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearBusinessEntityName() {
businessEntityName_ = getDefaultInstance().getBusinessEntityName();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* The business under which the service is offered.
* Ex. "businessEntities/GCP", "businessEntities/Maps"
* </pre>
*
* <code>string business_entity_name = 4;</code>
*
* @param value The bytes for businessEntityName to set.
* @return This builder for chaining.
*/
public Builder setBusinessEntityNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
businessEntityName_ = 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.billing.v1.Service)
}
// @@protoc_insertion_point(class_scope:google.cloud.billing.v1.Service)
private static final com.google.cloud.billing.v1.Service DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.billing.v1.Service();
}
public static com.google.cloud.billing.v1.Service getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Service> PARSER =
new com.google.protobuf.AbstractParser<Service>() {
@java.lang.Override
public Service 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<Service> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Service> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.billing.v1.Service getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/incubator-kie-drools | 35,809 | drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.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.compiler.kie.builder.impl;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.drools.compiler.builder.conf.DecisionTableConfigurationImpl;
import org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl;
import org.drools.compiler.compiler.io.memory.MemoryFileSystem;
import org.drools.compiler.kproject.models.KieModuleModelImpl;
import org.drools.drl.extensions.DecisionTableFactory;
import org.drools.io.InternalResource;
import org.drools.io.ResourceConfigurationImpl;
import org.drools.util.IoUtils;
import org.drools.util.PortablePath;
import org.drools.util.StringUtils;
import org.kie.api.KieServices;
import org.kie.api.builder.CompilationErrorsException;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.Message;
import org.kie.api.builder.Message.Level;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.Results;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceConfiguration;
import org.kie.api.io.ResourceType;
import org.kie.internal.builder.IncrementalResults;
import org.kie.internal.builder.InternalKieBuilder;
import org.kie.internal.builder.KieBuilderSet;
import org.kie.memorycompiler.CompilationProblem;
import org.kie.memorycompiler.CompilationResult;
import org.kie.memorycompiler.JavaCompiler;
import org.kie.memorycompiler.JavaCompilerFactory;
import org.kie.memorycompiler.JavaConfiguration;
import org.kie.memorycompiler.resources.ResourceReader;
import org.kie.util.maven.support.DependencyFilter;
import org.kie.util.maven.support.PomModel;
import org.kie.util.maven.support.ReleaseIdImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.drools.base.util.Drools.hasXmlSupport;
import static org.drools.util.StringUtils.codeAwareIndexOf;
import static org.kie.internal.builder.KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration;
public class KieBuilderImpl
implements
InternalKieBuilder {
private static final Logger log = LoggerFactory.getLogger( KieBuilderImpl.class );
static final String RESOURCES_ROOT = "src/main/resources/";
static final String RESOURCES_TEST_ROOT = "src/test/resources";
static final String JAVA_ROOT = "src/main/java/";
static final String JAVA_TEST_ROOT = "src/test/java/";
private static final String RESOURCES_ROOT_DOT_SEPARATOR = RESOURCES_ROOT.replace( '/', '.' );
private static final String SPRING_BOOT_ROOT = "BOOT-INF.classes.";
private static final PortablePath POM_PATH = PortablePath.of("pom.xml");
private static final String[] SUPPORTED_RESOURCES_ROOTS = new String[] { RESOURCES_ROOT_DOT_SEPARATOR, SPRING_BOOT_ROOT };
private ResultsImpl results;
private final ResourceReader srcMfs;
private MemoryFileSystem trgMfs;
private InternalKieModule kModule;
private byte[] pomXml;
private ReleaseId releaseId;
private KieModuleModel kModuleModel;
private Collection<KieModule> kieDependencies;
private KieBuilderSetImpl kieBuilderSet;
private ClassLoader classLoader;
private PomModel pomModel;
public KieBuilderImpl( File file ) {
this.srcMfs = new DiskResourceReader( file );
}
public KieBuilderImpl( KieFileSystem kieFileSystem ) {
this( kieFileSystem, null );
}
public KieBuilderImpl( KieFileSystem kieFileSystem,
ClassLoader classLoader ) {
this.classLoader = classLoader;
srcMfs = ( (KieFileSystemImpl) kieFileSystem ).asMemoryFileSystem();
}
@Override
public KieBuilder setDependencies( KieModule... dependencies ) {
this.kieDependencies = Arrays.asList( dependencies );
return this;
}
@Override
public KieBuilder setDependencies( Resource... resources ) {
KieRepositoryImpl kr = (KieRepositoryImpl) KieServices.Factory.get().getRepository();
List<KieModule> list = new ArrayList<>();
for ( Resource res : resources ) {
InternalKieModule depKieMod = (InternalKieModule) kr.getKieModule( res );
list.add( depKieMod );
}
this.kieDependencies = list;
return this;
}
private PomModel init(PomModel projectPomModel) {
results = new ResultsImpl();
final PomModel actualPomModel;
if (projectPomModel == null) {
// if pomModel is null it will generate one from pom.xml
// if pomXml is invalid, it assigns pomModel to null
actualPomModel = buildPomModel();
} else {
actualPomModel = projectPomModel;
}
KieServices ks = KieServices.Factory.get();
// if kModuleModelXML is null or invalid it will generate a default kModule, with a default kbase name
buildKieModuleModel();
if ( actualPomModel != null ) {
// creates ReleaseId from build pom
// If the pom was generated, it will be the same as teh default ReleaseId
releaseId = actualPomModel.getReleaseId();
// add all the pom dependencies to this builder ... not sure this is a good idea (?)
KieRepositoryImpl repository = (KieRepositoryImpl) ks.getRepository();
for ( ReleaseId dep : actualPomModel.getDependencies( DependencyFilter.COMPILE_FILTER ) ) {
KieModule depModule = repository.getKieModule( dep, actualPomModel );
if ( depModule != null ) {
addKieDependency( depModule );
}
}
} else {
// if the pomModel is null it means that the provided pom.xml is invalid so use the default releaseId
releaseId = KieServices.Factory.get().getRepository().getDefaultReleaseId();
}
return actualPomModel;
}
private void addKieDependency( KieModule depModule ) {
if ( kieDependencies == null ) {
kieDependencies = new ArrayList<>();
}
kieDependencies.add( depModule );
}
@Override
public KieBuilder buildAll() {
return buildAll( KieModuleKieProject::new, o -> true );
}
@Override
public KieBuilder buildAll( Class<? extends ProjectType> projectClass ) {
if (projectClass == null) {
return buildAll();
}
try {
BiFunction<InternalKieModule, ClassLoader, KieModuleKieProject> kprojectSupplier = getSupplier(projectClass);
return buildAll( kprojectSupplier, o -> true);
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException( e );
}
}
private BiFunction<InternalKieModule, ClassLoader, KieModuleKieProject> getSupplier(Class<?> canonicalModelKieProjectClass) throws IllegalAccessException, NoSuchFieldException {
return (BiFunction<InternalKieModule, ClassLoader, KieModuleKieProject>) canonicalModelKieProjectClass.getField("SUPPLIER").get(null);
}
@Override
public KieBuilder buildAll( Predicate<String> classFilter ) {
return buildAll( KieModuleKieProject::new, classFilter );
}
public KieBuilder buildAll( BiFunction<InternalKieModule, ClassLoader, KieModuleKieProject> kprojectSupplier, Predicate<String> classFilter ) {
final PomModel currentProjectPomModel = init(pomModel);
// kModuleModel will be null if a provided pom.xml or kmodule.xml is invalid
if ( !isBuilt() && kModuleModel != null ) {
trgMfs = new MemoryFileSystem();
writePomAndKModule();
addKBasesFilesToTrg();
markSource();
MemoryKieModule memoryKieModule = new MemoryKieModule( releaseId, kModuleModel, trgMfs );
if ( kieDependencies != null && !kieDependencies.isEmpty() ) {
for ( KieModule kieModule : kieDependencies ) {
memoryKieModule.addKieDependency( (InternalKieModule) kieModule );
}
}
if ( currentProjectPomModel != null ) {
memoryKieModule.setPomModel( currentProjectPomModel );
}
KieModuleKieProject kProject = kprojectSupplier.apply( memoryKieModule, classLoader );
for ( ReleaseId unresolvedDep : memoryKieModule.getUnresolvedDependencies() ) {
results.addMessage( Level.ERROR, "pom.xml", "Unresolved dependency " + unresolvedDep );
}
compileJavaClasses( kProject.getClassLoader(), classFilter );
buildKieProject( kProject.createBuildContext(results), kProject, trgMfs );
kModule = kProject.getInternalKieModule();
}
return this;
}
void markSource() {
srcMfs.mark();
}
Collection<String> getModifiedResourcesSinceLastMark() {
return srcMfs.getModifiedResourcesSinceLastMark();
}
void updateKieModuleMetaInfo() {
if (hasXmlSupport()) {
CompilationCacheProvider.get().writeKieModuleMetaInfo(kModule, trgMfs);
}
}
public static String getCompilationCachePath( ReleaseId releaseId,
String kbaseName ) {
return ( (ReleaseIdImpl) releaseId ).getCompilationCachePathPrefix() + kbaseName.replace( '.', '/' ) + "/kbase.cache";
}
public static void buildKieModule( InternalKieModule kModule,
BuildContext buildContext ) {
buildKieProject( buildContext, new KieModuleKieProject( kModule ), null );
}
private static void buildKieProject( BuildContext buildContext,
KieModuleKieProject kProject,
MemoryFileSystem trgMfs ) {
kProject.init();
kProject.verify( buildContext );
if ( buildContext.getMessages().filterMessages( Level.ERROR ).isEmpty() ) {
InternalKieModule kModule = kProject.getInternalKieModule();
if ( trgMfs != null ) {
if (hasXmlSupport()) {
CompilationCacheProvider.get().writeKieModuleMetaInfo( kModule, trgMfs );
}
kProject.writeProjectOutput(trgMfs, buildContext);
}
KieRepository kieRepository = KieServices.Factory.get().getRepository();
kieRepository.addKieModule( kModule );
for ( InternalKieModule kDep : kModule.getKieDependencies().values() ) {
kieRepository.addKieModule( kDep );
}
}
clearBuilderCache();
}
private static void clearBuilderCache() {
DecisionTableFactory.clearCompilerCache();
}
private void addKBasesFilesToTrg() {
for ( PortablePath filePath : srcMfs.getFilePaths() ) {
if ( filePath.startsWith( RESOURCES_ROOT ) ) {
copySourceToTarget( filePath );
}
}
}
String copySourceToTarget( PortablePath filePath ) {
if ( !filePath.startsWith( RESOURCES_ROOT ) ) {
return null;
}
Resource resource = getResource( srcMfs, filePath );
PortablePath trgFileName = filePath.substring( RESOURCES_ROOT.length() );
if ( resource != null ) {
trgMfs.write( trgFileName, resource, true );
} else {
trgMfs.remove( trgFileName );
}
return trgFileName.asString();
}
public void setkModule( final MemoryKieModule kModule ) {
this.kModule = kModule;
}
public void setTrgMfs( final MemoryFileSystem trgMfs ) {
this.trgMfs = trgMfs;
}
public MemoryFileSystem getTrgMfs() {
return trgMfs;
}
void cloneKieModuleForIncrementalCompilation() {
if ( !Arrays.equals( pomXml, getOrGeneratePomXml( srcMfs ) ) ) {
pomModel = null;
}
trgMfs = trgMfs.clone();
init(pomModel);
kModule = kModule.cloneForIncrementalCompilation( releaseId, kModuleModel, trgMfs );
}
private void addMetaInfBuilder() {
for ( PortablePath filePath : srcMfs.getFilePaths()) {
if ( filePath.startsWith( RESOURCES_ROOT ) && !isKieExtension( filePath.asString() ) ) {
trgMfs.write( filePath.substring( RESOURCES_ROOT.length() ),
getResource( srcMfs, filePath ),
true );
}
}
}
private static ResourceType getResourceType( InternalKieModule kieModule,
String fileName ) {
return getResourceType( kieModule.getResourceConfiguration( fileName ) );
}
private static ResourceType getResourceType( ResourceConfiguration conf ) {
return conf instanceof ResourceConfigurationImpl ? ( (ResourceConfigurationImpl) conf ).getResourceType() : null;
}
public static boolean filterFileInKBase( InternalKieModule kieModule, KieBaseModel kieBase, String fileName, Supplier<InternalResource> file, boolean useFolders ) {
return isFileInKieBase( kieBase, fileName, file, useFolders ) &&
( isKieExtension( fileName ) || getResourceType( kieModule, fileName ) != null );
}
private static boolean isKieExtension(String fileName) {
return !isJavaSourceFile( fileName ) && ResourceType.determineResourceType(fileName) != null;
}
private static boolean isFileInKieBase( KieBaseModel kieBase, String fileName, Supplier<InternalResource> file, boolean useFolders ) {
int lastSep = fileName.lastIndexOf( "/" );
if ( lastSep + 1 < fileName.length() && fileName.charAt( lastSep + 1 ) == '.' ) {
// skip dot files
return false;
}
if ( kieBase.getPackages().isEmpty() ) {
return true;
} else {
String folderNameForFile = lastSep > 0 ? fileName.substring( 0, lastSep ) : "";
String pkgNameForFile = packageNameForFile( fileName, folderNameForFile, !useFolders, file );
return isPackageInKieBase( kieBase, pkgNameForFile );
}
}
private static String packageNameForFile( String fileName, String folderNameForFile, boolean discoverPackage, Supplier<InternalResource> file ) {
String packageNameFromFolder = getRelativePackageName(folderNameForFile.replace( '/', '.' ));
if (discoverPackage) {
String packageNameForFile = packageNameFromAsset(fileName, file.get());
if (packageNameForFile != null) {
packageNameForFile = getRelativePackageName( packageNameForFile );
if ( !packageNameForFile.equals( packageNameFromFolder ) ) {
log.warn( "File '" + fileName + "' is in folder '" + folderNameForFile + "' but declares package '" + packageNameForFile +
"'. It is advised to have a correspondance between package and folder names." );
}
return packageNameForFile;
}
}
return packageNameFromFolder;
}
private static String packageNameFromAsset(String fileName, InternalResource file) {
if (file == null) {
return null;
}
if (fileName.endsWith( ".drl" )) {
return packageNameFromDrl( new String(file.getBytes()) );
}
if (fileName.endsWith( ".xls" ) || fileName.endsWith( ".xlsx" )) {
return packageNameFromDtable( file );
}
if (fileName.endsWith( ".csv" )) {
return packageNameFromCsv( file );
}
return null;
}
private static String packageNameFromDrl(String content) {
int pkgPos = codeAwareIndexOf( content, "package " );
if (pkgPos >= 0) {
pkgPos += "package ".length();
int semiPos = content.indexOf( ';', pkgPos );
int breakPos = content.indexOf( '\n', pkgPos );
int end = semiPos > 0 ? (breakPos > 0 ? Math.min( semiPos, breakPos ) : semiPos) : breakPos;
if ( end > 0 ) {
return content.substring( pkgPos, end ).trim();
}
}
return null;
}
private static String packageNameFromDtable(InternalResource resource) {
try {
String generatedDrl = DecisionTableFactory.loadFromResource( resource, new DecisionTableConfigurationImpl() );
return packageNameFromDrl( generatedDrl );
} catch (Exception e) {
return packageNameFromCsv( resource );
}
}
private static String packageNameFromCsv(InternalResource resource) {
String content = new String(resource.getBytes());
int pkgPos = content.indexOf( "RuleSet" );
if (pkgPos >= 0) {
pkgPos += "RuleSet ".length();
for (; !Character.isJavaIdentifierStart( content.charAt( pkgPos ) ); pkgPos++) {
};
int end = pkgPos+1;
for (; Character.isLetterOrDigit( content.charAt( end ) ) || content.charAt( end ) == '.'; end++) {
};
return content.substring( pkgPos, end ).trim();
}
return null;
}
public static boolean isPackageInKieBase( KieBaseModel kieBaseModel, String pkgName ) {
for ( String candidatePkg : kieBaseModel.getPackages() ) {
boolean isNegative = candidatePkg.startsWith( "!" );
if ( isNegative ) {
candidatePkg = candidatePkg.substring( 1 );
}
if ( candidatePkg.equals( "*" ) || pkgName.equals( candidatePkg ) || pkgName.endsWith( "." + candidatePkg ) ) {
return !isNegative;
}
if ( candidatePkg.endsWith( ".*" ) ) {
String relativePkgNameForFile = getRelativePackageName( pkgName );
String pkgNameNoWildcard = candidatePkg.substring( 0, candidatePkg.length() - 2 );
if ( relativePkgNameForFile.equals( pkgNameNoWildcard ) || relativePkgNameForFile.startsWith( pkgNameNoWildcard + "." ) ) {
return !isNegative;
}
if ( relativePkgNameForFile.startsWith( kieBaseModel.getName() + "." ) ) {
relativePkgNameForFile = relativePkgNameForFile.substring( kieBaseModel.getName().length() + 1 );
if ( relativePkgNameForFile.equals( pkgNameNoWildcard ) || relativePkgNameForFile.startsWith( pkgNameNoWildcard + "." ) ) {
return !isNegative;
}
}
}
}
return false;
}
public static boolean isPackageInKieBaseOrIncludedKieBases(final String pkgName, final KieBaseModel kieBaseModel, final KieModuleModel kieModuleModel) {
final Set<String> alreadyProcessesKieBaseModels = new HashSet<>();
return isPackageInKieBaseOrIncludedKieBases(pkgName, kieBaseModel, kieModuleModel, alreadyProcessesKieBaseModels);
}
private static boolean isPackageInKieBaseOrIncludedKieBases(final String pkgName, final KieBaseModel kieBaseModel,
final KieModuleModel kieModuleModel, final Set<String> alreadyProcessesKieBaseModels) {
boolean isPackageInKieBaseResult = isPackageInKieBase(kieBaseModel, pkgName);
if (!isPackageInKieBaseResult && kieBaseModel.getIncludes() != null && !kieBaseModel.getIncludes().isEmpty()) {
for (String includedKieBaseName : kieBaseModel.getIncludes()) {
if (!alreadyProcessesKieBaseModels.contains(includedKieBaseName)) {
KieBaseModel includedKieBaseModel = kieModuleModel.getKieBaseModels().get(includedKieBaseName);
if (includedKieBaseModel != null) {
isPackageInKieBaseResult = isPackageInKieBaseOrIncludedKieBases(pkgName, includedKieBaseModel, kieModuleModel);
if (isPackageInKieBaseResult) {
return true;
}
}
alreadyProcessesKieBaseModels.add(includedKieBaseName);
}
}
}
return isPackageInKieBaseResult;
}
private static String getRelativePackageName( String pkgNameForFile ) {
for ( String root : SUPPORTED_RESOURCES_ROOTS ) {
if ( pkgNameForFile.startsWith( root ) ) {
return pkgNameForFile.substring( root.length() );
}
}
return pkgNameForFile;
}
@Override
public Results getResults() {
if ( !isBuilt() ) {
buildAll();
}
return results;
}
@Override
public KieModule getKieModule() {
return getKieModule( false );
}
@Override
public KieModule getKieModule(Class<? extends ProjectType> projectClass) {
return getKieModule( false , projectClass);
}
@Override
public KieModule getKieModuleIgnoringErrors() {
return getKieModule( true );
}
private KieModule getKieModule(boolean ignoreErrors, Class<? extends ProjectType> projectClass) {
if ( !isBuilt() ) {
buildAll(projectClass);
}
if ( !ignoreErrors && ( getResults().hasMessages( Level.ERROR ) || kModule == null ) ) {
throw new CompilationErrorsException( getResults().getMessages( Level.ERROR ) );
}
return kModule;
}
private KieModule getKieModule( boolean ignoreErrors ) {
return getKieModule(ignoreErrors, DrlProject.class);
}
private boolean isBuilt() {
return kModule != null;
}
@Override
public InternalKieBuilder withKModuleModel( KieModuleModel kModuleModel ) {
this.kModuleModel = kModuleModel;
return this;
}
private void buildKieModuleModel() {
if (kModuleModel == null) {
if ( srcMfs.isAvailable( KieModuleModelImpl.KMODULE_SRC_PATH ) ) {
byte[] kModuleModelXml = srcMfs.getBytes( KieModuleModelImpl.KMODULE_SRC_PATH );
try {
kModuleModel = KieModuleModelImpl.fromXML( new ByteArrayInputStream( kModuleModelXml ) );
} catch (Exception e) {
results.addMessage( Level.ERROR,
"kmodule.xml",
"kmodule.xml found, but unable to read\n" + e.getMessage() );
// Create a default kModuleModel in the event of errors parsing the XML
kModuleModel = KieServices.Factory.get().newKieModuleModel();
}
} else {
// There's no kmodule.xml, create a default one
kModuleModel = KieServices.Factory.get().newKieModuleModel();
}
}
setDefaultsforEmptyKieModule( kModuleModel );
}
public static void setDefaultsforEmptyKieModule( KieModuleModel kModuleModel ) {
if ( kModuleModel != null && kModuleModel.getKieBaseModels().isEmpty() ) {
// would be null if they pass a corrupted kModuleModel
KieBaseModel kieBaseModel = kModuleModel.newKieBaseModel( "defaultKieBase" ).addPackage( "*" ).setDefault( true );
kieBaseModel.newKieSessionModel( "defaultKieSession" ).setDefault( true );
kieBaseModel.newKieSessionModel( "defaultStatelessKieSession" ).setType( KieSessionModel.KieSessionType.STATELESS ).setDefault( true );
}
}
public PomModel getPomModel() {
if ( pomModel == null ) {
pomModel = buildPomModel();
}
return pomModel;
}
/**
* This can be used for performance reason to avoid the recomputation of the pomModel when it is already available
*/
public void setPomModel( PomModel pomModel ) {
this.pomModel = pomModel;
if ( srcMfs.isAvailable( POM_PATH ) ) {
this.pomXml = srcMfs.getBytes( POM_PATH );
}
}
private PomModel buildPomModel() {
pomXml = getOrGeneratePomXml( srcMfs );
if ( pomXml == null ) {
// will be null if the provided pom is invalid
return null;
}
try {
PomModel tempPomModel = PomModel.Parser.parse( "pom.xml",
new ByteArrayInputStream( pomXml ) );
validatePomModel( tempPomModel ); // throws an exception if invalid
return tempPomModel;
} catch ( Exception e ) {
results.addMessage( Level.ERROR,
"pom.xml",
"maven pom.xml found, but unable to read\n" + e.getMessage() );
}
return null;
}
public static void validatePomModel( PomModel pomModel ) {
ReleaseId pomReleaseId = pomModel.getReleaseId();
if ( StringUtils.isEmpty( pomReleaseId.getGroupId() ) || StringUtils.isEmpty( pomReleaseId.getArtifactId() ) || StringUtils.isEmpty( pomReleaseId.getVersion() ) ) {
throw new RuntimeException( "Maven pom.properties exists but ReleaseId content is malformed" );
}
}
public static byte[] getOrGeneratePomXml( ResourceReader mfs ) {
if ( mfs.isAvailable( POM_PATH ) ) {
return mfs.getBytes( POM_PATH );
} else {
// There is no pom.xml, and thus no ReleaseId, so generate a pom.xml from the global detault.
return generatePomXml( KieServices.Factory.get().getRepository().getDefaultReleaseId() ).getBytes( IoUtils.UTF8_CHARSET );
}
}
public void writePomAndKModule() {
addMetaInfBuilder();
if ( pomXml != null ) {
ReleaseIdImpl g = (ReleaseIdImpl) releaseId;
trgMfs.write( g.getPomXmlPath(),
pomXml,
true );
trgMfs.write( g.getPomPropertiesPath(),
generatePomProperties( releaseId ).getBytes( IoUtils.UTF8_CHARSET ),
true );
}
if ( kModuleModel != null && hasXmlSupport() ) {
trgMfs.write( KieModuleModelImpl.KMODULE_JAR_PATH,
kModuleModel.toXML().getBytes( IoUtils.UTF8_CHARSET ),
true );
}
}
public static String generatePomXml( ReleaseId releaseId ) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append( "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" );
sBuilder.append( " xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\"> \n" );
sBuilder.append( " <modelVersion>4.0.0</modelVersion> \n" );
sBuilder.append( " <groupId>" );
sBuilder.append( releaseId.getGroupId() );
sBuilder.append( "</groupId> \n" );
sBuilder.append( " <artifactId>" );
sBuilder.append( releaseId.getArtifactId() );
sBuilder.append( "</artifactId> \n" );
sBuilder.append( " <version>" );
sBuilder.append( releaseId.getVersion() );
sBuilder.append( "</version> \n" );
sBuilder.append( " <packaging>jar</packaging> \n" );
sBuilder.append( " <name>Default</name> \n" );
sBuilder.append( "</project> \n" );
return sBuilder.toString();
}
public static String generatePomProperties( ReleaseId releaseId ) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append( "groupId=" );
sBuilder.append( releaseId.getGroupId() );
sBuilder.append( "\n" );
sBuilder.append( "artifactId=" );
sBuilder.append( releaseId.getArtifactId() );
sBuilder.append( "\n" );
sBuilder.append( "version=" );
sBuilder.append( releaseId.getVersion() );
sBuilder.append( "\n" );
return sBuilder.toString();
}
private void compileJavaClasses( ClassLoader classLoader, Predicate<String> classFilter ) {
List<String> classFiles = new ArrayList<>();
for ( PortablePath filePath : srcMfs.getFilePaths() ) {
if ( filePath.endsWith( ".class" ) ) {
trgMfs.write( filePath,
getResource( srcMfs, filePath ),
true );
classFiles.add( filePath.substring( 0, filePath.asString().length() - ".class".length() ).asString() );
}
}
List<String> javaFiles = new ArrayList<>();
List<String> javaTestFiles = new ArrayList<>();
for ( PortablePath filePath : srcMfs.getFilePaths() ) {
String fileName = filePath.asString();
if ( isJavaSourceFile( fileName )
&& noClassFileForGivenSourceFile( classFiles, fileName )
&& notVetoedByFilter( classFilter, fileName ) ) {
if ( !fileName.startsWith( JAVA_ROOT ) && !fileName.startsWith( JAVA_TEST_ROOT ) ) {
results.addMessage( Level.WARNING, fileName, "Found Java file out of the Java source folder: \"" + fileName + "\"" );
} else if ( fileName.substring( JAVA_ROOT.length() ).indexOf( '/' ) < 0 ) {
results.addMessage( Level.ERROR, fileName, "A Java class must have a package: " + fileName.substring( JAVA_ROOT.length() ) + " is not allowed" );
} else {
if ( fileName.startsWith( JAVA_ROOT ) ) {
javaFiles.add( fileName );
} else {
javaTestFiles.add( fileName );
}
}
}
}
if ( !javaFiles.isEmpty() || !javaTestFiles.isEmpty() ) {
KnowledgeBuilderConfigurationImpl kconf = newKnowledgeBuilderConfiguration(classLoader).as(KnowledgeBuilderConfigurationImpl.KEY);
JavaConfiguration javaConf = (JavaConfiguration) kconf.getDialectConfiguration( "java" );
compileJavaClasses( javaConf, classLoader, javaFiles, JAVA_ROOT );
compileJavaClasses( javaConf, classLoader, javaTestFiles, JAVA_TEST_ROOT );
}
}
private static boolean notVetoedByFilter( final Predicate<String> classFilter,
final String sourceFileName ) {
return classFilter.test( sourceFileName );
}
private static boolean noClassFileForGivenSourceFile( List<String> classFiles, String sourceFileName ) {
return !classFiles.contains( sourceFileName.substring( 0, sourceFileName.length() - ".java".length() ) );
}
private static boolean isJavaSourceFile( String fileName ) {
return fileName.endsWith( ".java" );
}
private void compileJavaClasses( JavaConfiguration javaConf,
ClassLoader classLoader,
List<String> javaFiles,
String rootFolder ) {
if ( !javaFiles.isEmpty() ) {
String[] sourceFiles = javaFiles.toArray( new String[ javaFiles.size() ] );
JavaCompiler javaCompiler = createCompiler( javaConf, rootFolder );
CompilationResult res = javaCompiler.compile( sourceFiles,
srcMfs,
trgMfs,
classLoader );
for ( CompilationProblem problem : res.getErrors() ) {
results.addMessage( new CompilationProblemAdapter( problem ) );
}
for ( CompilationProblem problem : res.getWarnings() ) {
results.addMessage( new CompilationProblemAdapter( problem ) );
}
}
}
private JavaCompiler createCompiler( JavaConfiguration javaConf, String sourceFolder ) {
JavaCompiler javaCompiler = JavaCompilerFactory.loadCompiler( javaConf );
javaCompiler.setSourceFolder( sourceFolder );
return javaCompiler;
}
public static String findPomProperties( ZipFile zipFile ) {
Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
while ( zipEntries.hasMoreElements() ) {
ZipEntry zipEntry = zipEntries.nextElement();
String fileName = zipEntry.getName();
if ( fileName.endsWith( "pom.properties" ) && fileName.startsWith( "META-INF/maven/" ) ) {
return fileName;
}
}
return null;
}
public static File findPomProperties( java.io.File root ) {
File mavenRoot = new File( root,
"META-INF/maven" );
return recurseToPomProperties( mavenRoot );
}
public static File recurseToPomProperties( File file ) {
if ( file.isDirectory() ) {
for ( java.io.File child : file.listFiles() ) {
if ( child.isDirectory() ) {
File returnedFile = recurseToPomProperties( child );
if ( returnedFile != null ) {
return returnedFile;
}
} else if ( child.getName().endsWith( "pom.properties" ) ) {
return child;
}
}
}
return null;
}
@Override
public KieBuilderSet createFileSet( String... files ) {
return createFileSet( Level.ERROR, files );
}
@Override
public KieBuilderSet createFileSet( Message.Level minimalLevel, String... files ) {
if ( kieBuilderSet == null || kieBuilderSet.getMinimalLevel() != minimalLevel ) {
kieBuilderSet = new KieBuilderSetImpl( this, minimalLevel );
}
return kieBuilderSet.setFiles( files );
}
@Override
public IncrementalResults incrementalBuild() {
return new KieBuilderSetImpl( this ).build();
}
private static Resource getResource( ResourceReader resourceReader, PortablePath pResourceName ) {
if (resourceReader instanceof MemoryFileSystem) {
return (( MemoryFileSystem ) resourceReader).getResource( pResourceName );
}
byte[] bytes = resourceReader.getBytes( pResourceName );
return bytes != null ? KieServices.get().getResources().newByteArrayResource( bytes ) : null;
}
}
|
apache/sis | 35,229 | endorsed/src/org.apache.sis.util/main/org/apache/sis/util/resources/Vocabulary.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.util.resources;
import java.io.InputStream;
import java.util.Map;
import java.util.Locale;
import java.util.MissingResourceException;
import org.opengis.util.InternationalString;
/**
* Locale-dependent resources for single words or short sentences.
*
* @author Martin Desruisseaux (IRD, Geomatys)
*/
public class Vocabulary extends IndexedResourceBundle {
/**
* Resource keys. This class is used when compiling sources, but no dependencies to
* {@code Keys} should appear in any resulting class files. Since the Java compiler
* inlines final integer values, using long identifiers will not bloat the constant
* pools of compiled classes.
*
* @author Martin Desruisseaux (IRD, Geomatys)
*/
public static final class Keys extends KeyConstants {
/**
* The unique instance of key constants handler.
*/
static final Keys INSTANCE = new Keys();
/**
* For {@link #INSTANCE} creation only.
*/
private Keys() {
}
/**
* Abstract
*/
public static final short Abstract = 1;
/**
* Accuracy
*/
public static final short Accuracy = 2;
/**
* Administrator
*/
public static final short Administrator = 3;
/**
* Aliases
*/
public static final short Aliases = 4;
/**
* Alternative identifiers
*/
public static final short AlternativeIdentifiers = 5;
/**
* Angle
*/
public static final short Angle = 6;
/**
* Degrees
*/
public static final short AngularDegrees = 7;
/**
* Minutes
*/
public static final short AngularMinutes = 8;
/**
* Seconds
*/
public static final short AngularSeconds = 9;
/**
* Attributes
*/
public static final short Attributes = 10;
/**
* Automatic
*/
public static final short Automatic = 11;
/**
* Axis changes
*/
public static final short AxisChanges = 12;
/**
* Axis {0}
*/
public static final short Axis_1 = 269;
/**
* Azimuth
*/
public static final short Azimuth = 13;
/**
* Background
*/
public static final short Background = 14;
/**
* Band {0}
*/
public static final short Band_1 = 15;
/**
* Barometric altitude
*/
public static final short BarometricAltitude = 16;
/**
* Bilinear
*/
public static final short Bilinear = 230;
/**
* Black
*/
public static final short Black = 17;
/**
* Blue
*/
public static final short Blue = 18;
/**
* Coordinate Reference Systems
*/
public static final short CRSs = 19;
/**
* Cardinality
*/
public static final short Cardinality = 20;
/**
* Categories
*/
public static final short Categories = 248;
/**
* Caused by {0}
*/
public static final short CausedBy_1 = 21;
/**
* {0} cells
*/
public static final short CellCount_1 = 22;
/**
* Cell geometry
*/
public static final short CellGeometry = 23;
/**
* Cells
*/
public static final short Cells = 24;
/**
* Character encoding
*/
public static final short CharacterEncoding = 25;
/**
* Characteristics
*/
public static final short Characteristics = 26;
/**
* Class
*/
public static final short Class = 240;
/**
* Classpath
*/
public static final short Classpath = 27;
/**
* Code
*/
public static final short Code = 28;
/**
* {0} code
*/
public static final short Code_1 = 29;
/**
* Color
*/
public static final short Color = 251;
/**
* Color index
*/
public static final short ColorIndex = 30;
/**
* Colors
*/
public static final short Colors = 228;
/**
* Commands
*/
public static final short Commands = 31;
/**
* Compression
*/
public static final short Compression = 273;
/**
* Configuration
*/
public static final short Configuration = 246;
/**
* Constant pressure surface
*/
public static final short ConstantPressureSurface = 32;
/**
* Constants
*/
public static final short Constants = 233;
/**
* Container
*/
public static final short Container = 33;
/**
* Controls
*/
public static final short Controls = 262;
/**
* Conversion
*/
public static final short Conversion = 34;
/**
* Coordinate
*/
public static final short Coordinate = 35;
/**
* Coordinate reference system
*/
public static final short CoordinateRefSys = 36;
/**
* Correlation
*/
public static final short Correlation = 37;
/**
* Coverage
*/
public static final short Coverage = 38;
/**
* Coverage domain
*/
public static final short CoverageDomain = 39;
/**
* Create
*/
public static final short Create = 40;
/**
* Creation date
*/
public static final short CreationDate = 41;
/**
* Credit
*/
public static final short Credit = 42;
/**
* Current date and time
*/
public static final short CurrentDateTime = 43;
/**
* Current directory
*/
public static final short CurrentDirectory = 44;
/**
* Cyan
*/
public static final short Cyan = 45;
/**
* Cycle omitted
*/
public static final short CycleOmitted = 46;
/**
* Data
*/
public static final short Data = 47;
/**
* Database
*/
public static final short DataBase = 48;
/**
* Data directory
*/
public static final short DataDirectory = 49;
/**
* Data formats
*/
public static final short DataFormats = 50;
/**
* Data type
*/
public static final short DataType = 51;
/**
* Date
*/
public static final short Date = 52;
/**
* Date and time
*/
public static final short DateAndTime = 243;
/**
* Datum
*/
public static final short Datum = 53;
/**
* Datum shift
*/
public static final short DatumShift = 54;
/**
* Daylight time
*/
public static final short DaylightTime = 55;
/**
* Default value
*/
public static final short DefaultValue = 56;
/**
* Deprecated
*/
public static final short Deprecated = 57;
/**
* Derived from {0}
*/
public static final short DerivedFrom_1 = 58;
/**
* Description
*/
public static final short Description = 59;
/**
* Designation
*/
public static final short Designation = 60;
/**
* Destination
*/
public static final short Destination = 61;
/**
* Details
*/
public static final short Details = 62;
/**
* Digital elevation model
*/
public static final short DigitalElevationModel = 63;
/**
* Dimension {0}
*/
public static final short Dimension_1 = 64;
/**
* Dimensions
*/
public static final short Dimensions = 65;
/**
* Directory
*/
public static final short Directory = 66;
/**
* Display
*/
public static final short Display = 67;
/**
* ″
*/
public static final short DittoMark = 68;
/**
* Domain
*/
public static final short Domain = 69;
/**
* Dublin Julian
*/
public static final short DublinJulian = 70;
/**
* East bound
*/
public static final short EastBound = 71;
/**
* Ellipsoid
*/
public static final short Ellipsoid = 72;
/**
* Ellipsoidal height
*/
public static final short EllipsoidalHeight = 74;
/**
* End date
*/
public static final short EndDate = 75;
/**
* End point
*/
public static final short EndPoint = 76;
/**
* Engineering
*/
public static final short Engineering = 77;
/**
* Ensemble accuracy
*/
public static final short EnsembleAccuracy = 278;
/**
* {0} entr{0,choice,0#y|2#ies}
*/
public static final short EntryCount_1 = 78;
/**
* Envelope
*/
public static final short Envelope = 79;
/**
* Errors
*/
public static final short Errors = 80;
/**
* Extent
*/
public static final short Extent = 81;
/**
* False
*/
public static final short False = 264;
/**
* File
*/
public static final short File = 82;
/**
* Fill value
*/
public static final short FillValue = 83;
/**
* Filter
*/
public static final short Filter = 84;
/**
* Format
*/
public static final short Format = 85;
/**
* Geocentric
*/
public static final short Geocentric = 86;
/**
* Geocentric conversion
*/
public static final short GeocentricConversion = 87;
/**
* Geocentric radius
*/
public static final short GeocentricRadius = 88;
/**
* Geodesic distance
*/
public static final short GeodesicDistance = 89;
/**
* Geodetic
*/
public static final short Geodetic = 90;
/**
* Geodetic dataset
*/
public static final short GeodeticDataset = 91;
/**
* Geographic
*/
public static final short Geographic = 92;
/**
* Geographic extent
*/
public static final short GeographicExtent = 93;
/**
* Geographic identifier
*/
public static final short GeographicIdentifier = 94;
/**
* Gray
*/
public static final short Gray = 95;
/**
* Grayscale
*/
public static final short Grayscale = 250;
/**
* Green
*/
public static final short Green = 96;
/**
* Grid extent
*/
public static final short GridExtent = 97;
/**
* Height
*/
public static final short Height = 98;
/**
* Identifier
*/
public static final short Identifier = 99;
/**
* Identifiers
*/
public static final short Identifiers = 100;
/**
* Identity
*/
public static final short Identity = 101;
/**
* Image
*/
public static final short Image = 102;
/**
* Image layout
*/
public static final short ImageLayout = 103;
/**
* Image size
*/
public static final short ImageSize = 234;
/**
* Image #{0}
*/
public static final short Image_1 = 261;
/**
* Implementation
*/
public static final short Implementation = 104;
/**
* in
*/
public static final short InBetweenWords = 105;
/**
* Index
*/
public static final short Index = 106;
/**
* Information
*/
public static final short Information = 247;
/**
* Interpolation
*/
public static final short Interpolation = 231;
/**
* Interval
*/
public static final short Interval = 253;
/**
* Invalid
*/
public static final short Invalid = 107;
/**
* Inverse operation
*/
public static final short InverseOperation = 108;
/**
* Isolines
*/
public static final short Isolines = 252;
/**
* Java home directory
*/
public static final short JavaHome = 110;
/**
* Julian
*/
public static final short Julian = 111;
/**
* Latitude
*/
public static final short Latitude = 112;
/**
* Layout
*/
public static final short Layout = 235;
/**
* Legend
*/
public static final short Legend = 113;
/**
* Level
*/
public static final short Level = 114;
/**
* Libraries
*/
public static final short Libraries = 115;
/**
* Linear transformation
*/
public static final short LinearTransformation = 116;
/**
* Local configuration
*/
public static final short LocalConfiguration = 117;
/**
* Locale
*/
public static final short Locale = 118;
/**
* Localization
*/
public static final short Localization = 119;
/**
* Location type
*/
public static final short LocationType = 120;
/**
* Logger
*/
public static final short Logger = 241;
/**
* Logging
*/
public static final short Logging = 121;
/**
* Logs
*/
public static final short Logs = 244;
/**
* Longitude
*/
public static final short Longitude = 122;
/**
* Lower bound
*/
public static final short LowerBound = 123;
/**
* Magenta
*/
public static final short Magenta = 124;
/**
* Mandatory
*/
public static final short Mandatory = 125;
/**
* Mapping
*/
public static final short Mapping = 126;
/**
* Maximum
*/
public static final short Maximum = 127;
/**
* Maximum value
*/
public static final short MaximumValue = 128;
/**
* Mean value
*/
public static final short MeanValue = 129;
/**
* Measures
*/
public static final short Measures = 130;
/**
* Message
*/
public static final short Message = 239;
/**
* Metadata
*/
public static final short Metadata = 131;
/**
* Method
*/
public static final short Method = 242;
/**
* Methods
*/
public static final short Methods = 132;
/**
* Minimum
*/
public static final short Minimum = 133;
/**
* Minimum value
*/
public static final short MinimumValue = 134;
/**
* Missing value
*/
public static final short MissingValue = 135;
/**
* Modified Julian
*/
public static final short ModifiedJulian = 136;
/**
* Module path
*/
public static final short ModulePath = 109;
/**
* … {0} more…
*/
public static final short More_1 = 137;
/**
* Multiplicity
*/
public static final short Multiplicity = 138;
/**
* Name
*/
public static final short Name = 139;
/**
* Nearest neighbor
*/
public static final short NearestNeighbor = 232;
/**
* Nil reason
*/
public static final short NilReason = 274;
/**
* No data
*/
public static final short Nodata = 140;
/**
* None
*/
public static final short None = 141;
/**
* North bound
*/
public static final short NorthBound = 142;
/**
* Not known
*/
public static final short NotKnown = 207;
/**
* Note
*/
public static final short Note = 143;
/**
* Number of dimensions
*/
public static final short NumberOfDimensions = 144;
/**
* Number of ‘NaN’
*/
public static final short NumberOfNaN = 145;
/**
* Number of tiles
*/
public static final short NumberOfTiles = 236;
/**
* Number of values
*/
public static final short NumberOfValues = 146;
/**
* Obligation
*/
public static final short Obligation = 147;
/**
* {0} ({1} of {2})
*/
public static final short Of_3 = 148;
/**
* Offset
*/
public static final short Offset = 149;
/**
* Operating system
*/
public static final short OperatingSystem = 150;
/**
* Operations
*/
public static final short Operations = 151;
/**
* Optional
*/
public static final short Optional = 152;
/**
* Options
*/
public static final short Options = 153;
/**
* Origin
*/
public static final short Origin = 154;
/**
* Origin in a cell center
*/
public static final short OriginInCellCenter = 155;
/**
* Original colors
*/
public static final short OriginalColors = 272;
/**
* Other
*/
public static final short Other = 280;
/**
* Other surface
*/
public static final short OtherSurface = 156;
/**
* Others
*/
public static final short Others = 157;
/**
* Page {0}
*/
public static final short Page_1 = 254;
/**
* Page {0} of {1}
*/
public static final short Page_2 = 255;
/**
* Panchromatic
*/
public static final short Panchromatic = 258;
/**
* {0} ({1})
*/
public static final short Parenthesis_2 = 158;
/**
* Paths
*/
public static final short Paths = 159;
/**
* Plug-ins
*/
public static final short Plugins = 160;
/**
* Preprocessing
*/
public static final short Preprocessing = 161;
/**
* Projected
*/
public static final short Projected = 162;
/**
* Properties
*/
public static final short Properties = 237;
/**
* Property
*/
public static final short Property = 238;
/**
* Publication date
*/
public static final short PublicationDate = 163;
/**
* Purpose
*/
public static final short Purpose = 164;
/**
* “{0}”
*/
public static final short Quoted_1 = 165;
/**
* Radiance
*/
public static final short Radiance = 256;
/**
* Read
*/
public static final short Read = 166;
/**
* Red
*/
public static final short Red = 167;
/**
* Reference system
*/
public static final short ReferenceSystem = 168;
/**
* Reflectance
*/
public static final short Reflectance = 257;
/**
* Reflective
*/
public static final short Reflective = 259;
/**
* Remarks
*/
public static final short Remarks = 169;
/**
* Remote configuration
*/
public static final short RemoteConfiguration = 170;
/**
* Representative value
*/
public static final short RepresentativeValue = 171;
/**
* Resolution
*/
public static final short Resolution = 172;
/**
* Resource identification
*/
public static final short ResourceIdentification = 173;
/**
* Resources
*/
public static final short Resources = 263;
/**
* Result
*/
public static final short Result = 174;
/**
* Retry
*/
public static final short Retry = 175;
/**
* Root
*/
public static final short Root = 176;
/**
* Root Mean Square
*/
public static final short RootMeanSquare = 177;
/**
* Same datum ensemble
*/
public static final short SameDatumEnsemble = 279;
/**
* Sample dimensions
*/
public static final short SampleDimensions = 178;
/**
* Scale
*/
public static final short Scale = 179;
/**
* Simplified
*/
public static final short Simplified = 180;
/**
* {0}/{1}
*/
public static final short SlashSeparatedList_2 = 181;
/**
* Slower
*/
public static final short Slower = 268;
/**
* Slowness
*/
public static final short Slowness = 267;
/**
* Source
*/
public static final short Source = 182;
/**
* South bound
*/
public static final short SouthBound = 183;
/**
* Spatial representation
*/
public static final short SpatialRepresentation = 184;
/**
* Sphere
*/
public static final short Sphere = 271;
/**
* Standard deviation
*/
public static final short StandardDeviation = 185;
/**
* Start date
*/
public static final short StartDate = 186;
/**
* Start point
*/
public static final short StartPoint = 187;
/**
* Stretching
*/
public static final short Stretching = 229;
/**
* Subset of {0}
*/
public static final short SubsetOf_1 = 188;
/**
* Summary
*/
public static final short Summary = 189;
/**
* Superseded by {0}.
*/
public static final short SupersededBy_1 = 190;
/**
* Temporal
*/
public static final short Temporal = 191;
/**
* Temporal extent
*/
public static final short TemporalExtent = 192;
/**
* Temporal ({0})
*/
public static final short Temporal_1 = 276;
/**
* Temporary files
*/
public static final short TemporaryFiles = 193;
/**
* Thermal
*/
public static final short Thermal = 260;
/**
* Tile size
*/
public static final short TileSize = 194;
/**
* Time
*/
public static final short Time = 195;
/**
* {0} time
*/
public static final short Time_1 = 196;
/**
* Timezone
*/
public static final short Timezone = 197;
/**
* Title
*/
public static final short Title = 270;
/**
* Topic category
*/
public static final short TopicCategory = 198;
/**
* Trace
*/
public static final short Trace = 245;
/**
* Transformation
*/
public static final short Transformation = 199;
/**
* Transformation accuracy
*/
public static final short TransformationAccuracy = 200;
/**
* Transparency
*/
public static final short Transparency = 201;
/**
* Transparent
*/
public static final short Transparent = 249;
/**
* Tropical year
*/
public static final short TropicalYear = 275;
/**
* True
*/
public static final short True = 265;
/**
* Truncated Julian
*/
public static final short TruncatedJulian = 202;
/**
* Type
*/
public static final short Type = 203;
/**
* Type of resource
*/
public static final short TypeOfResource = 204;
/**
* Unavailable content.
*/
public static final short UnavailableContent = 205;
/**
* Units
*/
public static final short Units = 206;
/**
* Unnamed
*/
public static final short Unnamed = 208;
/**
* Unnamed #{0}
*/
public static final short Unnamed_1 = 266;
/**
* Unspecified
*/
public static final short Unspecified = 209;
/**
* Unspecified datum change
*/
public static final short UnspecifiedDatumChange = 73;
/**
* Untitled
*/
public static final short Untitled = 210;
/**
* Upper bound
*/
public static final short UpperBound = 211;
/**
* User home directory
*/
public static final short UserHome = 212;
/**
* Value
*/
public static final short Value = 213;
/**
* Value domain
*/
public static final short ValueDomain = 214;
/**
* Value range
*/
public static final short ValueRange = 215;
/**
* Values
*/
public static final short Values = 216;
/**
* Variables
*/
public static final short Variables = 217;
/**
* {0} version {1}
*/
public static final short Version_2 = 218;
/**
* Versions
*/
public static final short Versions = 219;
/**
* Vertical
*/
public static final short Vertical = 220;
/**
* Visual
*/
public static final short Visual = 221;
/**
* Warnings
*/
public static final short Warnings = 222;
/**
* West bound
*/
public static final short WestBound = 223;
/**
* Width
*/
public static final short Width = 224;
/**
* {0} with {1}.
*/
public static final short With_2 = 277;
/**
* World
*/
public static final short World = 225;
/**
* Write
*/
public static final short Write = 226;
/**
* Yellow
*/
public static final short Yellow = 227;
}
/**
* Constructs a new resource bundle loading data from
* the resource file of the same name as this class.
*/
public Vocabulary() {
}
/**
* Opens the binary file containing the localized resources to load.
* This method delegates to {@link Class#getResourceAsStream(String)},
* but this delegation must be done from the same module as the one
* that provides the binary file.
*/
@Override
protected InputStream getResourceAsStream(final String name) {
return getClass().getResourceAsStream(name);
}
/**
* Returns the handle for the {@code Keys} constants.
*
* @return a handler for the constants declared in the inner {@code Keys} class.
*/
@Override
protected KeyConstants getKeyConstants() {
return Keys.INSTANCE;
}
/**
* Returns resources in the given locale.
*
* @param locale the locale, or {@code null} for the default locale.
* @return resources in the given locale.
* @throws MissingResourceException if resources cannot be found.
*/
public static Vocabulary forLocale(final Locale locale) {
/*
* We cannot factorize this method into the parent class, because we need to call
* `ResourceBundle.getBundle(String)` from the module that provides the resources.
* We do not cache the result because `ResourceBundle` already provides a cache.
*/
return (Vocabulary) getBundle(Vocabulary.class.getName(), nonNull(locale));
}
/**
* Returns resources in the locale specified in the given property map. This convenience method looks
* for the {@link #LOCALE_KEY} entry. If the given map is null, or contains no entry for the locale key,
* or the value is not an instance of {@link Locale}, then this method fallback on the default locale.
*
* @param properties the map of properties, or {@code null} if none.
* @return resources in the given locale.
* @throws MissingResourceException if resources cannot be found.
*/
public static Vocabulary forProperties(final Map<?,?> properties) throws MissingResourceException {
return forLocale(getLocale(properties));
}
/**
* Gets a string for the given key from this resource bundle or one of its parents.
*
* @param key the key for the desired string.
* @return the string for the given key.
* @throws MissingResourceException if no object for the given key can be found.
*/
public static String format(final short key) throws MissingResourceException {
return forLocale(null).getString(key);
}
/**
* The international string to be returned by {@code formatInternational(…)} methods.
* This implementation details is made public for allowing the creation of subclasses
* implementing some additional interfaces.
*/
public static class International extends ResourceInternationalString {
/** For cross-version compatibility. */
private static final long serialVersionUID = -5423999784169092823L;
/**
* Creates a new instance for the given vocabulary resource key.
*
* @param key one of the {@link Keys} values.
*/
protected International(short key) {super(key);}
International(short key, Object args) {super(key, args);}
@Override protected final KeyConstants getKeyConstants() {return Keys.INSTANCE;}
@Override protected final IndexedResourceBundle getBundle(final Locale locale) {
return forLocale(locale);
}
}
/**
* Gets an international string for the given key. This method does not check for the key
* validity. If the key is invalid, then a {@link MissingResourceException} may be thrown
* when a {@link InternationalString#toString(Locale)} method is invoked.
*
* @param key the key for the desired string.
* @return an international string for the given key.
*/
public static InternationalString formatInternational(final short key) {
return new International(key);
}
/**
* Gets an international string for the given key. This method does not check for the key
* validity. If the key is invalid, then a {@link MissingResourceException} may be thrown
* when a {@link InternationalString#toString(Locale)} method is invoked.
*
* <h4>API note</h4>
* This method is redundant with the one expecting {@code Object...}, but avoid the creation
* of a temporary array. There is no risk of confusion since the two methods delegate their
* work to the same {@code format} method anyway.
*
* @param key the key for the desired string.
* @param arg values to substitute to "{0}".
* @return an international string for the given key.
*/
public static InternationalString formatInternational(final short key, final Object arg) {
return new International(key, arg);
}
/**
* Gets an international string for the given key. This method does not check for the key
* validity. If the key is invalid, then a {@link MissingResourceException} may be thrown
* when a {@link InternationalString#toString(Locale)} method is invoked.
*
* @param key the key for the desired string.
* @param args values to substitute to "{0}", "{1}", <i>etc</i>.
* @return an international string for the given key.
*/
public static InternationalString formatInternational(final short key, final Object... args) {
return new International(key, args);
}
}
|
google/auto | 35,959 | common/src/main/java/com/google/auto/common/BasicAnnotationProcessor.java | /*
* Copyright 2014 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.auto.common;
import static com.google.auto.common.MoreElements.asExecutable;
import static com.google.auto.common.MoreElements.asType;
import static com.google.auto.common.MoreElements.isAnnotationPresent;
import static com.google.auto.common.MoreElements.isType;
import static com.google.auto.common.SuperficialValidation.validateElement;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.collect.Multimaps.filterKeys;
import static java.util.Objects.requireNonNull;
import static javax.lang.model.element.ElementKind.CONSTRUCTOR;
import static javax.lang.model.element.ElementKind.METHOD;
import static javax.lang.model.element.ElementKind.PACKAGE;
import static javax.tools.Diagnostic.Kind.ERROR;
import static javax.tools.Diagnostic.Kind.WARNING;
import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import java.lang.annotation.Annotation;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Name;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.Parameterizable;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;
import org.jspecify.annotations.Nullable;
/**
* An abstract {@link javax.annotation.processing.Processor Processor} implementation that defers
* processing of {@link Element}s to later rounds if they cannot be processed.
*
* <p>Subclasses put their processing logic in {@link Step} implementations. The steps are passed to
* the processor by returning them in the {@link #steps()} method, and can access the {@link
* ProcessingEnvironment} using {@link #processingEnv}.
*
* <p>Any logic that needs to happen once per round can be specified by overriding {@link
* #postRound(RoundEnvironment)}.
*
* <h2>Ill-formed elements are deferred</h2>
*
* Any annotated element whose nearest enclosing type is not well-formed is deferred, and not passed
* to any {@code Step}. This helps processors to avoid many common pitfalls, such as {@link
* javax.lang.model.type.ErrorType ErrorType} instances, {@link ClassCastException}s and badly
* coerced types.
*
* <p>A non-package element is considered well-formed if its type, type parameters, parameters,
* default values, supertypes, annotations, and enclosed elements are. Package elements are treated
* similarly, except that their enclosed elements are not validated. See {@link
* SuperficialValidation#validateElement(Element)} for details.
*
* <p>The primary disadvantage to this validation is that any element that forms a circular
* dependency with a type generated by another {@code BasicAnnotationProcessor} will never compile
* because the element will never be fully complete. All such compilations will fail with an error
* message on the offending type that describes the issue.
*
* <h2>Each {@code Step} can defer elements</h2>
*
* <p>Each {@code Step} can defer elements by including them in the set returned by {@link
* Step#process(ImmutableSetMultimap)}; elements deferred by a step will be passed back to that step
* in a later round of processing.
*
* <p>This feature is useful when one processor may depend on code generated by another, independent
* processor, in a way that isn't caught by the well-formedness check described above. For example,
* if an element {@code A} cannot be processed because processing it depends on the existence of
* some class {@code B}, then {@code A} should be deferred until a later round of processing, when
* {@code B} will have been generated by another processor.
*
* <p>If {@code A} directly references {@code B}, then the well-formedness check will correctly
* defer processing of {@code A} until {@code B} has been generated.
*
* <p>However, if {@code A} references {@code B} only indirectly (for example, from within a method
* body), then the well-formedness check will not defer processing {@code A}, but a processing step
* can reject {@code A}.
*/
public abstract class BasicAnnotationProcessor extends AbstractProcessor {
/* For every element that is not module/package, to be well-formed its
* enclosing-type in its entirety should be well-formed. Since modules
* don't get annotated (and are not supported here) they can be ignored.
*/
/**
* Packages and types that have been deferred because either they themselves reference
* as-yet-undefined types, or at least one of their contained elements does.
*/
private final Set<ElementFactory> deferredEnclosingElements = new LinkedHashSet<>();
/**
* Elements that were explicitly deferred in some {@link Step} by being returned from {@link
* Step#process}.
*/
private final SetMultimap<Step, ElementFactory> elementsDeferredBySteps =
LinkedHashMultimap.create();
private Elements elementUtils;
private Messager messager;
private ImmutableList<? extends Step> steps;
@Override
public final synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
this.elementUtils = processingEnv.getElementUtils();
this.messager = processingEnv.getMessager();
this.steps = ImmutableList.copyOf(steps());
}
/**
* Creates {@linkplain ProcessingStep processing steps} for this processor. {@link #processingEnv}
* is guaranteed to be set when this method is invoked.
*
* @deprecated Implement {@link #steps()} instead.
*/
@Deprecated
protected Iterable<? extends ProcessingStep> initSteps() {
throw new AssertionError("If steps() is not implemented, initSteps() must be.");
}
/**
* Creates {@linkplain Step processing steps} for this processor. {@link #processingEnv} is
* guaranteed to be set when this method is invoked.
*
* <p>Note: If you are migrating some steps from {@link ProcessingStep} to {@link Step}, then you
* can call {@link #asStep(ProcessingStep)} on any unmigrated steps.
*/
protected Iterable<? extends Step> steps() {
return Iterables.transform(initSteps(), BasicAnnotationProcessor::asStep);
}
/**
* An optional hook for logic to be executed at the end of each round.
*
* @deprecated use {@link #postRound(RoundEnvironment)} instead
*/
@Deprecated
protected void postProcess() {}
/** An optional hook for logic to be executed at the end of each round. */
protected void postRound(RoundEnvironment roundEnv) {
if (!roundEnv.processingOver()) {
postProcess();
}
}
private ImmutableSet<TypeElement> getSupportedAnnotationTypeElements() {
checkState(steps != null);
return steps.stream()
.flatMap(step -> getSupportedAnnotationTypeElements(step).stream())
.collect(toImmutableSet());
}
private ImmutableSet<TypeElement> getSupportedAnnotationTypeElements(Step step) {
return step.annotations().stream()
.map(elementUtils::getTypeElement)
.filter(Objects::nonNull)
.collect(toImmutableSet());
}
/**
* Returns the set of supported annotation types as collected from registered {@linkplain Step
* processing steps}.
*/
@Override
public final ImmutableSet<String> getSupportedAnnotationTypes() {
checkState(steps != null);
return steps.stream().flatMap(step -> step.annotations().stream()).collect(toImmutableSet());
}
@Override
public final boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
checkState(elementUtils != null);
checkState(messager != null);
checkState(steps != null);
// If this is the last round, report all of the missing elements if there
// were no errors raised in the round; otherwise reporting the missing
// elements just adds noise to the output.
if (roundEnv.processingOver()) {
postRound(roundEnv);
if (!roundEnv.errorRaised()) {
reportMissingElements(
ImmutableSet.<ElementFactory>builder()
.addAll(deferredEnclosingElements)
.addAll(elementsDeferredBySteps.values())
.build());
}
return false;
}
process(getWellFormedElementsByAnnotationType(roundEnv));
postRound(roundEnv);
return false;
}
/** Processes the valid elements, including those previously deferred by each step. */
private void process(ImmutableSetMultimap<TypeElement, Element> wellFormedElements) {
for (Step step : steps) {
ImmutableSet<TypeElement> annotationTypes = getSupportedAnnotationTypeElements(step);
ImmutableSetMultimap<TypeElement, Element> stepElements =
new ImmutableSetMultimap.Builder<TypeElement, Element>()
.putAll(indexByAnnotation(elementsDeferredBySteps.get(step), annotationTypes))
.putAll(filterKeys(wellFormedElements, annotationTypes::contains))
.build();
if (stepElements.isEmpty()) {
elementsDeferredBySteps.removeAll(step);
} else {
Set<? extends Element> rejectedElements =
step.process(toClassNameKeyedMultimap(stepElements));
elementsDeferredBySteps.replaceValues(
step,
rejectedElements.stream()
.map(element -> ElementFactory.forAnnotatedElement(element, messager))
.collect(toImmutableList()));
}
}
}
private void reportMissingElements(Set<ElementFactory> missingElementFactories) {
for (ElementFactory missingElementFactory : missingElementFactories) {
Element missingElement = missingElementFactory.getElement(elementUtils);
if (missingElement != null) {
messager.printMessage(
ERROR,
processingErrorMessage("this " + Ascii.toLowerCase(missingElement.getKind().name())),
missingElement);
} else {
messager.printMessage(ERROR, processingErrorMessage(missingElementFactory.toString));
}
}
}
private String processingErrorMessage(String target) {
return String.format(
"[%s:MiscError] %s was unable to process %s because not all of its dependencies could be "
+ "resolved. Check for compilation errors or a circular dependency with generated "
+ "code.",
getClass().getSimpleName(), getClass().getCanonicalName(), target);
}
/**
* Returns the superficially validated annotated elements of this round, including the validated
* previously ill-formed elements. Also update {@link #deferredEnclosingElements}.
*
* <p>Note that the elements deferred by processing steps are guaranteed to be well-formed;
* therefore, they are ignored (not returned) here, and they will be considered directly in the
* {@link #process(ImmutableSetMultimap)} method.
*/
private ImmutableSetMultimap<TypeElement, Element> getWellFormedElementsByAnnotationType(
RoundEnvironment roundEnv) {
ImmutableSet<ElementFactory> deferredEnclosingElementsCopy =
ImmutableSet.copyOf(deferredEnclosingElements);
deferredEnclosingElements.clear();
ImmutableSetMultimap.Builder<TypeElement, Element> prevIllFormedElementsBuilder =
ImmutableSetMultimap.builder();
for (ElementFactory deferredElementFactory : deferredEnclosingElementsCopy) {
Element deferredElement = deferredElementFactory.getElement(elementUtils);
if (deferredElement != null) {
findAnnotatedElements(
deferredElement, getSupportedAnnotationTypeElements(), prevIllFormedElementsBuilder);
} else {
deferredEnclosingElements.add(deferredElementFactory);
}
}
ImmutableSetMultimap<TypeElement, Element> prevIllFormedElements =
prevIllFormedElementsBuilder.build();
ImmutableSetMultimap.Builder<TypeElement, Element> wellFormedElementsBuilder =
ImmutableSetMultimap.builder();
// For optimization purposes, the ElementFactory instances for packages and types that have
// already been verified to be well-formed are stored.
Set<ElementFactory> wellFormedPackageOrTypeElements = new LinkedHashSet<>();
/* Look at
* 1. the previously ill-formed elements which have a present enclosing type (in case of
* Package element, the package itself), and
* 2. the new elements from this round
* and validate them.
*/
for (TypeElement annotationType : getSupportedAnnotationTypeElements()) {
Set<? extends Element> roundElements = roundEnv.getElementsAnnotatedWith(annotationType);
for (Element element : Sets.union(roundElements, prevIllFormedElements.get(annotationType))) {
// For every element that is not module/package, to be well-formed its
// enclosing-type in its entirety should be well-formed. Since modules
// don't get annotated (and not supported here) they can be ignored.
Element enclosing = (element.getKind() == PACKAGE) ? element : getEnclosingType(element);
ElementFactory enclosingFactory = ElementFactory.forAnnotatedElement(enclosing, messager);
boolean isWellFormedElement =
wellFormedPackageOrTypeElements.contains(enclosingFactory)
|| (!deferredEnclosingElements.contains(enclosingFactory)
&& validateElement(enclosing));
if (isWellFormedElement) {
wellFormedElementsBuilder.put(annotationType, element);
wellFormedPackageOrTypeElements.add(enclosingFactory);
} else {
deferredEnclosingElements.add(enclosingFactory);
}
}
}
return wellFormedElementsBuilder.build();
}
private ImmutableSetMultimap<TypeElement, Element> indexByAnnotation(
Set<ElementFactory> annotatedElementFactories, ImmutableSet<TypeElement> annotationTypes) {
ImmutableSetMultimap.Builder<TypeElement, Element> deferredElementsByAnnotationTypeBuilder =
ImmutableSetMultimap.builder();
for (ElementFactory elementFactory : annotatedElementFactories) {
Element element = elementFactory.getElement(elementUtils);
if (element != null) {
for (TypeElement annotationType : annotationTypes) {
if (isAnnotationPresent(element, annotationType)) {
deferredElementsByAnnotationTypeBuilder.put(annotationType, element);
}
}
}
}
return deferredElementsByAnnotationTypeBuilder.build();
}
/**
* Adds {@code element} and its enclosed elements to {@code annotatedElements} if they are
* annotated with any annotations in {@code annotationTypes}. Does not traverse to member types of
* {@code element}, so that if {@code Outer} is passed in the example below, looking for
* {@code @X}, then {@code Outer}, {@code Outer.foo}, and {@code Outer.foo()} will be added to the
* multimap, but neither {@code Inner} nor its members will.
*
* <pre>{@code
* @X class Outer {
* @X Object foo;
* @X void foo() {}
* @X static class Inner {
* @X Object bar;
* @X void bar() {}
* }
* }
* }</pre>
*/
private static void findAnnotatedElements(
Element element,
ImmutableSet<TypeElement> annotationTypes,
ImmutableSetMultimap.Builder<TypeElement, Element> annotatedElements) {
for (Element enclosedElement : element.getEnclosedElements()) {
if (!enclosedElement.getKind().isClass() && !enclosedElement.getKind().isInterface()) {
findAnnotatedElements(enclosedElement, annotationTypes, annotatedElements);
}
}
// element.getEnclosedElements() does NOT return parameter or type parameter elements
Parameterizable parameterizable = null;
if (isType(element)) {
parameterizable = asType(element);
} else if (isExecutable(element)) {
ExecutableElement executableElement = asExecutable(element);
parameterizable = executableElement;
for (VariableElement parameterElement : executableElement.getParameters()) {
findAnnotatedElements(parameterElement, annotationTypes, annotatedElements);
}
}
if (parameterizable != null) {
for (TypeParameterElement parameterElement : parameterizable.getTypeParameters()) {
findAnnotatedElements(parameterElement, annotationTypes, annotatedElements);
}
}
for (TypeElement annotationType : annotationTypes) {
if (isAnnotationPresent(element, annotationType)) {
annotatedElements.put(annotationType, element);
}
}
}
/**
* Returns the nearest enclosing {@link TypeElement} to the current element, throwing an {@link
* IllegalArgumentException} if the provided {@link Element} is not enclosed by a type.
*/
// TODO(user) move to MoreElements and make public.
private static TypeElement getEnclosingType(Element element) {
Element enclosingTypeElement = element;
while (enclosingTypeElement != null && !isType(enclosingTypeElement)) {
enclosingTypeElement = enclosingTypeElement.getEnclosingElement();
}
if (enclosingTypeElement == null) {
throw new IllegalArgumentException(element + " is not enclosed in any TypeElement.");
}
return asType(enclosingTypeElement);
}
private static ImmutableSetMultimap<String, Element> toClassNameKeyedMultimap(
SetMultimap<TypeElement, Element> elements) {
ImmutableSetMultimap.Builder<String, Element> builder = ImmutableSetMultimap.builder();
elements
.asMap()
.forEach(
(annotation, element) ->
builder.putAll(annotation.getQualifiedName().toString(), element));
return builder.build();
}
private static boolean isExecutable(Element element) {
return element.getKind() == METHOD || element.getKind() == CONSTRUCTOR;
}
/**
* Wraps the passed {@link ProcessingStep} in a {@link Step}. This is a convenience method to
* allow incremental migration to a String-based API. This method can be used to return a not yet
* converted {@link ProcessingStep} from {@link BasicAnnotationProcessor#steps()}.
*/
protected static Step asStep(ProcessingStep processingStep) {
return new ProcessingStepAsStep(processingStep);
}
/**
* The unit of processing logic that runs under the guarantee that all elements are complete and
* well-formed. A step may reject elements that are not ready for processing but may be at a later
* round.
*/
public interface Step {
/**
* The set of fully-qualified annotation type names processed by this step.
*
* <p>Warning: If the returned names are not names of annotations, they'll be ignored.
*/
Set<String> annotations();
/**
* The implementation of processing logic for the step. It is guaranteed that the keys in {@code
* elementsByAnnotation} will be a subset of the set returned by {@link #annotations()}.
*
* @return the elements (a subset of the values of {@code elementsByAnnotation}) that this step
* is unable to process, possibly until a later processing round. These elements will be
* passed back to this step at the next round of processing.
*/
Set<? extends Element> process(ImmutableSetMultimap<String, Element> elementsByAnnotation);
}
/**
* The unit of processing logic that runs under the guarantee that all elements are complete and
* well-formed. A step may reject elements that are not ready for processing but may be at a later
* round.
*
* @deprecated Implement {@link Step} instead. See {@link BasicAnnotationProcessor#steps()}.
*/
@Deprecated
public interface ProcessingStep {
/** The set of annotation types processed by this step. */
Set<? extends Class<? extends Annotation>> annotations();
/**
* The implementation of processing logic for the step. It is guaranteed that the keys in {@code
* elementsByAnnotation} will be a subset of the set returned by {@link #annotations()}.
*
* @return the elements (a subset of the values of {@code elementsByAnnotation}) that this step
* is unable to process, possibly until a later processing round. These elements will be
* passed back to this step at the next round of processing.
*/
Set<? extends Element> process(
SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation);
}
private static class ProcessingStepAsStep implements Step {
private final ProcessingStep processingStep;
private final ImmutableMap<String, Class<? extends Annotation>> annotationsByName;
ProcessingStepAsStep(ProcessingStep processingStep) {
this.processingStep = processingStep;
this.annotationsByName =
processingStep.annotations().stream()
.collect(
toImmutableMap(
c -> requireNonNull(c.getCanonicalName()),
(Class<? extends Annotation> aClass) -> aClass));
}
@Override
public Set<String> annotations() {
return annotationsByName.keySet();
}
@Override
public Set<? extends Element> process(
ImmutableSetMultimap<String, Element> elementsByAnnotation) {
return processingStep.process(toClassKeyedMultimap(elementsByAnnotation));
}
private ImmutableSetMultimap<Class<? extends Annotation>, Element> toClassKeyedMultimap(
SetMultimap<String, Element> elements) {
ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element> builder =
ImmutableSetMultimap.builder();
elements
.asMap()
.forEach(
(annotationName, annotatedElements) -> {
Class<? extends Annotation> annotation = annotationsByName.get(annotationName);
if (annotation != null) { // should not be null
builder.putAll(annotation, annotatedElements);
}
});
return builder.build();
}
}
/* Element Factories */
/**
* A factory for an annotated element.
*
* <p>Instead of saving elements, an {@code ElementFactory} is saved since there is no guarantee
* that any particular element will always be represented by the same object. (Reference: {@link
* Element}) For example, Eclipse compiler uses different {@code Element} instances per round. The
* factory allows us to reconstruct an equivalent element in a later round.
*/
private abstract static class ElementFactory {
final String toString;
private ElementFactory(Element element) {
this.toString = element.toString();
}
/** An {@link ElementFactory} for an annotated element. */
static ElementFactory forAnnotatedElement(Element element, Messager messager) {
/* The name of the ElementKind constants is used instead to accommodate for RECORD
* and RECORD_COMPONENT kinds, which are introduced in Java 16.
*/
switch (element.getKind().name()) {
case "PACKAGE":
return new PackageElementFactory(element);
case "CLASS":
case "ENUM":
case "INTERFACE":
case "ANNOTATION_TYPE":
case "RECORD":
return new TypeElementFactory(element);
case "TYPE_PARAMETER":
return new TypeParameterElementFactory(element, messager);
case "FIELD":
case "ENUM_CONSTANT":
case "RECORD_COMPONENT":
return new FieldOrRecordComponentElementFactory(element);
case "CONSTRUCTOR":
case "METHOD":
return new ExecutableElementFactory(element);
case "PARAMETER":
return new ParameterElementFactory(element);
default:
messager.printMessage(
WARNING,
String.format(
"%s does not support element type %s.",
ElementFactory.class.getCanonicalName(), element.getKind()));
return new UnsupportedElementFactory(element);
}
}
@Override
public boolean equals(@Nullable Object object) {
if (this == object) {
return true;
} else if (!(object instanceof ElementFactory)) {
return false;
}
ElementFactory that = (ElementFactory) object;
return this.toString.equals(that.toString);
}
@Override
public int hashCode() {
return toString.hashCode();
}
/**
* Returns the {@link Element} corresponding to the name information saved in this factory, or
* null if none exists.
*/
abstract @Nullable Element getElement(Elements elementUtils);
}
/**
* Saves the Element reference and returns it when inquired, with the hope that the same object
* still represents that element, or the required information is present.
*/
private static final class UnsupportedElementFactory extends ElementFactory {
private final Element element;
private UnsupportedElementFactory(Element element) {
super(element);
this.element = element;
}
@Override
Element getElement(Elements elementUtils) {
return element;
}
}
/* It's unfortunate that we have to track types and packages separately, but since there are
* two different methods to look them up in `Elements`, we end up with a lot of parallel
* logic. :(
*/
private static final class PackageElementFactory extends ElementFactory {
private PackageElementFactory(Element element) {
super(element);
}
@Override
@Nullable PackageElement getElement(Elements elementUtils) {
return elementUtils.getPackageElement(toString);
}
}
private static final class TypeElementFactory extends ElementFactory {
private TypeElementFactory(Element element) {
super(element);
}
@Override
@Nullable TypeElement getElement(Elements elementUtils) {
return elementUtils.getTypeElement(toString);
}
}
private static final class TypeParameterElementFactory extends ElementFactory {
private final ElementFactory enclosingElementFactory;
private TypeParameterElementFactory(Element element, Messager messager) {
super(element);
this.enclosingElementFactory =
ElementFactory.forAnnotatedElement(element.getEnclosingElement(), messager);
}
@Override
@Nullable TypeParameterElement getElement(Elements elementUtils) {
Parameterizable enclosingElement =
(Parameterizable) enclosingElementFactory.getElement(elementUtils);
if (enclosingElement == null) {
return null;
}
return enclosingElement.getTypeParameters().stream()
.filter(typeParamElement -> toString.equals(typeParamElement.toString()))
.collect(onlyElement());
}
@Override
public boolean equals(@Nullable Object object) {
if (this == object) {
return true;
} else if (!(object instanceof TypeParameterElementFactory)) {
return false;
}
TypeParameterElementFactory that = (TypeParameterElementFactory) object;
return this.toString.equals(that.toString)
&& this.enclosingElementFactory.equals(that.enclosingElementFactory);
}
@Override
public int hashCode() {
return Objects.hash(toString, enclosingElementFactory);
}
}
/** Represents FIELD, ENUM_CONSTANT, and RECORD_COMPONENT */
private static class FieldOrRecordComponentElementFactory extends ElementFactory {
private final TypeElementFactory enclosingTypeElementFactory;
private final ElementKind elementKind;
private FieldOrRecordComponentElementFactory(Element element) {
super(element); // toString is its simple name.
this.enclosingTypeElementFactory = new TypeElementFactory(getEnclosingType(element));
this.elementKind = element.getKind();
}
@Override
@Nullable Element getElement(Elements elementUtils) {
TypeElement enclosingTypeElement = enclosingTypeElementFactory.getElement(elementUtils);
if (enclosingTypeElement == null) {
return null;
}
return enclosingTypeElement.getEnclosedElements().stream()
.filter(
element ->
elementKind.equals(element.getKind()) && toString.equals(element.toString()))
.collect(onlyElement());
}
@Override
public boolean equals(@Nullable Object object) {
if (!super.equals(object) || !(object instanceof FieldOrRecordComponentElementFactory)) {
return false;
}
// To distinguish between a field and record_component
FieldOrRecordComponentElementFactory that = (FieldOrRecordComponentElementFactory) object;
return this.elementKind == that.elementKind;
}
@Override
public int hashCode() {
return Objects.hash(toString, elementKind);
}
}
/**
* Represents METHOD and CONSTRUCTOR.
*
* <p>The {@code equals()} and {@code hashCode()} have been overridden since the {@code toString}
* alone is not sufficient to make a distinction in all overloaded cases. For example, {@code <C
* extends Set<String>> void m(C c) {}}, and {@code <C extends SortedSet<String>> void m(C c) {}}
* both have the same toString {@code <C>m(C)} but are valid cases for overloading methods.
* Moreover, the needed enclosing type-element information is not included in the toString.
*
* <p>The executable element is retrieved by saving its enclosing type element, simple name, and
* ordinal position in the source code relative to other related overloaded methods, meaning those
* with the same simple name. This is possible because according to Java language specification
* for {@link TypeElement#getEnclosedElements()}: "As a particular instance of the general
* accuracy requirements and the ordering behavior required of this interface, the list of
* enclosed elements will be returned to the natural order for the originating source of
* information about the type. For example, if the information about the type is originating from
* a source file, the elements will be returned in source code order. (However, in that case the
* ordering of implicitly declared elements, such as default constructors, is not specified.)"
*
* <p>Simple name is saved since comparing the toString is not reliable when at least one
* parameter references ERROR, possibly because it is not generated yet. For example, method
* {@code void m(SomeGeneratedClass sgc)}, before the generation of {@code SomeGeneratedClass} has
* the toString {@code m(SomeGeneratedClass)}; however, after the generation it will have toString
* equal to {@code m(test.SomeGeneratedClass)} assuming that the package name is "test".
*/
private static final class ExecutableElementFactory extends ElementFactory {
private final TypeElementFactory enclosingTypeElementFactory;
private final Name simpleName;
/**
* The index of the element among all elements of the same kind within the enclosing type. If
* this is method {@code foo(...)} and the index is 0, that means that the method is the first
* method called {@code foo} in the enclosing type.
*/
private final int sameNameIndex;
private ExecutableElementFactory(Element element) {
super(element);
TypeElement enclosingTypeElement = getEnclosingType(element);
this.enclosingTypeElementFactory = new TypeElementFactory(enclosingTypeElement);
this.simpleName = element.getSimpleName();
ImmutableList<Element> methods = sameNameMethods(enclosingTypeElement, simpleName);
this.sameNameIndex = methods.indexOf(element);
checkState(this.sameNameIndex >= 0, "Did not find %s in %s", element, methods);
}
@Override
@Nullable ExecutableElement getElement(Elements elementUtils) {
TypeElement enclosingTypeElement = enclosingTypeElementFactory.getElement(elementUtils);
if (enclosingTypeElement == null) {
return null;
}
ImmutableList<Element> methods = sameNameMethods(enclosingTypeElement, simpleName);
return asExecutable(methods.get(sameNameIndex));
}
private static ImmutableList<Element> sameNameMethods(
TypeElement enclosingTypeElement, Name simpleName) {
return enclosingTypeElement.getEnclosedElements().stream()
.filter(element -> element.getSimpleName().equals(simpleName) && isExecutable(element))
.collect(toImmutableList());
}
@Override
public boolean equals(@Nullable Object object) {
if (this == object) {
return true;
} else if (!(object instanceof ExecutableElementFactory)) {
return false;
}
ExecutableElementFactory that = (ExecutableElementFactory) object;
return this.simpleName.equals(that.simpleName)
&& this.sameNameIndex == that.sameNameIndex
&& this.enclosingTypeElementFactory.equals(that.enclosingTypeElementFactory);
}
@Override
public int hashCode() {
return Objects.hash(simpleName, sameNameIndex, enclosingTypeElementFactory);
}
}
private static final class ParameterElementFactory extends ElementFactory {
private final ExecutableElementFactory enclosingExecutableElementFactory;
private ParameterElementFactory(Element element) {
super(element);
this.enclosingExecutableElementFactory =
new ExecutableElementFactory(element.getEnclosingElement());
}
@Override
@Nullable VariableElement getElement(Elements elementUtils) {
ExecutableElement enclosingExecutableElement =
enclosingExecutableElementFactory.getElement(elementUtils);
if (enclosingExecutableElement == null) {
return null;
} else {
return enclosingExecutableElement.getParameters().stream()
.filter(paramElement -> toString.equals(paramElement.toString()))
.collect(onlyElement());
}
}
@Override
public boolean equals(@Nullable Object object) {
if (this == object) {
return true;
} else if (!(object instanceof ParameterElementFactory)) {
return false;
}
ParameterElementFactory that = (ParameterElementFactory) object;
return this.toString.equals(that.toString)
&& this.enclosingExecutableElementFactory.equals(that.enclosingExecutableElementFactory);
}
@Override
public int hashCode() {
return Objects.hash(toString, enclosingExecutableElementFactory);
}
}
}
|
googleapis/google-cloud-java | 35,681 | java-analytics-admin/proto-google-analytics-admin-v1alpha/src/main/java/com/google/analytics/admin/v1alpha/UpdateGoogleAdsLinkRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/analytics/admin/v1alpha/analytics_admin.proto
// Protobuf Java Version: 3.25.8
package com.google.analytics.admin.v1alpha;
/**
*
*
* <pre>
* Request message for UpdateGoogleAdsLink RPC
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest}
*/
public final class UpdateGoogleAdsLinkRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest)
UpdateGoogleAdsLinkRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateGoogleAdsLinkRequest.newBuilder() to construct.
private UpdateGoogleAdsLinkRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateGoogleAdsLinkRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateGoogleAdsLinkRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateGoogleAdsLinkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateGoogleAdsLinkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest.class,
com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest.Builder.class);
}
private int bitField0_;
public static final int GOOGLE_ADS_LINK_FIELD_NUMBER = 1;
private com.google.analytics.admin.v1alpha.GoogleAdsLink googleAdsLink_;
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1alpha.GoogleAdsLink google_ads_link = 1;</code>
*
* @return Whether the googleAdsLink field is set.
*/
@java.lang.Override
public boolean hasGoogleAdsLink() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1alpha.GoogleAdsLink google_ads_link = 1;</code>
*
* @return The googleAdsLink.
*/
@java.lang.Override
public com.google.analytics.admin.v1alpha.GoogleAdsLink getGoogleAdsLink() {
return googleAdsLink_ == null
? com.google.analytics.admin.v1alpha.GoogleAdsLink.getDefaultInstance()
: googleAdsLink_;
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1alpha.GoogleAdsLink google_ads_link = 1;</code>
*/
@java.lang.Override
public com.google.analytics.admin.v1alpha.GoogleAdsLinkOrBuilder getGoogleAdsLinkOrBuilder() {
return googleAdsLink_ == null
? com.google.analytics.admin.v1alpha.GoogleAdsLink.getDefaultInstance()
: googleAdsLink_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getGoogleAdsLink());
}
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, getGoogleAdsLink());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest)) {
return super.equals(obj);
}
com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest other =
(com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest) obj;
if (hasGoogleAdsLink() != other.hasGoogleAdsLink()) return false;
if (hasGoogleAdsLink()) {
if (!getGoogleAdsLink().equals(other.getGoogleAdsLink())) 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 (hasGoogleAdsLink()) {
hash = (37 * hash) + GOOGLE_ADS_LINK_FIELD_NUMBER;
hash = (53 * hash) + getGoogleAdsLink().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest 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 UpdateGoogleAdsLink RPC
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest)
com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateGoogleAdsLinkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateGoogleAdsLinkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest.class,
com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest.Builder.class);
}
// Construct using com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getGoogleAdsLinkFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
googleAdsLink_ = null;
if (googleAdsLinkBuilder_ != null) {
googleAdsLinkBuilder_.dispose();
googleAdsLinkBuilder_ = null;
}
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateGoogleAdsLinkRequest_descriptor;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest
getDefaultInstanceForType() {
return com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest build() {
com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest buildPartial() {
com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest result =
new com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.googleAdsLink_ =
googleAdsLinkBuilder_ == null ? googleAdsLink_ : googleAdsLinkBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest) {
return mergeFrom((com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest other) {
if (other
== com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest.getDefaultInstance())
return this;
if (other.hasGoogleAdsLink()) {
mergeGoogleAdsLink(other.getGoogleAdsLink());
}
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(getGoogleAdsLinkFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.analytics.admin.v1alpha.GoogleAdsLink googleAdsLink_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1alpha.GoogleAdsLink,
com.google.analytics.admin.v1alpha.GoogleAdsLink.Builder,
com.google.analytics.admin.v1alpha.GoogleAdsLinkOrBuilder>
googleAdsLinkBuilder_;
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1alpha.GoogleAdsLink google_ads_link = 1;</code>
*
* @return Whether the googleAdsLink field is set.
*/
public boolean hasGoogleAdsLink() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1alpha.GoogleAdsLink google_ads_link = 1;</code>
*
* @return The googleAdsLink.
*/
public com.google.analytics.admin.v1alpha.GoogleAdsLink getGoogleAdsLink() {
if (googleAdsLinkBuilder_ == null) {
return googleAdsLink_ == null
? com.google.analytics.admin.v1alpha.GoogleAdsLink.getDefaultInstance()
: googleAdsLink_;
} else {
return googleAdsLinkBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1alpha.GoogleAdsLink google_ads_link = 1;</code>
*/
public Builder setGoogleAdsLink(com.google.analytics.admin.v1alpha.GoogleAdsLink value) {
if (googleAdsLinkBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
googleAdsLink_ = value;
} else {
googleAdsLinkBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1alpha.GoogleAdsLink google_ads_link = 1;</code>
*/
public Builder setGoogleAdsLink(
com.google.analytics.admin.v1alpha.GoogleAdsLink.Builder builderForValue) {
if (googleAdsLinkBuilder_ == null) {
googleAdsLink_ = builderForValue.build();
} else {
googleAdsLinkBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1alpha.GoogleAdsLink google_ads_link = 1;</code>
*/
public Builder mergeGoogleAdsLink(com.google.analytics.admin.v1alpha.GoogleAdsLink value) {
if (googleAdsLinkBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& googleAdsLink_ != null
&& googleAdsLink_
!= com.google.analytics.admin.v1alpha.GoogleAdsLink.getDefaultInstance()) {
getGoogleAdsLinkBuilder().mergeFrom(value);
} else {
googleAdsLink_ = value;
}
} else {
googleAdsLinkBuilder_.mergeFrom(value);
}
if (googleAdsLink_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1alpha.GoogleAdsLink google_ads_link = 1;</code>
*/
public Builder clearGoogleAdsLink() {
bitField0_ = (bitField0_ & ~0x00000001);
googleAdsLink_ = null;
if (googleAdsLinkBuilder_ != null) {
googleAdsLinkBuilder_.dispose();
googleAdsLinkBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1alpha.GoogleAdsLink google_ads_link = 1;</code>
*/
public com.google.analytics.admin.v1alpha.GoogleAdsLink.Builder getGoogleAdsLinkBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getGoogleAdsLinkFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1alpha.GoogleAdsLink google_ads_link = 1;</code>
*/
public com.google.analytics.admin.v1alpha.GoogleAdsLinkOrBuilder getGoogleAdsLinkOrBuilder() {
if (googleAdsLinkBuilder_ != null) {
return googleAdsLinkBuilder_.getMessageOrBuilder();
} else {
return googleAdsLink_ == null
? com.google.analytics.admin.v1alpha.GoogleAdsLink.getDefaultInstance()
: googleAdsLink_;
}
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1alpha.GoogleAdsLink google_ads_link = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1alpha.GoogleAdsLink,
com.google.analytics.admin.v1alpha.GoogleAdsLink.Builder,
com.google.analytics.admin.v1alpha.GoogleAdsLinkOrBuilder>
getGoogleAdsLinkFieldBuilder() {
if (googleAdsLinkBuilder_ == null) {
googleAdsLinkBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1alpha.GoogleAdsLink,
com.google.analytics.admin.v1alpha.GoogleAdsLink.Builder,
com.google.analytics.admin.v1alpha.GoogleAdsLinkOrBuilder>(
getGoogleAdsLink(), getParentForChildren(), isClean());
googleAdsLink_ = null;
}
return googleAdsLinkBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest)
}
// @@protoc_insertion_point(class_scope:google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest)
private static final com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest();
}
public static com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateGoogleAdsLinkRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateGoogleAdsLinkRequest>() {
@java.lang.Override
public UpdateGoogleAdsLinkRequest 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<UpdateGoogleAdsLinkRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateGoogleAdsLinkRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/flink | 36,001 | flink-runtime/src/test/java/org/apache/flink/runtime/dispatcher/DispatcherResourceCleanupTest.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.runtime.dispatcher;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.JobStatus;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.failure.FailureEnricher;
import org.apache.flink.core.testutils.OneShotLatch;
import org.apache.flink.runtime.blob.BlobServer;
import org.apache.flink.runtime.blob.BlobUtils;
import org.apache.flink.runtime.blob.TestingBlobStoreBuilder;
import org.apache.flink.runtime.client.DuplicateJobSubmissionException;
import org.apache.flink.runtime.client.JobSubmissionException;
import org.apache.flink.runtime.dispatcher.cleanup.TestingResourceCleanerFactory;
import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
import org.apache.flink.runtime.heartbeat.HeartbeatServices;
import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
import org.apache.flink.runtime.highavailability.JobResultEntry;
import org.apache.flink.runtime.highavailability.JobResultStore;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.JobGraphTestUtils;
import org.apache.flink.runtime.jobmaster.JobManagerRunner;
import org.apache.flink.runtime.jobmaster.JobManagerSharedServices;
import org.apache.flink.runtime.jobmaster.TestingJobManagerRunner;
import org.apache.flink.runtime.jobmaster.factories.JobManagerJobMetricGroupFactory;
import org.apache.flink.runtime.jobmaster.utils.TestingJobMasterGateway;
import org.apache.flink.runtime.jobmaster.utils.TestingJobMasterGatewayBuilder;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.rest.handler.legacy.utils.ArchivedExecutionGraphBuilder;
import org.apache.flink.runtime.rpc.FatalErrorHandler;
import org.apache.flink.runtime.rpc.RpcService;
import org.apache.flink.runtime.rpc.TestingRpcService;
import org.apache.flink.runtime.scheduler.ExecutionGraphInfo;
import org.apache.flink.runtime.testutils.TestingJobResultStore;
import org.apache.flink.runtime.util.TestingFatalErrorHandlerResource;
import org.apache.flink.streaming.api.graph.ExecutionPlan;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.Reference;
import org.apache.flink.util.TestLogger;
import org.apache.flink.util.concurrent.FutureUtils;
import org.apache.flink.util.function.ThrowingRunnable;
import org.hamcrest.core.IsInstanceOf;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.flink.runtime.dispatcher.AbstractDispatcherTest.awaitStatus;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
/** Tests the resource cleanup by the {@link Dispatcher}. */
public class DispatcherResourceCleanupTest extends TestLogger {
@ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule public ExpectedException expectedException = ExpectedException.none();
@Rule
public final TestingFatalErrorHandlerResource testingFatalErrorHandlerResource =
new TestingFatalErrorHandlerResource();
private static final Duration timeout = Duration.ofSeconds(10L);
private static TestingRpcService rpcService;
private JobID jobId;
private JobGraph jobGraph;
private TestingDispatcher dispatcher;
private DispatcherGateway dispatcherGateway;
private BlobServer blobServer;
private CompletableFuture<JobID> localCleanupFuture;
private CompletableFuture<JobID> globalCleanupFuture;
@BeforeClass
public static void setupClass() {
rpcService = new TestingRpcService();
}
@Before
public void setup() throws Exception {
jobGraph = JobGraphTestUtils.singleNoOpJobGraph();
jobId = jobGraph.getJobID();
globalCleanupFuture = new CompletableFuture<>();
localCleanupFuture = new CompletableFuture<>();
blobServer =
BlobUtils.createBlobServer(
new Configuration(),
Reference.owned(temporaryFolder.newFolder()),
new TestingBlobStoreBuilder().createTestingBlobStore());
}
private TestingJobManagerRunnerFactory startDispatcherAndSubmitJob() throws Exception {
return startDispatcherAndSubmitJob(0);
}
private TestingJobManagerRunnerFactory startDispatcherAndSubmitJob(
int numBlockingJobManagerRunners) throws Exception {
return startDispatcherAndSubmitJob(
createTestingDispatcherBuilder(), numBlockingJobManagerRunners);
}
private TestingJobManagerRunnerFactory startDispatcherAndSubmitJob(
TestingDispatcher.Builder dispatcherBuilder, int numBlockingJobManagerRunners)
throws Exception {
final TestingJobMasterServiceLeadershipRunnerFactory testingJobManagerRunnerFactoryNG =
new TestingJobMasterServiceLeadershipRunnerFactory(numBlockingJobManagerRunners);
startDispatcher(dispatcherBuilder, testingJobManagerRunnerFactoryNG);
submitJobAndWait();
return testingJobManagerRunnerFactoryNG;
}
private void startDispatcher(JobManagerRunnerFactory jobManagerRunnerFactory) throws Exception {
startDispatcher(createTestingDispatcherBuilder(), jobManagerRunnerFactory);
}
private void startDispatcher(
TestingDispatcher.Builder dispatcherBuilder,
JobManagerRunnerFactory jobManagerRunnerFactory)
throws Exception {
dispatcher =
dispatcherBuilder
.setJobManagerRunnerFactory(jobManagerRunnerFactory)
.build(rpcService);
dispatcher.start();
dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class);
}
private TestingDispatcher.Builder createTestingDispatcherBuilder() {
final JobManagerRunnerRegistry jobManagerRunnerRegistry =
new DefaultJobManagerRunnerRegistry(2);
return TestingDispatcher.builder()
.setBlobServer(blobServer)
.setJobManagerRunnerRegistry(jobManagerRunnerRegistry)
.setFatalErrorHandler(testingFatalErrorHandlerResource.getFatalErrorHandler())
.setResourceCleanerFactory(
TestingResourceCleanerFactory.builder()
// JobManagerRunnerRegistry needs to be added explicitly
// because cleaning it will trigger the closeAsync latch
// provided by TestingJobManagerRunner
.withLocallyCleanableResource(jobManagerRunnerRegistry)
.withGloballyCleanableResource(
(jobId, ignoredExecutor) -> {
globalCleanupFuture.complete(jobId);
return FutureUtils.completedVoidFuture();
})
.withLocallyCleanableResource(
(jobId, ignoredExecutor) -> {
localCleanupFuture.complete(jobId);
return FutureUtils.completedVoidFuture();
})
.build());
}
@After
public void teardown() throws Exception {
if (dispatcher != null) {
dispatcher.close();
}
if (blobServer != null) {
blobServer.close();
}
}
@AfterClass
public static void teardownClass() throws ExecutionException, InterruptedException {
if (rpcService != null) {
rpcService.closeAsync().get();
}
}
@Test
public void testGlobalCleanupWhenJobFinished() throws Exception {
final TestingJobManagerRunnerFactory jobManagerRunnerFactory =
startDispatcherAndSubmitJob();
// complete the job
finishJob(jobManagerRunnerFactory.takeCreatedJobManagerRunner());
assertGlobalCleanupTriggered(jobId);
}
@Test
public void testGlobalCleanupWhenJobCanceled() throws Exception {
final TestingJobManagerRunnerFactory jobManagerRunnerFactory =
startDispatcherAndSubmitJob();
// complete the job
cancelJob(jobManagerRunnerFactory.takeCreatedJobManagerRunner());
assertGlobalCleanupTriggered(jobId);
}
private CompletableFuture<Acknowledge> submitJob() {
return dispatcherGateway.submitJob(jobGraph, timeout);
}
private void submitJobAndWait() {
submitJob().join();
}
@Test
public void testLocalCleanupWhenJobNotFinished() throws Exception {
final TestingJobManagerRunnerFactory jobManagerRunnerFactory =
startDispatcherAndSubmitJob();
// job not finished
final TestingJobManagerRunner testingJobManagerRunner =
jobManagerRunnerFactory.takeCreatedJobManagerRunner();
suspendJob(testingJobManagerRunner);
assertLocalCleanupTriggered(jobId);
}
@Test
public void testGlobalCleanupWhenJobSubmissionFails() throws Exception {
startDispatcher(new FailingJobManagerRunnerFactory(new FlinkException("Test exception")));
final CompletableFuture<Acknowledge> submissionFuture = submitJob();
assertThatThrownBy(submissionFuture::get).hasCauseInstanceOf(JobSubmissionException.class);
assertGlobalCleanupTriggered(jobId);
}
@Test
public void testLocalCleanupWhenClosingDispatcher() throws Exception {
startDispatcherAndSubmitJob();
dispatcher.closeAsync().get();
assertLocalCleanupTriggered(jobId);
}
@Test
public void testGlobalCleanupWhenJobFinishedWhileClosingDispatcher() throws Exception {
final TestingJobManagerRunner testingJobManagerRunner =
TestingJobManagerRunner.newBuilder()
.setBlockingTermination(true)
.setJobId(jobId)
.build();
final Queue<JobManagerRunner> jobManagerRunners =
new ArrayDeque<>(Arrays.asList(testingJobManagerRunner));
startDispatcher(new QueueJobManagerRunnerFactory(jobManagerRunners));
submitJobAndWait();
final CompletableFuture<Void> dispatcherTerminationFuture = dispatcher.closeAsync();
testingJobManagerRunner.getCloseAsyncCalledLatch().await();
testingJobManagerRunner.completeResultFuture(
new ExecutionGraphInfo(
new ArchivedExecutionGraphBuilder()
.setJobID(jobId)
.setState(JobStatus.FINISHED)
.build()));
testingJobManagerRunner.completeTerminationFuture();
// check that no exceptions have been thrown
dispatcherTerminationFuture.get();
assertGlobalCleanupTriggered(jobId);
}
@Test
public void testJobBeingMarkedAsDirtyBeforeCleanup() throws Exception {
final OneShotLatch markAsDirtyLatch = new OneShotLatch();
final TestingDispatcher.Builder dispatcherBuilder =
createTestingDispatcherBuilder()
.setJobResultStore(
TestingJobResultStore.builder()
.withCreateDirtyResultConsumer(
ignoredJobResultEntry -> {
try {
markAsDirtyLatch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return FutureUtils.completedExceptionally(
e);
}
return FutureUtils.completedVoidFuture();
})
.build());
final TestingJobManagerRunnerFactory jobManagerRunnerFactory =
startDispatcherAndSubmitJob(dispatcherBuilder, 0);
finishJob(jobManagerRunnerFactory.takeCreatedJobManagerRunner());
assertThatNoCleanupWasTriggered();
markAsDirtyLatch.trigger();
assertGlobalCleanupTriggered(jobId);
}
@Test
public void testJobBeingMarkedAsCleanAfterCleanup() throws Exception {
final CompletableFuture<JobID> markAsCleanFuture = new CompletableFuture<>();
final JobResultStore jobResultStore =
TestingJobResultStore.builder()
.withMarkResultAsCleanConsumer(
jobID -> {
markAsCleanFuture.complete(jobID);
return FutureUtils.completedVoidFuture();
})
.build();
final OneShotLatch localCleanupLatch = new OneShotLatch();
final OneShotLatch globalCleanupLatch = new OneShotLatch();
final TestingResourceCleanerFactory resourceCleanerFactory =
TestingResourceCleanerFactory.builder()
.withLocallyCleanableResource(
(ignoredJobId, ignoredExecutor) -> {
try {
localCleanupLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return FutureUtils.completedVoidFuture();
})
.withGloballyCleanableResource(
(ignoredJobId, ignoredExecutor) -> {
try {
globalCleanupLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return FutureUtils.completedVoidFuture();
})
.build();
final TestingDispatcher.Builder dispatcherBuilder =
createTestingDispatcherBuilder()
.setJobResultStore(jobResultStore)
.setResourceCleanerFactory(resourceCleanerFactory);
final TestingJobManagerRunnerFactory jobManagerRunnerFactory =
startDispatcherAndSubmitJob(dispatcherBuilder, 0);
finishJob(jobManagerRunnerFactory.takeCreatedJobManagerRunner());
assertThat(markAsCleanFuture.isDone(), is(false));
localCleanupLatch.trigger();
assertThat(markAsCleanFuture.isDone(), is(false));
globalCleanupLatch.trigger();
assertThat(markAsCleanFuture.get(), is(jobId));
}
/**
* Tests that the previous JobManager needs to be completely terminated before a new job with
* the same {@link JobID} is started.
*/
@Test
public void testJobSubmissionUnderSameJobId() throws Exception {
final TestingJobManagerRunnerFactory jobManagerRunnerFactory =
startDispatcherAndSubmitJob(1);
final TestingJobManagerRunner testingJobManagerRunner =
jobManagerRunnerFactory.takeCreatedJobManagerRunner();
suspendJob(testingJobManagerRunner);
// wait until termination JobManagerRunner closeAsync has been called.
// this is necessary to avoid race conditions with completion of the 1st job and the
// submission of the 2nd job (DuplicateJobSubmissionException).
testingJobManagerRunner.getCloseAsyncCalledLatch().await();
final CompletableFuture<Acknowledge> submissionFuture =
dispatcherGateway.submitJob(jobGraph, timeout);
try {
submissionFuture.get(10L, TimeUnit.MILLISECONDS);
fail(
"The job submission future should not complete until the previous JobManager "
+ "termination future has been completed.");
} catch (TimeoutException ignored) {
// expected
} finally {
testingJobManagerRunner.completeTerminationFuture();
}
assertThat(submissionFuture.get(), equalTo(Acknowledge.get()));
}
/**
* Tests that a duplicate job submission won't delete any job meta data (submitted job graphs,
* blobs, etc.).
*/
@Test
public void testDuplicateJobSubmissionDoesNotDeleteJobMetaData() throws Exception {
final TestingJobManagerRunnerFactory testingJobManagerRunnerFactoryNG =
startDispatcherAndSubmitJob();
final CompletableFuture<Acknowledge> submissionFuture =
dispatcherGateway.submitJob(jobGraph, timeout);
try {
try {
submissionFuture.get();
fail("Expected a DuplicateJobSubmissionFailure.");
} catch (ExecutionException ee) {
assertThat(
ExceptionUtils.findThrowable(ee, DuplicateJobSubmissionException.class)
.isPresent(),
is(true));
}
assertThatNoCleanupWasTriggered();
} finally {
finishJob(testingJobManagerRunnerFactoryNG.takeCreatedJobManagerRunner());
}
assertGlobalCleanupTriggered(jobId);
}
private void finishJob(TestingJobManagerRunner takeCreatedJobManagerRunner) {
terminateJobWithState(takeCreatedJobManagerRunner, JobStatus.FINISHED);
}
private void suspendJob(TestingJobManagerRunner takeCreatedJobManagerRunner) {
terminateJobWithState(takeCreatedJobManagerRunner, JobStatus.SUSPENDED);
}
private void cancelJob(TestingJobManagerRunner takeCreatedJobManagerRunner) {
terminateJobWithState(takeCreatedJobManagerRunner, JobStatus.CANCELED);
}
private void terminateJobWithState(
TestingJobManagerRunner takeCreatedJobManagerRunner, JobStatus state) {
takeCreatedJobManagerRunner.completeResultFuture(
new ExecutionGraphInfo(
new ArchivedExecutionGraphBuilder()
.setJobID(jobId)
.setState(state)
.build()));
}
private void assertThatNoCleanupWasTriggered() {
assertThat(globalCleanupFuture.isDone(), is(false));
assertThat(localCleanupFuture.isDone(), is(false));
}
@Test
public void testDispatcherTerminationTerminatesRunningJobMasters() throws Exception {
final TestingJobManagerRunnerFactory jobManagerRunnerFactory =
startDispatcherAndSubmitJob();
dispatcher.closeAsync().get();
final TestingJobManagerRunner jobManagerRunner =
jobManagerRunnerFactory.takeCreatedJobManagerRunner();
assertThat(jobManagerRunner.getTerminationFuture().isDone(), is(true));
}
/** Tests that terminating the Dispatcher will wait for all JobMasters to be terminated. */
@Test
public void testDispatcherTerminationWaitsForJobMasterTerminations() throws Exception {
final TestingJobManagerRunnerFactory jobManagerRunnerFactory =
startDispatcherAndSubmitJob(1);
final CompletableFuture<Void> dispatcherTerminationFuture = dispatcher.closeAsync();
try {
dispatcherTerminationFuture.get(10L, TimeUnit.MILLISECONDS);
fail("We should not terminate before all running JobMasters have terminated.");
} catch (TimeoutException ignored) {
// expected
} finally {
jobManagerRunnerFactory.takeCreatedJobManagerRunner().completeTerminationFuture();
}
dispatcherTerminationFuture.get();
}
private void assertLocalCleanupTriggered(JobID jobId)
throws ExecutionException, InterruptedException, TimeoutException {
assertThat(localCleanupFuture.get(), equalTo(jobId));
assertThat(globalCleanupFuture.isDone(), is(false));
}
private void assertGlobalCleanupTriggered(JobID jobId)
throws ExecutionException, InterruptedException, TimeoutException {
assertThat(localCleanupFuture.isDone(), is(false));
assertThat(globalCleanupFuture.get(), equalTo(jobId));
}
@Test
public void testFatalErrorIfJobCannotBeMarkedDirtyInJobResultStore() throws Exception {
final JobResultStore jobResultStore =
TestingJobResultStore.builder()
.withCreateDirtyResultConsumer(
jobResult ->
FutureUtils.completedExceptionally(
new IOException("Expected IOException.")))
.build();
final TestingJobManagerRunnerFactory jobManagerRunnerFactory =
startDispatcherAndSubmitJob(
createTestingDispatcherBuilder().setJobResultStore(jobResultStore), 0);
ArchivedExecutionGraph executionGraph =
new ArchivedExecutionGraphBuilder()
.setJobID(jobId)
.setState(JobStatus.FINISHED)
.build();
final TestingJobManagerRunner testingJobManagerRunner =
jobManagerRunnerFactory.takeCreatedJobManagerRunner();
testingJobManagerRunner.completeResultFuture(new ExecutionGraphInfo(executionGraph));
final CompletableFuture<? extends Throwable> errorFuture =
this.testingFatalErrorHandlerResource.getFatalErrorHandler().getErrorFuture();
assertThat(errorFuture.get(), IsInstanceOf.instanceOf(FlinkException.class));
testingFatalErrorHandlerResource.getFatalErrorHandler().clearError();
}
@Test
public void testErrorHandlingIfJobCannotBeMarkedAsCleanInJobResultStore() throws Exception {
final CompletableFuture<JobResultEntry> dirtyJobFuture = new CompletableFuture<>();
final JobResultStore jobResultStore =
TestingJobResultStore.builder()
.withCreateDirtyResultConsumer(
jobResultEntry -> {
dirtyJobFuture.complete(jobResultEntry);
return FutureUtils.completedVoidFuture();
})
.withMarkResultAsCleanConsumer(
jobId ->
FutureUtils.completedExceptionally(
new IOException("Expected IOException.")))
.build();
final TestingJobManagerRunnerFactory jobManagerRunnerFactory =
startDispatcherAndSubmitJob(
createTestingDispatcherBuilder().setJobResultStore(jobResultStore), 0);
ArchivedExecutionGraph executionGraph =
new ArchivedExecutionGraphBuilder()
.setJobID(jobId)
.setState(JobStatus.FINISHED)
.build();
final TestingJobManagerRunner testingJobManagerRunner =
jobManagerRunnerFactory.takeCreatedJobManagerRunner();
testingJobManagerRunner.completeResultFuture(new ExecutionGraphInfo(executionGraph));
final CompletableFuture<? extends Throwable> errorFuture =
this.testingFatalErrorHandlerResource.getFatalErrorHandler().getErrorFuture();
try {
final Throwable unexpectedError = errorFuture.get(100, TimeUnit.MILLISECONDS);
fail(
"No error should have been reported but an "
+ unexpectedError.getClass()
+ " was handled.");
} catch (TimeoutException e) {
// expected
}
assertThat(dirtyJobFuture.get().getJobId(), is(jobId));
}
/** Tests that a failing {@link JobManagerRunner} will be properly cleaned up. */
@Test
public void testFailingJobManagerRunnerCleanup() throws Exception {
final FlinkException testException = new FlinkException("Test exception.");
final ArrayBlockingQueue<Optional<Exception>> queue = new ArrayBlockingQueue<>(2);
final BlockingJobManagerRunnerFactory blockingJobManagerRunnerFactory =
new BlockingJobManagerRunnerFactory(
() -> {
final Optional<Exception> maybeException = queue.take();
if (maybeException.isPresent()) {
throw maybeException.get();
}
});
startDispatcher(blockingJobManagerRunnerFactory);
final DispatcherGateway dispatcherGateway =
dispatcher.getSelfGateway(DispatcherGateway.class);
// submit and fail during job master runner construction
queue.offer(Optional.of(testException));
assertThatThrownBy(() -> dispatcherGateway.submitJob(jobGraph, Duration.ofMinutes(1)).get())
.hasCauseInstanceOf(FlinkException.class)
.hasRootCauseMessage(testException.getMessage());
// make sure we've cleaned up in correct order (including HA)
assertGlobalCleanupTriggered(jobId);
// don't fail this time
queue.offer(Optional.empty());
// submit job again
dispatcherGateway.submitJob(jobGraph, Duration.ofMinutes(1L)).get();
blockingJobManagerRunnerFactory.setJobStatus(JobStatus.RUNNING);
// Ensure job is running
awaitStatus(dispatcherGateway, jobId, JobStatus.RUNNING);
}
@Test
public void testArchivingFinishedJobToHistoryServer() throws Exception {
final CompletableFuture<Acknowledge> archiveFuture = new CompletableFuture<>();
final TestingDispatcher.Builder testingDispatcherBuilder =
createTestingDispatcherBuilder()
.setHistoryServerArchivist(executionGraphInfo -> archiveFuture);
final TestingJobManagerRunnerFactory jobManagerRunnerFactory =
startDispatcherAndSubmitJob(testingDispatcherBuilder, 0);
finishJob(jobManagerRunnerFactory.takeCreatedJobManagerRunner());
// Before the archiving is finished, the cleanup is not finished and the job is not
// terminated
assertThatNoCleanupWasTriggered();
final CompletableFuture<Void> jobTerminationFuture =
dispatcher.getJobTerminationFuture(jobId, Duration.ofHours(1));
assertFalse(jobTerminationFuture.isDone());
archiveFuture.complete(Acknowledge.get());
// Once the archive is finished, the cleanup is finished and the job is terminated.
assertGlobalCleanupTriggered(jobId);
jobTerminationFuture.join();
}
@Test
public void testNotArchivingSuspendedJobToHistoryServer() throws Exception {
final AtomicBoolean isArchived = new AtomicBoolean(false);
final TestingDispatcher.Builder testingDispatcherBuilder =
createTestingDispatcherBuilder()
.setHistoryServerArchivist(
executionGraphInfo -> {
isArchived.set(true);
return CompletableFuture.completedFuture(Acknowledge.get());
});
final TestingJobManagerRunnerFactory jobManagerRunnerFactory =
startDispatcherAndSubmitJob(testingDispatcherBuilder, 0);
suspendJob(jobManagerRunnerFactory.takeCreatedJobManagerRunner());
assertLocalCleanupTriggered(jobId);
dispatcher.getJobTerminationFuture(jobId, Duration.ofHours(1)).join();
assertFalse(isArchived.get());
}
private static final class BlockingJobManagerRunnerFactory
extends TestingJobMasterServiceLeadershipRunnerFactory {
private final ThrowingRunnable<Exception> jobManagerRunnerCreationLatch;
private TestingJobManagerRunner testingRunner;
BlockingJobManagerRunnerFactory(ThrowingRunnable<Exception> jobManagerRunnerCreationLatch) {
this.jobManagerRunnerCreationLatch = jobManagerRunnerCreationLatch;
}
@Override
public TestingJobManagerRunner createJobManagerRunner(
ExecutionPlan executionPlan,
Configuration configuration,
RpcService rpcService,
HighAvailabilityServices highAvailabilityServices,
HeartbeatServices heartbeatServices,
JobManagerSharedServices jobManagerSharedServices,
JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory,
FatalErrorHandler fatalErrorHandler,
Collection<FailureEnricher> failureEnrichers,
long initializationTimestamp)
throws Exception {
jobManagerRunnerCreationLatch.run();
this.testingRunner =
super.createJobManagerRunner(
executionPlan,
configuration,
rpcService,
highAvailabilityServices,
heartbeatServices,
jobManagerSharedServices,
jobManagerJobMetricGroupFactory,
fatalErrorHandler,
failureEnrichers,
initializationTimestamp);
TestingJobMasterGateway testingJobMasterGateway =
new TestingJobMasterGatewayBuilder()
.setRequestJobSupplier(
() ->
CompletableFuture.completedFuture(
new ExecutionGraphInfo(
ArchivedExecutionGraph
.createSparseArchivedExecutionGraph(
executionPlan
.getJobID(),
executionPlan.getName(),
JobStatus.RUNNING,
null,
null,
null,
1337))))
.build();
testingRunner.completeJobMasterGatewayFuture(testingJobMasterGateway);
return testingRunner;
}
public void setJobStatus(JobStatus newStatus) {
Preconditions.checkState(
testingRunner != null,
"JobManagerRunner must be created before this method is available");
this.testingRunner.setJobStatus(newStatus);
}
}
private static final class QueueJobManagerRunnerFactory implements JobManagerRunnerFactory {
private final Queue<? extends JobManagerRunner> jobManagerRunners;
private QueueJobManagerRunnerFactory(Queue<? extends JobManagerRunner> jobManagerRunners) {
this.jobManagerRunners = jobManagerRunners;
}
@Override
public JobManagerRunner createJobManagerRunner(
ExecutionPlan executionPlan,
Configuration configuration,
RpcService rpcService,
HighAvailabilityServices highAvailabilityServices,
HeartbeatServices heartbeatServices,
JobManagerSharedServices jobManagerServices,
JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory,
FatalErrorHandler fatalErrorHandler,
Collection<FailureEnricher> failureEnrichers,
long initializationTimestamp) {
return Optional.ofNullable(jobManagerRunners.poll())
.orElseThrow(
() ->
new IllegalStateException(
"Cannot create more JobManagerRunners."));
}
}
private class FailingJobManagerRunnerFactory implements JobManagerRunnerFactory {
private final Exception testException;
public FailingJobManagerRunnerFactory(FlinkException testException) {
this.testException = testException;
}
@Override
public JobManagerRunner createJobManagerRunner(
ExecutionPlan executionPlan,
Configuration configuration,
RpcService rpcService,
HighAvailabilityServices highAvailabilityServices,
HeartbeatServices heartbeatServices,
JobManagerSharedServices jobManagerServices,
JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory,
FatalErrorHandler fatalErrorHandler,
Collection<FailureEnricher> failureEnrichers,
long initializationTimestamp)
throws Exception {
throw testException;
}
}
}
|
google/ExoPlayer | 35,628 | testutils/src/test/java/com/google/android/exoplayer2/testutil/truth/SpannedSubjectTest.java | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.google.android.exoplayer2.testutil.truth;
import static com.google.android.exoplayer2.testutil.truth.SpannedSubject.assertThat;
import static com.google.android.exoplayer2.testutil.truth.SpannedSubject.spanned;
import static com.google.common.truth.ExpectFailure.assertThat;
import static com.google.common.truth.ExpectFailure.expectFailureAbout;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.Layout.Alignment;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.AlignmentSpan;
import android.text.style.AlignmentSpan.Standard;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.text.style.UnderlineSpan;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.testutil.truth.SpannedSubject.AndSpanFlags;
import com.google.android.exoplayer2.testutil.truth.SpannedSubject.WithSpanFlags;
import com.google.android.exoplayer2.text.span.HorizontalTextInVerticalContextSpan;
import com.google.android.exoplayer2.text.span.RubySpan;
import com.google.android.exoplayer2.text.span.TextAnnotation;
import com.google.android.exoplayer2.text.span.TextEmphasisSpan;
import com.google.android.exoplayer2.util.Util;
import com.google.common.truth.ExpectFailure;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Tests for {@link SpannedSubject}. */
@RunWith(AndroidJUnit4.class)
public class SpannedSubjectTest {
private static final String TEXT_PREFIX = "string with ";
private static final String SPANNED_TEXT = "span";
private static final String TEXT_SUFFIX = " inside";
private static final String TEXT_WITH_TARGET_SPAN = TEXT_PREFIX + SPANNED_TEXT + TEXT_SUFFIX;
private static final int SPAN_START = TEXT_PREFIX.length();
private static final int SPAN_END = (TEXT_PREFIX + SPANNED_TEXT).length();
private static final String UNRELATED_SPANNED_TEXT = "unrelated span";
private static final String TEXT_INFIX = " and ";
private static final String TEXT_WITH_TARGET_AND_UNRELATED_SPAN =
TEXT_PREFIX + SPANNED_TEXT + TEXT_INFIX + UNRELATED_SPANNED_TEXT + TEXT_SUFFIX;
private static final int UNRELATED_SPAN_START =
(TEXT_PREFIX + SPANNED_TEXT + TEXT_INFIX).length();
private static final int UNRELATED_SPAN_END =
UNRELATED_SPAN_START + UNRELATED_SPANNED_TEXT.length();
@Test
public void hasNoSpans_success() {
SpannableString spannable = SpannableString.valueOf("test with no spans");
assertThat(spannable).hasNoSpans();
}
@Test
public void hasNoSpans_failure() {
Spanned spanned = createSpannable(new UnderlineSpan());
AssertionError expected = expectFailure(whenTesting -> whenTesting.that(spanned).hasNoSpans());
assertThat(expected).factKeys().contains("Expected no spans");
assertThat(expected).factValue("but found").contains("start=" + SPAN_START);
}
@Test
public void italicSpan_success() {
SpannableString spannable =
createSpannable(new StyleSpan(Typeface.ITALIC), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasItalicSpanBetween(SPAN_START, SPAN_END)
.withFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void italicSpan_mismatchedIndex() {
checkHasSpanFailsDueToIndexMismatch(
new StyleSpan(Typeface.ITALIC), SpannedSubject::hasItalicSpanBetween);
}
@Test
public void italicSpan_mismatchedFlags() {
checkHasSpanFailsDueToFlagMismatch(
new StyleSpan(Typeface.ITALIC), SpannedSubject::hasItalicSpanBetween);
}
@Test
public void italicSpan_null() {
AssertionError expected =
expectFailure(whenTesting -> whenTesting.that(null).hasItalicSpanBetween(0, 5));
assertThat(expected).factKeys().containsExactly("Spanned must not be null");
}
@Test
public void boldSpan_success() {
SpannableString spannable =
createSpannable(new StyleSpan(Typeface.BOLD), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasBoldSpanBetween(SPAN_START, SPAN_END)
.withFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void boldSpan_mismatchedIndex() {
checkHasSpanFailsDueToIndexMismatch(
new StyleSpan(Typeface.BOLD), SpannedSubject::hasBoldSpanBetween);
}
@Test
public void boldSpan_mismatchedFlags() {
checkHasSpanFailsDueToFlagMismatch(
new StyleSpan(Typeface.BOLD), SpannedSubject::hasBoldSpanBetween);
}
@Test
public void boldItalicSpan_withOneSpan() {
SpannableString spannable =
createSpannable(new StyleSpan(Typeface.BOLD_ITALIC), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasBoldItalicSpanBetween(SPAN_START, SPAN_END)
.withFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void boldItalicSpan_withTwoSpans() {
SpannableString spannable = createSpannable(new StyleSpan(Typeface.BOLD));
spannable.setSpan(
new StyleSpan(Typeface.ITALIC), SPAN_START, SPAN_END, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasBoldItalicSpanBetween(SPAN_START, SPAN_END)
.withFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
// If the span is both BOLD and BOLD_ITALIC then the assertion should still succeed.
public void boldItalicSpan_withRepeatSpans() {
SpannableString spannable = createSpannable(new StyleSpan(Typeface.BOLD_ITALIC));
spannable.setSpan(
new StyleSpan(Typeface.BOLD), SPAN_START, SPAN_END, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasBoldItalicSpanBetween(SPAN_START, SPAN_END)
.withFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void boldItalicSpan_onlyItalic() {
SpannableString spannable = createSpannable(new StyleSpan(Typeface.ITALIC));
AssertionError expected =
expectFailure(
whenTesting ->
whenTesting.that(spannable).hasBoldItalicSpanBetween(SPAN_START, SPAN_END));
assertThat(expected)
.factKeys()
.contains(
String.format(
"No matching StyleSpans found between start=%s,end=%s", SPAN_START, SPAN_END));
assertThat(expected).factValue("but found styles").contains("[" + Typeface.ITALIC + "]");
}
@Test
public void boldItalicSpan_mismatchedIndex() {
checkHasSpanFailsDueToIndexMismatch(
new StyleSpan(Typeface.BOLD_ITALIC), SpannedSubject::hasBoldItalicSpanBetween);
}
@Test
public void boldItalicSpan_mismatchedFlags() {
checkHasSpanFailsDueToFlagMismatch(
new StyleSpan(Typeface.BOLD_ITALIC), SpannedSubject::hasBoldItalicSpanBetween);
}
@Test
public void noStyleSpan_success() {
SpannableString spannable = createSpannableWithUnrelatedSpanAnd(new StyleSpan(Typeface.ITALIC));
assertThat(spannable).hasNoStyleSpanBetween(UNRELATED_SPAN_START, UNRELATED_SPAN_END);
}
@Test
public void noStyleSpan_failure() {
checkHasNoSpanFails(new StyleSpan(Typeface.ITALIC), SpannedSubject::hasNoStyleSpanBetween);
}
@Test
public void underlineSpan_success() {
SpannableString spannable =
createSpannable(new UnderlineSpan(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasUnderlineSpanBetween(SPAN_START, SPAN_END)
.withFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void underlineSpan_mismatchedIndex() {
checkHasSpanFailsDueToIndexMismatch(
new UnderlineSpan(), SpannedSubject::hasUnderlineSpanBetween);
}
@Test
public void underlineSpan_mismatchedFlags() {
checkHasSpanFailsDueToFlagMismatch(
new UnderlineSpan(), SpannedSubject::hasUnderlineSpanBetween);
}
@Test
public void noUnderlineSpan_success() {
SpannableString spannable = createSpannableWithUnrelatedSpanAnd(new UnderlineSpan());
assertThat(spannable).hasNoUnderlineSpanBetween(UNRELATED_SPAN_START, UNRELATED_SPAN_END);
}
@Test
public void noUnderlineSpan_failure() {
checkHasNoSpanFails(new UnderlineSpan(), SpannedSubject::hasNoUnderlineSpanBetween);
}
@Test
public void strikethroughSpan_success() {
SpannableString spannable =
createSpannable(new StrikethroughSpan(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasStrikethroughSpanBetween(SPAN_START, SPAN_END)
.withFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void noStrikethroughSpan_success() {
SpannableString spannable = createSpannableWithUnrelatedSpanAnd(new StrikethroughSpan());
assertThat(spannable).hasNoStrikethroughSpanBetween(UNRELATED_SPAN_START, UNRELATED_SPAN_END);
}
@Test
public void noStrikethroughSpan_failure() {
checkHasNoSpanFails(new UnderlineSpan(), SpannedSubject::hasNoUnderlineSpanBetween);
}
@Test
public void alignmentSpan_success() {
SpannableString spannable =
createSpannable(
new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasAlignmentSpanBetween(SPAN_START, SPAN_END)
.withAlignment(Alignment.ALIGN_OPPOSITE)
.andFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void alignmentSpan_mismatchedIndex() {
checkHasSpanFailsDueToIndexMismatch(
new Standard(Alignment.ALIGN_CENTER), SpannedSubject::hasAlignmentSpanBetween);
}
@Test
public void alignmentSpan_wrongAlignment() {
SpannableString spannable =
createSpannable(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE));
AssertionError expected =
expectFailure(
whenTesting ->
whenTesting
.that(spannable)
.hasAlignmentSpanBetween(SPAN_START, SPAN_END)
.withAlignment(Alignment.ALIGN_CENTER));
assertThat(expected).factValue("value of").contains("alignment");
assertThat(expected).factValue("expected").contains("ALIGN_CENTER");
assertThat(expected).factValue("but was").contains("ALIGN_OPPOSITE");
}
@Test
public void alignmentSpan_wrongFlags() {
checkHasSpanFailsDueToFlagMismatch(
new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE),
(subject, start, end) ->
subject.hasAlignmentSpanBetween(start, end).withAlignment(Alignment.ALIGN_OPPOSITE));
}
@Test
public void noAlignmentSpan_success() {
SpannableString spannable =
createSpannableWithUnrelatedSpanAnd(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE));
assertThat(spannable).hasNoAlignmentSpanBetween(UNRELATED_SPAN_START, UNRELATED_SPAN_END);
}
@Test
public void noAlignmentSpan_failure() {
checkHasNoSpanFails(
new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE),
SpannedSubject::hasNoAlignmentSpanBetween);
}
@Test
public void foregroundColorSpan_success() {
SpannableString spannable =
createSpannable(new ForegroundColorSpan(Color.CYAN), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasForegroundColorSpanBetween(SPAN_START, SPAN_END)
.withColor(Color.CYAN)
.andFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void foregroundColorSpan_mismatchedIndex() {
checkHasSpanFailsDueToIndexMismatch(
new ForegroundColorSpan(Color.CYAN), SpannedSubject::hasForegroundColorSpanBetween);
}
@Test
public void foregroundColorSpan_wrongColor() {
SpannableString spannable = SpannableString.valueOf("test with cyan section");
int start = "test with ".length();
int end = start + "cyan".length();
spannable.setSpan(
new ForegroundColorSpan(Color.CYAN), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
AssertionError expected =
expectFailure(
whenTesting ->
whenTesting
.that(spannable)
.hasForegroundColorSpanBetween(start, end)
.withColor(Color.BLUE));
assertThat(expected).factValue("value of").contains("foregroundColor");
assertThat(expected).factValue("expected").contains("0xFF0000FF"); // Color.BLUE
assertThat(expected).factValue("but was").contains("0xFF00FFFF"); // Color.CYAN
}
@Test
public void foregroundColorSpan_wrongFlags() {
checkHasSpanFailsDueToFlagMismatch(
new ForegroundColorSpan(Color.CYAN),
(subject, start, end) ->
subject.hasForegroundColorSpanBetween(start, end).withColor(Color.CYAN));
}
@Test
public void noForegroundColorSpan_success() {
SpannableString spannable =
createSpannableWithUnrelatedSpanAnd(new ForegroundColorSpan(Color.CYAN));
assertThat(spannable).hasNoForegroundColorSpanBetween(UNRELATED_SPAN_START, UNRELATED_SPAN_END);
}
@Test
public void noForegroundColorSpan_failure() {
checkHasNoSpanFails(
new ForegroundColorSpan(Color.CYAN), SpannedSubject::hasNoForegroundColorSpanBetween);
}
@Test
public void backgroundColorSpan_success() {
SpannableString spannable =
createSpannable(new BackgroundColorSpan(Color.CYAN), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasBackgroundColorSpanBetween(SPAN_START, SPAN_END)
.withColor(Color.CYAN)
.andFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void backgroundColorSpan_mismatchedIndex() {
checkHasSpanFailsDueToIndexMismatch(
new BackgroundColorSpan(Color.CYAN), SpannedSubject::hasBackgroundColorSpanBetween);
}
@Test
public void backgroundColorSpan_wrongColor() {
SpannableString spannable = createSpannable(new BackgroundColorSpan(Color.CYAN));
AssertionError expected =
expectFailure(
whenTesting ->
whenTesting
.that(spannable)
.hasBackgroundColorSpanBetween(SPAN_START, SPAN_END)
.withColor(Color.BLUE));
assertThat(expected).factValue("value of").contains("backgroundColor");
assertThat(expected).factValue("expected").contains("0xFF0000FF"); // Color.BLUE
assertThat(expected).factValue("but was").contains("0xFF00FFFF"); // Color.CYAN
}
@Test
public void backgroundColorSpan_wrongFlags() {
checkHasSpanFailsDueToFlagMismatch(
new BackgroundColorSpan(Color.CYAN),
(subject, start, end) ->
subject.hasBackgroundColorSpanBetween(start, end).withColor(Color.CYAN));
}
@Test
public void noBackgroundColorSpan_success() {
SpannableString spannable =
createSpannableWithUnrelatedSpanAnd(new BackgroundColorSpan(Color.CYAN));
assertThat(spannable).hasNoBackgroundColorSpanBetween(UNRELATED_SPAN_START, UNRELATED_SPAN_END);
}
@Test
public void noBackgroundColorSpan_failure() {
checkHasNoSpanFails(
new BackgroundColorSpan(Color.CYAN), SpannedSubject::hasNoBackgroundColorSpanBetween);
}
@Test
public void typefaceSpan_success() {
SpannableString spannable =
createSpannable(new TypefaceSpan("courier"), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasTypefaceSpanBetween(SPAN_START, SPAN_END)
.withFamily("courier")
.andFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void typefaceSpan_wrongIndex() {
checkHasSpanFailsDueToIndexMismatch(
new TypefaceSpan("courier"), SpannedSubject::hasTypefaceSpanBetween);
}
@Test
public void typefaceSpan_wrongFamily() {
SpannableString spannable = createSpannable(new TypefaceSpan("courier"));
AssertionError expected =
expectFailure(
whenTesting ->
whenTesting
.that(spannable)
.hasTypefaceSpanBetween(SPAN_START, SPAN_END)
.withFamily("roboto"));
assertThat(expected).factValue("value of").contains("family");
assertThat(expected).factValue("expected").contains("roboto");
assertThat(expected).factValue("but was").contains("courier");
}
@Test
public void typefaceSpan_wrongFlags() {
checkHasSpanFailsDueToFlagMismatch(
new TypefaceSpan("courier"),
(subject, start, end) -> subject.hasTypefaceSpanBetween(start, end).withFamily("courier"));
}
@Test
public void noTypefaceSpan_success() {
SpannableString spannable = createSpannableWithUnrelatedSpanAnd(new TypefaceSpan("courier"));
assertThat(spannable).hasNoTypefaceSpanBetween(UNRELATED_SPAN_START, UNRELATED_SPAN_END);
}
@Test
public void noTypefaceSpan_failure() {
checkHasNoSpanFails(new TypefaceSpan("courier"), SpannedSubject::hasNoTypefaceSpanBetween);
}
@Test
public void absoluteSizeSpan_success() {
SpannableString spannable =
createSpannable(new AbsoluteSizeSpan(/* size= */ 5), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasAbsoluteSizeSpanBetween(SPAN_START, SPAN_END)
.withAbsoluteSize(5)
.andFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void absoluteSizeSpan_wrongIndex() {
checkHasSpanFailsDueToIndexMismatch(
new AbsoluteSizeSpan(/* size= */ 5), SpannedSubject::hasAbsoluteSizeSpanBetween);
}
@Test
public void absoluteSizeSpan_wrongSize() {
SpannableString spannable = createSpannable(new AbsoluteSizeSpan(/* size= */ 5));
AssertionError expected =
expectFailure(
whenTesting ->
whenTesting
.that(spannable)
.hasAbsoluteSizeSpanBetween(SPAN_START, SPAN_END)
.withAbsoluteSize(4));
assertThat(expected).factValue("value of").contains("absoluteSize");
assertThat(expected).factValue("expected").contains("4");
assertThat(expected).factValue("but was").contains("5");
}
@Test
public void absoluteSizeSpan_wrongFlags() {
checkHasSpanFailsDueToFlagMismatch(
new AbsoluteSizeSpan(/* size= */ 5),
(subject, start, end) ->
subject.hasAbsoluteSizeSpanBetween(start, end).withAbsoluteSize(5));
}
@Test
public void noAbsoluteSizeSpan_success() {
SpannableString spannable =
createSpannableWithUnrelatedSpanAnd(new AbsoluteSizeSpan(/* size= */ 5));
assertThat(spannable).hasNoAbsoluteSizeSpanBetween(UNRELATED_SPAN_START, UNRELATED_SPAN_END);
}
@Test
public void noAbsoluteSizeSpan_failure() {
checkHasNoSpanFails(
new AbsoluteSizeSpan(/* size= */ 5), SpannedSubject::hasNoAbsoluteSizeSpanBetween);
}
@Test
public void relativeSizeSpan_success() {
SpannableString spannable =
createSpannable(
new RelativeSizeSpan(/* proportion= */ 5), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasRelativeSizeSpanBetween(SPAN_START, SPAN_END)
.withSizeChange(5)
.andFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void relativeSizeSpan_wrongIndex() {
checkHasSpanFailsDueToIndexMismatch(
new RelativeSizeSpan(/* proportion= */ 5), SpannedSubject::hasRelativeSizeSpanBetween);
}
@Test
public void relativeSizeSpan_wrongSize() {
SpannableString spannable = createSpannable(new RelativeSizeSpan(/* proportion= */ 5));
AssertionError expected =
expectFailure(
whenTesting ->
whenTesting
.that(spannable)
.hasRelativeSizeSpanBetween(SPAN_START, SPAN_END)
.withSizeChange(4));
assertThat(expected).factValue("value of").contains("sizeChange");
assertThat(expected).factValue("expected").contains("4");
assertThat(expected).factValue("but was").contains("5");
}
@Test
public void relativeSizeSpan_wrongFlags() {
checkHasSpanFailsDueToFlagMismatch(
new RelativeSizeSpan(/* proportion= */ 5),
(subject, start, end) -> subject.hasRelativeSizeSpanBetween(start, end).withSizeChange(5));
}
@Test
public void noRelativeSizeSpan_success() {
SpannableString spannable =
createSpannableWithUnrelatedSpanAnd(new RelativeSizeSpan(/* proportion= */ 5));
assertThat(spannable).hasNoRelativeSizeSpanBetween(UNRELATED_SPAN_START, UNRELATED_SPAN_END);
}
@Test
public void noRelativeSizeSpan_failure() {
checkHasNoSpanFails(
new RelativeSizeSpan(/* proportion= */ 5), SpannedSubject::hasNoRelativeSizeSpanBetween);
}
@Test
public void rubySpan_success() {
SpannableString spannable =
createSpannable(
new RubySpan("ruby text", TextAnnotation.POSITION_BEFORE),
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasRubySpanBetween(SPAN_START, SPAN_END)
.withTextAndPosition("ruby text", TextAnnotation.POSITION_BEFORE)
.andFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void rubySpan_wrongEndIndex() {
checkHasSpanFailsDueToIndexMismatch(
new RubySpan("ruby text", TextAnnotation.POSITION_BEFORE),
SpannedSubject::hasRubySpanBetween);
}
@Test
public void rubySpan_wrongText() {
SpannableString spannable =
createSpannable(new RubySpan("ruby text", TextAnnotation.POSITION_BEFORE));
AssertionError expected =
expectFailure(
whenTesting ->
whenTesting
.that(spannable)
.hasRubySpanBetween(SPAN_START, SPAN_END)
.withTextAndPosition("incorrect text", TextAnnotation.POSITION_BEFORE));
assertThat(expected).factValue("value of").contains("rubyTextAndPosition");
assertThat(expected).factValue("expected").contains("text='incorrect text'");
assertThat(expected).factValue("but was").contains("text='ruby text'");
}
@Test
public void rubySpan_wrongPosition() {
SpannableString spannable =
createSpannable(new RubySpan("ruby text", TextAnnotation.POSITION_BEFORE));
AssertionError expected =
expectFailure(
whenTesting ->
whenTesting
.that(spannable)
.hasRubySpanBetween(SPAN_START, SPAN_END)
.withTextAndPosition("ruby text", TextAnnotation.POSITION_AFTER));
assertThat(expected).factValue("value of").contains("rubyTextAndPosition");
assertThat(expected)
.factValue("expected")
.contains("position=" + TextAnnotation.POSITION_AFTER);
assertThat(expected)
.factValue("but was")
.contains("position=" + TextAnnotation.POSITION_BEFORE);
}
@Test
public void rubySpan_wrongFlags() {
checkHasSpanFailsDueToFlagMismatch(
new RubySpan("ruby text", TextAnnotation.POSITION_BEFORE),
(subject, start, end) ->
subject
.hasRubySpanBetween(start, end)
.withTextAndPosition("ruby text", TextAnnotation.POSITION_BEFORE));
}
@Test
public void noRubySpan_success() {
SpannableString spannable =
createSpannableWithUnrelatedSpanAnd(
new RubySpan("ruby text", TextAnnotation.POSITION_BEFORE));
assertThat(spannable).hasNoRubySpanBetween(UNRELATED_SPAN_START, UNRELATED_SPAN_END);
}
@Test
public void noRubySpan_failure() {
checkHasNoSpanFails(
new RubySpan("ruby text", TextAnnotation.POSITION_BEFORE),
SpannedSubject::hasNoRubySpanBetween);
}
@Test
public void textEmphasis_success() {
SpannableString spannable =
createSpannable(
new TextEmphasisSpan(
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER));
assertThat(spannable)
.hasTextEmphasisSpanBetween(SPAN_START, SPAN_END)
.withMarkAndPosition(
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER)
.andFlags(Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
@Test
public void textEmphasis_wrongIndex() {
checkHasSpanFailsDueToIndexMismatch(
new TextEmphasisSpan(
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER),
SpannedSubject::hasTextEmphasisSpanBetween);
}
@Test
public void textEmphasis_wrongMarkShape() {
SpannableString spannable =
createSpannable(
new TextEmphasisSpan(
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER));
AssertionError expected =
expectFailure(
whenTesting ->
whenTesting
.that(spannable)
.hasTextEmphasisSpanBetween(SPAN_START, SPAN_END)
.withMarkAndPosition(
TextEmphasisSpan.MARK_SHAPE_SESAME,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER));
assertThat(expected).factValue("value of").contains("textEmphasisMarkAndPosition");
assertThat(expected)
.factValue("expected")
.contains(
Util.formatInvariant(
"{markShape=%d,markFill=%d,position=%d}",
TextEmphasisSpan.MARK_SHAPE_SESAME,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER));
assertThat(expected)
.factValue("but was")
.contains(
Util.formatInvariant(
"{markShape=%d,markFill=%d,position=%d}",
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER));
}
@Test
public void textEmphasis_wrongMarkFill() {
SpannableString spannable =
createSpannable(
new TextEmphasisSpan(
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER));
AssertionError expected =
expectFailure(
whenTesting ->
whenTesting
.that(spannable)
.hasTextEmphasisSpanBetween(SPAN_START, SPAN_END)
.withMarkAndPosition(
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_OPEN,
TextAnnotation.POSITION_AFTER));
assertThat(expected).factValue("value of").contains("textEmphasisMarkAndPosition");
assertThat(expected)
.factValue("expected")
.contains(
Util.formatInvariant(
"{markShape=%d,markFill=%d,position=%d}",
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_OPEN,
TextAnnotation.POSITION_AFTER));
assertThat(expected)
.factValue("but was")
.contains(
Util.formatInvariant(
"{markShape=%d,markFill=%d,position=%d}",
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER));
}
@Test
public void textEmphasis_wrongPosition() {
SpannableString spannable =
createSpannable(
new TextEmphasisSpan(
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_BEFORE));
AssertionError expected =
expectFailure(
whenTesting ->
whenTesting
.that(spannable)
.hasTextEmphasisSpanBetween(SPAN_START, SPAN_END)
.withMarkAndPosition(
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER));
assertThat(expected).factValue("value of").contains("textEmphasisMarkAndPosition");
assertThat(expected)
.factValue("expected")
.contains(
Util.formatInvariant(
"{markShape=%d,markFill=%d,position=%d}",
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER));
assertThat(expected)
.factValue("but was")
.contains(
Util.formatInvariant(
"{markShape=%d,markFill=%d,position=%d}",
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_BEFORE));
}
@Test
public void textEmphasis_wrongFlags() {
checkHasSpanFailsDueToFlagMismatch(
new TextEmphasisSpan(
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER),
(subject, start, end) ->
subject
.hasTextEmphasisSpanBetween(start, end)
.withMarkAndPosition(
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER));
}
@Test
public void noTextEmphasis_success() {
SpannableString spannable =
createSpannableWithUnrelatedSpanAnd(
new TextEmphasisSpan(
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER));
assertThat(spannable).hasNoTextEmphasisSpanBetween(UNRELATED_SPAN_START, UNRELATED_SPAN_END);
}
@Test
public void noTextEmphasis_failure() {
checkHasNoSpanFails(
new TextEmphasisSpan(
TextEmphasisSpan.MARK_SHAPE_CIRCLE,
TextEmphasisSpan.MARK_FILL_FILLED,
TextAnnotation.POSITION_AFTER),
SpannedSubject::hasNoTextEmphasisSpanBetween);
}
@Test
public void horizontalTextInVerticalContextSpan_success() {
SpannableString spannable =
createSpannable(
new HorizontalTextInVerticalContextSpan(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
assertThat(spannable)
.hasHorizontalTextInVerticalContextSpanBetween(SPAN_START, SPAN_END)
.withFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
@Test
public void noHorizontalTextInVerticalContextSpan_success() {
SpannableString spannable =
createSpannableWithUnrelatedSpanAnd(new HorizontalTextInVerticalContextSpan());
assertThat(spannable)
.hasNoHorizontalTextInVerticalContextSpanBetween(UNRELATED_SPAN_START, UNRELATED_SPAN_END);
}
@Test
public void noHorizontalTextInVerticalContextSpan_failure() {
checkHasNoSpanFails(
new HorizontalTextInVerticalContextSpan(),
SpannedSubject::hasNoHorizontalTextInVerticalContextSpanBetween);
}
private interface HasSpanFunction<T> {
T call(SpannedSubject s, int start, int end);
}
private static <T> void checkHasSpanFailsDueToIndexMismatch(
Object spanToInsert, HasSpanFunction<T> hasSpanFunction) {
SpannableString spannable = createSpannable(spanToInsert);
spannable.setSpan(spanToInsert, SPAN_START, SPAN_END, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
int incorrectStart = SPAN_START + 1;
AssertionError expected =
expectFailure(
whenTesting -> {
SpannedSubject subject = whenTesting.that(spannable);
hasSpanFunction.call(subject, incorrectStart, SPAN_END);
});
assertThat(expected).factValue("expected").contains("start=" + incorrectStart);
assertThat(expected).factValue("but found").contains("start=" + SPAN_START);
assertThat(expected).factValue("but found").contains(spanToInsert.getClass().getSimpleName());
}
private static void checkHasSpanFailsDueToFlagMismatch(
Object spanToInsert, HasSpanFunction<?> hasSpanFunction) {
SpannableString spannable = createSpannable(spanToInsert, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
AssertionError failure =
expectFailure(
whenTesting -> {
SpannedSubject subject = whenTesting.that(spannable);
Object withOrAndFlags = hasSpanFunction.call(subject, SPAN_START, SPAN_END);
if (withOrAndFlags instanceof WithSpanFlags) {
((WithSpanFlags) withOrAndFlags).withFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
} else if (withOrAndFlags instanceof AndSpanFlags) {
((AndSpanFlags) withOrAndFlags).andFlags(Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
} else {
throw new AssertionError(
"Unexpected return type: " + withOrAndFlags.getClass().getCanonicalName());
}
});
assertThat(failure)
.factValue("value of")
.contains(String.format("start=%s,end=%s", SPAN_START, SPAN_END));
assertThat(failure)
.factValue("expected to contain")
.contains(String.valueOf(Spanned.SPAN_INCLUSIVE_EXCLUSIVE));
assertThat(failure)
.factValue("but was")
.contains(String.valueOf(Spanned.SPAN_EXCLUSIVE_EXCLUSIVE));
}
private interface HasNoSpanFunction<T> {
void call(SpannedSubject s, int start, int end);
}
private static <T> void checkHasNoSpanFails(
Object spanToInsert, HasNoSpanFunction<T> hasNoSpanFunction) {
SpannableString spannable = createSpannable(spanToInsert);
AssertionError expected =
expectFailure(
whenTesting -> {
SpannedSubject subject = whenTesting.that(spannable);
hasNoSpanFunction.call(subject, SPAN_START, SPAN_END);
});
assertThat(expected).factKeys().contains("expected none");
assertThat(expected).factValue("but found").contains("start=" + SPAN_START);
}
private static SpannableString createSpannable(Object spanToInsert) {
return createSpannable(spanToInsert, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
private static SpannableString createSpannable(Object spanToInsert, int spanFlags) {
SpannableString spannable = SpannableString.valueOf(TEXT_WITH_TARGET_SPAN);
spannable.setSpan(spanToInsert, SPAN_START, SPAN_END, spanFlags);
return spannable;
}
private static SpannableString createSpannableWithUnrelatedSpanAnd(Object spanToInsert) {
SpannableString spannable = SpannableString.valueOf(TEXT_WITH_TARGET_AND_UNRELATED_SPAN);
spannable.setSpan(spanToInsert, SPAN_START, SPAN_END, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(
new Object(), UNRELATED_SPAN_START, UNRELATED_SPAN_END, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannable;
}
private static AssertionError expectFailure(
ExpectFailure.SimpleSubjectBuilderCallback<SpannedSubject, Spanned> callback) {
return expectFailureAbout(spanned(), callback);
}
}
|
apache/giraph | 35,644 | giraph-core/src/main/java/org/apache/giraph/bsp/BspService.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.giraph.bsp;
import org.apache.giraph.conf.GiraphConstants;
import org.apache.giraph.conf.ImmutableClassesGiraphConfiguration;
import org.apache.giraph.graph.GraphTaskManager;
import org.apache.giraph.job.JobProgressTracker;
import org.apache.giraph.partition.GraphPartitionerFactory;
import org.apache.giraph.utils.CheckpointingUtils;
import org.apache.giraph.worker.WorkerInfo;
import org.apache.giraph.writable.kryo.GiraphClassResolver;
import org.apache.giraph.zk.BspEvent;
import org.apache.giraph.zk.PredicateLock;
import org.apache.giraph.zk.ZooKeeperExt;
import org.apache.giraph.zk.ZooKeeperManager;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.apache.giraph.conf.GiraphConstants.RESTART_JOB_ID;
/**
* Zookeeper-based implementation of {@link CentralizedService}.
*
* @param <I> Vertex id
* @param <V> Vertex data
* @param <E> Edge data
*/
@SuppressWarnings("rawtypes")
public abstract class BspService<I extends WritableComparable,
V extends Writable, E extends Writable>
implements Watcher, CentralizedService<I, V, E> {
/** Unset superstep */
public static final long UNSET_SUPERSTEP = Long.MIN_VALUE;
/** Input superstep (superstep when loading the vertices happens) */
public static final long INPUT_SUPERSTEP = -1;
/** Unset application attempt */
public static final long UNSET_APPLICATION_ATTEMPT = Long.MIN_VALUE;
/** Base ZooKeeper directory */
public static final String BASE_DIR = "/_hadoopBsp";
/** Master job state znode above base dir */
public static final String MASTER_JOB_STATE_NODE = "/_masterJobState";
/** Input splits worker done directory */
public static final String INPUT_SPLITS_WORKER_DONE_DIR =
"/_inputSplitsWorkerDoneDir";
/** Input splits all done node*/
public static final String INPUT_SPLITS_ALL_DONE_NODE =
"/_inputSplitsAllDone";
/** Directory to store kryo className-ID assignment */
public static final String KRYO_REGISTERED_CLASS_DIR =
"/_kryo";
/** Directory of attempts of this application */
public static final String APPLICATION_ATTEMPTS_DIR =
"/_applicationAttemptsDir";
/** Where the master election happens */
public static final String MASTER_ELECTION_DIR = "/_masterElectionDir";
/** Superstep scope */
public static final String SUPERSTEP_DIR = "/_superstepDir";
/** Counter sub directory */
public static final String COUNTERS_DIR = "/_counters";
/** Metrics sub directory */
public static final String METRICS_DIR = "/_metrics";
/** Healthy workers register here. */
public static final String WORKER_HEALTHY_DIR = "/_workerHealthyDir";
/** Unhealthy workers register here. */
public static final String WORKER_UNHEALTHY_DIR = "/_workerUnhealthyDir";
/** Workers which wrote checkpoint notify here */
public static final String WORKER_WROTE_CHECKPOINT_DIR =
"/_workerWroteCheckpointDir";
/** Finished workers notify here */
public static final String WORKER_FINISHED_DIR = "/_workerFinishedDir";
/** Helps coordinate the partition exchnages */
public static final String PARTITION_EXCHANGE_DIR =
"/_partitionExchangeDir";
/** Denotes that the superstep is done */
public static final String SUPERSTEP_FINISHED_NODE = "/_superstepFinished";
/** Denotes that computation should be halted */
public static final String HALT_COMPUTATION_NODE = "/_haltComputation";
/** Memory observer dir */
public static final String MEMORY_OBSERVER_DIR = "/_memoryObserver";
/** User sets this flag to checkpoint and stop the job */
public static final String FORCE_CHECKPOINT_USER_FLAG = "/_checkpointAndStop";
/** Denotes which workers have been cleaned up */
public static final String CLEANED_UP_DIR = "/_cleanedUpDir";
/** JSON message count key */
public static final String JSONOBJ_NUM_MESSAGES_KEY = "_numMsgsKey";
/** JSON message bytes count key */
public static final String JSONOBJ_NUM_MESSAGE_BYTES_KEY = "_numMsgBytesKey";
/** JSON metrics key */
public static final String JSONOBJ_METRICS_KEY = "_metricsKey";
/** JSON state key */
public static final String JSONOBJ_STATE_KEY = "_stateKey";
/** JSON application attempt key */
public static final String JSONOBJ_APPLICATION_ATTEMPT_KEY =
"_applicationAttemptKey";
/** JSON superstep key */
public static final String JSONOBJ_SUPERSTEP_KEY =
"_superstepKey";
/** Suffix denotes a worker */
public static final String WORKER_SUFFIX = "_worker";
/** Suffix denotes a master */
public static final String MASTER_SUFFIX = "_master";
/** Class logger */
private static final Logger LOG = Logger.getLogger(BspService.class);
/** Path to the job's root */
protected final String basePath;
/** Path to the job state determined by the master (informative only) */
protected final String masterJobStatePath;
/** Input splits worker done directory */
protected final String inputSplitsWorkerDonePath;
/** Input splits all done node */
protected final String inputSplitsAllDonePath;
/** Path to the application attempts) */
protected final String applicationAttemptsPath;
/** Path to the cleaned up notifications */
protected final String cleanedUpPath;
/** Path to the checkpoint's root (including job id) */
protected final String checkpointBasePath;
/** Old checkpoint in case we want to restart some job */
protected final String savedCheckpointBasePath;
/** Path to the master election path */
protected final String masterElectionPath;
/** If this path exists computation will be halted */
protected final String haltComputationPath;
/** Path where memory observer stores data */
protected final String memoryObserverPath;
/** Kryo className-ID mapping directory */
protected final String kryoRegisteredClassPath;
/** Private ZooKeeper instance that implements the service */
private final ZooKeeperExt zk;
/** Has the Connection occurred? */
private final BspEvent connectedEvent;
/** Has worker registration changed (either healthy or unhealthy) */
private final BspEvent workerHealthRegistrationChanged;
/** Application attempt changed */
private final BspEvent applicationAttemptChanged;
/** Input splits worker done */
private final BspEvent inputSplitsWorkerDoneEvent;
/** Input splits all done */
private final BspEvent inputSplitsAllDoneEvent;
/** Superstep finished synchronization */
private final BspEvent superstepFinished;
/** Master election changed for any waited on attempt */
private final BspEvent masterElectionChildrenChanged;
/** Cleaned up directory children changed*/
private final BspEvent cleanedUpChildrenChanged;
/** Event to synchronize when workers have written their counters to the
* zookeeper*/
private final BspEvent writtenCountersToZK;
/** Registered list of BspEvents */
private final List<BspEvent> registeredBspEvents =
new ArrayList<BspEvent>();
/** Immutable configuration of the job*/
private final ImmutableClassesGiraphConfiguration<I, V, E> conf;
/** Job context (mainly for progress) */
private final Mapper<?, ?, ?, ?>.Context context;
/** Cached superstep (from ZooKeeper) */
private long cachedSuperstep = UNSET_SUPERSTEP;
/** Restarted from a checkpoint (manual or automatic) */
private long restartedSuperstep = UNSET_SUPERSTEP;
/** Cached application attempt (from ZooKeeper) */
private long cachedApplicationAttempt = UNSET_APPLICATION_ATTEMPT;
/** Job id, to ensure uniqueness */
private final String jobId;
/** Task id, from partition and application attempt to ensure uniqueness */
private final int taskId;
/** My hostname */
private final String hostname;
/** Combination of hostname '_' task (unique id) */
private final String hostnameTaskId;
/** Graph partitioner */
private final GraphPartitionerFactory<I, V, E> graphPartitionerFactory;
/** Mapper that will do the graph computation */
private final GraphTaskManager<I, V, E> graphTaskManager;
/** File system */
private final FileSystem fs;
/**
* Constructor.
*
* @param context Mapper context
* @param graphTaskManager GraphTaskManager for this compute node
*/
public BspService(
Mapper<?, ?, ?, ?>.Context context,
GraphTaskManager<I, V, E> graphTaskManager) {
this.connectedEvent = new PredicateLock(context);
this.workerHealthRegistrationChanged = new PredicateLock(context);
this.applicationAttemptChanged = new PredicateLock(context);
this.inputSplitsWorkerDoneEvent = new PredicateLock(context);
this.inputSplitsAllDoneEvent = new PredicateLock(context);
this.superstepFinished = new PredicateLock(context);
this.masterElectionChildrenChanged = new PredicateLock(context);
this.cleanedUpChildrenChanged = new PredicateLock(context);
this.writtenCountersToZK = new PredicateLock(context);
registerBspEvent(connectedEvent);
registerBspEvent(workerHealthRegistrationChanged);
registerBspEvent(inputSplitsWorkerDoneEvent);
registerBspEvent(inputSplitsAllDoneEvent);
registerBspEvent(applicationAttemptChanged);
registerBspEvent(superstepFinished);
registerBspEvent(masterElectionChildrenChanged);
registerBspEvent(cleanedUpChildrenChanged);
registerBspEvent(writtenCountersToZK);
this.context = context;
this.graphTaskManager = graphTaskManager;
this.conf = graphTaskManager.getConf();
this.jobId = conf.getJobId();
this.restartedSuperstep = conf.getLong(
GiraphConstants.RESTART_SUPERSTEP, UNSET_SUPERSTEP);
try {
this.hostname = conf.getLocalHostname();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
this.graphPartitionerFactory = conf.createGraphPartitioner();
basePath = ZooKeeperManager.getBasePath(conf) + BASE_DIR + "/" + jobId;
if (LOG.isInfoEnabled()) {
LOG.info(String.format("%s: %s",
GiraphConstants.ZOOKEEPER_BASE_PATH_COUNTER_GROUP, basePath));
}
masterJobStatePath = basePath + MASTER_JOB_STATE_NODE;
inputSplitsWorkerDonePath = basePath + INPUT_SPLITS_WORKER_DONE_DIR;
inputSplitsAllDonePath = basePath + INPUT_SPLITS_ALL_DONE_NODE;
applicationAttemptsPath = basePath + APPLICATION_ATTEMPTS_DIR;
cleanedUpPath = basePath + CLEANED_UP_DIR;
kryoRegisteredClassPath = basePath + KRYO_REGISTERED_CLASS_DIR;
String restartJobId = RESTART_JOB_ID.get(conf);
savedCheckpointBasePath =
CheckpointingUtils.getCheckpointBasePath(getConfiguration(),
restartJobId == null ? getJobId() : restartJobId);
checkpointBasePath = CheckpointingUtils.
getCheckpointBasePath(getConfiguration(), getJobId());
masterElectionPath = basePath + MASTER_ELECTION_DIR;
String serverPortList = graphTaskManager.getZookeeperList();
haltComputationPath = basePath + HALT_COMPUTATION_NODE;
memoryObserverPath = basePath + MEMORY_OBSERVER_DIR;
getContext().getCounter(GiraphConstants.ZOOKEEPER_HALT_NODE_COUNTER_GROUP,
haltComputationPath);
if (LOG.isInfoEnabled()) {
LOG.info("BspService: Path to create to halt is " + haltComputationPath);
}
if (LOG.isInfoEnabled()) {
LOG.info("BspService: Connecting to ZooKeeper with job " + jobId +
", partition " + conf.getTaskPartition() + " on " + serverPortList);
}
try {
this.zk = new ZooKeeperExt(serverPortList,
conf.getZooKeeperSessionTimeout(),
conf.getZookeeperOpsMaxAttempts(),
conf.getZookeeperOpsRetryWaitMsecs(),
this,
context);
connectedEvent.waitForTimeoutOrFail(
GiraphConstants.WAIT_ZOOKEEPER_TIMEOUT_MSEC.get(conf));
this.fs = FileSystem.get(getConfiguration());
} catch (IOException e) {
throw new RuntimeException(e);
}
boolean disableGiraphResolver =
GiraphConstants.DISABLE_GIRAPH_CLASS_RESOLVER.get(conf);
if (!disableGiraphResolver) {
GiraphClassResolver.setZookeeperInfo(zk, kryoRegisteredClassPath);
}
this.taskId = (int) getApplicationAttempt() * conf.getMaxWorkers() +
conf.getTaskPartition();
this.hostnameTaskId = hostname + "_" + getTaskId();
//Trying to restart from the latest superstep
if (restartJobId != null &&
restartedSuperstep == UNSET_SUPERSTEP) {
try {
restartedSuperstep = getLastCheckpointedSuperstep();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
this.cachedSuperstep = restartedSuperstep;
if ((restartedSuperstep != UNSET_SUPERSTEP) &&
(restartedSuperstep < 0)) {
throw new IllegalArgumentException(
"BspService: Invalid superstep to restart - " +
restartedSuperstep);
}
}
/**
* Get the superstep from a ZooKeeper path
*
* @param path Path to parse for the superstep
* @return Superstep from the path.
*/
public static long getSuperstepFromPath(String path) {
int foundSuperstepStart = path.indexOf(SUPERSTEP_DIR);
if (foundSuperstepStart == -1) {
throw new IllegalArgumentException(
"getSuperstepFromPath: Cannot find " + SUPERSTEP_DIR +
"from " + path);
}
foundSuperstepStart += SUPERSTEP_DIR.length() + 1;
int endIndex = foundSuperstepStart +
path.substring(foundSuperstepStart).indexOf("/");
if (endIndex == -1) {
throw new IllegalArgumentException(
"getSuperstepFromPath: Cannot find end of superstep from " +
path);
}
if (LOG.isTraceEnabled()) {
LOG.trace("getSuperstepFromPath: Got path=" + path +
", start=" + foundSuperstepStart + ", end=" + endIndex);
}
return Long.parseLong(path.substring(foundSuperstepStart, endIndex));
}
/**
* Get the hostname and id from a "healthy" worker path
*
* @param path Path to check
* @return Hostname and id from path
*/
public static String getHealthyHostnameIdFromPath(String path) {
int foundWorkerHealthyStart = path.indexOf(WORKER_HEALTHY_DIR);
if (foundWorkerHealthyStart == -1) {
throw new IllegalArgumentException(
"getHealthyHostnameidFromPath: Couldn't find " +
WORKER_HEALTHY_DIR + " from " + path);
}
foundWorkerHealthyStart += WORKER_HEALTHY_DIR.length();
return path.substring(foundWorkerHealthyStart);
}
/**
* Generate the base superstep directory path for a given application
* attempt
*
* @param attempt application attempt number
* @return directory path based on the an attempt
*/
public final String getSuperstepPath(long attempt) {
return applicationAttemptsPath + "/" + attempt + SUPERSTEP_DIR;
}
/**
* Generate the worker information "healthy" directory path for a
* superstep
*
* @param attempt application attempt number
* @param superstep superstep to use
* @return directory path based on the a superstep
*/
public final String getWorkerInfoHealthyPath(long attempt,
long superstep) {
return applicationAttemptsPath + "/" + attempt +
SUPERSTEP_DIR + "/" + superstep + WORKER_HEALTHY_DIR;
}
/**
* Generate the worker information "unhealthy" directory path for a
* superstep
*
* @param attempt application attempt number
* @param superstep superstep to use
* @return directory path based on the a superstep
*/
public final String getWorkerInfoUnhealthyPath(long attempt,
long superstep) {
return applicationAttemptsPath + "/" + attempt +
SUPERSTEP_DIR + "/" + superstep + WORKER_UNHEALTHY_DIR;
}
/**
* Generate the worker "wrote checkpoint" directory path for a
* superstep
*
* @param attempt application attempt number
* @param superstep superstep to use
* @return directory path based on the a superstep
*/
public final String getWorkerWroteCheckpointPath(long attempt,
long superstep) {
return applicationAttemptsPath + "/" + attempt +
SUPERSTEP_DIR + "/" + superstep + WORKER_WROTE_CHECKPOINT_DIR;
}
/**
* Generate the worker "finished" directory path for a
* superstep, for storing the superstep-related metrics
*
* @param attempt application attempt number
* @param superstep superstep to use
* @return directory path based on the a superstep
*/
public final String getWorkerMetricsFinishedPath(
long attempt, long superstep) {
return applicationAttemptsPath + "/" + attempt +
SUPERSTEP_DIR + "/" + superstep + WORKER_FINISHED_DIR + METRICS_DIR;
}
/**
* Generate the worker "finished" directory path for a
* superstep, for storing the superstep-related counters
*
* @param attempt application attempt number
* @param superstep superstep to use
* @return directory path based on the a superstep
*/
public final String getWorkerCountersFinishedPath(
long attempt, long superstep) {
return applicationAttemptsPath + "/" + attempt +
SUPERSTEP_DIR + "/" + superstep +
WORKER_FINISHED_DIR + COUNTERS_DIR;
}
/**
* Generate the "partition exchange" directory path for a superstep
*
* @param attempt application attempt number
* @param superstep superstep to use
* @return directory path based on the a superstep
*/
public final String getPartitionExchangePath(long attempt,
long superstep) {
return applicationAttemptsPath + "/" + attempt +
SUPERSTEP_DIR + "/" + superstep + PARTITION_EXCHANGE_DIR;
}
/**
* Based on the superstep, worker info, and attempt, get the appropriate
* worker path for the exchange.
*
* @param attempt Application attempt
* @param superstep Superstep
* @param workerInfo Worker info of the exchange.
* @return Path of the desired worker
*/
public final String getPartitionExchangeWorkerPath(long attempt,
long superstep,
WorkerInfo workerInfo) {
return getPartitionExchangePath(attempt, superstep) +
"/" + workerInfo.getHostnameId();
}
/**
* Generate the "superstep finished" directory path for a superstep
*
* @param attempt application attempt number
* @param superstep superstep to use
* @return directory path based on the a superstep
*/
public final String getSuperstepFinishedPath(long attempt, long superstep) {
return applicationAttemptsPath + "/" + attempt +
SUPERSTEP_DIR + "/" + superstep + SUPERSTEP_FINISHED_NODE;
}
/**
* Generate the base superstep directory path for a given application
* attempt
*
* @param superstep Superstep to use
* @return Directory path based on the a superstep
*/
public final String getCheckpointBasePath(long superstep) {
return checkpointBasePath + "/" + superstep;
}
/**
* In case when we restart another job this will give us a path
* to saved checkpoint.
* @param superstep superstep to use
* @return Direcory path for restarted job based on the superstep
*/
public final String getSavedCheckpointBasePath(long superstep) {
return savedCheckpointBasePath + "/" + superstep;
}
/**
* Get the ZooKeeperExt instance.
*
* @return ZooKeeperExt instance.
*/
public final ZooKeeperExt getZkExt() {
return zk;
}
@Override
public final long getRestartedSuperstep() {
return restartedSuperstep;
}
/**
* Set the restarted superstep
*
* @param superstep Set the manually restarted superstep
*/
public final void setRestartedSuperstep(long superstep) {
if (superstep < INPUT_SUPERSTEP) {
throw new IllegalArgumentException(
"setRestartedSuperstep: Bad argument " + superstep);
}
restartedSuperstep = superstep;
}
/**
* Get the file system
*
* @return file system
*/
public final FileSystem getFs() {
return fs;
}
public final ImmutableClassesGiraphConfiguration<I, V, E>
getConfiguration() {
return conf;
}
public final Mapper<?, ?, ?, ?>.Context getContext() {
return context;
}
public final String getHostname() {
return hostname;
}
public final String getHostnameTaskId() {
return hostnameTaskId;
}
public final int getTaskId() {
return taskId;
}
public final GraphTaskManager<I, V, E> getGraphTaskManager() {
return graphTaskManager;
}
public final BspEvent getWorkerHealthRegistrationChangedEvent() {
return workerHealthRegistrationChanged;
}
public final BspEvent getApplicationAttemptChangedEvent() {
return applicationAttemptChanged;
}
public final BspEvent getInputSplitsWorkerDoneEvent() {
return inputSplitsWorkerDoneEvent;
}
public final BspEvent getInputSplitsAllDoneEvent() {
return inputSplitsAllDoneEvent;
}
public final BspEvent getSuperstepFinishedEvent() {
return superstepFinished;
}
public final BspEvent getMasterElectionChildrenChangedEvent() {
return masterElectionChildrenChanged;
}
public final BspEvent getCleanedUpChildrenChangedEvent() {
return cleanedUpChildrenChanged;
}
public final BspEvent getWrittenCountersToZKEvent() {
return writtenCountersToZK;
}
/**
* Get the master commanded job state as a JSONObject. Also sets the
* watches to see if the master commanded job state changes.
*
* @return Last job state or null if none
*/
public final JSONObject getJobState() {
try {
getZkExt().createExt(masterJobStatePath,
null,
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT,
true);
} catch (KeeperException.NodeExistsException e) {
LOG.info("getJobState: Job state already exists (" +
masterJobStatePath + ")");
} catch (KeeperException e) {
throw new IllegalStateException("Failed to create job state path " +
"due to KeeperException", e);
} catch (InterruptedException e) {
throw new IllegalStateException("Failed to create job state path " +
"due to InterruptedException", e);
}
String jobState = null;
try {
List<String> childList =
getZkExt().getChildrenExt(
masterJobStatePath, true, true, true);
if (childList.isEmpty()) {
return null;
}
jobState =
new String(getZkExt().getData(childList.get(childList.size() - 1),
true, null), Charset.defaultCharset());
} catch (KeeperException.NoNodeException e) {
LOG.info("getJobState: Job state path is empty! - " +
masterJobStatePath);
} catch (KeeperException e) {
throw new IllegalStateException("Failed to get job state path " +
"children due to KeeperException", e);
} catch (InterruptedException e) {
throw new IllegalStateException("Failed to get job state path " +
"children due to InterruptedException", e);
}
try {
return new JSONObject(jobState);
} catch (JSONException e) {
throw new RuntimeException(
"getJobState: Failed to parse job state " + jobState);
}
}
/**
* Get the job id
*
* @return job id
*/
public final String getJobId() {
return jobId;
}
/**
* Get the latest application attempt and cache it.
*
* @return the latest application attempt
*/
public final long getApplicationAttempt() {
if (cachedApplicationAttempt != UNSET_APPLICATION_ATTEMPT) {
return cachedApplicationAttempt;
}
try {
getZkExt().createExt(applicationAttemptsPath,
null,
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT,
true);
} catch (KeeperException.NodeExistsException e) {
LOG.info("getApplicationAttempt: Node " +
applicationAttemptsPath + " already exists!");
} catch (KeeperException e) {
throw new IllegalStateException("Couldn't create application " +
"attempts path due to KeeperException", e);
} catch (InterruptedException e) {
throw new IllegalStateException("Couldn't create application " +
"attempts path due to InterruptedException", e);
}
try {
List<String> attemptList =
getZkExt().getChildrenExt(
applicationAttemptsPath, true, false, false);
if (attemptList.isEmpty()) {
cachedApplicationAttempt = 0;
} else {
cachedApplicationAttempt =
Long.parseLong(Collections.max(attemptList));
}
} catch (KeeperException e) {
throw new IllegalStateException("Couldn't get application " +
"attempts to KeeperException", e);
} catch (InterruptedException e) {
throw new IllegalStateException("Couldn't get application " +
"attempts to InterruptedException", e);
}
return cachedApplicationAttempt;
}
/**
* Get the latest superstep and cache it.
*
* @return the latest superstep
*/
public final long getSuperstep() {
if (cachedSuperstep != UNSET_SUPERSTEP) {
return cachedSuperstep;
}
String superstepPath = getSuperstepPath(getApplicationAttempt());
try {
getZkExt().createExt(superstepPath,
null,
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT,
true);
} catch (KeeperException.NodeExistsException e) {
if (LOG.isInfoEnabled()) {
LOG.info("getApplicationAttempt: Node " +
applicationAttemptsPath + " already exists!");
}
} catch (KeeperException e) {
throw new IllegalStateException(
"getSuperstep: KeeperException", e);
} catch (InterruptedException e) {
throw new IllegalStateException(
"getSuperstep: InterruptedException", e);
}
List<String> superstepList;
try {
superstepList =
getZkExt().getChildrenExt(superstepPath, true, false, false);
} catch (KeeperException e) {
throw new IllegalStateException(
"getSuperstep: KeeperException", e);
} catch (InterruptedException e) {
throw new IllegalStateException(
"getSuperstep: InterruptedException", e);
}
if (superstepList.isEmpty()) {
cachedSuperstep = INPUT_SUPERSTEP;
} else {
cachedSuperstep =
Long.parseLong(Collections.max(superstepList));
}
return cachedSuperstep;
}
/**
* Increment the cached superstep. Shouldn't be the initial value anymore.
*/
public final void incrCachedSuperstep() {
if (cachedSuperstep == UNSET_SUPERSTEP) {
throw new IllegalStateException(
"incrSuperstep: Invalid unset cached superstep " +
UNSET_SUPERSTEP);
}
++cachedSuperstep;
}
/**
* Set the cached superstep (should only be used for loading checkpoints
* or recovering from failure).
*
* @param superstep will be used as the next superstep iteration
*/
public final void setCachedSuperstep(long superstep) {
cachedSuperstep = superstep;
}
/**
* Set the cached application attempt (should only be used for restart from
* failure by the master)
*
* @param applicationAttempt Will denote the new application attempt
*/
public final void setApplicationAttempt(long applicationAttempt) {
cachedApplicationAttempt = applicationAttempt;
String superstepPath = getSuperstepPath(cachedApplicationAttempt);
try {
getZkExt().createExt(superstepPath,
null,
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT,
true);
} catch (KeeperException.NodeExistsException e) {
throw new IllegalArgumentException(
"setApplicationAttempt: Attempt already exists! - " +
superstepPath, e);
} catch (KeeperException e) {
throw new RuntimeException(
"setApplicationAttempt: KeeperException - " +
superstepPath, e);
} catch (InterruptedException e) {
throw new RuntimeException(
"setApplicationAttempt: InterruptedException - " +
superstepPath, e);
}
}
/**
* Register a BspEvent. Ensure that it will be signaled
* by catastrophic failure so that threads waiting on an event signal
* will be unblocked.
*
* @param event Event to be registered.
*/
public void registerBspEvent(BspEvent event) {
registeredBspEvents.add(event);
}
/**
* Subclasses can use this to instantiate their respective partitioners
*
* @return Instantiated graph partitioner factory
*/
protected GraphPartitionerFactory<I, V, E> getGraphPartitionerFactory() {
return graphPartitionerFactory;
}
/**
* Derived classes that want additional ZooKeeper events to take action
* should override this.
*
* @param event Event that occurred
* @return true if the event was processed here, false otherwise
*/
protected boolean processEvent(WatchedEvent event) {
return false;
}
@Override
public final void process(WatchedEvent event) {
// 1. Process all shared events
// 2. Process specific derived class events
if (LOG.isDebugEnabled()) {
LOG.debug("process: Got a new event, path = " + event.getPath() +
", type = " + event.getType() + ", state = " +
event.getState());
}
if ((event.getPath() == null) && (event.getType() == EventType.None)) {
if (event.getState() == KeeperState.Disconnected) {
// Watches may not be triggered for some time, so signal all BspEvents
for (BspEvent bspEvent : registeredBspEvents) {
bspEvent.signal();
}
LOG.warn("process: Disconnected from ZooKeeper (will automatically " +
"try to recover) " + event);
} else if (event.getState() == KeeperState.SyncConnected) {
if (LOG.isInfoEnabled()) {
LOG.info("process: Asynchronous connection complete.");
}
connectedEvent.signal();
} else {
LOG.warn("process: Got unknown null path event " + event);
}
return;
}
boolean eventProcessed = false;
if (event.getPath().startsWith(masterJobStatePath)) {
// This will cause all becomeMaster() MasterThreads to notice the
// change in job state and quit trying to become the master.
masterElectionChildrenChanged.signal();
eventProcessed = true;
} else if ((event.getPath().contains(WORKER_HEALTHY_DIR) ||
event.getPath().contains(WORKER_UNHEALTHY_DIR)) &&
(event.getType() == EventType.NodeChildrenChanged)) {
if (LOG.isDebugEnabled()) {
LOG.debug("process: workerHealthRegistrationChanged " +
"(worker health reported - healthy/unhealthy )");
}
workerHealthRegistrationChanged.signal();
eventProcessed = true;
} else if (event.getPath().contains(INPUT_SPLITS_ALL_DONE_NODE) &&
event.getType() == EventType.NodeCreated) {
if (LOG.isInfoEnabled()) {
LOG.info("process: all input splits done");
}
inputSplitsAllDoneEvent.signal();
eventProcessed = true;
} else if (event.getPath().contains(INPUT_SPLITS_WORKER_DONE_DIR) &&
event.getType() == EventType.NodeChildrenChanged) {
if (LOG.isDebugEnabled()) {
LOG.debug("process: worker done reading input splits");
}
inputSplitsWorkerDoneEvent.signal();
eventProcessed = true;
} else if (event.getPath().contains(SUPERSTEP_FINISHED_NODE) &&
event.getType() == EventType.NodeCreated) {
if (LOG.isInfoEnabled()) {
LOG.info("process: superstepFinished signaled");
}
superstepFinished.signal();
eventProcessed = true;
} else if (event.getPath().endsWith(applicationAttemptsPath) &&
event.getType() == EventType.NodeChildrenChanged) {
if (LOG.isInfoEnabled()) {
LOG.info("process: applicationAttemptChanged signaled");
}
applicationAttemptChanged.signal();
eventProcessed = true;
} else if (event.getPath().contains(MASTER_ELECTION_DIR) &&
event.getType() == EventType.NodeChildrenChanged) {
if (LOG.isInfoEnabled()) {
LOG.info("process: masterElectionChildrenChanged signaled");
}
masterElectionChildrenChanged.signal();
eventProcessed = true;
} else if (event.getPath().equals(cleanedUpPath) &&
event.getType() == EventType.NodeChildrenChanged) {
if (LOG.isInfoEnabled()) {
LOG.info("process: cleanedUpChildrenChanged signaled");
}
cleanedUpChildrenChanged.signal();
eventProcessed = true;
} else if (event.getPath().endsWith(COUNTERS_DIR) &&
event.getType() == EventType.NodeChildrenChanged) {
LOG.info("process: writtenCountersToZK signaled");
getWrittenCountersToZKEvent().signal();
eventProcessed = true;
}
if (!(processEvent(event)) && (!eventProcessed)) {
LOG.warn("process: Unknown and unprocessed event (path=" +
event.getPath() + ", type=" + event.getType() +
", state=" + event.getState() + ")");
}
}
/**
* Get the last saved superstep.
*
* @return Last good superstep number
* @throws IOException
*/
protected long getLastCheckpointedSuperstep() throws IOException {
return CheckpointingUtils.getLastCheckpointedSuperstep(getFs(),
savedCheckpointBasePath);
}
@Override
public JobProgressTracker getJobProgressTracker() {
return getGraphTaskManager().getJobProgressTracker();
}
/**
* For every worker this method returns unique number
* between 0 and N, where N is the total number of workers.
* This number stays the same throughout the computation.
* TaskID may be different from this number and task ID
* is not necessarily continuous
* @param workerInfo worker info object
* @return worker number
*/
protected int getWorkerId(WorkerInfo workerInfo) {
return getWorkerInfoList().indexOf(workerInfo);
}
/**
* Returns worker info corresponding to specified worker id.
* @param id unique worker id
* @return WorkerInfo
*/
protected WorkerInfo getWorkerInfoById(int id) {
return getWorkerInfoList().get(id);
}
}
|
apache/hive | 35,731 | standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ForeignKeysRequest.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 ForeignKeysRequest implements org.apache.thrift.TBase<ForeignKeysRequest, ForeignKeysRequest._Fields>, java.io.Serializable, Cloneable, Comparable<ForeignKeysRequest> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ForeignKeysRequest");
private static final org.apache.thrift.protocol.TField PARENT_DB_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("parent_db_name", org.apache.thrift.protocol.TType.STRING, (short)1);
private static final org.apache.thrift.protocol.TField PARENT_TBL_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("parent_tbl_name", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField FOREIGN_DB_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("foreign_db_name", org.apache.thrift.protocol.TType.STRING, (short)3);
private static final org.apache.thrift.protocol.TField FOREIGN_TBL_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("foreign_tbl_name", org.apache.thrift.protocol.TType.STRING, (short)4);
private static final org.apache.thrift.protocol.TField CAT_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("catName", org.apache.thrift.protocol.TType.STRING, (short)5);
private static final org.apache.thrift.protocol.TField VALID_WRITE_ID_LIST_FIELD_DESC = new org.apache.thrift.protocol.TField("validWriteIdList", org.apache.thrift.protocol.TType.STRING, (short)6);
private static final org.apache.thrift.protocol.TField TABLE_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("tableId", org.apache.thrift.protocol.TType.I64, (short)7);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new ForeignKeysRequestStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new ForeignKeysRequestTupleSchemeFactory();
private @org.apache.thrift.annotation.Nullable java.lang.String parent_db_name; // required
private @org.apache.thrift.annotation.Nullable java.lang.String parent_tbl_name; // required
private @org.apache.thrift.annotation.Nullable java.lang.String foreign_db_name; // required
private @org.apache.thrift.annotation.Nullable java.lang.String foreign_tbl_name; // required
private @org.apache.thrift.annotation.Nullable java.lang.String catName; // optional
private @org.apache.thrift.annotation.Nullable java.lang.String validWriteIdList; // optional
private long tableId; // 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 {
PARENT_DB_NAME((short)1, "parent_db_name"),
PARENT_TBL_NAME((short)2, "parent_tbl_name"),
FOREIGN_DB_NAME((short)3, "foreign_db_name"),
FOREIGN_TBL_NAME((short)4, "foreign_tbl_name"),
CAT_NAME((short)5, "catName"),
VALID_WRITE_ID_LIST((short)6, "validWriteIdList"),
TABLE_ID((short)7, "tableId");
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: // PARENT_DB_NAME
return PARENT_DB_NAME;
case 2: // PARENT_TBL_NAME
return PARENT_TBL_NAME;
case 3: // FOREIGN_DB_NAME
return FOREIGN_DB_NAME;
case 4: // FOREIGN_TBL_NAME
return FOREIGN_TBL_NAME;
case 5: // CAT_NAME
return CAT_NAME;
case 6: // VALID_WRITE_ID_LIST
return VALID_WRITE_ID_LIST;
case 7: // TABLE_ID
return TABLE_ID;
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 __TABLEID_ISSET_ID = 0;
private byte __isset_bitfield = 0;
private static final _Fields optionals[] = {_Fields.CAT_NAME,_Fields.VALID_WRITE_ID_LIST,_Fields.TABLE_ID};
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.PARENT_DB_NAME, new org.apache.thrift.meta_data.FieldMetaData("parent_db_name", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.PARENT_TBL_NAME, new org.apache.thrift.meta_data.FieldMetaData("parent_tbl_name", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.FOREIGN_DB_NAME, new org.apache.thrift.meta_data.FieldMetaData("foreign_db_name", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.FOREIGN_TBL_NAME, new org.apache.thrift.meta_data.FieldMetaData("foreign_tbl_name", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.CAT_NAME, new org.apache.thrift.meta_data.FieldMetaData("catName", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.VALID_WRITE_ID_LIST, new org.apache.thrift.meta_data.FieldMetaData("validWriteIdList", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.TABLE_ID, new org.apache.thrift.meta_data.FieldMetaData("tableId", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ForeignKeysRequest.class, metaDataMap);
}
public ForeignKeysRequest() {
this.tableId = -1L;
}
public ForeignKeysRequest(
java.lang.String parent_db_name,
java.lang.String parent_tbl_name,
java.lang.String foreign_db_name,
java.lang.String foreign_tbl_name)
{
this();
this.parent_db_name = parent_db_name;
this.parent_tbl_name = parent_tbl_name;
this.foreign_db_name = foreign_db_name;
this.foreign_tbl_name = foreign_tbl_name;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public ForeignKeysRequest(ForeignKeysRequest other) {
__isset_bitfield = other.__isset_bitfield;
if (other.isSetParent_db_name()) {
this.parent_db_name = other.parent_db_name;
}
if (other.isSetParent_tbl_name()) {
this.parent_tbl_name = other.parent_tbl_name;
}
if (other.isSetForeign_db_name()) {
this.foreign_db_name = other.foreign_db_name;
}
if (other.isSetForeign_tbl_name()) {
this.foreign_tbl_name = other.foreign_tbl_name;
}
if (other.isSetCatName()) {
this.catName = other.catName;
}
if (other.isSetValidWriteIdList()) {
this.validWriteIdList = other.validWriteIdList;
}
this.tableId = other.tableId;
}
public ForeignKeysRequest deepCopy() {
return new ForeignKeysRequest(this);
}
@Override
public void clear() {
this.parent_db_name = null;
this.parent_tbl_name = null;
this.foreign_db_name = null;
this.foreign_tbl_name = null;
this.catName = null;
this.validWriteIdList = null;
this.tableId = -1L;
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getParent_db_name() {
return this.parent_db_name;
}
public void setParent_db_name(@org.apache.thrift.annotation.Nullable java.lang.String parent_db_name) {
this.parent_db_name = parent_db_name;
}
public void unsetParent_db_name() {
this.parent_db_name = null;
}
/** Returns true if field parent_db_name is set (has been assigned a value) and false otherwise */
public boolean isSetParent_db_name() {
return this.parent_db_name != null;
}
public void setParent_db_nameIsSet(boolean value) {
if (!value) {
this.parent_db_name = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getParent_tbl_name() {
return this.parent_tbl_name;
}
public void setParent_tbl_name(@org.apache.thrift.annotation.Nullable java.lang.String parent_tbl_name) {
this.parent_tbl_name = parent_tbl_name;
}
public void unsetParent_tbl_name() {
this.parent_tbl_name = null;
}
/** Returns true if field parent_tbl_name is set (has been assigned a value) and false otherwise */
public boolean isSetParent_tbl_name() {
return this.parent_tbl_name != null;
}
public void setParent_tbl_nameIsSet(boolean value) {
if (!value) {
this.parent_tbl_name = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getForeign_db_name() {
return this.foreign_db_name;
}
public void setForeign_db_name(@org.apache.thrift.annotation.Nullable java.lang.String foreign_db_name) {
this.foreign_db_name = foreign_db_name;
}
public void unsetForeign_db_name() {
this.foreign_db_name = null;
}
/** Returns true if field foreign_db_name is set (has been assigned a value) and false otherwise */
public boolean isSetForeign_db_name() {
return this.foreign_db_name != null;
}
public void setForeign_db_nameIsSet(boolean value) {
if (!value) {
this.foreign_db_name = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getForeign_tbl_name() {
return this.foreign_tbl_name;
}
public void setForeign_tbl_name(@org.apache.thrift.annotation.Nullable java.lang.String foreign_tbl_name) {
this.foreign_tbl_name = foreign_tbl_name;
}
public void unsetForeign_tbl_name() {
this.foreign_tbl_name = null;
}
/** Returns true if field foreign_tbl_name is set (has been assigned a value) and false otherwise */
public boolean isSetForeign_tbl_name() {
return this.foreign_tbl_name != null;
}
public void setForeign_tbl_nameIsSet(boolean value) {
if (!value) {
this.foreign_tbl_name = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getCatName() {
return this.catName;
}
public void setCatName(@org.apache.thrift.annotation.Nullable java.lang.String catName) {
this.catName = catName;
}
public void unsetCatName() {
this.catName = null;
}
/** Returns true if field catName is set (has been assigned a value) and false otherwise */
public boolean isSetCatName() {
return this.catName != null;
}
public void setCatNameIsSet(boolean value) {
if (!value) {
this.catName = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getValidWriteIdList() {
return this.validWriteIdList;
}
public void setValidWriteIdList(@org.apache.thrift.annotation.Nullable java.lang.String validWriteIdList) {
this.validWriteIdList = validWriteIdList;
}
public void unsetValidWriteIdList() {
this.validWriteIdList = null;
}
/** Returns true if field validWriteIdList is set (has been assigned a value) and false otherwise */
public boolean isSetValidWriteIdList() {
return this.validWriteIdList != null;
}
public void setValidWriteIdListIsSet(boolean value) {
if (!value) {
this.validWriteIdList = null;
}
}
public long getTableId() {
return this.tableId;
}
public void setTableId(long tableId) {
this.tableId = tableId;
setTableIdIsSet(true);
}
public void unsetTableId() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __TABLEID_ISSET_ID);
}
/** Returns true if field tableId is set (has been assigned a value) and false otherwise */
public boolean isSetTableId() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __TABLEID_ISSET_ID);
}
public void setTableIdIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __TABLEID_ISSET_ID, value);
}
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case PARENT_DB_NAME:
if (value == null) {
unsetParent_db_name();
} else {
setParent_db_name((java.lang.String)value);
}
break;
case PARENT_TBL_NAME:
if (value == null) {
unsetParent_tbl_name();
} else {
setParent_tbl_name((java.lang.String)value);
}
break;
case FOREIGN_DB_NAME:
if (value == null) {
unsetForeign_db_name();
} else {
setForeign_db_name((java.lang.String)value);
}
break;
case FOREIGN_TBL_NAME:
if (value == null) {
unsetForeign_tbl_name();
} else {
setForeign_tbl_name((java.lang.String)value);
}
break;
case CAT_NAME:
if (value == null) {
unsetCatName();
} else {
setCatName((java.lang.String)value);
}
break;
case VALID_WRITE_ID_LIST:
if (value == null) {
unsetValidWriteIdList();
} else {
setValidWriteIdList((java.lang.String)value);
}
break;
case TABLE_ID:
if (value == null) {
unsetTableId();
} else {
setTableId((java.lang.Long)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case PARENT_DB_NAME:
return getParent_db_name();
case PARENT_TBL_NAME:
return getParent_tbl_name();
case FOREIGN_DB_NAME:
return getForeign_db_name();
case FOREIGN_TBL_NAME:
return getForeign_tbl_name();
case CAT_NAME:
return getCatName();
case VALID_WRITE_ID_LIST:
return getValidWriteIdList();
case TABLE_ID:
return getTableId();
}
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 PARENT_DB_NAME:
return isSetParent_db_name();
case PARENT_TBL_NAME:
return isSetParent_tbl_name();
case FOREIGN_DB_NAME:
return isSetForeign_db_name();
case FOREIGN_TBL_NAME:
return isSetForeign_tbl_name();
case CAT_NAME:
return isSetCatName();
case VALID_WRITE_ID_LIST:
return isSetValidWriteIdList();
case TABLE_ID:
return isSetTableId();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof ForeignKeysRequest)
return this.equals((ForeignKeysRequest)that);
return false;
}
public boolean equals(ForeignKeysRequest that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_parent_db_name = true && this.isSetParent_db_name();
boolean that_present_parent_db_name = true && that.isSetParent_db_name();
if (this_present_parent_db_name || that_present_parent_db_name) {
if (!(this_present_parent_db_name && that_present_parent_db_name))
return false;
if (!this.parent_db_name.equals(that.parent_db_name))
return false;
}
boolean this_present_parent_tbl_name = true && this.isSetParent_tbl_name();
boolean that_present_parent_tbl_name = true && that.isSetParent_tbl_name();
if (this_present_parent_tbl_name || that_present_parent_tbl_name) {
if (!(this_present_parent_tbl_name && that_present_parent_tbl_name))
return false;
if (!this.parent_tbl_name.equals(that.parent_tbl_name))
return false;
}
boolean this_present_foreign_db_name = true && this.isSetForeign_db_name();
boolean that_present_foreign_db_name = true && that.isSetForeign_db_name();
if (this_present_foreign_db_name || that_present_foreign_db_name) {
if (!(this_present_foreign_db_name && that_present_foreign_db_name))
return false;
if (!this.foreign_db_name.equals(that.foreign_db_name))
return false;
}
boolean this_present_foreign_tbl_name = true && this.isSetForeign_tbl_name();
boolean that_present_foreign_tbl_name = true && that.isSetForeign_tbl_name();
if (this_present_foreign_tbl_name || that_present_foreign_tbl_name) {
if (!(this_present_foreign_tbl_name && that_present_foreign_tbl_name))
return false;
if (!this.foreign_tbl_name.equals(that.foreign_tbl_name))
return false;
}
boolean this_present_catName = true && this.isSetCatName();
boolean that_present_catName = true && that.isSetCatName();
if (this_present_catName || that_present_catName) {
if (!(this_present_catName && that_present_catName))
return false;
if (!this.catName.equals(that.catName))
return false;
}
boolean this_present_validWriteIdList = true && this.isSetValidWriteIdList();
boolean that_present_validWriteIdList = true && that.isSetValidWriteIdList();
if (this_present_validWriteIdList || that_present_validWriteIdList) {
if (!(this_present_validWriteIdList && that_present_validWriteIdList))
return false;
if (!this.validWriteIdList.equals(that.validWriteIdList))
return false;
}
boolean this_present_tableId = true && this.isSetTableId();
boolean that_present_tableId = true && that.isSetTableId();
if (this_present_tableId || that_present_tableId) {
if (!(this_present_tableId && that_present_tableId))
return false;
if (this.tableId != that.tableId)
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetParent_db_name()) ? 131071 : 524287);
if (isSetParent_db_name())
hashCode = hashCode * 8191 + parent_db_name.hashCode();
hashCode = hashCode * 8191 + ((isSetParent_tbl_name()) ? 131071 : 524287);
if (isSetParent_tbl_name())
hashCode = hashCode * 8191 + parent_tbl_name.hashCode();
hashCode = hashCode * 8191 + ((isSetForeign_db_name()) ? 131071 : 524287);
if (isSetForeign_db_name())
hashCode = hashCode * 8191 + foreign_db_name.hashCode();
hashCode = hashCode * 8191 + ((isSetForeign_tbl_name()) ? 131071 : 524287);
if (isSetForeign_tbl_name())
hashCode = hashCode * 8191 + foreign_tbl_name.hashCode();
hashCode = hashCode * 8191 + ((isSetCatName()) ? 131071 : 524287);
if (isSetCatName())
hashCode = hashCode * 8191 + catName.hashCode();
hashCode = hashCode * 8191 + ((isSetValidWriteIdList()) ? 131071 : 524287);
if (isSetValidWriteIdList())
hashCode = hashCode * 8191 + validWriteIdList.hashCode();
hashCode = hashCode * 8191 + ((isSetTableId()) ? 131071 : 524287);
if (isSetTableId())
hashCode = hashCode * 8191 + org.apache.thrift.TBaseHelper.hashCode(tableId);
return hashCode;
}
@Override
public int compareTo(ForeignKeysRequest other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetParent_db_name(), other.isSetParent_db_name());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetParent_db_name()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.parent_db_name, other.parent_db_name);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetParent_tbl_name(), other.isSetParent_tbl_name());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetParent_tbl_name()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.parent_tbl_name, other.parent_tbl_name);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetForeign_db_name(), other.isSetForeign_db_name());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetForeign_db_name()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.foreign_db_name, other.foreign_db_name);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetForeign_tbl_name(), other.isSetForeign_tbl_name());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetForeign_tbl_name()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.foreign_tbl_name, other.foreign_tbl_name);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetCatName(), other.isSetCatName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetCatName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.catName, other.catName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetValidWriteIdList(), other.isSetValidWriteIdList());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetValidWriteIdList()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.validWriteIdList, other.validWriteIdList);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetTableId(), other.isSetTableId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTableId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.tableId, other.tableId);
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("ForeignKeysRequest(");
boolean first = true;
sb.append("parent_db_name:");
if (this.parent_db_name == null) {
sb.append("null");
} else {
sb.append(this.parent_db_name);
}
first = false;
if (!first) sb.append(", ");
sb.append("parent_tbl_name:");
if (this.parent_tbl_name == null) {
sb.append("null");
} else {
sb.append(this.parent_tbl_name);
}
first = false;
if (!first) sb.append(", ");
sb.append("foreign_db_name:");
if (this.foreign_db_name == null) {
sb.append("null");
} else {
sb.append(this.foreign_db_name);
}
first = false;
if (!first) sb.append(", ");
sb.append("foreign_tbl_name:");
if (this.foreign_tbl_name == null) {
sb.append("null");
} else {
sb.append(this.foreign_tbl_name);
}
first = false;
if (isSetCatName()) {
if (!first) sb.append(", ");
sb.append("catName:");
if (this.catName == null) {
sb.append("null");
} else {
sb.append(this.catName);
}
first = false;
}
if (isSetValidWriteIdList()) {
if (!first) sb.append(", ");
sb.append("validWriteIdList:");
if (this.validWriteIdList == null) {
sb.append("null");
} else {
sb.append(this.validWriteIdList);
}
first = false;
}
if (isSetTableId()) {
if (!first) sb.append(", ");
sb.append("tableId:");
sb.append(this.tableId);
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class ForeignKeysRequestStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public ForeignKeysRequestStandardScheme getScheme() {
return new ForeignKeysRequestStandardScheme();
}
}
private static class ForeignKeysRequestStandardScheme extends org.apache.thrift.scheme.StandardScheme<ForeignKeysRequest> {
public void read(org.apache.thrift.protocol.TProtocol iprot, ForeignKeysRequest 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: // PARENT_DB_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.parent_db_name = iprot.readString();
struct.setParent_db_nameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // PARENT_TBL_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.parent_tbl_name = iprot.readString();
struct.setParent_tbl_nameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // FOREIGN_DB_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.foreign_db_name = iprot.readString();
struct.setForeign_db_nameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // FOREIGN_TBL_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.foreign_tbl_name = iprot.readString();
struct.setForeign_tbl_nameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 5: // CAT_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.catName = iprot.readString();
struct.setCatNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 6: // VALID_WRITE_ID_LIST
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.validWriteIdList = iprot.readString();
struct.setValidWriteIdListIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 7: // TABLE_ID
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.tableId = iprot.readI64();
struct.setTableIdIsSet(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, ForeignKeysRequest struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.parent_db_name != null) {
oprot.writeFieldBegin(PARENT_DB_NAME_FIELD_DESC);
oprot.writeString(struct.parent_db_name);
oprot.writeFieldEnd();
}
if (struct.parent_tbl_name != null) {
oprot.writeFieldBegin(PARENT_TBL_NAME_FIELD_DESC);
oprot.writeString(struct.parent_tbl_name);
oprot.writeFieldEnd();
}
if (struct.foreign_db_name != null) {
oprot.writeFieldBegin(FOREIGN_DB_NAME_FIELD_DESC);
oprot.writeString(struct.foreign_db_name);
oprot.writeFieldEnd();
}
if (struct.foreign_tbl_name != null) {
oprot.writeFieldBegin(FOREIGN_TBL_NAME_FIELD_DESC);
oprot.writeString(struct.foreign_tbl_name);
oprot.writeFieldEnd();
}
if (struct.catName != null) {
if (struct.isSetCatName()) {
oprot.writeFieldBegin(CAT_NAME_FIELD_DESC);
oprot.writeString(struct.catName);
oprot.writeFieldEnd();
}
}
if (struct.validWriteIdList != null) {
if (struct.isSetValidWriteIdList()) {
oprot.writeFieldBegin(VALID_WRITE_ID_LIST_FIELD_DESC);
oprot.writeString(struct.validWriteIdList);
oprot.writeFieldEnd();
}
}
if (struct.isSetTableId()) {
oprot.writeFieldBegin(TABLE_ID_FIELD_DESC);
oprot.writeI64(struct.tableId);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class ForeignKeysRequestTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public ForeignKeysRequestTupleScheme getScheme() {
return new ForeignKeysRequestTupleScheme();
}
}
private static class ForeignKeysRequestTupleScheme extends org.apache.thrift.scheme.TupleScheme<ForeignKeysRequest> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, ForeignKeysRequest struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetParent_db_name()) {
optionals.set(0);
}
if (struct.isSetParent_tbl_name()) {
optionals.set(1);
}
if (struct.isSetForeign_db_name()) {
optionals.set(2);
}
if (struct.isSetForeign_tbl_name()) {
optionals.set(3);
}
if (struct.isSetCatName()) {
optionals.set(4);
}
if (struct.isSetValidWriteIdList()) {
optionals.set(5);
}
if (struct.isSetTableId()) {
optionals.set(6);
}
oprot.writeBitSet(optionals, 7);
if (struct.isSetParent_db_name()) {
oprot.writeString(struct.parent_db_name);
}
if (struct.isSetParent_tbl_name()) {
oprot.writeString(struct.parent_tbl_name);
}
if (struct.isSetForeign_db_name()) {
oprot.writeString(struct.foreign_db_name);
}
if (struct.isSetForeign_tbl_name()) {
oprot.writeString(struct.foreign_tbl_name);
}
if (struct.isSetCatName()) {
oprot.writeString(struct.catName);
}
if (struct.isSetValidWriteIdList()) {
oprot.writeString(struct.validWriteIdList);
}
if (struct.isSetTableId()) {
oprot.writeI64(struct.tableId);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, ForeignKeysRequest struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(7);
if (incoming.get(0)) {
struct.parent_db_name = iprot.readString();
struct.setParent_db_nameIsSet(true);
}
if (incoming.get(1)) {
struct.parent_tbl_name = iprot.readString();
struct.setParent_tbl_nameIsSet(true);
}
if (incoming.get(2)) {
struct.foreign_db_name = iprot.readString();
struct.setForeign_db_nameIsSet(true);
}
if (incoming.get(3)) {
struct.foreign_tbl_name = iprot.readString();
struct.setForeign_tbl_nameIsSet(true);
}
if (incoming.get(4)) {
struct.catName = iprot.readString();
struct.setCatNameIsSet(true);
}
if (incoming.get(5)) {
struct.validWriteIdList = iprot.readString();
struct.setValidWriteIdListIsSet(true);
}
if (incoming.get(6)) {
struct.tableId = iprot.readI64();
struct.setTableIdIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
|
apache/ignite | 35,264 | modules/core/src/test/java/org/apache/ignite/internal/binary/BinaryObjectBuilderDefaultMappersSelfTest.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.binary;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.ignite.IgniteBinary;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.binary.BinaryBasicIdMapper;
import org.apache.ignite.binary.BinaryBasicNameMapper;
import org.apache.ignite.binary.BinaryIdMapper;
import org.apache.ignite.binary.BinaryNameMapper;
import org.apache.ignite.binary.BinaryObject;
import org.apache.ignite.binary.BinaryObjectBuilder;
import org.apache.ignite.binary.BinaryType;
import org.apache.ignite.binary.BinaryTypeConfiguration;
import org.apache.ignite.configuration.BinaryConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.binary.mutabletest.GridBinaryTestClasses;
import org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl;
import org.apache.ignite.internal.util.GridUnsafe;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.testframework.GridTestUtils;
import org.junit.Assert;
import org.junit.Test;
import static org.apache.ignite.internal.util.GridUnsafe.BIG_ENDIAN;
/**
* Binary builder test.
*/
public class BinaryObjectBuilderDefaultMappersSelfTest extends AbstractBinaryArraysTest {
/** */
private static IgniteConfiguration cfg;
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
BinaryTypeConfiguration customTypeCfg = new BinaryTypeConfiguration();
customTypeCfg.setTypeName(CustomIdMapper.class.getName());
customTypeCfg.setIdMapper(new BinaryIdMapper() {
@Override public int typeId(String clsName) {
return ~BinaryContext.defaultIdMapper().typeId(clsName);
}
@Override public int fieldId(int typeId, String fieldName) {
return typeId + ~BinaryContext.defaultIdMapper().fieldId(typeId, fieldName);
}
});
BinaryConfiguration bCfg = new BinaryConfiguration();
bCfg.setCompactFooter(compactFooter());
bCfg.setTypeConfigurations(Arrays.asList(
new BinaryTypeConfiguration(Key.class.getName()),
new BinaryTypeConfiguration(Value.class.getName()),
new BinaryTypeConfiguration("org.gridgain.grid.internal.util.binary.mutabletest.*"),
customTypeCfg));
bCfg.setIdMapper(new BinaryBasicIdMapper(false));
bCfg.setNameMapper(new BinaryBasicNameMapper(false));
cfg.setBinaryConfiguration(bCfg);
this.cfg = cfg;
return cfg;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
startGrids(1);
}
/**
* @return Whether to use compact footer.
*/
protected boolean compactFooter() {
return true;
}
/**
*
*/
@Test
public void testAllFieldsSerialization() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.setDefaultData();
obj.enumArr = null;
GridBinaryTestClasses.TestObjectAllTypes deserialized = builder(toBinary(obj)).build().deserialize();
GridTestUtils.deepEquals(obj, deserialized);
}
/**
* @throws Exception If failed.
*/
@Test
public void testNullField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("objField", (Object)null);
builder.setField("otherField", "value");
BinaryObject obj = builder.build();
assertNull(obj.field("objField"));
assertEquals("value", obj.field("otherField"));
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(obj), obj.hashCode());
builder = builder(obj);
builder.setField("objField", "value", Object.class);
builder.setField("otherField", (Object)null);
obj = builder.build();
assertNull(obj.field("otherField"));
assertEquals("value", obj.field("objField"));
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(obj), obj.hashCode());
}
/**
* @throws Exception If failed.
*/
@Test
public void testByteField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("byteField", (byte)1);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertEquals((byte)1, po.<Byte>field("byteField").byteValue());
}
/**
* @throws Exception If failed.
*/
@Test
public void testShortField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("shortField", (short)1);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertEquals((short)1, po.<Short>field("shortField").shortValue());
}
/**
* @throws Exception If failed.
*/
@Test
public void testIntField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("intField", 1);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertEquals(1, po.<Integer>field("intField").intValue());
}
/**
* @throws Exception If failed.
*/
@Test
public void testLongField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("longField", 1L);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertEquals(1L, po.<Long>field("longField").longValue());
}
/**
* @throws Exception If failed.
*/
@Test
public void testFloatField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("floatField", 1.0f);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertEquals(1.0f, po.<Float>field("floatField").floatValue(), 0);
}
/**
* @throws Exception If failed.
*/
@Test
public void testDoubleField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("doubleField", 1.0d);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertEquals(1.0d, po.<Double>field("doubleField").doubleValue(), 0);
}
/**
* @throws Exception If failed.
*/
@Test
public void testCharField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("charField", (char)1);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertEquals((char)1, po.<Character>field("charField").charValue());
}
/**
* @return Expected hash code.
* @param fullName Full name of type.
*/
private int expectedHashCode(String fullName) {
BinaryIdMapper idMapper = cfg.getBinaryConfiguration().getIdMapper();
BinaryNameMapper nameMapper = cfg.getBinaryConfiguration().getNameMapper();
if (idMapper == null)
idMapper = BinaryContext.defaultIdMapper();
if (nameMapper == null)
nameMapper = BinaryContext.defaultNameMapper();
return idMapper.typeId(nameMapper.typeName(fullName));
}
/**
* @throws Exception If failed.
*/
@Test
public void testBooleanField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("booleanField", true);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertTrue(po.<Boolean>field("booleanField"));
}
/**
* @throws Exception If failed.
*/
@Test
public void testDecimalField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("decimalField", BigDecimal.TEN);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertEquals(BigDecimal.TEN, po.<BigDecimal>field("decimalField"));
}
/**
* @throws Exception If failed.
*/
@Test
public void testStringField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("stringField", "str");
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertEquals("str", po.<String>field("stringField"));
}
/**
* @throws Exception If failed.
*/
@Test
public void testDateField() throws Exception {
Date date = new Date();
assertEquals(date, builder("C").setField("d", date).build().<Date>field("d"));
}
/**
* @throws Exception If failed.
*/
@Test
public void testTimestampField() throws Exception {
Timestamp ts = new Timestamp(new Date().getTime());
ts.setNanos(1000);
assertEquals(ts, builder("C").setField("t", ts).build().<Timestamp>field("t"));
}
/**
* @throws Exception If failed.
*/
@Test
public void testUuidField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
UUID uuid = UUID.randomUUID();
builder.setField("uuidField", uuid);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertEquals(uuid, po.<UUID>field("uuidField"));
}
/**
* @throws Exception If failed.
*/
@Test
public void testByteArrayField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("byteArrayField", new byte[] {1, 2, 3});
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertTrue(Arrays.equals(new byte[] {1, 2, 3}, po.<byte[]>field("byteArrayField")));
}
/**
* @throws Exception If failed.
*/
@Test
public void testShortArrayField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("shortArrayField", new short[] {1, 2, 3});
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertTrue(Arrays.equals(new short[] {1, 2, 3}, po.<short[]>field("shortArrayField")));
}
/**
* @throws Exception If failed.
*/
@Test
public void testIntArrayField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("intArrayField", new int[] {1, 2, 3});
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertTrue(Arrays.equals(new int[] {1, 2, 3}, po.<int[]>field("intArrayField")));
}
/**
* @throws Exception If failed.
*/
@Test
public void testLongArrayField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("longArrayField", new long[] {1, 2, 3});
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertTrue(Arrays.equals(new long[] {1, 2, 3}, po.<long[]>field("longArrayField")));
}
/**
* @throws Exception If failed.
*/
@Test
public void testFloatArrayField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("floatArrayField", new float[] {1, 2, 3});
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertTrue(Arrays.equals(new float[] {1, 2, 3}, po.<float[]>field("floatArrayField")));
}
/**
* @throws Exception If failed.
*/
@Test
public void testDoubleArrayField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("doubleArrayField", new double[] {1, 2, 3});
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertTrue(Arrays.equals(new double[] {1, 2, 3}, po.<double[]>field("doubleArrayField")));
}
/**
* @throws Exception If failed.
*/
@Test
public void testCharArrayField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("charArrayField", new char[] {1, 2, 3});
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertTrue(Arrays.equals(new char[] {1, 2, 3}, po.<char[]>field("charArrayField")));
}
/**
* @throws Exception If failed.
*/
@Test
public void testBooleanArrayField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("booleanArrayField", new boolean[] {true, false});
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
boolean[] arr = po.field("booleanArrayField");
assertEquals(2, arr.length);
assertTrue(arr[0]);
assertFalse(arr[1]);
}
/**
* @throws Exception If failed.
*/
@Test
public void testDecimalArrayField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("decimalArrayField", new BigDecimal[] {BigDecimal.ONE, BigDecimal.TEN});
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertTrue(Arrays.equals(new BigDecimal[] {BigDecimal.ONE, BigDecimal.TEN}, po.<String[]>field("decimalArrayField")));
}
/**
* @throws Exception If failed.
*/
@Test
public void testStringArrayField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("stringArrayField", new String[] {"str1", "str2", "str3"});
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertTrue(Arrays.equals(new String[] {"str1", "str2", "str3"}, po.<String[]>field("stringArrayField")));
}
/**
* @throws Exception If failed.
*/
@Test
public void testDateArrayField() throws Exception {
Date date1 = new Date();
Date date2 = new Date(date1.getTime() + 1000);
Date[] dateArr = new Date[] { date1, date2 };
assertTrue(Arrays.equals(dateArr, builder("C").setField("da", dateArr).build().<Date[]>field("da")));
}
/**
* @throws Exception If failed.
*/
@Test
public void testTimestampArrayField() throws Exception {
Timestamp ts1 = new Timestamp(new Date().getTime());
Timestamp ts2 = new Timestamp(new Date().getTime() + 1000);
ts1.setNanos(1000);
ts2.setNanos(2000);
Timestamp[] tsArr = new Timestamp[] { ts1, ts2 };
assertTrue(Arrays.equals(tsArr, builder("C").setField("ta", tsArr).build().<Timestamp[]>field("ta")));
}
/**
* @throws Exception If failed.
*/
@Test
public void testUuidArrayField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
UUID[] arr = new UUID[] {UUID.randomUUID(), UUID.randomUUID()};
builder.setField("uuidArrayField", arr);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertTrue(Arrays.equals(arr, po.<UUID[]>field("uuidArrayField")));
}
/**
* @throws Exception If failed.
*/
@Test
public void testObjectField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("objectField", new Value(1));
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertEquals(1, po.<BinaryObject>field("objectField").<Value>deserialize().i);
}
/**
* @throws Exception If failed.
*/
@Test
public void testObjectArrayField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("objectArrayField", new Value[] {new Value(1), new Value(2)});
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
Object[] arr = useBinaryArrays ? po.<BinaryArray>field("objectArrayField").array() : po.field("objectArrayField");
assertEquals(2, arr.length);
assertEquals(1, ((BinaryObject)arr[0]).<Value>deserialize().i);
assertEquals(2, ((BinaryObject)arr[1]).<Value>deserialize().i);
}
/**
* @throws Exception If failed.
*/
@Test
public void testCollectionField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("collectionField", Arrays.asList(new Value(1), new Value(2)));
builder.setField("collectionField2", Arrays.asList(new Value(1), new Value(2)), Collection.class);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
List<Value> list = po.field("collectionField");
assertEquals(2, list.size());
assertEquals(1, list.get(0).i);
assertEquals(2, list.get(1).i);
List<BinaryObject> list2 = po.field("collectionField2");
assertEquals(2, list2.size());
assertEquals(1, list2.get(0).<Value>deserialize().i);
assertEquals(2, list2.get(1).<Value>deserialize().i);
}
/**
* @throws Exception If failed.
*/
@Test
public void testMapField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("mapField", F.asMap(new Key(1), new Value(1), new Key(2), new Value(2)));
builder.setField("mapField2", F.asMap(new Key(1), new Value(1), new Key(2), new Value(2)), Map.class);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
// Test non-standard map.
Map<Key, Value> map = po.field("mapField");
assertEquals(2, map.size());
for (Map.Entry<Key, Value> e : map.entrySet())
assertEquals(e.getKey().i, e.getValue().i);
// Test binary map
Map<BinaryObject, BinaryObject> map2 = po.field("mapField2");
assertEquals(2, map2.size());
for (Map.Entry<BinaryObject, BinaryObject> e : map2.entrySet())
assertEquals(e.getKey().<Key>deserialize().i, e.getValue().<Value>deserialize().i);
}
/**
* @throws Exception If failed.
*/
@Test
public void testSeveralFields() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("i", 111);
builder.setField("f", 111.111f);
builder.setField("iArr", new int[] {1, 2, 3});
builder.setField("obj", new Key(1));
builder.setField("col", Arrays.asList(new Value(1), new Value(2)), Collection.class);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertEquals(111, po.<Integer>field("i").intValue());
assertEquals(111.111f, po.<Float>field("f").floatValue(), 0);
assertTrue(Arrays.equals(new int[] {1, 2, 3}, po.<int[]>field("iArr")));
assertEquals(1, po.<BinaryObject>field("obj").<Key>deserialize().i);
List<BinaryObject> list = po.field("col");
assertEquals(2, list.size());
assertEquals(1, list.get(0).<Value>deserialize().i);
assertEquals(2, list.get(1).<Value>deserialize().i);
}
/**
* @throws Exception If failed.
*/
@Test
public void testOffheapBinary() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("i", 111);
builder.setField("f", 111.111f);
builder.setField("iArr", new int[] {1, 2, 3});
builder.setField("obj", new Key(1));
builder.setField("col", Arrays.asList(new Value(1), new Value(2)), Collection.class);
BinaryObject po = builder.build();
byte[] arr = ((CacheObjectBinaryProcessorImpl)(grid(0)).context().cacheObjects()).marshal(po);
long ptr = GridUnsafe.allocateMemory(arr.length + 5);
try {
long ptr0 = ptr;
GridUnsafe.putBoolean(null, ptr0++, false);
int len = arr.length;
if (BIG_ENDIAN)
GridUnsafe.putIntLE(ptr0, len);
else
GridUnsafe.putInt(ptr0, len);
GridUnsafe.copyHeapOffheap(arr, GridUnsafe.BYTE_ARR_OFF, ptr0 + 4, arr.length);
BinaryObject offheapObj = (BinaryObject)
((CacheObjectBinaryProcessorImpl)(grid(0)).context().cacheObjects()).unmarshal(ptr, false);
assertEquals(BinaryObjectOffheapImpl.class, offheapObj.getClass());
assertEquals(expectedHashCode("Class"), offheapObj.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), offheapObj.hashCode());
assertEquals(111, offheapObj.<Integer>field("i").intValue());
assertEquals(111.111f, offheapObj.<Float>field("f").floatValue(), 0);
assertTrue(Arrays.equals(new int[] {1, 2, 3}, offheapObj.<int[]>field("iArr")));
assertEquals(1, offheapObj.<BinaryObject>field("obj").<Key>deserialize().i);
List<BinaryObject> list = offheapObj.field("col");
assertEquals(2, list.size());
assertEquals(1, list.get(0).<Value>deserialize().i);
assertEquals(2, list.get(1).<Value>deserialize().i);
assertEquals(po, offheapObj);
assertEquals(offheapObj, po);
}
finally {
GridUnsafe.freeMemory(ptr);
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testBuildAndDeserialize() throws Exception {
BinaryObjectBuilder builder = builder(Value.class.getName());
builder.setField("i", 1);
BinaryObject bo = builder.build();
assertEquals(expectedHashCode(Value.class.getName()), bo.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(bo), bo.hashCode());
assertEquals(1, bo.<Value>deserialize().i);
}
/**
* @throws Exception If failed.
*/
@Test
public void testMetaData2() throws Exception {
BinaryObjectBuilder builder = builder("org.test.MetaTest2");
builder.setField("objectField", "a", Object.class);
BinaryObject bo = builder.build();
BinaryType meta = bo.type();
assertEquals(expectedTypeName("org.test.MetaTest2"), meta.typeName());
assertEquals("Object", meta.fieldTypeName("objectField"));
}
/**
* @param fullClsName Class name.
* @return Expected type name according to configuration.
*/
private String expectedTypeName(String fullClsName) {
BinaryNameMapper mapper = cfg.getBinaryConfiguration().getNameMapper();
if (mapper == null)
mapper = BinaryContext.defaultNameMapper();
return mapper.typeName(fullClsName);
}
/**
* @throws Exception If failed.
*/
@Test
public void testMetaData() throws Exception {
String cls = "org.test.MetaTest" + (useBinaryArrays ? "0" : "");
BinaryObjectBuilder builder = builder(cls);
builder.setField("intField", 1);
builder.setField("byteArrayField", new byte[] {1, 2, 3});
BinaryObject po = builder.build();
BinaryType meta = po.type();
assertEquals(expectedTypeName(cls), meta.typeName());
Collection<String> fields = meta.fieldNames();
assertEquals(2, fields.size());
assertTrue(fields.contains("intField"));
assertTrue(fields.contains("byteArrayField"));
assertEquals("int", meta.fieldTypeName("intField"));
assertEquals("byte[]", meta.fieldTypeName("byteArrayField"));
builder = builder(cls);
builder.setField("intField", 2);
builder.setField("uuidField", UUID.randomUUID());
po = builder.build();
meta = po.type();
assertEquals(expectedTypeName(cls), meta.typeName());
fields = meta.fieldNames();
assertEquals(3, fields.size());
assertTrue(fields.contains("intField"));
assertTrue(fields.contains("byteArrayField"));
assertTrue(fields.contains("uuidField"));
assertEquals("int", meta.fieldTypeName("intField"));
assertEquals("byte[]", meta.fieldTypeName("byteArrayField"));
assertEquals("UUID", meta.fieldTypeName("uuidField"));
}
/**
*
*/
@Test
public void testGetFromCopiedObj() {
BinaryObject objStr = builder(GridBinaryTestClasses.TestObjectAllTypes.class.getName()).setField("str", "aaa").build();
BinaryObjectBuilder builder = builder(objStr);
assertEquals("aaa", builder.getField("str"));
builder.setField("str", "bbb");
assertEquals("bbb", builder.getField("str"));
assertNull(builder.getField("i_"));
Assert.assertEquals("bbb", builder.build().<GridBinaryTestClasses.TestObjectAllTypes>deserialize().str);
}
/**
*
*/
@SuppressWarnings("unchecked")
@Test
public void testCopyFromInnerObjects() {
ArrayList<Object> list = new ArrayList<>();
list.add(new GridBinaryTestClasses.TestObjectAllTypes());
list.add(list.get(0));
GridBinaryTestClasses.TestObjectContainer c = new GridBinaryTestClasses.TestObjectContainer(list);
BinaryObjectBuilder builder = builder(toBinary(c));
builder.<List>getField("foo").add("!!!");
BinaryObject res = builder.build();
GridBinaryTestClasses.TestObjectContainer deserialized = res.deserialize();
List deserializedList = (List)deserialized.foo;
assertSame(deserializedList.get(0), deserializedList.get(1));
assertEquals("!!!", deserializedList.get(2));
assertTrue(deserializedList.get(0) instanceof GridBinaryTestClasses.TestObjectAllTypes);
}
/**
*
*/
@Test
public void testSetBinaryObject() {
// Prepare marshaller context.
CacheObjectBinaryProcessorImpl proc = ((CacheObjectBinaryProcessorImpl)(grid(0)).context().cacheObjects());
proc.marshal(new GridBinaryTestClasses.TestObjectContainer());
proc.marshal(new GridBinaryTestClasses.TestObjectAllTypes());
// Actual test.
BinaryObject binaryObj = builder(GridBinaryTestClasses.TestObjectContainer.class.getName())
.setField("foo", toBinary(new GridBinaryTestClasses.TestObjectAllTypes()))
.build();
assertTrue(binaryObj.<GridBinaryTestClasses.TestObjectContainer>deserialize().foo instanceof
GridBinaryTestClasses.TestObjectAllTypes);
}
/**
*
*/
@Test
public void testPlainBinaryObjectCopyFrom() {
GridBinaryTestClasses.TestObjectPlainBinary obj =
new GridBinaryTestClasses.TestObjectPlainBinary(toBinary(new GridBinaryTestClasses.TestObjectAllTypes()));
BinaryObjectBuilder builder = builder(toBinary(obj));
assertTrue(builder.getField("plainBinary") instanceof BinaryObject);
GridBinaryTestClasses.TestObjectPlainBinary deserialized = builder.build().deserialize();
assertTrue(deserialized.plainBinary != null);
}
/**
*
*/
@Test
public void testRemoveFromNewObject() {
BinaryObjectBuilder builder = builder(GridBinaryTestClasses.TestObjectAllTypes.class.getName());
builder.setField("str", "a");
builder.removeField("str");
Assert.assertNull(builder.build().<GridBinaryTestClasses.TestObjectAllTypes>deserialize().str);
}
/**
*
*/
@Test
public void testRemoveFromExistingObject() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.setDefaultData();
obj.enumArr = null;
BinaryObjectBuilder builder = builder(toBinary(obj));
builder.removeField("str");
BinaryObject binary = builder.build();
GridBinaryTestClasses.TestObjectAllTypes deserialzied = binary.deserialize();
assertNull(deserialzied.str);
}
/**
*
*/
@Test
public void testRemoveFromExistingObjectAfterGet() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.setDefaultData();
obj.enumArr = null;
BinaryObjectBuilder builder = builder(toBinary(obj));
builder.getField("i_");
builder.removeField("str");
Assert.assertNull(builder.build().<GridBinaryTestClasses.TestObjectAllTypes>deserialize().str);
}
/**
* @throws IgniteCheckedException If any error occurs.
*/
@Test
public void testDontBrokeCyclicDependency() throws IgniteCheckedException {
GridBinaryTestClasses.TestObjectOuter outer = new GridBinaryTestClasses.TestObjectOuter();
outer.inner = new GridBinaryTestClasses.TestObjectInner();
outer.inner.outer = outer;
outer.foo = "a";
BinaryObjectBuilder builder = builder(toBinary(outer));
builder.setField("foo", "b");
GridBinaryTestClasses.TestObjectOuter res = builder.build().deserialize();
assertEquals("b", res.foo);
assertSame(res, res.inner.outer);
}
/**
* @return Binaries.
*/
private IgniteBinary binaries() {
return grid(0).binary();
}
/**
* @param obj Object.
* @return Binary object.
*/
private BinaryObject toBinary(Object obj) {
return binaries().toBinary(obj);
}
/**
* @return Builder.
*/
private BinaryObjectBuilder builder(String clsName) {
return binaries().builder(clsName);
}
/**
* @return Builder.
*/
private BinaryObjectBuilder builder(BinaryObject obj) {
return binaries().builder(obj);
}
/**
*
*/
private static class CustomIdMapper {
/** */
private String str = "a";
/** */
private int i = 10;
}
/**
*/
private static class Key {
/** */
private int i;
/**
*/
private Key() {
// No-op.
}
/**
* @param i Index.
*/
private Key(int i) {
this.i = i;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Key key = (Key)o;
return i == key.i;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return i;
}
}
/**
*/
private static class Value {
/** */
private int i;
/**
*/
private Value() {
// No-op.
}
/**
* @param i Index.
*/
private Value(int i) {
this.i = i;
}
}
}
|
apache/jclouds | 35,641 | apis/ec2/src/test/java/org/jclouds/ec2/features/InstanceApiTest.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.jclouds.ec2.features;
import static org.jclouds.reflect.Reflection2.method;
import java.io.IOException;
import java.util.Map;
import org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;
import org.jclouds.ec2.domain.BlockDevice;
import org.jclouds.ec2.domain.InstanceType;
import org.jclouds.ec2.domain.Volume.InstanceInitiatedShutdownBehavior;
import org.jclouds.ec2.options.RunInstancesOptions;
import org.jclouds.ec2.xml.BlockDeviceMappingHandler;
import org.jclouds.ec2.xml.BooleanValueHandler;
import org.jclouds.ec2.xml.DescribeInstancesResponseHandler;
import org.jclouds.ec2.xml.GetConsoleOutputResponseHandler;
import org.jclouds.ec2.xml.InstanceInitiatedShutdownBehaviorHandler;
import org.jclouds.ec2.xml.InstanceStateChangeHandler;
import org.jclouds.ec2.xml.InstanceTypeHandler;
import org.jclouds.ec2.xml.RunInstancesResponseHandler;
import org.jclouds.ec2.xml.StringValueHandler;
import org.jclouds.ec2.xml.UnencodeStringValueHandler;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ReleasePayloadAndReturn;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.reflect.Invokable;
/**
* Tests behavior of {@code InstanceApi}
*/
// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire
@Test(groups = "unit", testName = "InstanceApiTest")
public class InstanceApiTest extends BaseEC2ApiTest<InstanceApi> {
public void testDescribeInstances() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "describeInstancesInRegion", String.class, String[].class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Action=DescribeInstances", "application/x-www-form-urlencoded",
false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, DescribeInstancesResponseHandler.class);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testDescribeInstancesArgs() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "describeInstancesInRegion", String.class, String[].class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1", "2"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Action=DescribeInstances&InstanceId.1=1&InstanceId.2=2",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, DescribeInstancesResponseHandler.class);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testTerminateInstances() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "terminateInstancesInRegion", String.class,
String[].class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1", "2"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Action=TerminateInstances&InstanceId.1=1&InstanceId.2=2",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, InstanceStateChangeHandler.class);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(request);
}
public void testRunInstances() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "runInstancesInRegion", String.class, String.class,
String.class, int.class, int.class, RunInstancesOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, null, "ami-voo", 1, 1));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
try {
assertPayloadEquals(request, "Action=RunInstances&ImageId=ami-voo&MinCount=1&MaxCount=1",
"application/x-www-form-urlencoded", false);
} catch (AssertionError e) {
// mvn 3.0 osx 10.6.5 somehow sorts differently
assertPayloadEquals(request, "Action=RunInstances&ImageId=ami-voo&MaxCount=1&MinCount=1",
"application/x-www-form-urlencoded", false);
}
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, RunInstancesResponseHandler.class);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testRunInstancesOptions() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "runInstancesInRegion", String.class, String.class,
String.class, int.class, int.class, RunInstancesOptions[].class);
GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of("eu-west-1", "eu-west-1a", "ami-voo",
1, 5, new RunInstancesOptions().withKernelId("kernelId").withSecurityGroups("group1", "group2")));
assertRequestLineEquals(request, "POST https://ec2.eu-west-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.eu-west-1.amazonaws.com\n");
try {
assertPayloadEquals(
request,
"Action=RunInstances&ImageId=ami-voo&MinCount=1&MaxCount=5&KernelId=kernelId&SecurityGroup.1=group1&SecurityGroup.2=group2&Placement.AvailabilityZone=eu-west-1a",
"application/x-www-form-urlencoded", false);
} catch (AssertionError e) {
// mvn 3.0 osx 10.6.5 somehow sorts differently
assertPayloadEquals(
request,
"Action=RunInstances&ImageId=ami-voo&MaxCount=5&MinCount=1&KernelId=kernelId&SecurityGroup.1=group1&SecurityGroup.2=group2&Placement.AvailabilityZone=eu-west-1a",
"application/x-www-form-urlencoded", false);
}
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, RunInstancesResponseHandler.class);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testStopInstances() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "stopInstancesInRegion", String.class, boolean.class,
String[].class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, true, "1", "2"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Action=StopInstances&Force=true&InstanceId.1=1&InstanceId.2=2",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, InstanceStateChangeHandler.class);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testRebootInstances() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "rebootInstancesInRegion", String.class, String[].class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1", "2"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Action=RebootInstances&InstanceId.1=1&InstanceId.2=2",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testStartInstances() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "startInstancesInRegion", String.class, String[].class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1", "2"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Action=StartInstances&InstanceId.1=1&InstanceId.2=2",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, InstanceStateChangeHandler.class);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testGetUserDataForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "getUserDataForInstanceInRegion", String.class, String.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request,
"Action=DescribeInstanceAttribute&Attribute=userData&InstanceId=1",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, UnencodeStringValueHandler.class);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testGetRootDeviceNameForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "getRootDeviceNameForInstanceInRegion", String.class,
String.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request,
"Action=DescribeInstanceAttribute&Attribute=rootDeviceName&InstanceId=1",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, StringValueHandler.class);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testGetRamdiskForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "getRamdiskForInstanceInRegion", String.class, String.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request,
"Action=DescribeInstanceAttribute&Attribute=ramdisk&InstanceId=1",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, StringValueHandler.class);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testGetDisableApiTerminationForInstanceInRegion() throws SecurityException, NoSuchMethodException,
IOException {
Invokable<?, ?> method = method(InstanceApi.class, "isApiTerminationDisabledForInstanceInRegion", String.class,
String.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request,
"Action=DescribeInstanceAttribute&Attribute=disableApiTermination&InstanceId=1",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, BooleanValueHandler.class);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testGetKernelForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "getKernelForInstanceInRegion", String.class, String.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Action=DescribeInstanceAttribute&Attribute=kernel&InstanceId=1",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, StringValueHandler.class);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testGetInstanceTypeForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "getInstanceTypeForInstanceInRegion", String.class,
String.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request,
"Action=DescribeInstanceAttribute&Attribute=instanceType&InstanceId=1",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, InstanceTypeHandler.class);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testGetInstanceInitiatedShutdownBehaviorForInstanceInRegion() throws SecurityException,
NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "getInstanceInitiatedShutdownBehaviorForInstanceInRegion",
String.class, String.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(
request,
"Action=DescribeInstanceAttribute&Attribute=instanceInitiatedShutdownBehavior&InstanceId=1",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, InstanceInitiatedShutdownBehaviorHandler.class);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
public void testGetBlockDeviceMappingForInstanceInRegion() throws SecurityException, NoSuchMethodException,
IOException {
Invokable<?, ?> method = method(InstanceApi.class, "getBlockDeviceMappingForInstanceInRegion", String.class,
String.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request,
"Action=DescribeInstanceAttribute&Attribute=blockDeviceMapping&InstanceId=1",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, BlockDeviceMappingHandler.class);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
HttpRequest setUserDataForInstance = HttpRequest.builder().method("POST")
.endpoint("https://ec2.us-east-1.amazonaws.com/")
.addHeader("Host", "ec2.us-east-1.amazonaws.com")
.addFormParam("Action", "ModifyInstanceAttribute")
.addFormParam("Attribute", "userData")
.addFormParam("InstanceId", "1")
.addFormParam("Signature", "SfxT/1i/WokibleyEHo0zHizHisLzbDzzRxfOdnr1vY=")
.addFormParam("SignatureMethod", "HmacSHA256")
.addFormParam("SignatureVersion", "2")
.addFormParam("Timestamp", "2009-11-08T15:54:08.897Z")
.addFormParam("Value", "dGVzdA==")
.addFormParam("Version", "2010-08-31")
.addFormParam("AWSAccessKeyId", "identity").build();
public void testSetUserDataForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "setUserDataForInstanceInRegion", String.class, String.class,
byte[].class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1", "test".getBytes()));
request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, setUserDataForInstance.getPayload().getRawContent().toString(),
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
HttpRequest setRamdiskForInstance = HttpRequest.builder().method("POST")
.endpoint("https://ec2.us-east-1.amazonaws.com/")
.addHeader("Host", "ec2.us-east-1.amazonaws.com")
.addFormParam("Action", "ModifyInstanceAttribute")
.addFormParam("Attribute", "ramdisk")
.addFormParam("InstanceId", "1")
.addFormParam("Signature", "aMQzFsknmQt1OA8Rb8aIzZoFXGK23UvrMIy8imNVUeQ=")
.addFormParam("SignatureMethod", "HmacSHA256")
.addFormParam("SignatureVersion", "2")
.addFormParam("Timestamp", "2009-11-08T15:54:08.897Z")
.addFormParam("Value", "test")
.addFormParam("Version", "2010-08-31")
.addFormParam("AWSAccessKeyId", "identity").build();
public void testSetRamdiskForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "setRamdiskForInstanceInRegion", String.class, String.class,
String.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1", "test"));
request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, setRamdiskForInstance.getPayload().getRawContent().toString(),
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
HttpRequest setKernelForInstance = HttpRequest.builder().method("POST")
.endpoint("https://ec2.us-east-1.amazonaws.com/")
.addHeader("Host", "ec2.us-east-1.amazonaws.com")
.addFormParam("Action", "ModifyInstanceAttribute")
.addFormParam("Attribute", "kernel")
.addFormParam("InstanceId", "1")
.addFormParam("Signature", "GaQ9sC0uXHlN5JAMWQpYx+c3XaF38qZgJex/kyqdR1E=")
.addFormParam("SignatureMethod", "HmacSHA256")
.addFormParam("SignatureVersion", "2")
.addFormParam("Timestamp", "2009-11-08T15:54:08.897Z")
.addFormParam("Value", "test")
.addFormParam("Version", "2010-08-31")
.addFormParam("AWSAccessKeyId", "identity").build();
public void testSetKernelForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "setKernelForInstanceInRegion", String.class, String.class,
String.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1", "test"));
request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, setKernelForInstance.getPayload().getRawContent().toString(),
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
HttpRequest setApiTerminationDisabled = HttpRequest.builder().method("POST")
.endpoint("https://ec2.us-east-1.amazonaws.com/")
.addHeader("Host", "ec2.us-east-1.amazonaws.com")
.addFormParam("Action", "ModifyInstanceAttribute")
.addFormParam("Attribute", "disableApiTermination")
.addFormParam("InstanceId", "1")
.addFormParam("Signature", "hErzi+f4jBADviJ+LVTTGhlHWhMR/pyPUSBZgaHC79I=")
.addFormParam("SignatureMethod", "HmacSHA256")
.addFormParam("SignatureVersion", "2")
.addFormParam("Timestamp", "2009-11-08T15:54:08.897Z")
.addFormParam("Value", "true")
.addFormParam("Version", "2010-08-31")
.addFormParam("AWSAccessKeyId", "identity").build();
public void testSetApiTerminationDisabledForInstanceInRegion() throws SecurityException, NoSuchMethodException,
IOException {
Invokable<?, ?> method = method(InstanceApi.class, "setApiTerminationDisabledForInstanceInRegion", String.class,
String.class, boolean.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1", true));
request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, setApiTerminationDisabled.getPayload().getRawContent().toString(),
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
HttpRequest instanceTypeForInstance = HttpRequest.builder().method("POST")
.endpoint("https://ec2.us-east-1.amazonaws.com/")
.addHeader("Host", "ec2.us-east-1.amazonaws.com")
.addFormParam("Action", "ModifyInstanceAttribute")
.addFormParam("Attribute", "instanceType")
.addFormParam("InstanceId", "1")
.addFormParam("Signature", "OYJQ1w79NoxkcrawNK6U71k3Wl78kqz2ikzTXmQCX2E=")
.addFormParam("SignatureMethod", "HmacSHA256")
.addFormParam("SignatureVersion", "2")
.addFormParam("Timestamp", "2009-11-08T15:54:08.897Z")
.addFormParam("Value", "c1.medium")
.addFormParam("Version", "2010-08-31")
.addFormParam("AWSAccessKeyId", "identity").build();
public void testSetInstanceTypeForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "setInstanceTypeForInstanceInRegion", String.class,
String.class, String.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1", InstanceType.C1_MEDIUM));
request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, instanceTypeForInstance.getPayload().getRawContent().toString(),
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
HttpRequest setInstanceInitiatedShutdownBehavior = HttpRequest.builder().method("POST")
.endpoint("https://ec2.us-east-1.amazonaws.com/")
.addHeader("Host", "ec2.us-east-1.amazonaws.com")
.addFormParam("Action", "ModifyInstanceAttribute")
.addFormParam("Attribute", "instanceInitiatedShutdownBehavior")
.addFormParam("InstanceId", "1")
.addFormParam("Signature", "2Tgi9M9AcCv5Y+EXwq0SD6g8bBGtPPEgjdTtfdGZQlI=")
.addFormParam("SignatureMethod", "HmacSHA256")
.addFormParam("SignatureVersion", "2")
.addFormParam("Timestamp", "2009-11-08T15:54:08.897Z")
.addFormParam("Value", "terminate")
.addFormParam("Version", "2010-08-31")
.addFormParam("AWSAccessKeyId", "identity").build();
public void testSetInstanceInitiatedShutdownBehaviorForInstanceInRegion() throws SecurityException,
NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "setInstanceInitiatedShutdownBehaviorForInstanceInRegion",
String.class, String.class, InstanceInitiatedShutdownBehavior.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1", InstanceInitiatedShutdownBehavior.TERMINATE));
request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, setInstanceInitiatedShutdownBehavior.getPayload().getRawContent().toString(),
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
HttpRequest setBlockDeviceMapping = HttpRequest.builder().method("POST")
.endpoint("https://ec2.us-east-1.amazonaws.com/")
.addHeader("Host", "ec2.us-east-1.amazonaws.com")
.addFormParam("Action", "ModifyInstanceAttribute")
.addFormParam("BlockDeviceMapping.1.DeviceName", "/dev/sda1")
.addFormParam("BlockDeviceMapping.1.Ebs.DeleteOnTermination", "true")
.addFormParam("BlockDeviceMapping.1.Ebs.VolumeId", "vol-test1")
.addFormParam("InstanceId", "1").build();
public void testSetBlockDeviceMappingForInstanceInRegion() throws SecurityException, NoSuchMethodException,
IOException {
Invokable<?, ?> method = method(InstanceApi.class, "setBlockDeviceMappingForInstanceInRegion", String.class,
String.class, Map.class);
Map<String, BlockDevice> mapping = Maps.newLinkedHashMap();
mapping.put("/dev/sda1", new BlockDevice("vol-test1", true));
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1", mapping));
request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, filter.filter(setBlockDeviceMapping).getPayload().getRawContent().toString(),
"application/x-www-form-urlencoded", false);
checkFilters(request);
}
public void testGetConsoleOutputForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(InstanceApi.class, "getConsoleOutputForInstanceInRegion", String.class, String.class);
GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "1"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request,
"Action=GetConsoleOutput&InstanceId=1",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, GetConsoleOutputResponseHandler.class);
assertFallbackClassEquals(method, null);
checkFilters(request);
}
}
|
googleads/google-ads-java | 35,734 | google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/errors/UserListErrorEnum.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v19/errors/user_list_error.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v19.errors;
/**
* <pre>
* Container for enum describing possible user list errors.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.errors.UserListErrorEnum}
*/
public final class UserListErrorEnum extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v19.errors.UserListErrorEnum)
UserListErrorEnumOrBuilder {
private static final long serialVersionUID = 0L;
// Use UserListErrorEnum.newBuilder() to construct.
private UserListErrorEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UserListErrorEnum() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new UserListErrorEnum();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.errors.UserListErrorProto.internal_static_google_ads_googleads_v19_errors_UserListErrorEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.errors.UserListErrorProto.internal_static_google_ads_googleads_v19_errors_UserListErrorEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.errors.UserListErrorEnum.class, com.google.ads.googleads.v19.errors.UserListErrorEnum.Builder.class);
}
/**
* <pre>
* Enum describing possible user list errors.
* </pre>
*
* Protobuf enum {@code google.ads.googleads.v19.errors.UserListErrorEnum.UserListError}
*/
public enum UserListError
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <pre>
* Enum unspecified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
UNSPECIFIED(0),
/**
* <pre>
* The received error code is not known in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
UNKNOWN(1),
/**
* <pre>
* Creating and updating external remarketing user lists is not supported.
* </pre>
*
* <code>EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED = 2;</code>
*/
EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED(2),
/**
* <pre>
* Concrete type of user list is required.
* </pre>
*
* <code>CONCRETE_TYPE_REQUIRED = 3;</code>
*/
CONCRETE_TYPE_REQUIRED(3),
/**
* <pre>
* Creating/updating user list conversion types requires specifying the
* conversion type Id.
* </pre>
*
* <code>CONVERSION_TYPE_ID_REQUIRED = 4;</code>
*/
CONVERSION_TYPE_ID_REQUIRED(4),
/**
* <pre>
* Remarketing user list cannot have duplicate conversion types.
* </pre>
*
* <code>DUPLICATE_CONVERSION_TYPES = 5;</code>
*/
DUPLICATE_CONVERSION_TYPES(5),
/**
* <pre>
* Conversion type is invalid/unknown.
* </pre>
*
* <code>INVALID_CONVERSION_TYPE = 6;</code>
*/
INVALID_CONVERSION_TYPE(6),
/**
* <pre>
* User list description is empty or invalid.
* </pre>
*
* <code>INVALID_DESCRIPTION = 7;</code>
*/
INVALID_DESCRIPTION(7),
/**
* <pre>
* User list name is empty or invalid.
* </pre>
*
* <code>INVALID_NAME = 8;</code>
*/
INVALID_NAME(8),
/**
* <pre>
* Type of the UserList does not match.
* </pre>
*
* <code>INVALID_TYPE = 9;</code>
*/
INVALID_TYPE(9),
/**
* <pre>
* Embedded logical user lists are not allowed.
* </pre>
*
* <code>CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND = 10;</code>
*/
CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND(10),
/**
* <pre>
* User list rule operand is invalid.
* </pre>
*
* <code>INVALID_USER_LIST_LOGICAL_RULE_OPERAND = 11;</code>
*/
INVALID_USER_LIST_LOGICAL_RULE_OPERAND(11),
/**
* <pre>
* Name is already being used for another user list for the account.
* </pre>
*
* <code>NAME_ALREADY_USED = 12;</code>
*/
NAME_ALREADY_USED(12),
/**
* <pre>
* Name is required when creating a new conversion type.
* </pre>
*
* <code>NEW_CONVERSION_TYPE_NAME_REQUIRED = 13;</code>
*/
NEW_CONVERSION_TYPE_NAME_REQUIRED(13),
/**
* <pre>
* The given conversion type name has been used.
* </pre>
*
* <code>CONVERSION_TYPE_NAME_ALREADY_USED = 14;</code>
*/
CONVERSION_TYPE_NAME_ALREADY_USED(14),
/**
* <pre>
* Only an owner account may edit a user list.
* </pre>
*
* <code>OWNERSHIP_REQUIRED_FOR_SET = 15;</code>
*/
OWNERSHIP_REQUIRED_FOR_SET(15),
/**
* <pre>
* Creating user list without setting type in oneof user_list field, or
* creating/updating read-only user list types is not allowed.
* </pre>
*
* <code>USER_LIST_MUTATE_NOT_SUPPORTED = 16;</code>
*/
USER_LIST_MUTATE_NOT_SUPPORTED(16),
/**
* <pre>
* Rule is invalid.
* </pre>
*
* <code>INVALID_RULE = 17;</code>
*/
INVALID_RULE(17),
/**
* <pre>
* The specified date range is empty.
* </pre>
*
* <code>INVALID_DATE_RANGE = 27;</code>
*/
INVALID_DATE_RANGE(27),
/**
* <pre>
* A UserList which is privacy sensitive or legal rejected cannot be mutated
* by external users.
* </pre>
*
* <code>CAN_NOT_MUTATE_SENSITIVE_USERLIST = 28;</code>
*/
CAN_NOT_MUTATE_SENSITIVE_USERLIST(28),
/**
* <pre>
* Maximum number of rulebased user lists a customer can have.
* </pre>
*
* <code>MAX_NUM_RULEBASED_USERLISTS = 29;</code>
*/
MAX_NUM_RULEBASED_USERLISTS(29),
/**
* <pre>
* BasicUserList's billable record field cannot be modified once it is set.
* </pre>
*
* <code>CANNOT_MODIFY_BILLABLE_RECORD_COUNT = 30;</code>
*/
CANNOT_MODIFY_BILLABLE_RECORD_COUNT(30),
/**
* <pre>
* crm_based_user_list.app_id field must be set when upload_key_type is
* MOBILE_ADVERTISING_ID.
* </pre>
*
* <code>APP_ID_NOT_SET = 31;</code>
*/
APP_ID_NOT_SET(31),
/**
* <pre>
* Name of the user list is reserved for system generated lists and cannot
* be used.
* </pre>
*
* <code>USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST = 32;</code>
*/
USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST(32),
/**
* <pre>
* Advertiser needs to be on the allow-list to use remarketing lists created
* from advertiser uploaded data (for example, Customer Match lists).
* </pre>
*
* <code>ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA = 37;</code>
*/
ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA(37),
/**
* <pre>
* The provided rule_type is not supported for the user list.
* </pre>
*
* <code>RULE_TYPE_IS_NOT_SUPPORTED = 34;</code>
*/
RULE_TYPE_IS_NOT_SUPPORTED(34),
/**
* <pre>
* Similar user list cannot be used as a logical user list operand.
* </pre>
*
* <code>CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND = 35;</code>
*/
CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND(35),
/**
* <pre>
* Logical user list should not have a mix of CRM based user list and other
* types of lists in its rules.
* </pre>
*
* <code>CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS = 36;</code>
*/
CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS(36),
/**
* <pre>
* crm_based_user_list.app_id field can only be set when upload_key_type is
* MOBILE_ADVERTISING_ID.
* </pre>
*
* <code>APP_ID_NOT_ALLOWED = 39;</code>
*/
APP_ID_NOT_ALLOWED(39),
/**
* <pre>
* Google system generated user lists cannot be mutated.
* </pre>
*
* <code>CANNOT_MUTATE_SYSTEM_LIST = 40;</code>
*/
CANNOT_MUTATE_SYSTEM_LIST(40),
/**
* <pre>
* The mobile app associated with the remarketing list is sensitive.
* </pre>
*
* <code>MOBILE_APP_IS_SENSITIVE = 41;</code>
*/
MOBILE_APP_IS_SENSITIVE(41),
/**
* <pre>
* One or more given seed lists do not exist.
* </pre>
*
* <code>SEED_LIST_DOES_NOT_EXIST = 42;</code>
*/
SEED_LIST_DOES_NOT_EXIST(42),
/**
* <pre>
* One or more given seed lists are not accessible to the current user.
* </pre>
*
* <code>INVALID_SEED_LIST_ACCESS_REASON = 43;</code>
*/
INVALID_SEED_LIST_ACCESS_REASON(43),
/**
* <pre>
* One or more given seed lists have an unsupported type.
* </pre>
*
* <code>INVALID_SEED_LIST_TYPE = 44;</code>
*/
INVALID_SEED_LIST_TYPE(44),
/**
* <pre>
* One or more invalid country codes are added to Lookalike UserList.
* </pre>
*
* <code>INVALID_COUNTRY_CODES = 45;</code>
*/
INVALID_COUNTRY_CODES(45),
UNRECOGNIZED(-1),
;
/**
* <pre>
* Enum unspecified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
public static final int UNSPECIFIED_VALUE = 0;
/**
* <pre>
* The received error code is not known in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
public static final int UNKNOWN_VALUE = 1;
/**
* <pre>
* Creating and updating external remarketing user lists is not supported.
* </pre>
*
* <code>EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED = 2;</code>
*/
public static final int EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED_VALUE = 2;
/**
* <pre>
* Concrete type of user list is required.
* </pre>
*
* <code>CONCRETE_TYPE_REQUIRED = 3;</code>
*/
public static final int CONCRETE_TYPE_REQUIRED_VALUE = 3;
/**
* <pre>
* Creating/updating user list conversion types requires specifying the
* conversion type Id.
* </pre>
*
* <code>CONVERSION_TYPE_ID_REQUIRED = 4;</code>
*/
public static final int CONVERSION_TYPE_ID_REQUIRED_VALUE = 4;
/**
* <pre>
* Remarketing user list cannot have duplicate conversion types.
* </pre>
*
* <code>DUPLICATE_CONVERSION_TYPES = 5;</code>
*/
public static final int DUPLICATE_CONVERSION_TYPES_VALUE = 5;
/**
* <pre>
* Conversion type is invalid/unknown.
* </pre>
*
* <code>INVALID_CONVERSION_TYPE = 6;</code>
*/
public static final int INVALID_CONVERSION_TYPE_VALUE = 6;
/**
* <pre>
* User list description is empty or invalid.
* </pre>
*
* <code>INVALID_DESCRIPTION = 7;</code>
*/
public static final int INVALID_DESCRIPTION_VALUE = 7;
/**
* <pre>
* User list name is empty or invalid.
* </pre>
*
* <code>INVALID_NAME = 8;</code>
*/
public static final int INVALID_NAME_VALUE = 8;
/**
* <pre>
* Type of the UserList does not match.
* </pre>
*
* <code>INVALID_TYPE = 9;</code>
*/
public static final int INVALID_TYPE_VALUE = 9;
/**
* <pre>
* Embedded logical user lists are not allowed.
* </pre>
*
* <code>CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND = 10;</code>
*/
public static final int CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND_VALUE = 10;
/**
* <pre>
* User list rule operand is invalid.
* </pre>
*
* <code>INVALID_USER_LIST_LOGICAL_RULE_OPERAND = 11;</code>
*/
public static final int INVALID_USER_LIST_LOGICAL_RULE_OPERAND_VALUE = 11;
/**
* <pre>
* Name is already being used for another user list for the account.
* </pre>
*
* <code>NAME_ALREADY_USED = 12;</code>
*/
public static final int NAME_ALREADY_USED_VALUE = 12;
/**
* <pre>
* Name is required when creating a new conversion type.
* </pre>
*
* <code>NEW_CONVERSION_TYPE_NAME_REQUIRED = 13;</code>
*/
public static final int NEW_CONVERSION_TYPE_NAME_REQUIRED_VALUE = 13;
/**
* <pre>
* The given conversion type name has been used.
* </pre>
*
* <code>CONVERSION_TYPE_NAME_ALREADY_USED = 14;</code>
*/
public static final int CONVERSION_TYPE_NAME_ALREADY_USED_VALUE = 14;
/**
* <pre>
* Only an owner account may edit a user list.
* </pre>
*
* <code>OWNERSHIP_REQUIRED_FOR_SET = 15;</code>
*/
public static final int OWNERSHIP_REQUIRED_FOR_SET_VALUE = 15;
/**
* <pre>
* Creating user list without setting type in oneof user_list field, or
* creating/updating read-only user list types is not allowed.
* </pre>
*
* <code>USER_LIST_MUTATE_NOT_SUPPORTED = 16;</code>
*/
public static final int USER_LIST_MUTATE_NOT_SUPPORTED_VALUE = 16;
/**
* <pre>
* Rule is invalid.
* </pre>
*
* <code>INVALID_RULE = 17;</code>
*/
public static final int INVALID_RULE_VALUE = 17;
/**
* <pre>
* The specified date range is empty.
* </pre>
*
* <code>INVALID_DATE_RANGE = 27;</code>
*/
public static final int INVALID_DATE_RANGE_VALUE = 27;
/**
* <pre>
* A UserList which is privacy sensitive or legal rejected cannot be mutated
* by external users.
* </pre>
*
* <code>CAN_NOT_MUTATE_SENSITIVE_USERLIST = 28;</code>
*/
public static final int CAN_NOT_MUTATE_SENSITIVE_USERLIST_VALUE = 28;
/**
* <pre>
* Maximum number of rulebased user lists a customer can have.
* </pre>
*
* <code>MAX_NUM_RULEBASED_USERLISTS = 29;</code>
*/
public static final int MAX_NUM_RULEBASED_USERLISTS_VALUE = 29;
/**
* <pre>
* BasicUserList's billable record field cannot be modified once it is set.
* </pre>
*
* <code>CANNOT_MODIFY_BILLABLE_RECORD_COUNT = 30;</code>
*/
public static final int CANNOT_MODIFY_BILLABLE_RECORD_COUNT_VALUE = 30;
/**
* <pre>
* crm_based_user_list.app_id field must be set when upload_key_type is
* MOBILE_ADVERTISING_ID.
* </pre>
*
* <code>APP_ID_NOT_SET = 31;</code>
*/
public static final int APP_ID_NOT_SET_VALUE = 31;
/**
* <pre>
* Name of the user list is reserved for system generated lists and cannot
* be used.
* </pre>
*
* <code>USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST = 32;</code>
*/
public static final int USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST_VALUE = 32;
/**
* <pre>
* Advertiser needs to be on the allow-list to use remarketing lists created
* from advertiser uploaded data (for example, Customer Match lists).
* </pre>
*
* <code>ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA = 37;</code>
*/
public static final int ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA_VALUE = 37;
/**
* <pre>
* The provided rule_type is not supported for the user list.
* </pre>
*
* <code>RULE_TYPE_IS_NOT_SUPPORTED = 34;</code>
*/
public static final int RULE_TYPE_IS_NOT_SUPPORTED_VALUE = 34;
/**
* <pre>
* Similar user list cannot be used as a logical user list operand.
* </pre>
*
* <code>CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND = 35;</code>
*/
public static final int CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND_VALUE = 35;
/**
* <pre>
* Logical user list should not have a mix of CRM based user list and other
* types of lists in its rules.
* </pre>
*
* <code>CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS = 36;</code>
*/
public static final int CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS_VALUE = 36;
/**
* <pre>
* crm_based_user_list.app_id field can only be set when upload_key_type is
* MOBILE_ADVERTISING_ID.
* </pre>
*
* <code>APP_ID_NOT_ALLOWED = 39;</code>
*/
public static final int APP_ID_NOT_ALLOWED_VALUE = 39;
/**
* <pre>
* Google system generated user lists cannot be mutated.
* </pre>
*
* <code>CANNOT_MUTATE_SYSTEM_LIST = 40;</code>
*/
public static final int CANNOT_MUTATE_SYSTEM_LIST_VALUE = 40;
/**
* <pre>
* The mobile app associated with the remarketing list is sensitive.
* </pre>
*
* <code>MOBILE_APP_IS_SENSITIVE = 41;</code>
*/
public static final int MOBILE_APP_IS_SENSITIVE_VALUE = 41;
/**
* <pre>
* One or more given seed lists do not exist.
* </pre>
*
* <code>SEED_LIST_DOES_NOT_EXIST = 42;</code>
*/
public static final int SEED_LIST_DOES_NOT_EXIST_VALUE = 42;
/**
* <pre>
* One or more given seed lists are not accessible to the current user.
* </pre>
*
* <code>INVALID_SEED_LIST_ACCESS_REASON = 43;</code>
*/
public static final int INVALID_SEED_LIST_ACCESS_REASON_VALUE = 43;
/**
* <pre>
* One or more given seed lists have an unsupported type.
* </pre>
*
* <code>INVALID_SEED_LIST_TYPE = 44;</code>
*/
public static final int INVALID_SEED_LIST_TYPE_VALUE = 44;
/**
* <pre>
* One or more invalid country codes are added to Lookalike UserList.
* </pre>
*
* <code>INVALID_COUNTRY_CODES = 45;</code>
*/
public static final int INVALID_COUNTRY_CODES_VALUE = 45;
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 UserListError 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 UserListError forNumber(int value) {
switch (value) {
case 0: return UNSPECIFIED;
case 1: return UNKNOWN;
case 2: return EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED;
case 3: return CONCRETE_TYPE_REQUIRED;
case 4: return CONVERSION_TYPE_ID_REQUIRED;
case 5: return DUPLICATE_CONVERSION_TYPES;
case 6: return INVALID_CONVERSION_TYPE;
case 7: return INVALID_DESCRIPTION;
case 8: return INVALID_NAME;
case 9: return INVALID_TYPE;
case 10: return CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND;
case 11: return INVALID_USER_LIST_LOGICAL_RULE_OPERAND;
case 12: return NAME_ALREADY_USED;
case 13: return NEW_CONVERSION_TYPE_NAME_REQUIRED;
case 14: return CONVERSION_TYPE_NAME_ALREADY_USED;
case 15: return OWNERSHIP_REQUIRED_FOR_SET;
case 16: return USER_LIST_MUTATE_NOT_SUPPORTED;
case 17: return INVALID_RULE;
case 27: return INVALID_DATE_RANGE;
case 28: return CAN_NOT_MUTATE_SENSITIVE_USERLIST;
case 29: return MAX_NUM_RULEBASED_USERLISTS;
case 30: return CANNOT_MODIFY_BILLABLE_RECORD_COUNT;
case 31: return APP_ID_NOT_SET;
case 32: return USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST;
case 37: return ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA;
case 34: return RULE_TYPE_IS_NOT_SUPPORTED;
case 35: return CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND;
case 36: return CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS;
case 39: return APP_ID_NOT_ALLOWED;
case 40: return CANNOT_MUTATE_SYSTEM_LIST;
case 41: return MOBILE_APP_IS_SENSITIVE;
case 42: return SEED_LIST_DOES_NOT_EXIST;
case 43: return INVALID_SEED_LIST_ACCESS_REASON;
case 44: return INVALID_SEED_LIST_TYPE;
case 45: return INVALID_COUNTRY_CODES;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<UserListError>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
UserListError> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<UserListError>() {
public UserListError findValueByNumber(int number) {
return UserListError.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return com.google.ads.googleads.v19.errors.UserListErrorEnum.getDescriptor().getEnumTypes().get(0);
}
private static final UserListError[] VALUES = values();
public static UserListError 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 UserListError(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.ads.googleads.v19.errors.UserListErrorEnum.UserListError)
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v19.errors.UserListErrorEnum)) {
return super.equals(obj);
}
com.google.ads.googleads.v19.errors.UserListErrorEnum other = (com.google.ads.googleads.v19.errors.UserListErrorEnum) obj;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v19.errors.UserListErrorEnum parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.errors.UserListErrorEnum parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.errors.UserListErrorEnum parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.errors.UserListErrorEnum parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.errors.UserListErrorEnum parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.errors.UserListErrorEnum parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.errors.UserListErrorEnum parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.errors.UserListErrorEnum parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v19.errors.UserListErrorEnum parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.errors.UserListErrorEnum parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v19.errors.UserListErrorEnum parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.errors.UserListErrorEnum parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v19.errors.UserListErrorEnum prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Container for enum describing possible user list errors.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.errors.UserListErrorEnum}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.errors.UserListErrorEnum)
com.google.ads.googleads.v19.errors.UserListErrorEnumOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.errors.UserListErrorProto.internal_static_google_ads_googleads_v19_errors_UserListErrorEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.errors.UserListErrorProto.internal_static_google_ads_googleads_v19_errors_UserListErrorEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.errors.UserListErrorEnum.class, com.google.ads.googleads.v19.errors.UserListErrorEnum.Builder.class);
}
// Construct using com.google.ads.googleads.v19.errors.UserListErrorEnum.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v19.errors.UserListErrorProto.internal_static_google_ads_googleads_v19_errors_UserListErrorEnum_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v19.errors.UserListErrorEnum getDefaultInstanceForType() {
return com.google.ads.googleads.v19.errors.UserListErrorEnum.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v19.errors.UserListErrorEnum build() {
com.google.ads.googleads.v19.errors.UserListErrorEnum result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v19.errors.UserListErrorEnum buildPartial() {
com.google.ads.googleads.v19.errors.UserListErrorEnum result = new com.google.ads.googleads.v19.errors.UserListErrorEnum(this);
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v19.errors.UserListErrorEnum) {
return mergeFrom((com.google.ads.googleads.v19.errors.UserListErrorEnum)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v19.errors.UserListErrorEnum other) {
if (other == com.google.ads.googleads.v19.errors.UserListErrorEnum.getDefaultInstance()) return this;
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v19.errors.UserListErrorEnum)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v19.errors.UserListErrorEnum)
private static final com.google.ads.googleads.v19.errors.UserListErrorEnum DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v19.errors.UserListErrorEnum();
}
public static com.google.ads.googleads.v19.errors.UserListErrorEnum getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UserListErrorEnum>
PARSER = new com.google.protobuf.AbstractParser<UserListErrorEnum>() {
@java.lang.Override
public UserListErrorEnum 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<UserListErrorEnum> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UserListErrorEnum> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v19.errors.UserListErrorEnum getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 35,734 | google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/errors/UserListErrorEnum.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v20/errors/user_list_error.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v20.errors;
/**
* <pre>
* Container for enum describing possible user list errors.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.errors.UserListErrorEnum}
*/
public final class UserListErrorEnum extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v20.errors.UserListErrorEnum)
UserListErrorEnumOrBuilder {
private static final long serialVersionUID = 0L;
// Use UserListErrorEnum.newBuilder() to construct.
private UserListErrorEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UserListErrorEnum() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new UserListErrorEnum();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.errors.UserListErrorProto.internal_static_google_ads_googleads_v20_errors_UserListErrorEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.errors.UserListErrorProto.internal_static_google_ads_googleads_v20_errors_UserListErrorEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.errors.UserListErrorEnum.class, com.google.ads.googleads.v20.errors.UserListErrorEnum.Builder.class);
}
/**
* <pre>
* Enum describing possible user list errors.
* </pre>
*
* Protobuf enum {@code google.ads.googleads.v20.errors.UserListErrorEnum.UserListError}
*/
public enum UserListError
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <pre>
* Enum unspecified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
UNSPECIFIED(0),
/**
* <pre>
* The received error code is not known in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
UNKNOWN(1),
/**
* <pre>
* Creating and updating external remarketing user lists is not supported.
* </pre>
*
* <code>EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED = 2;</code>
*/
EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED(2),
/**
* <pre>
* Concrete type of user list is required.
* </pre>
*
* <code>CONCRETE_TYPE_REQUIRED = 3;</code>
*/
CONCRETE_TYPE_REQUIRED(3),
/**
* <pre>
* Creating/updating user list conversion types requires specifying the
* conversion type Id.
* </pre>
*
* <code>CONVERSION_TYPE_ID_REQUIRED = 4;</code>
*/
CONVERSION_TYPE_ID_REQUIRED(4),
/**
* <pre>
* Remarketing user list cannot have duplicate conversion types.
* </pre>
*
* <code>DUPLICATE_CONVERSION_TYPES = 5;</code>
*/
DUPLICATE_CONVERSION_TYPES(5),
/**
* <pre>
* Conversion type is invalid/unknown.
* </pre>
*
* <code>INVALID_CONVERSION_TYPE = 6;</code>
*/
INVALID_CONVERSION_TYPE(6),
/**
* <pre>
* User list description is empty or invalid.
* </pre>
*
* <code>INVALID_DESCRIPTION = 7;</code>
*/
INVALID_DESCRIPTION(7),
/**
* <pre>
* User list name is empty or invalid.
* </pre>
*
* <code>INVALID_NAME = 8;</code>
*/
INVALID_NAME(8),
/**
* <pre>
* Type of the UserList does not match.
* </pre>
*
* <code>INVALID_TYPE = 9;</code>
*/
INVALID_TYPE(9),
/**
* <pre>
* Embedded logical user lists are not allowed.
* </pre>
*
* <code>CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND = 10;</code>
*/
CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND(10),
/**
* <pre>
* User list rule operand is invalid.
* </pre>
*
* <code>INVALID_USER_LIST_LOGICAL_RULE_OPERAND = 11;</code>
*/
INVALID_USER_LIST_LOGICAL_RULE_OPERAND(11),
/**
* <pre>
* Name is already being used for another user list for the account.
* </pre>
*
* <code>NAME_ALREADY_USED = 12;</code>
*/
NAME_ALREADY_USED(12),
/**
* <pre>
* Name is required when creating a new conversion type.
* </pre>
*
* <code>NEW_CONVERSION_TYPE_NAME_REQUIRED = 13;</code>
*/
NEW_CONVERSION_TYPE_NAME_REQUIRED(13),
/**
* <pre>
* The given conversion type name has been used.
* </pre>
*
* <code>CONVERSION_TYPE_NAME_ALREADY_USED = 14;</code>
*/
CONVERSION_TYPE_NAME_ALREADY_USED(14),
/**
* <pre>
* Only an owner account may edit a user list.
* </pre>
*
* <code>OWNERSHIP_REQUIRED_FOR_SET = 15;</code>
*/
OWNERSHIP_REQUIRED_FOR_SET(15),
/**
* <pre>
* Creating user list without setting type in oneof user_list field, or
* creating/updating read-only user list types is not allowed.
* </pre>
*
* <code>USER_LIST_MUTATE_NOT_SUPPORTED = 16;</code>
*/
USER_LIST_MUTATE_NOT_SUPPORTED(16),
/**
* <pre>
* Rule is invalid.
* </pre>
*
* <code>INVALID_RULE = 17;</code>
*/
INVALID_RULE(17),
/**
* <pre>
* The specified date range is empty.
* </pre>
*
* <code>INVALID_DATE_RANGE = 27;</code>
*/
INVALID_DATE_RANGE(27),
/**
* <pre>
* A UserList which is privacy sensitive or legal rejected cannot be mutated
* by external users.
* </pre>
*
* <code>CAN_NOT_MUTATE_SENSITIVE_USERLIST = 28;</code>
*/
CAN_NOT_MUTATE_SENSITIVE_USERLIST(28),
/**
* <pre>
* Maximum number of rulebased user lists a customer can have.
* </pre>
*
* <code>MAX_NUM_RULEBASED_USERLISTS = 29;</code>
*/
MAX_NUM_RULEBASED_USERLISTS(29),
/**
* <pre>
* BasicUserList's billable record field cannot be modified once it is set.
* </pre>
*
* <code>CANNOT_MODIFY_BILLABLE_RECORD_COUNT = 30;</code>
*/
CANNOT_MODIFY_BILLABLE_RECORD_COUNT(30),
/**
* <pre>
* crm_based_user_list.app_id field must be set when upload_key_type is
* MOBILE_ADVERTISING_ID.
* </pre>
*
* <code>APP_ID_NOT_SET = 31;</code>
*/
APP_ID_NOT_SET(31),
/**
* <pre>
* Name of the user list is reserved for system generated lists and cannot
* be used.
* </pre>
*
* <code>USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST = 32;</code>
*/
USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST(32),
/**
* <pre>
* Advertiser needs to be on the allow-list to use remarketing lists created
* from advertiser uploaded data (for example, Customer Match lists).
* </pre>
*
* <code>ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA = 37;</code>
*/
ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA(37),
/**
* <pre>
* The provided rule_type is not supported for the user list.
* </pre>
*
* <code>RULE_TYPE_IS_NOT_SUPPORTED = 34;</code>
*/
RULE_TYPE_IS_NOT_SUPPORTED(34),
/**
* <pre>
* Similar user list cannot be used as a logical user list operand.
* </pre>
*
* <code>CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND = 35;</code>
*/
CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND(35),
/**
* <pre>
* Logical user list should not have a mix of CRM based user list and other
* types of lists in its rules.
* </pre>
*
* <code>CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS = 36;</code>
*/
CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS(36),
/**
* <pre>
* crm_based_user_list.app_id field can only be set when upload_key_type is
* MOBILE_ADVERTISING_ID.
* </pre>
*
* <code>APP_ID_NOT_ALLOWED = 39;</code>
*/
APP_ID_NOT_ALLOWED(39),
/**
* <pre>
* Google system generated user lists cannot be mutated.
* </pre>
*
* <code>CANNOT_MUTATE_SYSTEM_LIST = 40;</code>
*/
CANNOT_MUTATE_SYSTEM_LIST(40),
/**
* <pre>
* The mobile app associated with the remarketing list is sensitive.
* </pre>
*
* <code>MOBILE_APP_IS_SENSITIVE = 41;</code>
*/
MOBILE_APP_IS_SENSITIVE(41),
/**
* <pre>
* One or more given seed lists do not exist.
* </pre>
*
* <code>SEED_LIST_DOES_NOT_EXIST = 42;</code>
*/
SEED_LIST_DOES_NOT_EXIST(42),
/**
* <pre>
* One or more given seed lists are not accessible to the current user.
* </pre>
*
* <code>INVALID_SEED_LIST_ACCESS_REASON = 43;</code>
*/
INVALID_SEED_LIST_ACCESS_REASON(43),
/**
* <pre>
* One or more given seed lists have an unsupported type.
* </pre>
*
* <code>INVALID_SEED_LIST_TYPE = 44;</code>
*/
INVALID_SEED_LIST_TYPE(44),
/**
* <pre>
* One or more invalid country codes are added to Lookalike UserList.
* </pre>
*
* <code>INVALID_COUNTRY_CODES = 45;</code>
*/
INVALID_COUNTRY_CODES(45),
UNRECOGNIZED(-1),
;
/**
* <pre>
* Enum unspecified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
public static final int UNSPECIFIED_VALUE = 0;
/**
* <pre>
* The received error code is not known in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
public static final int UNKNOWN_VALUE = 1;
/**
* <pre>
* Creating and updating external remarketing user lists is not supported.
* </pre>
*
* <code>EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED = 2;</code>
*/
public static final int EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED_VALUE = 2;
/**
* <pre>
* Concrete type of user list is required.
* </pre>
*
* <code>CONCRETE_TYPE_REQUIRED = 3;</code>
*/
public static final int CONCRETE_TYPE_REQUIRED_VALUE = 3;
/**
* <pre>
* Creating/updating user list conversion types requires specifying the
* conversion type Id.
* </pre>
*
* <code>CONVERSION_TYPE_ID_REQUIRED = 4;</code>
*/
public static final int CONVERSION_TYPE_ID_REQUIRED_VALUE = 4;
/**
* <pre>
* Remarketing user list cannot have duplicate conversion types.
* </pre>
*
* <code>DUPLICATE_CONVERSION_TYPES = 5;</code>
*/
public static final int DUPLICATE_CONVERSION_TYPES_VALUE = 5;
/**
* <pre>
* Conversion type is invalid/unknown.
* </pre>
*
* <code>INVALID_CONVERSION_TYPE = 6;</code>
*/
public static final int INVALID_CONVERSION_TYPE_VALUE = 6;
/**
* <pre>
* User list description is empty or invalid.
* </pre>
*
* <code>INVALID_DESCRIPTION = 7;</code>
*/
public static final int INVALID_DESCRIPTION_VALUE = 7;
/**
* <pre>
* User list name is empty or invalid.
* </pre>
*
* <code>INVALID_NAME = 8;</code>
*/
public static final int INVALID_NAME_VALUE = 8;
/**
* <pre>
* Type of the UserList does not match.
* </pre>
*
* <code>INVALID_TYPE = 9;</code>
*/
public static final int INVALID_TYPE_VALUE = 9;
/**
* <pre>
* Embedded logical user lists are not allowed.
* </pre>
*
* <code>CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND = 10;</code>
*/
public static final int CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND_VALUE = 10;
/**
* <pre>
* User list rule operand is invalid.
* </pre>
*
* <code>INVALID_USER_LIST_LOGICAL_RULE_OPERAND = 11;</code>
*/
public static final int INVALID_USER_LIST_LOGICAL_RULE_OPERAND_VALUE = 11;
/**
* <pre>
* Name is already being used for another user list for the account.
* </pre>
*
* <code>NAME_ALREADY_USED = 12;</code>
*/
public static final int NAME_ALREADY_USED_VALUE = 12;
/**
* <pre>
* Name is required when creating a new conversion type.
* </pre>
*
* <code>NEW_CONVERSION_TYPE_NAME_REQUIRED = 13;</code>
*/
public static final int NEW_CONVERSION_TYPE_NAME_REQUIRED_VALUE = 13;
/**
* <pre>
* The given conversion type name has been used.
* </pre>
*
* <code>CONVERSION_TYPE_NAME_ALREADY_USED = 14;</code>
*/
public static final int CONVERSION_TYPE_NAME_ALREADY_USED_VALUE = 14;
/**
* <pre>
* Only an owner account may edit a user list.
* </pre>
*
* <code>OWNERSHIP_REQUIRED_FOR_SET = 15;</code>
*/
public static final int OWNERSHIP_REQUIRED_FOR_SET_VALUE = 15;
/**
* <pre>
* Creating user list without setting type in oneof user_list field, or
* creating/updating read-only user list types is not allowed.
* </pre>
*
* <code>USER_LIST_MUTATE_NOT_SUPPORTED = 16;</code>
*/
public static final int USER_LIST_MUTATE_NOT_SUPPORTED_VALUE = 16;
/**
* <pre>
* Rule is invalid.
* </pre>
*
* <code>INVALID_RULE = 17;</code>
*/
public static final int INVALID_RULE_VALUE = 17;
/**
* <pre>
* The specified date range is empty.
* </pre>
*
* <code>INVALID_DATE_RANGE = 27;</code>
*/
public static final int INVALID_DATE_RANGE_VALUE = 27;
/**
* <pre>
* A UserList which is privacy sensitive or legal rejected cannot be mutated
* by external users.
* </pre>
*
* <code>CAN_NOT_MUTATE_SENSITIVE_USERLIST = 28;</code>
*/
public static final int CAN_NOT_MUTATE_SENSITIVE_USERLIST_VALUE = 28;
/**
* <pre>
* Maximum number of rulebased user lists a customer can have.
* </pre>
*
* <code>MAX_NUM_RULEBASED_USERLISTS = 29;</code>
*/
public static final int MAX_NUM_RULEBASED_USERLISTS_VALUE = 29;
/**
* <pre>
* BasicUserList's billable record field cannot be modified once it is set.
* </pre>
*
* <code>CANNOT_MODIFY_BILLABLE_RECORD_COUNT = 30;</code>
*/
public static final int CANNOT_MODIFY_BILLABLE_RECORD_COUNT_VALUE = 30;
/**
* <pre>
* crm_based_user_list.app_id field must be set when upload_key_type is
* MOBILE_ADVERTISING_ID.
* </pre>
*
* <code>APP_ID_NOT_SET = 31;</code>
*/
public static final int APP_ID_NOT_SET_VALUE = 31;
/**
* <pre>
* Name of the user list is reserved for system generated lists and cannot
* be used.
* </pre>
*
* <code>USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST = 32;</code>
*/
public static final int USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST_VALUE = 32;
/**
* <pre>
* Advertiser needs to be on the allow-list to use remarketing lists created
* from advertiser uploaded data (for example, Customer Match lists).
* </pre>
*
* <code>ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA = 37;</code>
*/
public static final int ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA_VALUE = 37;
/**
* <pre>
* The provided rule_type is not supported for the user list.
* </pre>
*
* <code>RULE_TYPE_IS_NOT_SUPPORTED = 34;</code>
*/
public static final int RULE_TYPE_IS_NOT_SUPPORTED_VALUE = 34;
/**
* <pre>
* Similar user list cannot be used as a logical user list operand.
* </pre>
*
* <code>CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND = 35;</code>
*/
public static final int CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND_VALUE = 35;
/**
* <pre>
* Logical user list should not have a mix of CRM based user list and other
* types of lists in its rules.
* </pre>
*
* <code>CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS = 36;</code>
*/
public static final int CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS_VALUE = 36;
/**
* <pre>
* crm_based_user_list.app_id field can only be set when upload_key_type is
* MOBILE_ADVERTISING_ID.
* </pre>
*
* <code>APP_ID_NOT_ALLOWED = 39;</code>
*/
public static final int APP_ID_NOT_ALLOWED_VALUE = 39;
/**
* <pre>
* Google system generated user lists cannot be mutated.
* </pre>
*
* <code>CANNOT_MUTATE_SYSTEM_LIST = 40;</code>
*/
public static final int CANNOT_MUTATE_SYSTEM_LIST_VALUE = 40;
/**
* <pre>
* The mobile app associated with the remarketing list is sensitive.
* </pre>
*
* <code>MOBILE_APP_IS_SENSITIVE = 41;</code>
*/
public static final int MOBILE_APP_IS_SENSITIVE_VALUE = 41;
/**
* <pre>
* One or more given seed lists do not exist.
* </pre>
*
* <code>SEED_LIST_DOES_NOT_EXIST = 42;</code>
*/
public static final int SEED_LIST_DOES_NOT_EXIST_VALUE = 42;
/**
* <pre>
* One or more given seed lists are not accessible to the current user.
* </pre>
*
* <code>INVALID_SEED_LIST_ACCESS_REASON = 43;</code>
*/
public static final int INVALID_SEED_LIST_ACCESS_REASON_VALUE = 43;
/**
* <pre>
* One or more given seed lists have an unsupported type.
* </pre>
*
* <code>INVALID_SEED_LIST_TYPE = 44;</code>
*/
public static final int INVALID_SEED_LIST_TYPE_VALUE = 44;
/**
* <pre>
* One or more invalid country codes are added to Lookalike UserList.
* </pre>
*
* <code>INVALID_COUNTRY_CODES = 45;</code>
*/
public static final int INVALID_COUNTRY_CODES_VALUE = 45;
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 UserListError 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 UserListError forNumber(int value) {
switch (value) {
case 0: return UNSPECIFIED;
case 1: return UNKNOWN;
case 2: return EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED;
case 3: return CONCRETE_TYPE_REQUIRED;
case 4: return CONVERSION_TYPE_ID_REQUIRED;
case 5: return DUPLICATE_CONVERSION_TYPES;
case 6: return INVALID_CONVERSION_TYPE;
case 7: return INVALID_DESCRIPTION;
case 8: return INVALID_NAME;
case 9: return INVALID_TYPE;
case 10: return CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND;
case 11: return INVALID_USER_LIST_LOGICAL_RULE_OPERAND;
case 12: return NAME_ALREADY_USED;
case 13: return NEW_CONVERSION_TYPE_NAME_REQUIRED;
case 14: return CONVERSION_TYPE_NAME_ALREADY_USED;
case 15: return OWNERSHIP_REQUIRED_FOR_SET;
case 16: return USER_LIST_MUTATE_NOT_SUPPORTED;
case 17: return INVALID_RULE;
case 27: return INVALID_DATE_RANGE;
case 28: return CAN_NOT_MUTATE_SENSITIVE_USERLIST;
case 29: return MAX_NUM_RULEBASED_USERLISTS;
case 30: return CANNOT_MODIFY_BILLABLE_RECORD_COUNT;
case 31: return APP_ID_NOT_SET;
case 32: return USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST;
case 37: return ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA;
case 34: return RULE_TYPE_IS_NOT_SUPPORTED;
case 35: return CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND;
case 36: return CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS;
case 39: return APP_ID_NOT_ALLOWED;
case 40: return CANNOT_MUTATE_SYSTEM_LIST;
case 41: return MOBILE_APP_IS_SENSITIVE;
case 42: return SEED_LIST_DOES_NOT_EXIST;
case 43: return INVALID_SEED_LIST_ACCESS_REASON;
case 44: return INVALID_SEED_LIST_TYPE;
case 45: return INVALID_COUNTRY_CODES;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<UserListError>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
UserListError> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<UserListError>() {
public UserListError findValueByNumber(int number) {
return UserListError.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return com.google.ads.googleads.v20.errors.UserListErrorEnum.getDescriptor().getEnumTypes().get(0);
}
private static final UserListError[] VALUES = values();
public static UserListError 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 UserListError(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.ads.googleads.v20.errors.UserListErrorEnum.UserListError)
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v20.errors.UserListErrorEnum)) {
return super.equals(obj);
}
com.google.ads.googleads.v20.errors.UserListErrorEnum other = (com.google.ads.googleads.v20.errors.UserListErrorEnum) obj;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v20.errors.UserListErrorEnum parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.errors.UserListErrorEnum parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.errors.UserListErrorEnum parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.errors.UserListErrorEnum parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.errors.UserListErrorEnum parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.errors.UserListErrorEnum parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.errors.UserListErrorEnum parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.errors.UserListErrorEnum parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v20.errors.UserListErrorEnum parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.errors.UserListErrorEnum parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v20.errors.UserListErrorEnum parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.errors.UserListErrorEnum parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v20.errors.UserListErrorEnum prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Container for enum describing possible user list errors.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.errors.UserListErrorEnum}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.errors.UserListErrorEnum)
com.google.ads.googleads.v20.errors.UserListErrorEnumOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.errors.UserListErrorProto.internal_static_google_ads_googleads_v20_errors_UserListErrorEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.errors.UserListErrorProto.internal_static_google_ads_googleads_v20_errors_UserListErrorEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.errors.UserListErrorEnum.class, com.google.ads.googleads.v20.errors.UserListErrorEnum.Builder.class);
}
// Construct using com.google.ads.googleads.v20.errors.UserListErrorEnum.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v20.errors.UserListErrorProto.internal_static_google_ads_googleads_v20_errors_UserListErrorEnum_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v20.errors.UserListErrorEnum getDefaultInstanceForType() {
return com.google.ads.googleads.v20.errors.UserListErrorEnum.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v20.errors.UserListErrorEnum build() {
com.google.ads.googleads.v20.errors.UserListErrorEnum result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v20.errors.UserListErrorEnum buildPartial() {
com.google.ads.googleads.v20.errors.UserListErrorEnum result = new com.google.ads.googleads.v20.errors.UserListErrorEnum(this);
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v20.errors.UserListErrorEnum) {
return mergeFrom((com.google.ads.googleads.v20.errors.UserListErrorEnum)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v20.errors.UserListErrorEnum other) {
if (other == com.google.ads.googleads.v20.errors.UserListErrorEnum.getDefaultInstance()) return this;
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v20.errors.UserListErrorEnum)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v20.errors.UserListErrorEnum)
private static final com.google.ads.googleads.v20.errors.UserListErrorEnum DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v20.errors.UserListErrorEnum();
}
public static com.google.ads.googleads.v20.errors.UserListErrorEnum getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UserListErrorEnum>
PARSER = new com.google.protobuf.AbstractParser<UserListErrorEnum>() {
@java.lang.Override
public UserListErrorEnum 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<UserListErrorEnum> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UserListErrorEnum> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v20.errors.UserListErrorEnum getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 35,734 | google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/errors/UserListErrorEnum.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v21/errors/user_list_error.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v21.errors;
/**
* <pre>
* Container for enum describing possible user list errors.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.errors.UserListErrorEnum}
*/
public final class UserListErrorEnum extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v21.errors.UserListErrorEnum)
UserListErrorEnumOrBuilder {
private static final long serialVersionUID = 0L;
// Use UserListErrorEnum.newBuilder() to construct.
private UserListErrorEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UserListErrorEnum() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new UserListErrorEnum();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.errors.UserListErrorProto.internal_static_google_ads_googleads_v21_errors_UserListErrorEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.errors.UserListErrorProto.internal_static_google_ads_googleads_v21_errors_UserListErrorEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.errors.UserListErrorEnum.class, com.google.ads.googleads.v21.errors.UserListErrorEnum.Builder.class);
}
/**
* <pre>
* Enum describing possible user list errors.
* </pre>
*
* Protobuf enum {@code google.ads.googleads.v21.errors.UserListErrorEnum.UserListError}
*/
public enum UserListError
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <pre>
* Enum unspecified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
UNSPECIFIED(0),
/**
* <pre>
* The received error code is not known in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
UNKNOWN(1),
/**
* <pre>
* Creating and updating external remarketing user lists is not supported.
* </pre>
*
* <code>EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED = 2;</code>
*/
EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED(2),
/**
* <pre>
* Concrete type of user list is required.
* </pre>
*
* <code>CONCRETE_TYPE_REQUIRED = 3;</code>
*/
CONCRETE_TYPE_REQUIRED(3),
/**
* <pre>
* Creating/updating user list conversion types requires specifying the
* conversion type Id.
* </pre>
*
* <code>CONVERSION_TYPE_ID_REQUIRED = 4;</code>
*/
CONVERSION_TYPE_ID_REQUIRED(4),
/**
* <pre>
* Remarketing user list cannot have duplicate conversion types.
* </pre>
*
* <code>DUPLICATE_CONVERSION_TYPES = 5;</code>
*/
DUPLICATE_CONVERSION_TYPES(5),
/**
* <pre>
* Conversion type is invalid/unknown.
* </pre>
*
* <code>INVALID_CONVERSION_TYPE = 6;</code>
*/
INVALID_CONVERSION_TYPE(6),
/**
* <pre>
* User list description is empty or invalid.
* </pre>
*
* <code>INVALID_DESCRIPTION = 7;</code>
*/
INVALID_DESCRIPTION(7),
/**
* <pre>
* User list name is empty or invalid.
* </pre>
*
* <code>INVALID_NAME = 8;</code>
*/
INVALID_NAME(8),
/**
* <pre>
* Type of the UserList does not match.
* </pre>
*
* <code>INVALID_TYPE = 9;</code>
*/
INVALID_TYPE(9),
/**
* <pre>
* Embedded logical user lists are not allowed.
* </pre>
*
* <code>CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND = 10;</code>
*/
CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND(10),
/**
* <pre>
* User list rule operand is invalid.
* </pre>
*
* <code>INVALID_USER_LIST_LOGICAL_RULE_OPERAND = 11;</code>
*/
INVALID_USER_LIST_LOGICAL_RULE_OPERAND(11),
/**
* <pre>
* Name is already being used for another user list for the account.
* </pre>
*
* <code>NAME_ALREADY_USED = 12;</code>
*/
NAME_ALREADY_USED(12),
/**
* <pre>
* Name is required when creating a new conversion type.
* </pre>
*
* <code>NEW_CONVERSION_TYPE_NAME_REQUIRED = 13;</code>
*/
NEW_CONVERSION_TYPE_NAME_REQUIRED(13),
/**
* <pre>
* The given conversion type name has been used.
* </pre>
*
* <code>CONVERSION_TYPE_NAME_ALREADY_USED = 14;</code>
*/
CONVERSION_TYPE_NAME_ALREADY_USED(14),
/**
* <pre>
* Only an owner account may edit a user list.
* </pre>
*
* <code>OWNERSHIP_REQUIRED_FOR_SET = 15;</code>
*/
OWNERSHIP_REQUIRED_FOR_SET(15),
/**
* <pre>
* Creating user list without setting type in oneof user_list field, or
* creating/updating read-only user list types is not allowed.
* </pre>
*
* <code>USER_LIST_MUTATE_NOT_SUPPORTED = 16;</code>
*/
USER_LIST_MUTATE_NOT_SUPPORTED(16),
/**
* <pre>
* Rule is invalid.
* </pre>
*
* <code>INVALID_RULE = 17;</code>
*/
INVALID_RULE(17),
/**
* <pre>
* The specified date range is empty.
* </pre>
*
* <code>INVALID_DATE_RANGE = 27;</code>
*/
INVALID_DATE_RANGE(27),
/**
* <pre>
* A UserList which is privacy sensitive or legal rejected cannot be mutated
* by external users.
* </pre>
*
* <code>CAN_NOT_MUTATE_SENSITIVE_USERLIST = 28;</code>
*/
CAN_NOT_MUTATE_SENSITIVE_USERLIST(28),
/**
* <pre>
* Maximum number of rulebased user lists a customer can have.
* </pre>
*
* <code>MAX_NUM_RULEBASED_USERLISTS = 29;</code>
*/
MAX_NUM_RULEBASED_USERLISTS(29),
/**
* <pre>
* BasicUserList's billable record field cannot be modified once it is set.
* </pre>
*
* <code>CANNOT_MODIFY_BILLABLE_RECORD_COUNT = 30;</code>
*/
CANNOT_MODIFY_BILLABLE_RECORD_COUNT(30),
/**
* <pre>
* crm_based_user_list.app_id field must be set when upload_key_type is
* MOBILE_ADVERTISING_ID.
* </pre>
*
* <code>APP_ID_NOT_SET = 31;</code>
*/
APP_ID_NOT_SET(31),
/**
* <pre>
* Name of the user list is reserved for system generated lists and cannot
* be used.
* </pre>
*
* <code>USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST = 32;</code>
*/
USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST(32),
/**
* <pre>
* Advertiser needs to be on the allow-list to use remarketing lists created
* from advertiser uploaded data (for example, Customer Match lists).
* </pre>
*
* <code>ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA = 37;</code>
*/
ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA(37),
/**
* <pre>
* The provided rule_type is not supported for the user list.
* </pre>
*
* <code>RULE_TYPE_IS_NOT_SUPPORTED = 34;</code>
*/
RULE_TYPE_IS_NOT_SUPPORTED(34),
/**
* <pre>
* Similar user list cannot be used as a logical user list operand.
* </pre>
*
* <code>CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND = 35;</code>
*/
CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND(35),
/**
* <pre>
* Logical user list should not have a mix of CRM based user list and other
* types of lists in its rules.
* </pre>
*
* <code>CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS = 36;</code>
*/
CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS(36),
/**
* <pre>
* crm_based_user_list.app_id field can only be set when upload_key_type is
* MOBILE_ADVERTISING_ID.
* </pre>
*
* <code>APP_ID_NOT_ALLOWED = 39;</code>
*/
APP_ID_NOT_ALLOWED(39),
/**
* <pre>
* Google system generated user lists cannot be mutated.
* </pre>
*
* <code>CANNOT_MUTATE_SYSTEM_LIST = 40;</code>
*/
CANNOT_MUTATE_SYSTEM_LIST(40),
/**
* <pre>
* The mobile app associated with the remarketing list is sensitive.
* </pre>
*
* <code>MOBILE_APP_IS_SENSITIVE = 41;</code>
*/
MOBILE_APP_IS_SENSITIVE(41),
/**
* <pre>
* One or more given seed lists do not exist.
* </pre>
*
* <code>SEED_LIST_DOES_NOT_EXIST = 42;</code>
*/
SEED_LIST_DOES_NOT_EXIST(42),
/**
* <pre>
* One or more given seed lists are not accessible to the current user.
* </pre>
*
* <code>INVALID_SEED_LIST_ACCESS_REASON = 43;</code>
*/
INVALID_SEED_LIST_ACCESS_REASON(43),
/**
* <pre>
* One or more given seed lists have an unsupported type.
* </pre>
*
* <code>INVALID_SEED_LIST_TYPE = 44;</code>
*/
INVALID_SEED_LIST_TYPE(44),
/**
* <pre>
* One or more invalid country codes are added to Lookalike UserList.
* </pre>
*
* <code>INVALID_COUNTRY_CODES = 45;</code>
*/
INVALID_COUNTRY_CODES(45),
UNRECOGNIZED(-1),
;
/**
* <pre>
* Enum unspecified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
public static final int UNSPECIFIED_VALUE = 0;
/**
* <pre>
* The received error code is not known in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
public static final int UNKNOWN_VALUE = 1;
/**
* <pre>
* Creating and updating external remarketing user lists is not supported.
* </pre>
*
* <code>EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED = 2;</code>
*/
public static final int EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED_VALUE = 2;
/**
* <pre>
* Concrete type of user list is required.
* </pre>
*
* <code>CONCRETE_TYPE_REQUIRED = 3;</code>
*/
public static final int CONCRETE_TYPE_REQUIRED_VALUE = 3;
/**
* <pre>
* Creating/updating user list conversion types requires specifying the
* conversion type Id.
* </pre>
*
* <code>CONVERSION_TYPE_ID_REQUIRED = 4;</code>
*/
public static final int CONVERSION_TYPE_ID_REQUIRED_VALUE = 4;
/**
* <pre>
* Remarketing user list cannot have duplicate conversion types.
* </pre>
*
* <code>DUPLICATE_CONVERSION_TYPES = 5;</code>
*/
public static final int DUPLICATE_CONVERSION_TYPES_VALUE = 5;
/**
* <pre>
* Conversion type is invalid/unknown.
* </pre>
*
* <code>INVALID_CONVERSION_TYPE = 6;</code>
*/
public static final int INVALID_CONVERSION_TYPE_VALUE = 6;
/**
* <pre>
* User list description is empty or invalid.
* </pre>
*
* <code>INVALID_DESCRIPTION = 7;</code>
*/
public static final int INVALID_DESCRIPTION_VALUE = 7;
/**
* <pre>
* User list name is empty or invalid.
* </pre>
*
* <code>INVALID_NAME = 8;</code>
*/
public static final int INVALID_NAME_VALUE = 8;
/**
* <pre>
* Type of the UserList does not match.
* </pre>
*
* <code>INVALID_TYPE = 9;</code>
*/
public static final int INVALID_TYPE_VALUE = 9;
/**
* <pre>
* Embedded logical user lists are not allowed.
* </pre>
*
* <code>CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND = 10;</code>
*/
public static final int CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND_VALUE = 10;
/**
* <pre>
* User list rule operand is invalid.
* </pre>
*
* <code>INVALID_USER_LIST_LOGICAL_RULE_OPERAND = 11;</code>
*/
public static final int INVALID_USER_LIST_LOGICAL_RULE_OPERAND_VALUE = 11;
/**
* <pre>
* Name is already being used for another user list for the account.
* </pre>
*
* <code>NAME_ALREADY_USED = 12;</code>
*/
public static final int NAME_ALREADY_USED_VALUE = 12;
/**
* <pre>
* Name is required when creating a new conversion type.
* </pre>
*
* <code>NEW_CONVERSION_TYPE_NAME_REQUIRED = 13;</code>
*/
public static final int NEW_CONVERSION_TYPE_NAME_REQUIRED_VALUE = 13;
/**
* <pre>
* The given conversion type name has been used.
* </pre>
*
* <code>CONVERSION_TYPE_NAME_ALREADY_USED = 14;</code>
*/
public static final int CONVERSION_TYPE_NAME_ALREADY_USED_VALUE = 14;
/**
* <pre>
* Only an owner account may edit a user list.
* </pre>
*
* <code>OWNERSHIP_REQUIRED_FOR_SET = 15;</code>
*/
public static final int OWNERSHIP_REQUIRED_FOR_SET_VALUE = 15;
/**
* <pre>
* Creating user list without setting type in oneof user_list field, or
* creating/updating read-only user list types is not allowed.
* </pre>
*
* <code>USER_LIST_MUTATE_NOT_SUPPORTED = 16;</code>
*/
public static final int USER_LIST_MUTATE_NOT_SUPPORTED_VALUE = 16;
/**
* <pre>
* Rule is invalid.
* </pre>
*
* <code>INVALID_RULE = 17;</code>
*/
public static final int INVALID_RULE_VALUE = 17;
/**
* <pre>
* The specified date range is empty.
* </pre>
*
* <code>INVALID_DATE_RANGE = 27;</code>
*/
public static final int INVALID_DATE_RANGE_VALUE = 27;
/**
* <pre>
* A UserList which is privacy sensitive or legal rejected cannot be mutated
* by external users.
* </pre>
*
* <code>CAN_NOT_MUTATE_SENSITIVE_USERLIST = 28;</code>
*/
public static final int CAN_NOT_MUTATE_SENSITIVE_USERLIST_VALUE = 28;
/**
* <pre>
* Maximum number of rulebased user lists a customer can have.
* </pre>
*
* <code>MAX_NUM_RULEBASED_USERLISTS = 29;</code>
*/
public static final int MAX_NUM_RULEBASED_USERLISTS_VALUE = 29;
/**
* <pre>
* BasicUserList's billable record field cannot be modified once it is set.
* </pre>
*
* <code>CANNOT_MODIFY_BILLABLE_RECORD_COUNT = 30;</code>
*/
public static final int CANNOT_MODIFY_BILLABLE_RECORD_COUNT_VALUE = 30;
/**
* <pre>
* crm_based_user_list.app_id field must be set when upload_key_type is
* MOBILE_ADVERTISING_ID.
* </pre>
*
* <code>APP_ID_NOT_SET = 31;</code>
*/
public static final int APP_ID_NOT_SET_VALUE = 31;
/**
* <pre>
* Name of the user list is reserved for system generated lists and cannot
* be used.
* </pre>
*
* <code>USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST = 32;</code>
*/
public static final int USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST_VALUE = 32;
/**
* <pre>
* Advertiser needs to be on the allow-list to use remarketing lists created
* from advertiser uploaded data (for example, Customer Match lists).
* </pre>
*
* <code>ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA = 37;</code>
*/
public static final int ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA_VALUE = 37;
/**
* <pre>
* The provided rule_type is not supported for the user list.
* </pre>
*
* <code>RULE_TYPE_IS_NOT_SUPPORTED = 34;</code>
*/
public static final int RULE_TYPE_IS_NOT_SUPPORTED_VALUE = 34;
/**
* <pre>
* Similar user list cannot be used as a logical user list operand.
* </pre>
*
* <code>CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND = 35;</code>
*/
public static final int CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND_VALUE = 35;
/**
* <pre>
* Logical user list should not have a mix of CRM based user list and other
* types of lists in its rules.
* </pre>
*
* <code>CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS = 36;</code>
*/
public static final int CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS_VALUE = 36;
/**
* <pre>
* crm_based_user_list.app_id field can only be set when upload_key_type is
* MOBILE_ADVERTISING_ID.
* </pre>
*
* <code>APP_ID_NOT_ALLOWED = 39;</code>
*/
public static final int APP_ID_NOT_ALLOWED_VALUE = 39;
/**
* <pre>
* Google system generated user lists cannot be mutated.
* </pre>
*
* <code>CANNOT_MUTATE_SYSTEM_LIST = 40;</code>
*/
public static final int CANNOT_MUTATE_SYSTEM_LIST_VALUE = 40;
/**
* <pre>
* The mobile app associated with the remarketing list is sensitive.
* </pre>
*
* <code>MOBILE_APP_IS_SENSITIVE = 41;</code>
*/
public static final int MOBILE_APP_IS_SENSITIVE_VALUE = 41;
/**
* <pre>
* One or more given seed lists do not exist.
* </pre>
*
* <code>SEED_LIST_DOES_NOT_EXIST = 42;</code>
*/
public static final int SEED_LIST_DOES_NOT_EXIST_VALUE = 42;
/**
* <pre>
* One or more given seed lists are not accessible to the current user.
* </pre>
*
* <code>INVALID_SEED_LIST_ACCESS_REASON = 43;</code>
*/
public static final int INVALID_SEED_LIST_ACCESS_REASON_VALUE = 43;
/**
* <pre>
* One or more given seed lists have an unsupported type.
* </pre>
*
* <code>INVALID_SEED_LIST_TYPE = 44;</code>
*/
public static final int INVALID_SEED_LIST_TYPE_VALUE = 44;
/**
* <pre>
* One or more invalid country codes are added to Lookalike UserList.
* </pre>
*
* <code>INVALID_COUNTRY_CODES = 45;</code>
*/
public static final int INVALID_COUNTRY_CODES_VALUE = 45;
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 UserListError 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 UserListError forNumber(int value) {
switch (value) {
case 0: return UNSPECIFIED;
case 1: return UNKNOWN;
case 2: return EXTERNAL_REMARKETING_USER_LIST_MUTATE_NOT_SUPPORTED;
case 3: return CONCRETE_TYPE_REQUIRED;
case 4: return CONVERSION_TYPE_ID_REQUIRED;
case 5: return DUPLICATE_CONVERSION_TYPES;
case 6: return INVALID_CONVERSION_TYPE;
case 7: return INVALID_DESCRIPTION;
case 8: return INVALID_NAME;
case 9: return INVALID_TYPE;
case 10: return CAN_NOT_ADD_LOGICAL_LIST_AS_LOGICAL_LIST_OPERAND;
case 11: return INVALID_USER_LIST_LOGICAL_RULE_OPERAND;
case 12: return NAME_ALREADY_USED;
case 13: return NEW_CONVERSION_TYPE_NAME_REQUIRED;
case 14: return CONVERSION_TYPE_NAME_ALREADY_USED;
case 15: return OWNERSHIP_REQUIRED_FOR_SET;
case 16: return USER_LIST_MUTATE_NOT_SUPPORTED;
case 17: return INVALID_RULE;
case 27: return INVALID_DATE_RANGE;
case 28: return CAN_NOT_MUTATE_SENSITIVE_USERLIST;
case 29: return MAX_NUM_RULEBASED_USERLISTS;
case 30: return CANNOT_MODIFY_BILLABLE_RECORD_COUNT;
case 31: return APP_ID_NOT_SET;
case 32: return USERLIST_NAME_IS_RESERVED_FOR_SYSTEM_LIST;
case 37: return ADVERTISER_NOT_ON_ALLOWLIST_FOR_USING_UPLOADED_DATA;
case 34: return RULE_TYPE_IS_NOT_SUPPORTED;
case 35: return CAN_NOT_ADD_A_SIMILAR_USERLIST_AS_LOGICAL_LIST_OPERAND;
case 36: return CAN_NOT_MIX_CRM_BASED_IN_LOGICAL_LIST_WITH_OTHER_LISTS;
case 39: return APP_ID_NOT_ALLOWED;
case 40: return CANNOT_MUTATE_SYSTEM_LIST;
case 41: return MOBILE_APP_IS_SENSITIVE;
case 42: return SEED_LIST_DOES_NOT_EXIST;
case 43: return INVALID_SEED_LIST_ACCESS_REASON;
case 44: return INVALID_SEED_LIST_TYPE;
case 45: return INVALID_COUNTRY_CODES;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<UserListError>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
UserListError> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<UserListError>() {
public UserListError findValueByNumber(int number) {
return UserListError.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return com.google.ads.googleads.v21.errors.UserListErrorEnum.getDescriptor().getEnumTypes().get(0);
}
private static final UserListError[] VALUES = values();
public static UserListError 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 UserListError(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.ads.googleads.v21.errors.UserListErrorEnum.UserListError)
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v21.errors.UserListErrorEnum)) {
return super.equals(obj);
}
com.google.ads.googleads.v21.errors.UserListErrorEnum other = (com.google.ads.googleads.v21.errors.UserListErrorEnum) obj;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v21.errors.UserListErrorEnum parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.errors.UserListErrorEnum parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.errors.UserListErrorEnum parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.errors.UserListErrorEnum parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.errors.UserListErrorEnum parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.errors.UserListErrorEnum parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.errors.UserListErrorEnum parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.errors.UserListErrorEnum parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v21.errors.UserListErrorEnum parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.errors.UserListErrorEnum parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v21.errors.UserListErrorEnum parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.errors.UserListErrorEnum parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v21.errors.UserListErrorEnum prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Container for enum describing possible user list errors.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.errors.UserListErrorEnum}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.errors.UserListErrorEnum)
com.google.ads.googleads.v21.errors.UserListErrorEnumOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.errors.UserListErrorProto.internal_static_google_ads_googleads_v21_errors_UserListErrorEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.errors.UserListErrorProto.internal_static_google_ads_googleads_v21_errors_UserListErrorEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.errors.UserListErrorEnum.class, com.google.ads.googleads.v21.errors.UserListErrorEnum.Builder.class);
}
// Construct using com.google.ads.googleads.v21.errors.UserListErrorEnum.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v21.errors.UserListErrorProto.internal_static_google_ads_googleads_v21_errors_UserListErrorEnum_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v21.errors.UserListErrorEnum getDefaultInstanceForType() {
return com.google.ads.googleads.v21.errors.UserListErrorEnum.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v21.errors.UserListErrorEnum build() {
com.google.ads.googleads.v21.errors.UserListErrorEnum result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v21.errors.UserListErrorEnum buildPartial() {
com.google.ads.googleads.v21.errors.UserListErrorEnum result = new com.google.ads.googleads.v21.errors.UserListErrorEnum(this);
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v21.errors.UserListErrorEnum) {
return mergeFrom((com.google.ads.googleads.v21.errors.UserListErrorEnum)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v21.errors.UserListErrorEnum other) {
if (other == com.google.ads.googleads.v21.errors.UserListErrorEnum.getDefaultInstance()) return this;
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v21.errors.UserListErrorEnum)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v21.errors.UserListErrorEnum)
private static final com.google.ads.googleads.v21.errors.UserListErrorEnum DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v21.errors.UserListErrorEnum();
}
public static com.google.ads.googleads.v21.errors.UserListErrorEnum getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UserListErrorEnum>
PARSER = new com.google.protobuf.AbstractParser<UserListErrorEnum>() {
@java.lang.Override
public UserListErrorEnum 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<UserListErrorEnum> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UserListErrorEnum> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v21.errors.UserListErrorEnum getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-api-java-client-services | 35,797 | clients/google-api-services-compute/beta/2.0.0/com/google/api/services/compute/model/Route.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 a Route resource.
*
* A route defines a path from VM instances in the VPC network to a specific destination. This
* destination can be inside or outside the VPC network. For more information, read theRoutes
* overview.
*
* <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 Route extends com.google.api.client.json.GenericJson {
/**
* [Output Only] AS path.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<RouteAsPath> asPaths;
/**
* [Output Only] Creation timestamp inRFC3339 text format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String creationTimestamp;
/**
* An optional description of this resource. Provide this field when you create the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* The destination range of outgoing packets that this route applies to. Both IPv4 and IPv6 are
* supported. Must specify an IPv4 range (e.g. 192.0.2.0/24) or an IPv6 range in RFC 4291 format
* (e.g. 2001:db8::/32). IPv6 range will be displayed using RFC 5952 compressed format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String destRange;
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.math.BigInteger id;
/**
* [Output Only] Type of this resource. Always compute#routes for Route resources.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* Name of the resource. Provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply withRFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Fully-qualified URL of the network that this route applies to.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String network;
/**
* The URL to a gateway that should handle matching packets. You can only specify the internet
* gateway using a full or partial valid URL: projects/project/global/gateways/default-internet-
* gateway
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextHopGateway;
/**
* [Output Only] The full resource name of the Network Connectivity Center hub that will handle
* matching packets.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextHopHub;
/**
* The URL to a forwarding rule of typeloadBalancingScheme=INTERNAL that should handle matching
* packets or the IP address of the forwarding Rule. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/project/regions/region/for
* wardingRules/forwardingRule - regions/region/forwardingRules/forwardingRule
*
* If an IP address is provided, must specify an IPv4 address in dot-decimal notation or an IPv6
* address in RFC 4291 format. For example, the following are all valid IP addresses:
* - 10.128.0.56 - 2001:db8::2d9:51:0:0 - 2001:db8:0:0:2d9:51:0:0
*
* IPv6 addresses will be displayed using RFC 5952 compressed format (e.g. 2001:db8::2d9:51:0:0).
* Should never be an IPv4-mapped IPv6 address.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextHopIlb;
/**
* The URL to an instance that should handle matching packets. You can specify this as a full or
* partial URL. For example:
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/instances/
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextHopInstance;
/**
* [Output only] Internal fixed region-to-region cost that Google Cloud calculates based on
* factors such as network performance, distance, and available bandwidth between regions.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Long nextHopInterRegionCost;
/**
* [Output Only] The URL to an InterconnectAttachment which is the next hop for the route. This
* field will only be populated for dynamic routes generated by Cloud Router with a linked
* interconnectAttachment or the static route generated by each L2 Interconnect Attachment.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextHopInterconnectAttachment;
/**
* The network IP address of an instance that should handle matching packets. Both IPv6 address
* and IPv4 addresses are supported. Must specify an IPv4 address in dot-decimal notation (e.g.
* 192.0.2.99) or an IPv6 address in RFC 4291 format (e.g. 2001:db8::2d9:51:0:0 or
* 2001:db8:0:0:2d9:51:0:0). IPv6 addresses will be displayed using RFC 5952 compressed format
* (e.g. 2001:db8::2d9:51:0:0). Should never be an IPv4-mapped IPv6 address.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextHopIp;
/**
* [Output Only] Multi-Exit Discriminator, a BGP route metric that indicates the desirability of a
* particular route in a network.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Long nextHopMed;
/**
* The URL of the local network if it should handle matching packets.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextHopNetwork;
/**
* [Output Only] Indicates the origin of the route. Can be IGP (Interior Gateway Protocol), EGP
* (Exterior Gateway Protocol), or INCOMPLETE.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextHopOrigin;
/**
* [Output Only] The network peering name that should handle matching packets, which should
* conform to RFC1035.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextHopPeering;
/**
* The URL to a VpnTunnel that should handle matching packets.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextHopVpnTunnel;
/**
* Input only. [Input Only] Additional params passed with the request, but not persisted as part
* of resource payload.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private RouteParams params;
/**
* The priority of this route. Priority is used to break ties in cases where there is more than
* one matching route of equal prefix length. In cases where multiple routes have equal prefix
* length, the one with the lowest-numbered priority value wins. The default value is `1000`. The
* priority value must be from `0` to `65535`, inclusive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Long priority;
/**
* [Output only] The status of the route.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String routeStatus;
/**
* [Output Only] The type of this route, which can be one of the following values: - 'TRANSIT' for
* a transit route that this router learned from another Cloud Router and will readvertise to one
* of its BGP peers - 'SUBNET' for a route from a subnet of the VPC - 'BGP' for a route learned
* from a BGP peer of this router - 'STATIC' for a static route
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String routeType;
/**
* [Output Only] Server-defined fully-qualified URL for this resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String selfLink;
/**
* A list of instance tags to which this route applies.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> tags;
/**
* [Output Only] If potential misconfigurations are detected for this route, this field will be
* populated with warning messages.
* 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] AS path.
* @return value or {@code null} for none
*/
public java.util.List<RouteAsPath> getAsPaths() {
return asPaths;
}
/**
* [Output Only] AS path.
* @param asPaths asPaths or {@code null} for none
*/
public Route setAsPaths(java.util.List<RouteAsPath> asPaths) {
this.asPaths = asPaths;
return this;
}
/**
* [Output Only] Creation timestamp inRFC3339 text format.
* @return value or {@code null} for none
*/
public java.lang.String getCreationTimestamp() {
return creationTimestamp;
}
/**
* [Output Only] Creation timestamp inRFC3339 text format.
* @param creationTimestamp creationTimestamp or {@code null} for none
*/
public Route setCreationTimestamp(java.lang.String creationTimestamp) {
this.creationTimestamp = creationTimestamp;
return this;
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* An optional description of this resource. Provide this field when you create the resource.
* @param description description or {@code null} for none
*/
public Route setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* The destination range of outgoing packets that this route applies to. Both IPv4 and IPv6 are
* supported. Must specify an IPv4 range (e.g. 192.0.2.0/24) or an IPv6 range in RFC 4291 format
* (e.g. 2001:db8::/32). IPv6 range will be displayed using RFC 5952 compressed format.
* @return value or {@code null} for none
*/
public java.lang.String getDestRange() {
return destRange;
}
/**
* The destination range of outgoing packets that this route applies to. Both IPv4 and IPv6 are
* supported. Must specify an IPv4 range (e.g. 192.0.2.0/24) or an IPv6 range in RFC 4291 format
* (e.g. 2001:db8::/32). IPv6 range will be displayed using RFC 5952 compressed format.
* @param destRange destRange or {@code null} for none
*/
public Route setDestRange(java.lang.String destRange) {
this.destRange = destRange;
return this;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @return value or {@code null} for none
*/
public java.math.BigInteger getId() {
return id;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @param id id or {@code null} for none
*/
public Route setId(java.math.BigInteger id) {
this.id = id;
return this;
}
/**
* [Output Only] Type of this resource. Always compute#routes for Route resources.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* [Output Only] Type of this resource. Always compute#routes for Route resources.
* @param kind kind or {@code null} for none
*/
public Route setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* Name of the resource. Provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply withRFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of the resource. Provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply withRFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`. The first character must be
* a lowercase letter, and all following characters (except for the last character) must be a
* dash, lowercase letter, or digit. The last character must be a lowercase letter or digit.
* @param name name or {@code null} for none
*/
public Route setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Fully-qualified URL of the network that this route applies to.
* @return value or {@code null} for none
*/
public java.lang.String getNetwork() {
return network;
}
/**
* Fully-qualified URL of the network that this route applies to.
* @param network network or {@code null} for none
*/
public Route setNetwork(java.lang.String network) {
this.network = network;
return this;
}
/**
* The URL to a gateway that should handle matching packets. You can only specify the internet
* gateway using a full or partial valid URL: projects/project/global/gateways/default-internet-
* gateway
* @return value or {@code null} for none
*/
public java.lang.String getNextHopGateway() {
return nextHopGateway;
}
/**
* The URL to a gateway that should handle matching packets. You can only specify the internet
* gateway using a full or partial valid URL: projects/project/global/gateways/default-internet-
* gateway
* @param nextHopGateway nextHopGateway or {@code null} for none
*/
public Route setNextHopGateway(java.lang.String nextHopGateway) {
this.nextHopGateway = nextHopGateway;
return this;
}
/**
* [Output Only] The full resource name of the Network Connectivity Center hub that will handle
* matching packets.
* @return value or {@code null} for none
*/
public java.lang.String getNextHopHub() {
return nextHopHub;
}
/**
* [Output Only] The full resource name of the Network Connectivity Center hub that will handle
* matching packets.
* @param nextHopHub nextHopHub or {@code null} for none
*/
public Route setNextHopHub(java.lang.String nextHopHub) {
this.nextHopHub = nextHopHub;
return this;
}
/**
* The URL to a forwarding rule of typeloadBalancingScheme=INTERNAL that should handle matching
* packets or the IP address of the forwarding Rule. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/project/regions/region/for
* wardingRules/forwardingRule - regions/region/forwardingRules/forwardingRule
*
* If an IP address is provided, must specify an IPv4 address in dot-decimal notation or an IPv6
* address in RFC 4291 format. For example, the following are all valid IP addresses:
* - 10.128.0.56 - 2001:db8::2d9:51:0:0 - 2001:db8:0:0:2d9:51:0:0
*
* IPv6 addresses will be displayed using RFC 5952 compressed format (e.g. 2001:db8::2d9:51:0:0).
* Should never be an IPv4-mapped IPv6 address.
* @return value or {@code null} for none
*/
public java.lang.String getNextHopIlb() {
return nextHopIlb;
}
/**
* The URL to a forwarding rule of typeloadBalancingScheme=INTERNAL that should handle matching
* packets or the IP address of the forwarding Rule. For example, the following are all valid
* URLs: - https://www.googleapis.com/compute/v1/projects/project/regions/region/for
* wardingRules/forwardingRule - regions/region/forwardingRules/forwardingRule
*
* If an IP address is provided, must specify an IPv4 address in dot-decimal notation or an IPv6
* address in RFC 4291 format. For example, the following are all valid IP addresses:
* - 10.128.0.56 - 2001:db8::2d9:51:0:0 - 2001:db8:0:0:2d9:51:0:0
*
* IPv6 addresses will be displayed using RFC 5952 compressed format (e.g. 2001:db8::2d9:51:0:0).
* Should never be an IPv4-mapped IPv6 address.
* @param nextHopIlb nextHopIlb or {@code null} for none
*/
public Route setNextHopIlb(java.lang.String nextHopIlb) {
this.nextHopIlb = nextHopIlb;
return this;
}
/**
* The URL to an instance that should handle matching packets. You can specify this as a full or
* partial URL. For example:
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/instances/
* @return value or {@code null} for none
*/
public java.lang.String getNextHopInstance() {
return nextHopInstance;
}
/**
* The URL to an instance that should handle matching packets. You can specify this as a full or
* partial URL. For example:
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/instances/
* @param nextHopInstance nextHopInstance or {@code null} for none
*/
public Route setNextHopInstance(java.lang.String nextHopInstance) {
this.nextHopInstance = nextHopInstance;
return this;
}
/**
* [Output only] Internal fixed region-to-region cost that Google Cloud calculates based on
* factors such as network performance, distance, and available bandwidth between regions.
* @return value or {@code null} for none
*/
public java.lang.Long getNextHopInterRegionCost() {
return nextHopInterRegionCost;
}
/**
* [Output only] Internal fixed region-to-region cost that Google Cloud calculates based on
* factors such as network performance, distance, and available bandwidth between regions.
* @param nextHopInterRegionCost nextHopInterRegionCost or {@code null} for none
*/
public Route setNextHopInterRegionCost(java.lang.Long nextHopInterRegionCost) {
this.nextHopInterRegionCost = nextHopInterRegionCost;
return this;
}
/**
* [Output Only] The URL to an InterconnectAttachment which is the next hop for the route. This
* field will only be populated for dynamic routes generated by Cloud Router with a linked
* interconnectAttachment or the static route generated by each L2 Interconnect Attachment.
* @return value or {@code null} for none
*/
public java.lang.String getNextHopInterconnectAttachment() {
return nextHopInterconnectAttachment;
}
/**
* [Output Only] The URL to an InterconnectAttachment which is the next hop for the route. This
* field will only be populated for dynamic routes generated by Cloud Router with a linked
* interconnectAttachment or the static route generated by each L2 Interconnect Attachment.
* @param nextHopInterconnectAttachment nextHopInterconnectAttachment or {@code null} for none
*/
public Route setNextHopInterconnectAttachment(java.lang.String nextHopInterconnectAttachment) {
this.nextHopInterconnectAttachment = nextHopInterconnectAttachment;
return this;
}
/**
* The network IP address of an instance that should handle matching packets. Both IPv6 address
* and IPv4 addresses are supported. Must specify an IPv4 address in dot-decimal notation (e.g.
* 192.0.2.99) or an IPv6 address in RFC 4291 format (e.g. 2001:db8::2d9:51:0:0 or
* 2001:db8:0:0:2d9:51:0:0). IPv6 addresses will be displayed using RFC 5952 compressed format
* (e.g. 2001:db8::2d9:51:0:0). Should never be an IPv4-mapped IPv6 address.
* @return value or {@code null} for none
*/
public java.lang.String getNextHopIp() {
return nextHopIp;
}
/**
* The network IP address of an instance that should handle matching packets. Both IPv6 address
* and IPv4 addresses are supported. Must specify an IPv4 address in dot-decimal notation (e.g.
* 192.0.2.99) or an IPv6 address in RFC 4291 format (e.g. 2001:db8::2d9:51:0:0 or
* 2001:db8:0:0:2d9:51:0:0). IPv6 addresses will be displayed using RFC 5952 compressed format
* (e.g. 2001:db8::2d9:51:0:0). Should never be an IPv4-mapped IPv6 address.
* @param nextHopIp nextHopIp or {@code null} for none
*/
public Route setNextHopIp(java.lang.String nextHopIp) {
this.nextHopIp = nextHopIp;
return this;
}
/**
* [Output Only] Multi-Exit Discriminator, a BGP route metric that indicates the desirability of a
* particular route in a network.
* @return value or {@code null} for none
*/
public java.lang.Long getNextHopMed() {
return nextHopMed;
}
/**
* [Output Only] Multi-Exit Discriminator, a BGP route metric that indicates the desirability of a
* particular route in a network.
* @param nextHopMed nextHopMed or {@code null} for none
*/
public Route setNextHopMed(java.lang.Long nextHopMed) {
this.nextHopMed = nextHopMed;
return this;
}
/**
* The URL of the local network if it should handle matching packets.
* @return value or {@code null} for none
*/
public java.lang.String getNextHopNetwork() {
return nextHopNetwork;
}
/**
* The URL of the local network if it should handle matching packets.
* @param nextHopNetwork nextHopNetwork or {@code null} for none
*/
public Route setNextHopNetwork(java.lang.String nextHopNetwork) {
this.nextHopNetwork = nextHopNetwork;
return this;
}
/**
* [Output Only] Indicates the origin of the route. Can be IGP (Interior Gateway Protocol), EGP
* (Exterior Gateway Protocol), or INCOMPLETE.
* @return value or {@code null} for none
*/
public java.lang.String getNextHopOrigin() {
return nextHopOrigin;
}
/**
* [Output Only] Indicates the origin of the route. Can be IGP (Interior Gateway Protocol), EGP
* (Exterior Gateway Protocol), or INCOMPLETE.
* @param nextHopOrigin nextHopOrigin or {@code null} for none
*/
public Route setNextHopOrigin(java.lang.String nextHopOrigin) {
this.nextHopOrigin = nextHopOrigin;
return this;
}
/**
* [Output Only] The network peering name that should handle matching packets, which should
* conform to RFC1035.
* @return value or {@code null} for none
*/
public java.lang.String getNextHopPeering() {
return nextHopPeering;
}
/**
* [Output Only] The network peering name that should handle matching packets, which should
* conform to RFC1035.
* @param nextHopPeering nextHopPeering or {@code null} for none
*/
public Route setNextHopPeering(java.lang.String nextHopPeering) {
this.nextHopPeering = nextHopPeering;
return this;
}
/**
* The URL to a VpnTunnel that should handle matching packets.
* @return value or {@code null} for none
*/
public java.lang.String getNextHopVpnTunnel() {
return nextHopVpnTunnel;
}
/**
* The URL to a VpnTunnel that should handle matching packets.
* @param nextHopVpnTunnel nextHopVpnTunnel or {@code null} for none
*/
public Route setNextHopVpnTunnel(java.lang.String nextHopVpnTunnel) {
this.nextHopVpnTunnel = nextHopVpnTunnel;
return this;
}
/**
* Input only. [Input Only] Additional params passed with the request, but not persisted as part
* of resource payload.
* @return value or {@code null} for none
*/
public RouteParams getParams() {
return params;
}
/**
* Input only. [Input Only] Additional params passed with the request, but not persisted as part
* of resource payload.
* @param params params or {@code null} for none
*/
public Route setParams(RouteParams params) {
this.params = params;
return this;
}
/**
* The priority of this route. Priority is used to break ties in cases where there is more than
* one matching route of equal prefix length. In cases where multiple routes have equal prefix
* length, the one with the lowest-numbered priority value wins. The default value is `1000`. The
* priority value must be from `0` to `65535`, inclusive.
* @return value or {@code null} for none
*/
public java.lang.Long getPriority() {
return priority;
}
/**
* The priority of this route. Priority is used to break ties in cases where there is more than
* one matching route of equal prefix length. In cases where multiple routes have equal prefix
* length, the one with the lowest-numbered priority value wins. The default value is `1000`. The
* priority value must be from `0` to `65535`, inclusive.
* @param priority priority or {@code null} for none
*/
public Route setPriority(java.lang.Long priority) {
this.priority = priority;
return this;
}
/**
* [Output only] The status of the route.
* @return value or {@code null} for none
*/
public java.lang.String getRouteStatus() {
return routeStatus;
}
/**
* [Output only] The status of the route.
* @param routeStatus routeStatus or {@code null} for none
*/
public Route setRouteStatus(java.lang.String routeStatus) {
this.routeStatus = routeStatus;
return this;
}
/**
* [Output Only] The type of this route, which can be one of the following values: - 'TRANSIT' for
* a transit route that this router learned from another Cloud Router and will readvertise to one
* of its BGP peers - 'SUBNET' for a route from a subnet of the VPC - 'BGP' for a route learned
* from a BGP peer of this router - 'STATIC' for a static route
* @return value or {@code null} for none
*/
public java.lang.String getRouteType() {
return routeType;
}
/**
* [Output Only] The type of this route, which can be one of the following values: - 'TRANSIT' for
* a transit route that this router learned from another Cloud Router and will readvertise to one
* of its BGP peers - 'SUBNET' for a route from a subnet of the VPC - 'BGP' for a route learned
* from a BGP peer of this router - 'STATIC' for a static route
* @param routeType routeType or {@code null} for none
*/
public Route setRouteType(java.lang.String routeType) {
this.routeType = routeType;
return this;
}
/**
* [Output Only] Server-defined fully-qualified URL for this resource.
* @return value or {@code null} for none
*/
public java.lang.String getSelfLink() {
return selfLink;
}
/**
* [Output Only] Server-defined fully-qualified URL for this resource.
* @param selfLink selfLink or {@code null} for none
*/
public Route setSelfLink(java.lang.String selfLink) {
this.selfLink = selfLink;
return this;
}
/**
* A list of instance tags to which this route applies.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTags() {
return tags;
}
/**
* A list of instance tags to which this route applies.
* @param tags tags or {@code null} for none
*/
public Route setTags(java.util.List<java.lang.String> tags) {
this.tags = tags;
return this;
}
/**
* [Output Only] If potential misconfigurations are detected for this route, this field will be
* populated with warning messages.
* @return value or {@code null} for none
*/
public java.util.List<Warnings> getWarnings() {
return warnings;
}
/**
* [Output Only] If potential misconfigurations are detected for this route, this field will be
* populated with warning messages.
* @param warnings warnings or {@code null} for none
*/
public Route setWarnings(java.util.List<Warnings> warnings) {
this.warnings = warnings;
return this;
}
@Override
public Route set(String fieldName, Object value) {
return (Route) super.set(fieldName, value);
}
@Override
public Route clone() {
return (Route) super.clone();
}
/**
* Model definition for RouteWarnings.
*/
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 RouteWarningsData.
*/
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();
}
}
}
}
|
openjdk/jdk8 | 35,665 | jdk/src/share/classes/jdk/internal/org/objectweb/asm/commons/InstructionAdapter.java | /*
* 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 is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package jdk.internal.org.objectweb.asm.commons;
import jdk.internal.org.objectweb.asm.Handle;
import jdk.internal.org.objectweb.asm.Label;
import jdk.internal.org.objectweb.asm.MethodVisitor;
import jdk.internal.org.objectweb.asm.Opcodes;
import jdk.internal.org.objectweb.asm.Type;
/**
* A {@link MethodVisitor} providing a more detailed API to generate and
* transform instructions.
*
* @author Eric Bruneton
*/
public class InstructionAdapter extends MethodVisitor {
public final static Type OBJECT_TYPE = Type.getType("Ljava/lang/Object;");
/**
* Creates a new {@link InstructionAdapter}. <i>Subclasses must not use this
* constructor</i>. Instead, they must use the
* {@link #InstructionAdapter(int, MethodVisitor)} version.
*
* @param mv
* the method visitor to which this adapter delegates calls.
* @throws IllegalStateException
* If a subclass calls this constructor.
*/
public InstructionAdapter(final MethodVisitor mv) {
this(Opcodes.ASM5, mv);
if (getClass() != InstructionAdapter.class) {
throw new IllegalStateException();
}
}
/**
* Creates a new {@link InstructionAdapter}.
*
* @param api
* the ASM API version implemented by this visitor. Must be one
* of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}.
* @param mv
* the method visitor to which this adapter delegates calls.
*/
protected InstructionAdapter(final int api, final MethodVisitor mv) {
super(api, mv);
}
@Override
public void visitInsn(final int opcode) {
switch (opcode) {
case Opcodes.NOP:
nop();
break;
case Opcodes.ACONST_NULL:
aconst(null);
break;
case Opcodes.ICONST_M1:
case Opcodes.ICONST_0:
case Opcodes.ICONST_1:
case Opcodes.ICONST_2:
case Opcodes.ICONST_3:
case Opcodes.ICONST_4:
case Opcodes.ICONST_5:
iconst(opcode - Opcodes.ICONST_0);
break;
case Opcodes.LCONST_0:
case Opcodes.LCONST_1:
lconst(opcode - Opcodes.LCONST_0);
break;
case Opcodes.FCONST_0:
case Opcodes.FCONST_1:
case Opcodes.FCONST_2:
fconst(opcode - Opcodes.FCONST_0);
break;
case Opcodes.DCONST_0:
case Opcodes.DCONST_1:
dconst(opcode - Opcodes.DCONST_0);
break;
case Opcodes.IALOAD:
aload(Type.INT_TYPE);
break;
case Opcodes.LALOAD:
aload(Type.LONG_TYPE);
break;
case Opcodes.FALOAD:
aload(Type.FLOAT_TYPE);
break;
case Opcodes.DALOAD:
aload(Type.DOUBLE_TYPE);
break;
case Opcodes.AALOAD:
aload(OBJECT_TYPE);
break;
case Opcodes.BALOAD:
aload(Type.BYTE_TYPE);
break;
case Opcodes.CALOAD:
aload(Type.CHAR_TYPE);
break;
case Opcodes.SALOAD:
aload(Type.SHORT_TYPE);
break;
case Opcodes.IASTORE:
astore(Type.INT_TYPE);
break;
case Opcodes.LASTORE:
astore(Type.LONG_TYPE);
break;
case Opcodes.FASTORE:
astore(Type.FLOAT_TYPE);
break;
case Opcodes.DASTORE:
astore(Type.DOUBLE_TYPE);
break;
case Opcodes.AASTORE:
astore(OBJECT_TYPE);
break;
case Opcodes.BASTORE:
astore(Type.BYTE_TYPE);
break;
case Opcodes.CASTORE:
astore(Type.CHAR_TYPE);
break;
case Opcodes.SASTORE:
astore(Type.SHORT_TYPE);
break;
case Opcodes.POP:
pop();
break;
case Opcodes.POP2:
pop2();
break;
case Opcodes.DUP:
dup();
break;
case Opcodes.DUP_X1:
dupX1();
break;
case Opcodes.DUP_X2:
dupX2();
break;
case Opcodes.DUP2:
dup2();
break;
case Opcodes.DUP2_X1:
dup2X1();
break;
case Opcodes.DUP2_X2:
dup2X2();
break;
case Opcodes.SWAP:
swap();
break;
case Opcodes.IADD:
add(Type.INT_TYPE);
break;
case Opcodes.LADD:
add(Type.LONG_TYPE);
break;
case Opcodes.FADD:
add(Type.FLOAT_TYPE);
break;
case Opcodes.DADD:
add(Type.DOUBLE_TYPE);
break;
case Opcodes.ISUB:
sub(Type.INT_TYPE);
break;
case Opcodes.LSUB:
sub(Type.LONG_TYPE);
break;
case Opcodes.FSUB:
sub(Type.FLOAT_TYPE);
break;
case Opcodes.DSUB:
sub(Type.DOUBLE_TYPE);
break;
case Opcodes.IMUL:
mul(Type.INT_TYPE);
break;
case Opcodes.LMUL:
mul(Type.LONG_TYPE);
break;
case Opcodes.FMUL:
mul(Type.FLOAT_TYPE);
break;
case Opcodes.DMUL:
mul(Type.DOUBLE_TYPE);
break;
case Opcodes.IDIV:
div(Type.INT_TYPE);
break;
case Opcodes.LDIV:
div(Type.LONG_TYPE);
break;
case Opcodes.FDIV:
div(Type.FLOAT_TYPE);
break;
case Opcodes.DDIV:
div(Type.DOUBLE_TYPE);
break;
case Opcodes.IREM:
rem(Type.INT_TYPE);
break;
case Opcodes.LREM:
rem(Type.LONG_TYPE);
break;
case Opcodes.FREM:
rem(Type.FLOAT_TYPE);
break;
case Opcodes.DREM:
rem(Type.DOUBLE_TYPE);
break;
case Opcodes.INEG:
neg(Type.INT_TYPE);
break;
case Opcodes.LNEG:
neg(Type.LONG_TYPE);
break;
case Opcodes.FNEG:
neg(Type.FLOAT_TYPE);
break;
case Opcodes.DNEG:
neg(Type.DOUBLE_TYPE);
break;
case Opcodes.ISHL:
shl(Type.INT_TYPE);
break;
case Opcodes.LSHL:
shl(Type.LONG_TYPE);
break;
case Opcodes.ISHR:
shr(Type.INT_TYPE);
break;
case Opcodes.LSHR:
shr(Type.LONG_TYPE);
break;
case Opcodes.IUSHR:
ushr(Type.INT_TYPE);
break;
case Opcodes.LUSHR:
ushr(Type.LONG_TYPE);
break;
case Opcodes.IAND:
and(Type.INT_TYPE);
break;
case Opcodes.LAND:
and(Type.LONG_TYPE);
break;
case Opcodes.IOR:
or(Type.INT_TYPE);
break;
case Opcodes.LOR:
or(Type.LONG_TYPE);
break;
case Opcodes.IXOR:
xor(Type.INT_TYPE);
break;
case Opcodes.LXOR:
xor(Type.LONG_TYPE);
break;
case Opcodes.I2L:
cast(Type.INT_TYPE, Type.LONG_TYPE);
break;
case Opcodes.I2F:
cast(Type.INT_TYPE, Type.FLOAT_TYPE);
break;
case Opcodes.I2D:
cast(Type.INT_TYPE, Type.DOUBLE_TYPE);
break;
case Opcodes.L2I:
cast(Type.LONG_TYPE, Type.INT_TYPE);
break;
case Opcodes.L2F:
cast(Type.LONG_TYPE, Type.FLOAT_TYPE);
break;
case Opcodes.L2D:
cast(Type.LONG_TYPE, Type.DOUBLE_TYPE);
break;
case Opcodes.F2I:
cast(Type.FLOAT_TYPE, Type.INT_TYPE);
break;
case Opcodes.F2L:
cast(Type.FLOAT_TYPE, Type.LONG_TYPE);
break;
case Opcodes.F2D:
cast(Type.FLOAT_TYPE, Type.DOUBLE_TYPE);
break;
case Opcodes.D2I:
cast(Type.DOUBLE_TYPE, Type.INT_TYPE);
break;
case Opcodes.D2L:
cast(Type.DOUBLE_TYPE, Type.LONG_TYPE);
break;
case Opcodes.D2F:
cast(Type.DOUBLE_TYPE, Type.FLOAT_TYPE);
break;
case Opcodes.I2B:
cast(Type.INT_TYPE, Type.BYTE_TYPE);
break;
case Opcodes.I2C:
cast(Type.INT_TYPE, Type.CHAR_TYPE);
break;
case Opcodes.I2S:
cast(Type.INT_TYPE, Type.SHORT_TYPE);
break;
case Opcodes.LCMP:
lcmp();
break;
case Opcodes.FCMPL:
cmpl(Type.FLOAT_TYPE);
break;
case Opcodes.FCMPG:
cmpg(Type.FLOAT_TYPE);
break;
case Opcodes.DCMPL:
cmpl(Type.DOUBLE_TYPE);
break;
case Opcodes.DCMPG:
cmpg(Type.DOUBLE_TYPE);
break;
case Opcodes.IRETURN:
areturn(Type.INT_TYPE);
break;
case Opcodes.LRETURN:
areturn(Type.LONG_TYPE);
break;
case Opcodes.FRETURN:
areturn(Type.FLOAT_TYPE);
break;
case Opcodes.DRETURN:
areturn(Type.DOUBLE_TYPE);
break;
case Opcodes.ARETURN:
areturn(OBJECT_TYPE);
break;
case Opcodes.RETURN:
areturn(Type.VOID_TYPE);
break;
case Opcodes.ARRAYLENGTH:
arraylength();
break;
case Opcodes.ATHROW:
athrow();
break;
case Opcodes.MONITORENTER:
monitorenter();
break;
case Opcodes.MONITOREXIT:
monitorexit();
break;
default:
throw new IllegalArgumentException();
}
}
@Override
public void visitIntInsn(final int opcode, final int operand) {
switch (opcode) {
case Opcodes.BIPUSH:
iconst(operand);
break;
case Opcodes.SIPUSH:
iconst(operand);
break;
case Opcodes.NEWARRAY:
switch (operand) {
case Opcodes.T_BOOLEAN:
newarray(Type.BOOLEAN_TYPE);
break;
case Opcodes.T_CHAR:
newarray(Type.CHAR_TYPE);
break;
case Opcodes.T_BYTE:
newarray(Type.BYTE_TYPE);
break;
case Opcodes.T_SHORT:
newarray(Type.SHORT_TYPE);
break;
case Opcodes.T_INT:
newarray(Type.INT_TYPE);
break;
case Opcodes.T_FLOAT:
newarray(Type.FLOAT_TYPE);
break;
case Opcodes.T_LONG:
newarray(Type.LONG_TYPE);
break;
case Opcodes.T_DOUBLE:
newarray(Type.DOUBLE_TYPE);
break;
default:
throw new IllegalArgumentException();
}
break;
default:
throw new IllegalArgumentException();
}
}
@Override
public void visitVarInsn(final int opcode, final int var) {
switch (opcode) {
case Opcodes.ILOAD:
load(var, Type.INT_TYPE);
break;
case Opcodes.LLOAD:
load(var, Type.LONG_TYPE);
break;
case Opcodes.FLOAD:
load(var, Type.FLOAT_TYPE);
break;
case Opcodes.DLOAD:
load(var, Type.DOUBLE_TYPE);
break;
case Opcodes.ALOAD:
load(var, OBJECT_TYPE);
break;
case Opcodes.ISTORE:
store(var, Type.INT_TYPE);
break;
case Opcodes.LSTORE:
store(var, Type.LONG_TYPE);
break;
case Opcodes.FSTORE:
store(var, Type.FLOAT_TYPE);
break;
case Opcodes.DSTORE:
store(var, Type.DOUBLE_TYPE);
break;
case Opcodes.ASTORE:
store(var, OBJECT_TYPE);
break;
case Opcodes.RET:
ret(var);
break;
default:
throw new IllegalArgumentException();
}
}
@Override
public void visitTypeInsn(final int opcode, final String type) {
Type t = Type.getObjectType(type);
switch (opcode) {
case Opcodes.NEW:
anew(t);
break;
case Opcodes.ANEWARRAY:
newarray(t);
break;
case Opcodes.CHECKCAST:
checkcast(t);
break;
case Opcodes.INSTANCEOF:
instanceOf(t);
break;
default:
throw new IllegalArgumentException();
}
}
@Override
public void visitFieldInsn(final int opcode, final String owner,
final String name, final String desc) {
switch (opcode) {
case Opcodes.GETSTATIC:
getstatic(owner, name, desc);
break;
case Opcodes.PUTSTATIC:
putstatic(owner, name, desc);
break;
case Opcodes.GETFIELD:
getfield(owner, name, desc);
break;
case Opcodes.PUTFIELD:
putfield(owner, name, desc);
break;
default:
throw new IllegalArgumentException();
}
}
@Deprecated
@Override
public void visitMethodInsn(final int opcode, final String owner,
final String name, final String desc) {
if (api >= Opcodes.ASM5) {
super.visitMethodInsn(opcode, owner, name, desc);
return;
}
doVisitMethodInsn(opcode, owner, name, desc,
opcode == Opcodes.INVOKEINTERFACE);
}
@Override
public void visitMethodInsn(final int opcode, final String owner,
final String name, final String desc, final boolean itf) {
if (api < Opcodes.ASM5) {
super.visitMethodInsn(opcode, owner, name, desc, itf);
return;
}
doVisitMethodInsn(opcode, owner, name, desc, itf);
}
private void doVisitMethodInsn(int opcode, final String owner,
final String name, final String desc, final boolean itf) {
switch (opcode) {
case Opcodes.INVOKESPECIAL:
invokespecial(owner, name, desc, itf);
break;
case Opcodes.INVOKEVIRTUAL:
invokevirtual(owner, name, desc, itf);
break;
case Opcodes.INVOKESTATIC:
invokestatic(owner, name, desc, itf);
break;
case Opcodes.INVOKEINTERFACE:
invokeinterface(owner, name, desc);
break;
default:
throw new IllegalArgumentException();
}
}
@Override
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm,
Object... bsmArgs) {
invokedynamic(name, desc, bsm, bsmArgs);
}
@Override
public void visitJumpInsn(final int opcode, final Label label) {
switch (opcode) {
case Opcodes.IFEQ:
ifeq(label);
break;
case Opcodes.IFNE:
ifne(label);
break;
case Opcodes.IFLT:
iflt(label);
break;
case Opcodes.IFGE:
ifge(label);
break;
case Opcodes.IFGT:
ifgt(label);
break;
case Opcodes.IFLE:
ifle(label);
break;
case Opcodes.IF_ICMPEQ:
ificmpeq(label);
break;
case Opcodes.IF_ICMPNE:
ificmpne(label);
break;
case Opcodes.IF_ICMPLT:
ificmplt(label);
break;
case Opcodes.IF_ICMPGE:
ificmpge(label);
break;
case Opcodes.IF_ICMPGT:
ificmpgt(label);
break;
case Opcodes.IF_ICMPLE:
ificmple(label);
break;
case Opcodes.IF_ACMPEQ:
ifacmpeq(label);
break;
case Opcodes.IF_ACMPNE:
ifacmpne(label);
break;
case Opcodes.GOTO:
goTo(label);
break;
case Opcodes.JSR:
jsr(label);
break;
case Opcodes.IFNULL:
ifnull(label);
break;
case Opcodes.IFNONNULL:
ifnonnull(label);
break;
default:
throw new IllegalArgumentException();
}
}
@Override
public void visitLabel(final Label label) {
mark(label);
}
@Override
public void visitLdcInsn(final Object cst) {
if (cst instanceof Integer) {
int val = ((Integer) cst).intValue();
iconst(val);
} else if (cst instanceof Byte) {
int val = ((Byte) cst).intValue();
iconst(val);
} else if (cst instanceof Character) {
int val = ((Character) cst).charValue();
iconst(val);
} else if (cst instanceof Short) {
int val = ((Short) cst).intValue();
iconst(val);
} else if (cst instanceof Boolean) {
int val = ((Boolean) cst).booleanValue() ? 1 : 0;
iconst(val);
} else if (cst instanceof Float) {
float val = ((Float) cst).floatValue();
fconst(val);
} else if (cst instanceof Long) {
long val = ((Long) cst).longValue();
lconst(val);
} else if (cst instanceof Double) {
double val = ((Double) cst).doubleValue();
dconst(val);
} else if (cst instanceof String) {
aconst(cst);
} else if (cst instanceof Type) {
tconst((Type) cst);
} else if (cst instanceof Handle) {
hconst((Handle) cst);
} else {
throw new IllegalArgumentException();
}
}
@Override
public void visitIincInsn(final int var, final int increment) {
iinc(var, increment);
}
@Override
public void visitTableSwitchInsn(final int min, final int max,
final Label dflt, final Label... labels) {
tableswitch(min, max, dflt, labels);
}
@Override
public void visitLookupSwitchInsn(final Label dflt, final int[] keys,
final Label[] labels) {
lookupswitch(dflt, keys, labels);
}
@Override
public void visitMultiANewArrayInsn(final String desc, final int dims) {
multianewarray(desc, dims);
}
// -----------------------------------------------------------------------
public void nop() {
mv.visitInsn(Opcodes.NOP);
}
public void aconst(final Object cst) {
if (cst == null) {
mv.visitInsn(Opcodes.ACONST_NULL);
} else {
mv.visitLdcInsn(cst);
}
}
public void iconst(final int cst) {
if (cst >= -1 && cst <= 5) {
mv.visitInsn(Opcodes.ICONST_0 + cst);
} else if (cst >= Byte.MIN_VALUE && cst <= Byte.MAX_VALUE) {
mv.visitIntInsn(Opcodes.BIPUSH, cst);
} else if (cst >= Short.MIN_VALUE && cst <= Short.MAX_VALUE) {
mv.visitIntInsn(Opcodes.SIPUSH, cst);
} else {
mv.visitLdcInsn(new Integer(cst));
}
}
public void lconst(final long cst) {
if (cst == 0L || cst == 1L) {
mv.visitInsn(Opcodes.LCONST_0 + (int) cst);
} else {
mv.visitLdcInsn(new Long(cst));
}
}
public void fconst(final float cst) {
int bits = Float.floatToIntBits(cst);
if (bits == 0L || bits == 0x3f800000 || bits == 0x40000000) { // 0..2
mv.visitInsn(Opcodes.FCONST_0 + (int) cst);
} else {
mv.visitLdcInsn(new Float(cst));
}
}
public void dconst(final double cst) {
long bits = Double.doubleToLongBits(cst);
if (bits == 0L || bits == 0x3ff0000000000000L) { // +0.0d and 1.0d
mv.visitInsn(Opcodes.DCONST_0 + (int) cst);
} else {
mv.visitLdcInsn(new Double(cst));
}
}
public void tconst(final Type type) {
mv.visitLdcInsn(type);
}
public void hconst(final Handle handle) {
mv.visitLdcInsn(handle);
}
public void load(final int var, final Type type) {
mv.visitVarInsn(type.getOpcode(Opcodes.ILOAD), var);
}
public void aload(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IALOAD));
}
public void store(final int var, final Type type) {
mv.visitVarInsn(type.getOpcode(Opcodes.ISTORE), var);
}
public void astore(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IASTORE));
}
public void pop() {
mv.visitInsn(Opcodes.POP);
}
public void pop2() {
mv.visitInsn(Opcodes.POP2);
}
public void dup() {
mv.visitInsn(Opcodes.DUP);
}
public void dup2() {
mv.visitInsn(Opcodes.DUP2);
}
public void dupX1() {
mv.visitInsn(Opcodes.DUP_X1);
}
public void dupX2() {
mv.visitInsn(Opcodes.DUP_X2);
}
public void dup2X1() {
mv.visitInsn(Opcodes.DUP2_X1);
}
public void dup2X2() {
mv.visitInsn(Opcodes.DUP2_X2);
}
public void swap() {
mv.visitInsn(Opcodes.SWAP);
}
public void add(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IADD));
}
public void sub(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.ISUB));
}
public void mul(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IMUL));
}
public void div(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IDIV));
}
public void rem(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IREM));
}
public void neg(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.INEG));
}
public void shl(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.ISHL));
}
public void shr(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.ISHR));
}
public void ushr(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IUSHR));
}
public void and(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IAND));
}
public void or(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IOR));
}
public void xor(final Type type) {
mv.visitInsn(type.getOpcode(Opcodes.IXOR));
}
public void iinc(final int var, final int increment) {
mv.visitIincInsn(var, increment);
}
public void cast(final Type from, final Type to) {
if (from != to) {
if (from == Type.DOUBLE_TYPE) {
if (to == Type.FLOAT_TYPE) {
mv.visitInsn(Opcodes.D2F);
} else if (to == Type.LONG_TYPE) {
mv.visitInsn(Opcodes.D2L);
} else {
mv.visitInsn(Opcodes.D2I);
cast(Type.INT_TYPE, to);
}
} else if (from == Type.FLOAT_TYPE) {
if (to == Type.DOUBLE_TYPE) {
mv.visitInsn(Opcodes.F2D);
} else if (to == Type.LONG_TYPE) {
mv.visitInsn(Opcodes.F2L);
} else {
mv.visitInsn(Opcodes.F2I);
cast(Type.INT_TYPE, to);
}
} else if (from == Type.LONG_TYPE) {
if (to == Type.DOUBLE_TYPE) {
mv.visitInsn(Opcodes.L2D);
} else if (to == Type.FLOAT_TYPE) {
mv.visitInsn(Opcodes.L2F);
} else {
mv.visitInsn(Opcodes.L2I);
cast(Type.INT_TYPE, to);
}
} else {
if (to == Type.BYTE_TYPE) {
mv.visitInsn(Opcodes.I2B);
} else if (to == Type.CHAR_TYPE) {
mv.visitInsn(Opcodes.I2C);
} else if (to == Type.DOUBLE_TYPE) {
mv.visitInsn(Opcodes.I2D);
} else if (to == Type.FLOAT_TYPE) {
mv.visitInsn(Opcodes.I2F);
} else if (to == Type.LONG_TYPE) {
mv.visitInsn(Opcodes.I2L);
} else if (to == Type.SHORT_TYPE) {
mv.visitInsn(Opcodes.I2S);
}
}
}
}
public void lcmp() {
mv.visitInsn(Opcodes.LCMP);
}
public void cmpl(final Type type) {
mv.visitInsn(type == Type.FLOAT_TYPE ? Opcodes.FCMPL : Opcodes.DCMPL);
}
public void cmpg(final Type type) {
mv.visitInsn(type == Type.FLOAT_TYPE ? Opcodes.FCMPG : Opcodes.DCMPG);
}
public void ifeq(final Label label) {
mv.visitJumpInsn(Opcodes.IFEQ, label);
}
public void ifne(final Label label) {
mv.visitJumpInsn(Opcodes.IFNE, label);
}
public void iflt(final Label label) {
mv.visitJumpInsn(Opcodes.IFLT, label);
}
public void ifge(final Label label) {
mv.visitJumpInsn(Opcodes.IFGE, label);
}
public void ifgt(final Label label) {
mv.visitJumpInsn(Opcodes.IFGT, label);
}
public void ifle(final Label label) {
mv.visitJumpInsn(Opcodes.IFLE, label);
}
public void ificmpeq(final Label label) {
mv.visitJumpInsn(Opcodes.IF_ICMPEQ, label);
}
public void ificmpne(final Label label) {
mv.visitJumpInsn(Opcodes.IF_ICMPNE, label);
}
public void ificmplt(final Label label) {
mv.visitJumpInsn(Opcodes.IF_ICMPLT, label);
}
public void ificmpge(final Label label) {
mv.visitJumpInsn(Opcodes.IF_ICMPGE, label);
}
public void ificmpgt(final Label label) {
mv.visitJumpInsn(Opcodes.IF_ICMPGT, label);
}
public void ificmple(final Label label) {
mv.visitJumpInsn(Opcodes.IF_ICMPLE, label);
}
public void ifacmpeq(final Label label) {
mv.visitJumpInsn(Opcodes.IF_ACMPEQ, label);
}
public void ifacmpne(final Label label) {
mv.visitJumpInsn(Opcodes.IF_ACMPNE, label);
}
public void goTo(final Label label) {
mv.visitJumpInsn(Opcodes.GOTO, label);
}
public void jsr(final Label label) {
mv.visitJumpInsn(Opcodes.JSR, label);
}
public void ret(final int var) {
mv.visitVarInsn(Opcodes.RET, var);
}
public void tableswitch(final int min, final int max, final Label dflt,
final Label... labels) {
mv.visitTableSwitchInsn(min, max, dflt, labels);
}
public void lookupswitch(final Label dflt, final int[] keys,
final Label[] labels) {
mv.visitLookupSwitchInsn(dflt, keys, labels);
}
public void areturn(final Type t) {
mv.visitInsn(t.getOpcode(Opcodes.IRETURN));
}
public void getstatic(final String owner, final String name,
final String desc) {
mv.visitFieldInsn(Opcodes.GETSTATIC, owner, name, desc);
}
public void putstatic(final String owner, final String name,
final String desc) {
mv.visitFieldInsn(Opcodes.PUTSTATIC, owner, name, desc);
}
public void getfield(final String owner, final String name,
final String desc) {
mv.visitFieldInsn(Opcodes.GETFIELD, owner, name, desc);
}
public void putfield(final String owner, final String name,
final String desc) {
mv.visitFieldInsn(Opcodes.PUTFIELD, owner, name, desc);
}
@Deprecated
public void invokevirtual(final String owner, final String name,
final String desc) {
if (api >= Opcodes.ASM5) {
invokevirtual(owner, name, desc, false);
return;
}
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc);
}
public void invokevirtual(final String owner, final String name,
final String desc, final boolean itf) {
if (api < Opcodes.ASM5) {
if (itf) {
throw new IllegalArgumentException(
"INVOKEVIRTUAL on interfaces require ASM 5");
}
invokevirtual(owner, name, desc);
return;
}
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc, itf);
}
@Deprecated
public void invokespecial(final String owner, final String name,
final String desc) {
if (api >= Opcodes.ASM5) {
invokespecial(owner, name, desc, false);
return;
}
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, owner, name, desc, false);
}
public void invokespecial(final String owner, final String name,
final String desc, final boolean itf) {
if (api < Opcodes.ASM5) {
if (itf) {
throw new IllegalArgumentException(
"INVOKESPECIAL on interfaces require ASM 5");
}
invokespecial(owner, name, desc);
return;
}
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, owner, name, desc, itf);
}
@Deprecated
public void invokestatic(final String owner, final String name,
final String desc) {
if (api < Opcodes.ASM5) {
invokestatic(owner, name, desc, false);
return;
}
mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, false);
}
public void invokestatic(final String owner, final String name,
final String desc, final boolean itf) {
if (api < Opcodes.ASM5) {
if (itf) {
throw new IllegalArgumentException(
"INVOKESTATIC on interfaces require ASM 5");
}
invokestatic(owner, name, desc);
return;
}
mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, itf);
}
public void invokeinterface(final String owner, final String name,
final String desc) {
mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, owner, name, desc, true);
}
public void invokedynamic(String name, String desc, Handle bsm,
Object[] bsmArgs) {
mv.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs);
}
public void anew(final Type type) {
mv.visitTypeInsn(Opcodes.NEW, type.getInternalName());
}
public void newarray(final Type type) {
int typ;
switch (type.getSort()) {
case Type.BOOLEAN:
typ = Opcodes.T_BOOLEAN;
break;
case Type.CHAR:
typ = Opcodes.T_CHAR;
break;
case Type.BYTE:
typ = Opcodes.T_BYTE;
break;
case Type.SHORT:
typ = Opcodes.T_SHORT;
break;
case Type.INT:
typ = Opcodes.T_INT;
break;
case Type.FLOAT:
typ = Opcodes.T_FLOAT;
break;
case Type.LONG:
typ = Opcodes.T_LONG;
break;
case Type.DOUBLE:
typ = Opcodes.T_DOUBLE;
break;
default:
mv.visitTypeInsn(Opcodes.ANEWARRAY, type.getInternalName());
return;
}
mv.visitIntInsn(Opcodes.NEWARRAY, typ);
}
public void arraylength() {
mv.visitInsn(Opcodes.ARRAYLENGTH);
}
public void athrow() {
mv.visitInsn(Opcodes.ATHROW);
}
public void checkcast(final Type type) {
mv.visitTypeInsn(Opcodes.CHECKCAST, type.getInternalName());
}
public void instanceOf(final Type type) {
mv.visitTypeInsn(Opcodes.INSTANCEOF, type.getInternalName());
}
public void monitorenter() {
mv.visitInsn(Opcodes.MONITORENTER);
}
public void monitorexit() {
mv.visitInsn(Opcodes.MONITOREXIT);
}
public void multianewarray(final String desc, final int dims) {
mv.visitMultiANewArrayInsn(desc, dims);
}
public void ifnull(final Label label) {
mv.visitJumpInsn(Opcodes.IFNULL, label);
}
public void ifnonnull(final Label label) {
mv.visitJumpInsn(Opcodes.IFNONNULL, label);
}
public void mark(final Label label) {
mv.visitLabel(label);
}
}
|
apache/rocketmq | 35,951 | remoting/src/main/java/org/apache/rocketmq/remoting/netty/NettyRemotingServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.remoting.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.ProtocolDetectionResult;
import io.netty.handler.codec.ProtocolDetectionState;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import io.netty.handler.codec.haproxy.HAProxyProtocolVersion;
import io.netty.handler.codec.haproxy.HAProxyTLV;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.Pair;
import org.apache.rocketmq.common.ThreadFactoryImpl;
import org.apache.rocketmq.common.constant.HAProxyConstants;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.common.utils.BinaryUtil;
import org.apache.rocketmq.common.utils.NetworkUtil;
import org.apache.rocketmq.common.utils.ThreadUtils;
import org.apache.rocketmq.logging.org.slf4j.Logger;
import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;
import org.apache.rocketmq.remoting.ChannelEventListener;
import org.apache.rocketmq.remoting.InvokeCallback;
import org.apache.rocketmq.remoting.RemotingServer;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.common.TlsMode;
import org.apache.rocketmq.remoting.exception.RemotingSendRequestException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.apache.rocketmq.remoting.exception.RemotingTooMuchRequestException;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.security.cert.CertificateException;
import java.time.Duration;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class NettyRemotingServer extends NettyRemotingAbstract implements RemotingServer {
private static final Logger log = LoggerFactory.getLogger(LoggerName.ROCKETMQ_REMOTING_NAME);
private static final Logger TRAFFIC_LOGGER = LoggerFactory.getLogger(LoggerName.ROCKETMQ_TRAFFIC_NAME);
private final ServerBootstrap serverBootstrap;
protected final EventLoopGroup eventLoopGroupSelector;
protected final EventLoopGroup eventLoopGroupBoss;
protected final NettyServerConfig nettyServerConfig;
private final ExecutorService publicExecutor;
private final ScheduledExecutorService scheduledExecutorService;
private final ChannelEventListener channelEventListener;
private final HashedWheelTimer timer = new HashedWheelTimer(r -> new Thread(r, "ServerHouseKeepingService"));
private DefaultEventExecutorGroup defaultEventExecutorGroup;
/**
* NettyRemotingServer may hold multiple SubRemotingServer, each server will be stored in this container with a
* ListenPort key.
*/
private final ConcurrentMap<Integer/*Port*/, NettyRemotingAbstract> remotingServerTable = new ConcurrentHashMap<>();
public static final String HANDSHAKE_HANDLER_NAME = "handshakeHandler";
public static final String HA_PROXY_DECODER = "HAProxyDecoder";
public static final String HA_PROXY_HANDLER = "HAProxyHandler";
public static final String TLS_MODE_HANDLER = "TlsModeHandler";
public static final String TLS_HANDLER_NAME = "sslHandler";
public static final String FILE_REGION_ENCODER_NAME = "fileRegionEncoder";
// sharable handlers
protected final TlsModeHandler tlsModeHandler = new TlsModeHandler(TlsSystemConfig.tlsMode);
protected final NettyEncoder encoder = new NettyEncoder();
protected final NettyConnectManageHandler connectionManageHandler = new NettyConnectManageHandler();
protected final NettyServerHandler serverHandler = new NettyServerHandler();
protected final RemotingCodeDistributionHandler distributionHandler = new RemotingCodeDistributionHandler();
public NettyRemotingServer(final NettyServerConfig nettyServerConfig) {
this(nettyServerConfig, null);
}
public NettyRemotingServer(final NettyServerConfig nettyServerConfig,
final ChannelEventListener channelEventListener) {
super(nettyServerConfig.getServerOnewaySemaphoreValue(), nettyServerConfig.getServerAsyncSemaphoreValue());
this.serverBootstrap = new ServerBootstrap();
this.nettyServerConfig = nettyServerConfig;
this.channelEventListener = channelEventListener;
this.publicExecutor = buildPublicExecutor(nettyServerConfig);
this.scheduledExecutorService = buildScheduleExecutor();
this.eventLoopGroupBoss = buildEventLoopGroupBoss();
this.eventLoopGroupSelector = buildEventLoopGroupSelector();
loadSslContext();
}
protected EventLoopGroup buildEventLoopGroupSelector() {
if (useEpoll()) {
return new EpollEventLoopGroup(nettyServerConfig.getServerSelectorThreads(), new ThreadFactoryImpl("NettyServerEPOLLSelector_"));
} else {
return new NioEventLoopGroup(nettyServerConfig.getServerSelectorThreads(), new ThreadFactoryImpl("NettyServerNIOSelector_"));
}
}
protected EventLoopGroup buildEventLoopGroupBoss() {
if (useEpoll()) {
return new EpollEventLoopGroup(1, new ThreadFactoryImpl("NettyEPOLLBoss_"));
} else {
return new NioEventLoopGroup(1, new ThreadFactoryImpl("NettyNIOBoss_"));
}
}
private ExecutorService buildPublicExecutor(NettyServerConfig nettyServerConfig) {
int publicThreadNums = nettyServerConfig.getServerCallbackExecutorThreads();
if (publicThreadNums <= 0) {
publicThreadNums = 4;
}
return Executors.newFixedThreadPool(publicThreadNums, new ThreadFactoryImpl("NettyServerPublicExecutor_"));
}
private ScheduledExecutorService buildScheduleExecutor() {
return ThreadUtils.newScheduledThreadPool(1,
new ThreadFactoryImpl("NettyServerScheduler_", true),
new ThreadPoolExecutor.DiscardOldestPolicy());
}
public void loadSslContext() {
TlsMode tlsMode = TlsSystemConfig.tlsMode;
log.info("Server is running in TLS {} mode", tlsMode.getName());
if (tlsMode != TlsMode.DISABLED) {
try {
sslContext = TlsHelper.buildSslContext(false);
log.info("SslContext created for server");
} catch (CertificateException | IOException e) {
log.error("Failed to create SslContext for server", e);
}
}
}
private boolean useEpoll() {
return NetworkUtil.isLinuxPlatform()
&& nettyServerConfig.isUseEpollNativeSelector()
&& Epoll.isAvailable();
}
protected void initServerBootstrap(ServerBootstrap serverBootstrap) {
serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector)
.channel(useEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.option(ChannelOption.SO_REUSEADDR, true)
.childOption(ChannelOption.SO_KEEPALIVE, false)
.childOption(ChannelOption.TCP_NODELAY, true)
.localAddress(new InetSocketAddress(this.nettyServerConfig.getBindAddress(),
this.nettyServerConfig.getListenPort()))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
configChannel(ch);
}
});
addCustomConfig(serverBootstrap);
}
@Override
public void start() {
this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(nettyServerConfig.getServerWorkerThreads(),
new ThreadFactoryImpl("NettyServerCodecThread_"));
initServerBootstrap(serverBootstrap);
try {
ChannelFuture sync = serverBootstrap.bind().sync();
InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
if (0 == nettyServerConfig.getListenPort()) {
this.nettyServerConfig.setListenPort(addr.getPort());
}
log.info("RemotingServer started, listening {}:{}", this.nettyServerConfig.getBindAddress(),
this.nettyServerConfig.getListenPort());
this.remotingServerTable.put(this.nettyServerConfig.getListenPort(), this);
} catch (Exception e) {
throw new IllegalStateException(String.format("Failed to bind to %s:%d", nettyServerConfig.getBindAddress(),
nettyServerConfig.getListenPort()), e);
}
if (this.channelEventListener != null) {
this.nettyEventExecutor.start();
}
TimerTask timerScanResponseTable = new TimerTask() {
@Override
public void run(Timeout timeout) {
try {
NettyRemotingServer.this.scanResponseTable();
} catch (Throwable e) {
log.error("scanResponseTable exception", e);
} finally {
timer.newTimeout(this, 1000, TimeUnit.MILLISECONDS);
}
}
};
this.timer.newTimeout(timerScanResponseTable, 1000 * 3, TimeUnit.MILLISECONDS);
scheduledExecutorService.scheduleWithFixedDelay(() -> {
try {
NettyRemotingServer.this.printRemotingCodeDistribution();
} catch (Throwable e) {
TRAFFIC_LOGGER.error("NettyRemotingServer print remoting code distribution exception", e);
}
}, 1, 1, TimeUnit.SECONDS);
}
/**
* config channel in ChannelInitializer
*
* @param ch the SocketChannel needed to init
* @return the initialized ChannelPipeline, sub class can use it to extent in the future
*/
protected ChannelPipeline configChannel(SocketChannel ch) {
return ch.pipeline()
.addLast(nettyServerConfig.isServerNettyWorkerGroupEnable() ? defaultEventExecutorGroup : null,
HANDSHAKE_HANDLER_NAME, new HandshakeHandler())
.addLast(nettyServerConfig.isServerNettyWorkerGroupEnable() ? defaultEventExecutorGroup : null,
encoder,
new NettyDecoder(),
distributionHandler,
new IdleStateHandler(0, 0,
nettyServerConfig.getServerChannelMaxIdleTimeSeconds()),
connectionManageHandler,
serverHandler
);
}
private void addCustomConfig(ServerBootstrap childHandler) {
if (nettyServerConfig.getServerSocketSndBufSize() > 0) {
log.info("server set SO_SNDBUF to {}", nettyServerConfig.getServerSocketSndBufSize());
childHandler.childOption(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize());
}
if (nettyServerConfig.getServerSocketRcvBufSize() > 0) {
log.info("server set SO_RCVBUF to {}", nettyServerConfig.getServerSocketRcvBufSize());
childHandler.childOption(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize());
}
if (nettyServerConfig.getWriteBufferLowWaterMark() > 0 && nettyServerConfig.getWriteBufferHighWaterMark() > 0) {
log.info("server set netty WRITE_BUFFER_WATER_MARK to {},{}",
nettyServerConfig.getWriteBufferLowWaterMark(), nettyServerConfig.getWriteBufferHighWaterMark());
childHandler.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(
nettyServerConfig.getWriteBufferLowWaterMark(), nettyServerConfig.getWriteBufferHighWaterMark()));
}
if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
}
}
@Override
public void shutdown() {
try {
if (nettyServerConfig.isEnableShutdownGracefully() && isShuttingDown.compareAndSet(false, true)) {
Thread.sleep(Duration.ofSeconds(nettyServerConfig.getShutdownWaitTimeSeconds()).toMillis());
}
this.timer.stop();
this.eventLoopGroupBoss.shutdownGracefully();
this.eventLoopGroupSelector.shutdownGracefully();
this.nettyEventExecutor.shutdown();
if (this.defaultEventExecutorGroup != null) {
this.defaultEventExecutorGroup.shutdownGracefully();
}
} catch (Exception e) {
log.error("NettyRemotingServer shutdown exception, ", e);
}
if (this.publicExecutor != null) {
try {
this.publicExecutor.shutdown();
} catch (Exception e) {
log.error("NettyRemotingServer shutdown exception, ", e);
}
}
}
@Override
public void registerProcessor(int requestCode, NettyRequestProcessor processor, ExecutorService executor) {
ExecutorService executorThis = executor;
if (null == executor) {
executorThis = this.publicExecutor;
}
Pair<NettyRequestProcessor, ExecutorService> pair = new Pair<>(processor, executorThis);
this.processorTable.put(requestCode, pair);
}
@Override
public void registerDefaultProcessor(NettyRequestProcessor processor, ExecutorService executor) {
this.defaultRequestProcessorPair = new Pair<>(processor, executor);
}
@Override
public int localListenPort() {
return this.nettyServerConfig.getListenPort();
}
@Override
public Pair<NettyRequestProcessor, ExecutorService> getProcessorPair(int requestCode) {
return processorTable.get(requestCode);
}
@Override
public Pair<NettyRequestProcessor, ExecutorService> getDefaultProcessorPair() {
return defaultRequestProcessorPair;
}
@Override
public RemotingServer newRemotingServer(final int port) {
SubRemotingServer remotingServer = new SubRemotingServer(port,
this.nettyServerConfig.getServerOnewaySemaphoreValue(),
this.nettyServerConfig.getServerAsyncSemaphoreValue());
NettyRemotingAbstract existingServer = this.remotingServerTable.putIfAbsent(port, remotingServer);
if (existingServer != null) {
throw new RuntimeException("The port " + port + " already in use by another RemotingServer");
}
return remotingServer;
}
@Override
public void removeRemotingServer(final int port) {
this.remotingServerTable.remove(port);
}
@Override
public RemotingCommand invokeSync(final Channel channel, final RemotingCommand request, final long timeoutMillis)
throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException {
return this.invokeSyncImpl(channel, request, timeoutMillis);
}
@Override
public void invokeAsync(Channel channel, RemotingCommand request, long timeoutMillis, InvokeCallback invokeCallback)
throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException {
this.invokeAsyncImpl(channel, request, timeoutMillis, invokeCallback);
}
@Override
public void invokeOneway(Channel channel, RemotingCommand request, long timeoutMillis) throws InterruptedException,
RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException {
this.invokeOnewayImpl(channel, request, timeoutMillis);
}
@Override
public ChannelEventListener getChannelEventListener() {
return channelEventListener;
}
@Override
public ExecutorService getCallbackExecutor() {
return this.publicExecutor;
}
private void printRemotingCodeDistribution() {
if (distributionHandler != null) {
String inBoundSnapshotString = distributionHandler.getInBoundSnapshotString();
if (inBoundSnapshotString != null) {
TRAFFIC_LOGGER.info("Port: {}, RequestCode Distribution: {}",
nettyServerConfig.getListenPort(), inBoundSnapshotString);
}
String outBoundSnapshotString = distributionHandler.getOutBoundSnapshotString();
if (outBoundSnapshotString != null) {
TRAFFIC_LOGGER.info("Port: {}, ResponseCode Distribution: {}",
nettyServerConfig.getListenPort(), outBoundSnapshotString);
}
}
}
public DefaultEventExecutorGroup getDefaultEventExecutorGroup() {
return defaultEventExecutorGroup;
}
public NettyEncoder getEncoder() {
return encoder;
}
public NettyConnectManageHandler getConnectionManageHandler() {
return connectionManageHandler;
}
public NettyServerHandler getServerHandler() {
return serverHandler;
}
public RemotingCodeDistributionHandler getDistributionHandler() {
return distributionHandler;
}
public class HandshakeHandler extends ByteToMessageDecoder {
public HandshakeHandler() {
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
try {
ProtocolDetectionResult<HAProxyProtocolVersion> detectionResult = HAProxyMessageDecoder.detectProtocol(byteBuf);
if (detectionResult.state() == ProtocolDetectionState.NEEDS_MORE_DATA) {
return;
}
if (detectionResult.state() == ProtocolDetectionState.DETECTED) {
ctx.pipeline().addAfter(defaultEventExecutorGroup, ctx.name(), HA_PROXY_DECODER, new HAProxyMessageDecoder())
.addAfter(defaultEventExecutorGroup, HA_PROXY_DECODER, HA_PROXY_HANDLER, new HAProxyMessageHandler())
.addAfter(defaultEventExecutorGroup, HA_PROXY_HANDLER, TLS_MODE_HANDLER, tlsModeHandler);
} else {
ctx.pipeline().addAfter(defaultEventExecutorGroup, ctx.name(), TLS_MODE_HANDLER, tlsModeHandler);
}
try {
// Remove this handler
ctx.pipeline().remove(this);
} catch (NoSuchElementException e) {
log.error("Error while removing HandshakeHandler", e);
}
} catch (Exception e) {
log.error("process proxy protocol negotiator failed.", e);
throw e;
}
}
}
@ChannelHandler.Sharable
public class TlsModeHandler extends SimpleChannelInboundHandler<ByteBuf> {
private final TlsMode tlsMode;
private static final byte HANDSHAKE_MAGIC_CODE = 0x16;
TlsModeHandler(TlsMode tlsMode) {
this.tlsMode = tlsMode;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
// Peek the current read index byte to determine if the content is starting with TLS handshake
byte b = msg.getByte(msg.readerIndex());
if (b == HANDSHAKE_MAGIC_CODE) {
switch (tlsMode) {
case DISABLED:
ctx.close();
log.warn("Clients intend to establish an SSL connection while this server is running in SSL disabled mode");
throw new UnsupportedOperationException("The NettyRemotingServer in SSL disabled mode doesn't support ssl client");
case PERMISSIVE:
case ENFORCING:
if (null != sslContext) {
ctx.pipeline()
.addAfter(defaultEventExecutorGroup, TLS_MODE_HANDLER, TLS_HANDLER_NAME, sslContext.newHandler(ctx.channel().alloc()))
.addAfter(defaultEventExecutorGroup, TLS_HANDLER_NAME, FILE_REGION_ENCODER_NAME, new FileRegionEncoder());
log.info("Handlers prepended to channel pipeline to establish SSL connection");
} else {
ctx.close();
log.error("Trying to establish an SSL connection but SslContext is null");
}
break;
default:
log.warn("Unknown TLS mode");
break;
}
} else if (tlsMode == TlsMode.ENFORCING) {
ctx.close();
log.warn("Clients intend to establish an insecure connection while this server is running in SSL enforcing mode");
}
try {
// Remove this handler
ctx.pipeline().remove(this);
} catch (NoSuchElementException e) {
log.error("Error while removing TlsModeHandler", e);
}
// Hand over this message to the next .
ctx.fireChannelRead(msg.retain());
}
}
@ChannelHandler.Sharable
public class NettyServerHandler extends SimpleChannelInboundHandler<RemotingCommand> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, RemotingCommand msg) {
int localPort = RemotingHelper.parseSocketAddressPort(ctx.channel().localAddress());
NettyRemotingAbstract remotingAbstract = NettyRemotingServer.this.remotingServerTable.get(localPort);
if (localPort != -1 && remotingAbstract != null) {
remotingAbstract.processMessageReceived(ctx, msg);
return;
}
// The related remoting server has been shutdown, so close the connected channel
RemotingHelper.closeChannel(ctx.channel());
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
if (channel.isWritable()) {
if (!channel.config().isAutoRead()) {
channel.config().setAutoRead(true);
log.info("Channel[{}] turns writable, bytes to buffer before changing channel to un-writable: {}",
RemotingHelper.parseChannelRemoteAddr(channel), channel.bytesBeforeUnwritable());
}
} else {
channel.config().setAutoRead(false);
log.warn("Channel[{}] auto-read is disabled, bytes to drain before it turns writable: {}",
RemotingHelper.parseChannelRemoteAddr(channel), channel.bytesBeforeWritable());
}
super.channelWritabilityChanged(ctx);
}
}
@ChannelHandler.Sharable
public class NettyConnectManageHandler extends ChannelDuplexHandler {
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
log.info("NETTY SERVER PIPELINE: channelRegistered {}", remoteAddress);
super.channelRegistered(ctx);
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
log.info("NETTY SERVER PIPELINE: channelUnregistered, the channel[{}]", remoteAddress);
super.channelUnregistered(ctx);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
log.info("NETTY SERVER PIPELINE: channelActive, the channel[{}]", remoteAddress);
super.channelActive(ctx);
if (NettyRemotingServer.this.channelEventListener != null) {
NettyRemotingServer.this.putNettyEvent(new NettyEvent(NettyEventType.CONNECT, remoteAddress, ctx.channel()));
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
log.info("NETTY SERVER PIPELINE: channelInactive, the channel[{}]", remoteAddress);
super.channelInactive(ctx);
if (NettyRemotingServer.this.channelEventListener != null) {
NettyRemotingServer.this.putNettyEvent(new NettyEvent(NettyEventType.CLOSE, remoteAddress, ctx.channel()));
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state().equals(IdleState.ALL_IDLE)) {
final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
log.warn("NETTY SERVER PIPELINE: IDLE exception [{}]", remoteAddress);
RemotingHelper.closeChannel(ctx.channel());
if (NettyRemotingServer.this.channelEventListener != null) {
NettyRemotingServer.this
.putNettyEvent(new NettyEvent(NettyEventType.IDLE, remoteAddress, ctx.channel()));
}
}
}
ctx.fireUserEventTriggered(evt);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
final String remoteAddress = RemotingHelper.parseChannelRemoteAddr(ctx.channel());
log.warn("NETTY SERVER PIPELINE: exceptionCaught {}", remoteAddress);
log.warn("NETTY SERVER PIPELINE: exceptionCaught exception.", cause);
if (NettyRemotingServer.this.channelEventListener != null) {
NettyRemotingServer.this.putNettyEvent(new NettyEvent(NettyEventType.EXCEPTION, remoteAddress, ctx.channel()));
}
RemotingHelper.closeChannel(ctx.channel());
}
}
/**
* The NettyRemotingServer supports bind multiple ports, each port bound by a SubRemotingServer. The
* SubRemotingServer will delegate all the functions to NettyRemotingServer, so the sub server can share all the
* resources from its parent server.
*/
class SubRemotingServer extends NettyRemotingAbstract implements RemotingServer {
private volatile int listenPort;
private volatile Channel serverChannel;
SubRemotingServer(final int port, final int permitsOnway, final int permitsAsync) {
super(permitsOnway, permitsAsync);
listenPort = port;
}
@Override
public void registerProcessor(final int requestCode, final NettyRequestProcessor processor,
final ExecutorService executor) {
ExecutorService executorThis = executor;
if (null == executor) {
executorThis = NettyRemotingServer.this.publicExecutor;
}
Pair<NettyRequestProcessor, ExecutorService> pair = new Pair<>(processor, executorThis);
this.processorTable.put(requestCode, pair);
}
@Override
public void registerDefaultProcessor(final NettyRequestProcessor processor, final ExecutorService executor) {
this.defaultRequestProcessorPair = new Pair<>(processor, executor);
}
@Override
public int localListenPort() {
return listenPort;
}
@Override
public Pair<NettyRequestProcessor, ExecutorService> getProcessorPair(final int requestCode) {
return this.processorTable.get(requestCode);
}
@Override
public Pair<NettyRequestProcessor, ExecutorService> getDefaultProcessorPair() {
return this.defaultRequestProcessorPair;
}
@Override
public RemotingServer newRemotingServer(final int port) {
throw new UnsupportedOperationException("The SubRemotingServer of NettyRemotingServer " +
"doesn't support new nested RemotingServer");
}
@Override
public void removeRemotingServer(final int port) {
throw new UnsupportedOperationException("The SubRemotingServer of NettyRemotingServer " +
"doesn't support remove nested RemotingServer");
}
@Override
public RemotingCommand invokeSync(final Channel channel, final RemotingCommand request,
final long timeoutMillis) throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException {
return this.invokeSyncImpl(channel, request, timeoutMillis);
}
@Override
public void invokeAsync(final Channel channel, final RemotingCommand request, final long timeoutMillis,
final InvokeCallback invokeCallback) throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException {
this.invokeAsyncImpl(channel, request, timeoutMillis, invokeCallback);
}
@Override
public void invokeOneway(final Channel channel, final RemotingCommand request,
final long timeoutMillis) throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException {
this.invokeOnewayImpl(channel, request, timeoutMillis);
}
@Override
public void start() {
try {
if (listenPort < 0) {
listenPort = 0;
}
this.serverChannel = NettyRemotingServer.this.serverBootstrap.bind(listenPort).sync().channel();
if (0 == listenPort) {
InetSocketAddress addr = (InetSocketAddress) this.serverChannel.localAddress();
this.listenPort = addr.getPort();
}
} catch (InterruptedException e) {
throw new RuntimeException("this.subRemotingServer.serverBootstrap.bind().sync() InterruptedException", e);
}
}
@Override
public void shutdown() {
isShuttingDown.set(true);
if (this.serverChannel != null) {
try {
this.serverChannel.close().await(5, TimeUnit.SECONDS);
} catch (InterruptedException ignored) {
}
}
}
@Override
public ChannelEventListener getChannelEventListener() {
return NettyRemotingServer.this.getChannelEventListener();
}
@Override
public ExecutorService getCallbackExecutor() {
return NettyRemotingServer.this.getCallbackExecutor();
}
}
public class HAProxyMessageHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HAProxyMessage) {
handleWithMessage((HAProxyMessage) msg, ctx.channel());
} else {
super.channelRead(ctx, msg);
}
ctx.pipeline().remove(this);
}
/**
* The definition of key refers to the implementation of nginx
* <a href="https://nginx.org/en/docs/http/ngx_http_core_module.html#var_proxy_protocol_addr">ngx_http_core_module</a>
* @param msg
* @param channel
*/
private void handleWithMessage(HAProxyMessage msg, Channel channel) {
try {
if (StringUtils.isNotBlank(msg.sourceAddress())) {
RemotingHelper.setPropertyToAttr(channel, AttributeKeys.PROXY_PROTOCOL_ADDR, msg.sourceAddress());
}
if (msg.sourcePort() > 0) {
RemotingHelper.setPropertyToAttr(channel, AttributeKeys.PROXY_PROTOCOL_PORT, String.valueOf(msg.sourcePort()));
}
if (StringUtils.isNotBlank(msg.destinationAddress())) {
RemotingHelper.setPropertyToAttr(channel, AttributeKeys.PROXY_PROTOCOL_SERVER_ADDR, msg.destinationAddress());
}
if (msg.destinationPort() > 0) {
RemotingHelper.setPropertyToAttr(channel, AttributeKeys.PROXY_PROTOCOL_SERVER_PORT, String.valueOf(msg.destinationPort()));
}
if (CollectionUtils.isNotEmpty(msg.tlvs())) {
msg.tlvs().forEach(tlv -> {
handleHAProxyTLV(tlv, channel);
});
}
} finally {
msg.release();
}
}
}
protected void handleHAProxyTLV(HAProxyTLV tlv, Channel channel) {
byte[] valueBytes = ByteBufUtil.getBytes(tlv.content());
if (!BinaryUtil.isAscii(valueBytes)) {
return;
}
AttributeKey<String> key = AttributeKeys.valueOf(
HAProxyConstants.PROXY_PROTOCOL_TLV_PREFIX + String.format("%02x", tlv.typeByteValue()));
RemotingHelper.setPropertyToAttr(channel, key, new String(valueBytes, CharsetUtil.UTF_8));
}
}
|
oracle/fastr | 36,189 | com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/primitive/BinaryMapNode.java | /*
* Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 3 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 3 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.r.nodes.primitive;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.profiles.BranchProfile;
import com.oracle.truffle.api.profiles.ConditionProfile;
import com.oracle.truffle.api.profiles.LoopConditionProfile;
import com.oracle.truffle.r.nodes.profile.VectorLengthProfile;
import com.oracle.truffle.r.runtime.DSLConfig;
import com.oracle.truffle.r.runtime.RError;
import com.oracle.truffle.r.runtime.RInternalError;
import com.oracle.truffle.r.runtime.RRuntime;
import com.oracle.truffle.r.runtime.RType;
import com.oracle.truffle.r.runtime.data.RComplex;
import com.oracle.truffle.r.runtime.data.RRaw;
import com.oracle.truffle.r.runtime.data.RScalarVector;
import com.oracle.truffle.r.runtime.data.RSharingAttributeStorage;
import com.oracle.truffle.r.runtime.data.VectorDataLibrary;
import com.oracle.truffle.r.runtime.data.VectorDataLibrary.SeqIterator;
import com.oracle.truffle.r.runtime.data.VectorDataLibrary.SeqWriteIterator;
import com.oracle.truffle.r.runtime.data.WarningInfo;
import com.oracle.truffle.r.runtime.data.model.RAbstractVector;
import com.oracle.truffle.r.runtime.data.nodes.attributes.CopyAttributesNode;
import com.oracle.truffle.r.runtime.data.nodes.attributes.CopyAttributesNodeGen;
import com.oracle.truffle.r.runtime.data.nodes.attributes.HasFixedAttributeNode;
import com.oracle.truffle.r.runtime.data.nodes.attributes.SpecialAttributesFunctions.GetDimAttributeNode;
import com.oracle.truffle.r.runtime.nodes.RBaseNode;
final class BinaryMapScalarNode extends BinaryMapNode {
@Child private VectorDataLibrary leftLib;
@Child private VectorDataLibrary rightLib;
BinaryMapScalarNode(BinaryMapFunctionNode function, RAbstractVector left, RAbstractVector right, RType argumentType, RType resultType) {
super(function, left, right, argumentType, resultType);
this.leftLib = VectorDataLibrary.getFactory().create(left.getData());
this.rightLib = VectorDataLibrary.getFactory().create(right.getData());
}
@Override
public boolean isSupported(RAbstractVector left, RAbstractVector right) {
return leftLib.accepts(left.getData()) && rightLib.accepts(right.getData());
}
@Override
public Object apply(RAbstractVector originalLeft, RAbstractVector originalRight) {
assert isSupported(originalLeft, originalRight);
RAbstractVector left = leftClass.cast(originalLeft);
RAbstractVector right = rightClass.cast(originalRight);
assert left != null;
assert right != null;
function.enable(left, right);
Object leftData = left.getData();
Object rightData = right.getData();
assert leftLib.getLength(leftData) == 1;
assert rightLib.getLength(rightData) == 1;
switch (argumentType) {
case Raw:
byte leftValueRaw = leftLib.getRawAt(leftData, 0);
byte rightValueRaw = rightLib.getRawAt(rightData, 0);
switch (resultType) {
case Raw:
return RRaw.valueOf(function.applyRaw(leftValueRaw, rightValueRaw));
case Logical:
return function.applyLogical(RRuntime.raw2int(leftValueRaw), RRuntime.raw2int(rightValueRaw));
default:
throw RInternalError.shouldNotReachHere();
}
case Logical:
byte leftValueLogical = leftLib.getLogicalAt(leftData, 0);
byte rightValueLogical = rightLib.getLogicalAt(rightData, 0);
return function.applyLogical(leftValueLogical, rightValueLogical);
case Integer:
int leftValueInt = leftLib.getIntAt(leftData, 0);
int rightValueInt = rightLib.getIntAt(rightData, 0);
switch (resultType) {
case Logical:
return function.applyLogical(leftValueInt, rightValueInt);
case Integer:
return function.applyInteger(leftValueInt, rightValueInt);
case Double:
return function.applyDouble(leftValueInt, rightValueInt);
default:
throw RInternalError.shouldNotReachHere();
}
case Double:
double leftValueDouble = leftLib.getDoubleAt(leftData, 0);
double rightValueDouble = rightLib.getDoubleAt(rightData, 0);
switch (resultType) {
case Logical:
return function.applyLogical(leftValueDouble, rightValueDouble);
case Double:
return function.applyDouble(leftValueDouble, rightValueDouble);
default:
throw RInternalError.shouldNotReachHere();
}
case Complex:
RComplex leftValueComplex = leftLib.getComplexAt(leftData, 0);
RComplex rightValueComplex = rightLib.getComplexAt(rightData, 0);
switch (resultType) {
case Logical:
return function.applyLogical(leftValueComplex, rightValueComplex);
case Complex:
return function.applyComplex(leftValueComplex, rightValueComplex);
default:
throw RInternalError.shouldNotReachHere();
}
case Character:
String leftValueString = leftLib.getStringAt(leftData, 0);
String rightValueString = rightLib.getStringAt(rightData, 0);
switch (resultType) {
case Logical:
return function.applyLogical(leftValueString, rightValueString);
default:
throw RInternalError.shouldNotReachHere();
}
default:
throw RInternalError.shouldNotReachHere();
}
}
}
final class BinaryMapVectorNode extends BinaryMapNode {
@Child private VectorMapBinaryInternalNode vectorNode;
@Child private CopyAttributesNode copyAttributes;
@Child private GetDimAttributeNode getLeftDimNode = GetDimAttributeNode.create();
@Child private GetDimAttributeNode getRightDimNode = GetDimAttributeNode.create();
@Child private HasFixedAttributeNode hasLeftDimNode = HasFixedAttributeNode.createDim();
@Child private HasFixedAttributeNode hasRightDimNode = HasFixedAttributeNode.createDim();
@Child private VectorDataLibrary leftLibrary;
@Child private VectorDataLibrary rightLibrary;
@Child private VectorDataLibrary resultLibrary;
// profiles
private final VectorLengthProfile leftLengthProfile;
private final VectorLengthProfile rightLengthProfile;
private final ConditionProfile dimensionsProfile;
private final ConditionProfile maxLengthProfile;
private final ConditionProfile seenEmpty;
private final ConditionProfile shareLeft;
private final ConditionProfile shareRight;
private final BranchProfile hasWarningsBranchProfile;
// compile-time optimization flags
private final boolean mayContainMetadata;
private final boolean mayFoldConstantTime;
private final boolean mayShareLeft;
private final boolean mayShareRight;
BinaryMapVectorNode(BinaryMapFunctionNode function, RAbstractVector left, RAbstractVector right, RType argumentType, RType resultType, boolean copyAttributes, boolean isGeneric) {
super(function, left, right, argumentType, resultType);
this.leftLengthProfile = VectorLengthProfile.create();
this.rightLengthProfile = VectorLengthProfile.create();
this.seenEmpty = ConditionProfile.createBinaryProfile();
this.vectorNode = VectorMapBinaryInternalNode.create(resultType, argumentType);
boolean leftVectorImpl = left.isMaterialized();
boolean rightVectorImpl = right.isMaterialized();
this.mayContainMetadata = leftVectorImpl || rightVectorImpl;
this.mayFoldConstantTime = function.mayFoldConstantTime(left, right);
this.mayShareLeft = left.getRType() == resultType && leftVectorImpl;
this.mayShareRight = right.getRType() == resultType && rightVectorImpl;
// lazily create profiles only if needed to avoid unnecessary allocations
this.shareLeft = mayShareLeft ? ConditionProfile.createBinaryProfile() : null;
this.shareRight = mayShareRight ? ConditionProfile.createBinaryProfile() : null;
this.dimensionsProfile = mayContainMetadata ? ConditionProfile.createBinaryProfile() : null;
this.hasWarningsBranchProfile = BranchProfile.create();
this.copyAttributes = mayContainMetadata ? CopyAttributesNodeGen.create(copyAttributes) : null;
this.maxLengthProfile = ConditionProfile.createBinaryProfile();
if (isGeneric) {
leftLibrary = VectorDataLibrary.getFactory().getUncached();
rightLibrary = VectorDataLibrary.getFactory().getUncached();
} else {
leftLibrary = VectorDataLibrary.getFactory().create(left.getData());
rightLibrary = VectorDataLibrary.getFactory().create(right.getData());
}
}
@Override
public boolean isSupported(RAbstractVector left, RAbstractVector right) {
return leftLibrary.accepts(left.getData()) && rightLibrary.accepts(right.getData()) && getDataClass(left) == leftDataClass && getDataClass(right) == rightDataClass;
}
@Override
public Object apply(RAbstractVector originalLeft, RAbstractVector originalRight) {
assert isSupported(originalLeft, originalRight);
RAbstractVector left = leftClass.cast(originalLeft);
RAbstractVector right = rightClass.cast(originalRight);
WarningInfo warningInfo = null;
function.initialize(leftLibrary, left, rightLibrary, right);
Object leftData = left.getData();
Object rightData = right.getData();
if (mayContainMetadata && (dimensionsProfile.profile(hasLeftDimNode.execute(left) && hasRightDimNode.execute(right)))) {
if (differentDimensions(left, right)) {
throw error(RError.Message.NON_CONFORMABLE_ARRAYS);
}
}
RAbstractVector target = null;
int leftLength = leftLengthProfile.profile(leftLibrary.getLength(leftData));
int rightLength = rightLengthProfile.profile(rightLibrary.getLength(rightData));
if (seenEmpty.profile(leftLength == 0 || rightLength == 0)) {
/*
* It is safe to skip attribute handling here as they are never copied if length is 0 of
* either side. Note that dimension check still needs to be performed.
*/
return resultType.getEmpty();
}
if (mayFoldConstantTime && function.mayFoldConstantTime(left, right)) {
function.enable(left, right);
warningInfo = new WarningInfo();
Object leftDataCast = leftLibrary.cast(leftData, argumentType);
Object rightDataCast = rightLibrary.cast(rightData, argumentType);
target = function.tryFoldConstantTime(warningInfo, leftDataCast, leftLength, rightDataCast, rightLength);
}
if (target == null) {
int maxLength = maxLengthProfile.profile(leftLength >= rightLength) ? leftLength : rightLength;
assert left.getLength() == leftLength;
assert right.getLength() == rightLength;
SeqIterator leftIter = leftLibrary.iterator(leftData);
SeqIterator rightIter = rightLibrary.iterator(rightData);
if (mayShareLeft && left.getRType() == resultType && shareLeft.profile(leftLength == maxLength && ((RSharingAttributeStorage) left).isTemporary())) {
target = left;
SeqWriteIterator resultIter = leftLibrary.writeIterator(leftData);
try {
warningInfo = resultIter.getWarningInfo();
vectorNode.execute(function, leftLength, rightLength, leftData, leftLibrary, resultIter, leftData, leftLibrary, leftIter, rightData, rightLibrary, rightIter);
} finally {
leftLibrary.commitWriteIterator(leftData, resultIter, function.isComplete());
}
} else if (mayShareRight && right.getRType() == resultType && shareRight.profile(rightLength == maxLength && ((RSharingAttributeStorage) right).isTemporary())) {
target = right;
SeqWriteIterator resultIter = rightLibrary.writeIterator(rightData);
try {
warningInfo = resultIter.getWarningInfo();
vectorNode.execute(function, leftLength, rightLength, rightData, rightLibrary, resultIter, leftData, leftLibrary, leftIter, rightData, rightLibrary, rightIter);
} finally {
rightLibrary.commitWriteIterator(rightData, resultIter, function.isComplete());
}
} else {
target = resultType.create(maxLength, false);
Object targetData = target.getData();
SeqWriteIterator resultIter = getResultLibrary().writeIterator(targetData);
try {
warningInfo = resultIter.getWarningInfo();
vectorNode.execute(function, leftLength, rightLength, targetData, getResultLibrary(), resultIter, leftData, leftLibrary, leftIter, rightData, rightLibrary, rightIter);
} finally {
getResultLibrary().commitWriteIterator(targetData, resultIter, function.isComplete());
}
}
RBaseNode.reportWork(this, maxLength);
}
if (mayContainMetadata) {
target = copyAttributes.execute(target, left, leftLength, right, rightLength);
}
assert warningInfo != null;
if (warningInfo.hasIntergerOverflow()) {
hasWarningsBranchProfile.enter();
RError.warning(this, RError.Message.INTEGER_OVERFLOW);
}
assert RAbstractVector.verifyVector(target);
return target;
}
private VectorDataLibrary getResultLibrary() {
if (resultLibrary == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
resultLibrary = insert(VectorDataLibrary.getFactory().createDispatched(DSLConfig.getGenericVectorAccessCacheSize()));
}
return resultLibrary;
}
private boolean differentDimensions(RAbstractVector left, RAbstractVector right) {
int[] leftDimensions = getLeftDimNode.getDimensions(left);
int[] rightDimensions = getRightDimNode.getDimensions(right);
int leftLength = leftDimensions.length;
int rightLength = rightDimensions.length;
if (leftLength != rightLength) {
return true;
}
if (leftLength > 0) {
for (int i = 0; i < leftLength; i++) {
if (leftDimensions[i] != rightDimensions[i]) {
return true;
}
}
}
return false;
}
}
abstract class VectorMapBinaryInternalNode extends RBaseNode {
private abstract static class MapBinaryIndexedAction {
public abstract void perform(BinaryMapFunctionNode action, Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter, Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter);
}
private static final MapBinaryIndexedAction LOGICAL_LOGICAL = new MapBinaryIndexedAction() {
@Override
public void perform(BinaryMapFunctionNode arithmetic, Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter, Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
resultLib.setNextLogical(resultData, resultIter,
arithmetic.applyLogical(leftLib.getNextLogical(leftData, leftIter), rightLib.getNextLogical(rightData, rightIter)));
}
};
private static final MapBinaryIndexedAction LOGICAL_INTEGER = new MapBinaryIndexedAction() {
@Override
public void perform(BinaryMapFunctionNode arithmetic, Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter, Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
resultLib.setNextLogical(resultData, resultIter,
arithmetic.applyLogical(leftLib.getNextInt(leftData, leftIter), rightLib.getNextInt(rightData, rightIter)));
}
};
private static final MapBinaryIndexedAction LOGICAL_DOUBLE = new MapBinaryIndexedAction() {
@Override
public void perform(BinaryMapFunctionNode arithmetic, Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter, Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
resultLib.setNextLogical(resultData, resultIter,
arithmetic.applyLogical(leftLib.getNextDouble(leftData, leftIter), rightLib.getNextDouble(rightData, rightIter)));
}
};
private static final MapBinaryIndexedAction LOGICAL_COMPLEX = new MapBinaryIndexedAction() {
@Override
public void perform(BinaryMapFunctionNode arithmetic, Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter, Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
resultLib.setNextLogical(resultData, resultIter,
arithmetic.applyLogical(leftLib.getNextComplex(leftData, leftIter), rightLib.getNextComplex(rightData, rightIter)));
}
};
private static final MapBinaryIndexedAction LOGICAL_CHARACTER = new MapBinaryIndexedAction() {
@Override
public void perform(BinaryMapFunctionNode arithmetic, Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter, Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
resultLib.setNextLogical(resultData, resultIter,
arithmetic.applyLogical(leftLib.getNextString(leftData, leftIter), rightLib.getNextString(rightData, rightIter)));
}
};
private static final MapBinaryIndexedAction LOGICAL_RAW = new MapBinaryIndexedAction() {
@Override
public void perform(BinaryMapFunctionNode arithmetic, Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter, Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
resultLib.setNextLogical(resultData, resultIter,
arithmetic.applyLogical(RRuntime.raw2int(leftLib.getNextRaw(leftData, leftIter)), RRuntime.raw2int(rightLib.getNextRaw(rightData, rightIter))));
}
};
private static final MapBinaryIndexedAction RAW_RAW = new MapBinaryIndexedAction() {
@Override
public void perform(BinaryMapFunctionNode arithmetic, Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter, Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
resultLib.setNextRaw(resultData, resultIter,
arithmetic.applyRaw(leftLib.getNextRaw(leftData, leftIter), rightLib.getNextRaw(rightData, rightIter)));
}
};
private static final MapBinaryIndexedAction INTEGER_INTEGER = new MapBinaryIndexedAction() {
@Override
public void perform(BinaryMapFunctionNode arithmetic, Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter, Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
resultLib.setNextInt(resultData, resultIter,
arithmetic.applyInteger(resultIter.getWarningInfo(), leftLib.getNextInt(leftData, leftIter), rightLib.getNextInt(rightData, rightIter)));
}
};
private static final MapBinaryIndexedAction DOUBLE_INTEGER = new MapBinaryIndexedAction() {
@Override
public void perform(BinaryMapFunctionNode arithmetic, Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter, Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
resultLib.setNextDouble(resultData, resultIter,
arithmetic.applyDouble(leftLib.getNextInt(leftData, leftIter), rightLib.getNextInt(rightData, rightIter)));
}
};
private static final MapBinaryIndexedAction DOUBLE = new MapBinaryIndexedAction() {
@Override
public void perform(BinaryMapFunctionNode arithmetic, Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter, Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
resultLib.setNextDouble(resultData, resultIter,
arithmetic.applyDouble(leftLib.getNextDouble(leftData, leftIter), rightLib.getNextDouble(rightData, rightIter)));
}
};
private static final MapBinaryIndexedAction COMPLEX = new MapBinaryIndexedAction() {
@Override
public void perform(BinaryMapFunctionNode arithmetic, Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter, Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
RComplex value = arithmetic.applyComplex(leftLib.getNextComplex(leftData, leftIter), rightLib.getNextComplex(rightData, rightIter));
resultLib.setNextComplex(resultData, resultIter, value);
}
};
private static final MapBinaryIndexedAction CHARACTER = new MapBinaryIndexedAction() {
@Override
public void perform(BinaryMapFunctionNode arithmetic, Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter, Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
resultLib.setNextString(resultData, resultIter,
arithmetic.applyCharacter(leftLib.getNextString(leftData, leftIter), rightLib.getNextString(rightData, rightIter)));
}
};
private final MapBinaryIndexedAction indexedAction;
protected VectorMapBinaryInternalNode(RType resultType, RType argumentType) {
this.indexedAction = createIndexedAction(resultType, argumentType);
}
public static VectorMapBinaryInternalNode create(RType resultType, RType argumentType) {
return VectorMapBinaryInternalNodeGen.create(resultType, argumentType);
}
private static MapBinaryIndexedAction createIndexedAction(RType resultType, RType argumentType) {
switch (resultType) {
case Raw:
assert argumentType == RType.Raw;
return RAW_RAW;
case Logical:
switch (argumentType) {
case Raw:
return LOGICAL_RAW;
case Logical:
return LOGICAL_LOGICAL;
case Integer:
return LOGICAL_INTEGER;
case Double:
return LOGICAL_DOUBLE;
case Complex:
return LOGICAL_COMPLEX;
case Character:
return LOGICAL_CHARACTER;
default:
throw RInternalError.shouldNotReachHere();
}
case Integer:
assert argumentType == RType.Integer;
return INTEGER_INTEGER;
case Double:
switch (argumentType) {
case Integer:
return DOUBLE_INTEGER;
case Double:
return DOUBLE;
default:
throw RInternalError.shouldNotReachHere();
}
case Complex:
assert argumentType == RType.Complex;
return COMPLEX;
case Character:
assert argumentType == RType.Character;
return CHARACTER;
default:
throw RInternalError.shouldNotReachHere();
}
}
public abstract void execute(BinaryMapFunctionNode node, int leftLength, int rightLength,
Object resultData, VectorDataLibrary result, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary left, SeqIterator leftIter,
Object rightData, VectorDataLibrary right, SeqIterator rightIter);
@Specialization(guards = {"leftLength == 1", "rightLength == 1"})
protected void doScalarScalar(BinaryMapFunctionNode node, @SuppressWarnings("unused") int leftLength, @SuppressWarnings("unused") int rightLength,
Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter,
Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
leftLib.next(leftData, leftIter);
rightLib.next(rightData, rightIter);
resultLib.next(resultData, resultIter);
indexedAction.perform(node, resultData, resultLib, resultIter, leftData, leftLib, leftIter, rightData, rightLib, rightIter);
}
@Specialization(replaces = "doScalarScalar", guards = {"leftLength == 1"})
protected void doScalarVector(BinaryMapFunctionNode node, @SuppressWarnings("unused") int leftLength, @SuppressWarnings("unused") int rightLength,
Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter,
Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
leftLib.next(leftData, leftIter);
while (rightLib.nextLoopCondition(rightData, rightIter)) {
resultLib.next(resultData, resultIter);
indexedAction.perform(node, resultData, resultLib, resultIter, leftData, leftLib, leftIter, rightData, rightLib, rightIter);
}
}
@Specialization(replaces = "doScalarScalar", guards = {"rightLength == 1"})
protected void doVectorScalar(BinaryMapFunctionNode node, @SuppressWarnings("unused") int leftLength, @SuppressWarnings("unused") int rightLength,
Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter,
Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
rightLib.next(rightData, rightIter);
while (leftLib.nextLoopCondition(leftData, leftIter)) {
resultLib.next(resultData, resultIter);
indexedAction.perform(node, resultData, resultLib, resultIter, leftData, leftLib, leftIter, rightData, rightLib, rightIter);
}
}
@Specialization(guards = {"leftLength == rightLength"})
protected void doSameLength(BinaryMapFunctionNode node, @SuppressWarnings("unused") int leftLength, @SuppressWarnings("unused") int rightLength,
Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter,
Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter) {
while (leftLib.nextLoopCondition(leftData, leftIter)) {
rightLib.next(rightData, rightIter);
resultLib.next(resultData, resultIter);
indexedAction.perform(node, resultData, resultLib, resultIter, leftData, leftLib, leftIter, rightData, rightLib, rightIter);
}
}
@Specialization(guards = {"leftLength > rightLength"})
protected void doMultiplesLeft(BinaryMapFunctionNode node, int leftLength, int rightLength,
Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter,
Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter,
@Cached("createCountingProfile()") LoopConditionProfile leftProfile,
@Cached("createBinaryProfile()") ConditionProfile smallRemainderProfile) {
assert resultLib.getLength(resultData) == leftLength;
// This specialization no longer handles leftLength == rightLength
// (leftLength > rightLength now forces doSameLength() use)
// because result == right would be possible and it would have to be checked
// in each subsequent if (result != left) { result.next(resultData, resultIter); }
assert (resultData != rightData);
leftProfile.profileCounted(leftLength);
while (leftProfile.inject(leftIter.getIndex() + 1 < leftLength)) {
rightIter.reset();
if (smallRemainderProfile.profile((leftLength - leftIter.getIndex() - 1) >= rightLength)) {
// we need at least rightLength more elements
while (rightLib.nextLoopCondition(rightData, rightIter) && leftLib.nextLoopCondition(leftData, leftIter)) {
resultLib.next(resultData, resultIter);
indexedAction.perform(node, resultData, resultLib, resultIter, leftData, leftLib, leftIter, rightData, rightLib, rightIter);
}
} else {
while (rightLib.nextLoopCondition(rightData, rightIter) && leftLib.nextLoopCondition(leftData, leftIter)) {
resultLib.next(resultData, resultIter);
indexedAction.perform(node, resultData, resultLib, resultIter, leftData, leftLib, leftIter, rightData, rightLib, rightIter);
}
RError.warning(this, RError.Message.LENGTH_NOT_MULTI);
}
}
}
@Specialization(guards = {"rightLength > leftLength"})
protected void doMultiplesRight(BinaryMapFunctionNode node, int leftLength, int rightLength,
Object resultData, VectorDataLibrary resultLib, SeqWriteIterator resultIter,
Object leftData, VectorDataLibrary leftLib, SeqIterator leftIter,
Object rightData, VectorDataLibrary rightLib, SeqIterator rightIter,
@Cached("createCountingProfile()") LoopConditionProfile rightProfile,
@Cached("createBinaryProfile()") ConditionProfile smallRemainderProfile) {
assert resultLib.getLength(resultData) == rightLength;
assert resultData != leftData;
rightProfile.profileCounted(rightLength);
while (rightProfile.inject(rightIter.getIndex() + 1 < rightLength)) {
leftIter.reset();
if (smallRemainderProfile.profile((rightLength - rightIter.getIndex() - 1) >= leftLength)) {
// we need at least leftLength more elements
while (leftLib.nextLoopCondition(leftData, leftIter) && rightLib.nextLoopCondition(rightData, rightIter)) {
resultLib.next(resultData, resultIter);
indexedAction.perform(node, resultData, resultLib, resultIter, leftData, leftLib, leftIter, rightData, rightLib, rightIter);
}
} else {
while (leftLib.nextLoopCondition(leftData, leftIter) && rightLib.nextLoopCondition(rightData, rightIter)) {
resultLib.next(resultData, resultIter);
indexedAction.perform(node, resultData, resultLib, resultIter, leftData, leftLib, leftIter, rightData, rightLib, rightIter);
}
RError.warning(this, RError.Message.LENGTH_NOT_MULTI);
}
}
}
}
/**
* Implements a binary map operation that maps two vectors into a single result vector of the
* maximum size of both vectors. Vectors with smaller length are repeated. The actual implementation
* is provided using a {@link BinaryMapFunctionNode}.
* <p>
* The implementation tries to share input vectors if they are implementing
* {@link RSharingAttributeStorage}.
*/
public abstract class BinaryMapNode extends RBaseNode {
@Child protected BinaryMapFunctionNode function;
protected final Class<? extends RAbstractVector> leftClass;
protected final Class<? extends RAbstractVector> rightClass;
protected final Class<?> leftDataClass;
protected final Class<?> rightDataClass;
protected final RType argumentType;
protected final RType resultType;
protected BinaryMapNode(BinaryMapFunctionNode function, RAbstractVector left, RAbstractVector right, RType argumentType, RType resultType) {
this.function = function;
this.leftClass = left.getClass();
this.rightClass = right.getClass();
this.leftDataClass = getDataClass(left);
this.rightDataClass = getDataClass(right);
this.argumentType = argumentType;
this.resultType = resultType;
}
public static BinaryMapNode create(BinaryMapFunctionNode function, RAbstractVector left, RAbstractVector right, RType argumentType, RType resultType, boolean copyAttributes, boolean isGeneric) {
if (left instanceof RScalarVector && right instanceof RScalarVector) {
return new BinaryMapScalarNode(function, left, right, argumentType, resultType);
} else {
return new BinaryMapVectorNode(function, left, right, argumentType, resultType, copyAttributes, isGeneric);
}
}
public abstract boolean isSupported(RAbstractVector left, RAbstractVector right);
public abstract Object apply(RAbstractVector originalLeft, RAbstractVector originalRight);
protected static Class<?> getDataClass(RAbstractVector vec) {
return vec.getData().getClass();
}
}
|
apache/geode | 35,476 | geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/cli/commands/LuceneIndexCommandsJUnitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.lucene.internal.cli.commands;
import static org.apache.geode.cache.Region.SEPARATOR;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junitparams.Parameters;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.apache.geode.cache.execute.Execution;
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.cache.lucene.LuceneSerializer;
import org.apache.geode.cache.lucene.internal.LuceneIndexStats;
import org.apache.geode.cache.lucene.internal.cli.LuceneCliStrings;
import org.apache.geode.cache.lucene.internal.cli.LuceneDestroyIndexInfo;
import org.apache.geode.cache.lucene.internal.cli.LuceneIndexDetails;
import org.apache.geode.cache.lucene.internal.cli.LuceneIndexInfo;
import org.apache.geode.cache.lucene.internal.cli.LuceneIndexStatus;
import org.apache.geode.cache.lucene.internal.cli.LuceneQueryInfo;
import org.apache.geode.cache.lucene.internal.cli.LuceneSearchResults;
import org.apache.geode.cache.lucene.internal.cli.functions.LuceneCreateIndexFunction;
import org.apache.geode.cache.lucene.internal.cli.functions.LuceneDescribeIndexFunction;
import org.apache.geode.cache.lucene.internal.cli.functions.LuceneDestroyIndexFunction;
import org.apache.geode.cache.lucene.internal.cli.functions.LuceneListIndexFunction;
import org.apache.geode.cache.lucene.internal.repository.serializer.HeterogeneousLuceneSerializer;
import org.apache.geode.cache.lucene.internal.repository.serializer.PrimitiveSerializer;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.execute.AbstractExecution;
import org.apache.geode.internal.security.SecurityService;
import org.apache.geode.internal.serialization.KnownVersion;
import org.apache.geode.internal.util.CollectionUtils;
import org.apache.geode.management.cli.Result.Status;
import org.apache.geode.management.internal.cli.result.CommandResult;
import org.apache.geode.management.internal.cli.result.model.ResultModel;
import org.apache.geode.management.internal.cli.result.model.TabularResultModel;
import org.apache.geode.management.internal.cli.shell.Gfsh;
import org.apache.geode.management.internal.functions.CliFunctionResult;
import org.apache.geode.management.internal.i18n.CliStrings;
import org.apache.geode.test.junit.categories.LuceneTest;
import org.apache.geode.test.junit.runners.GeodeParamsRunner;
/**
* The LuceneIndexCommandsJUnitTest class is a test suite of test cases testing the contract and
* functionality of the Lucene Index Commands.
*
* @see LuceneCreateIndexCommand
* @see LuceneDescribeIndexCommand
* @see LuceneDestroyIndexCommand
* @see LuceneListIndexCommand
* @see LuceneSearchIndexCommand
*/
@Category(LuceneTest.class)
@RunWith(GeodeParamsRunner.class)
public class LuceneIndexCommandsJUnitTest {
private InternalCache mockCache;
@Before
public void before() {
mockCache = mock(InternalCache.class, "InternalCache");
when(mockCache.getSecurityService()).thenReturn(mock(SecurityService.class));
}
@Test
public void testListIndexWithoutStats() {
final String serverName = "mockServer";
final AbstractExecution mockFunctionExecutor =
mock(AbstractExecution.class, "Function Executor");
final ResultCollector mockResultCollector = mock(ResultCollector.class, "ResultCollector");
String[] searchableFields = {"field1", "field2", "field3"};
Map<String, Analyzer> fieldAnalyzers = new HashMap<>();
fieldAnalyzers.put("field1", new StandardAnalyzer());
fieldAnalyzers.put("field2", new KeywordAnalyzer());
fieldAnalyzers.put("field3", null);
LuceneSerializer serializer = new HeterogeneousLuceneSerializer();
final LuceneIndexDetails indexDetails1 =
createIndexDetails("memberFive", SEPARATOR + "Employees",
searchableFields, fieldAnalyzers, LuceneIndexStatus.INITIALIZED, serverName,
serializer);
final LuceneIndexDetails indexDetails2 =
createIndexDetails("memberSix", SEPARATOR + "Employees", searchableFields, fieldAnalyzers,
LuceneIndexStatus.NOT_INITIALIZED, serverName, serializer);
final LuceneIndexDetails indexDetails3 =
createIndexDetails("memberTen", SEPARATOR + "Employees",
searchableFields, fieldAnalyzers, LuceneIndexStatus.INITIALIZED, serverName,
serializer);
final List<Set<LuceneIndexDetails>> results = new ArrayList<>();
results.add(CollectionUtils.asSet(indexDetails2, indexDetails1, indexDetails3));
when(mockFunctionExecutor.execute(any(LuceneListIndexFunction.class)))
.thenReturn(mockResultCollector);
when(mockResultCollector.getResult()).thenReturn(results);
final LuceneListIndexCommand command =
new LuceneTestListIndexCommand(mockCache, mockFunctionExecutor);
ResultModel result = command.listIndex(false);
TabularResultModel data = result.getTableSection("lucene-indexes");
assertThat(data.getValuesInColumn("Index Name"))
.isEqualTo(Arrays.asList("memberFive", "memberSix", "memberTen"));
assertThat(data.getValuesInColumn("Region Path"))
.isEqualTo(Arrays.asList(SEPARATOR + "Employees", SEPARATOR + "Employees",
SEPARATOR + "Employees"));
assertThat(data.getValuesInColumn("Indexed Fields")).isEqualTo(Arrays.asList(
"[field1, field2, field3]", "[field1, field2, field3]", "[field1, field2, field3]"));
assertThat(data.getValuesInColumn("Field Analyzer"))
.isEqualTo(Arrays.asList("{field1=StandardAnalyzer, field2=KeywordAnalyzer}",
"{field1=StandardAnalyzer, field2=KeywordAnalyzer}",
"{field1=StandardAnalyzer, field2=KeywordAnalyzer}"));
assertThat(data.getValuesInColumn("Status"))
.isEqualTo(Arrays.asList("INITIALIZED", "NOT_INITIALIZED", "INITIALIZED"));
}
@Test
public void testListIndexWithStats() {
final String serverName = "mockServer";
final AbstractExecution mockFunctionExecutor =
mock(AbstractExecution.class, "Function Executor");
final ResultCollector mockResultCollector = mock(ResultCollector.class, "ResultCollector");
final LuceneIndexStats mockIndexStats1 = getMockIndexStats(1, 10, 5, 1);
final LuceneIndexStats mockIndexStats2 = getMockIndexStats(2, 20, 10, 2);
final LuceneIndexStats mockIndexStats3 = getMockIndexStats(3, 30, 15, 3);
String[] searchableFields = {"field1", "field2", "field3"};
Map<String, Analyzer> fieldAnalyzers = new HashMap<>();
fieldAnalyzers.put("field1", new StandardAnalyzer());
fieldAnalyzers.put("field2", new KeywordAnalyzer());
fieldAnalyzers.put("field3", null);
LuceneSerializer serializer = new HeterogeneousLuceneSerializer();
final LuceneIndexDetails indexDetails1 =
createIndexDetails("memberFive", SEPARATOR + "Employees", searchableFields, fieldAnalyzers,
mockIndexStats1, LuceneIndexStatus.INITIALIZED, serverName, serializer);
final LuceneIndexDetails indexDetails2 =
createIndexDetails("memberSix", SEPARATOR + "Employees", searchableFields, fieldAnalyzers,
mockIndexStats2, LuceneIndexStatus.INITIALIZED, serverName, serializer);
final LuceneIndexDetails indexDetails3 =
createIndexDetails("memberTen", SEPARATOR + "Employees", searchableFields, fieldAnalyzers,
mockIndexStats3, LuceneIndexStatus.INITIALIZED, serverName, serializer);
final List<Set<LuceneIndexDetails>> results = new ArrayList<>();
results.add(CollectionUtils.asSet(indexDetails2, indexDetails1, indexDetails3));
when(mockFunctionExecutor.execute(any(LuceneListIndexFunction.class)))
.thenReturn(mockResultCollector);
when(mockResultCollector.getResult()).thenReturn(results);
final LuceneListIndexCommand command =
new LuceneTestListIndexCommand(mockCache, mockFunctionExecutor);
ResultModel result = command.listIndex(true);
TabularResultModel data = result.getTableSection("lucene-indexes");
assertThat(data.getValuesInColumn("Index Name"))
.isEqualTo(Arrays.asList("memberFive", "memberSix", "memberTen"));
assertThat(data.getValuesInColumn("Region Path"))
.isEqualTo(Arrays.asList(SEPARATOR + "Employees", SEPARATOR + "Employees",
SEPARATOR + "Employees"));
assertThat(data.getValuesInColumn("Indexed Fields")).isEqualTo(Arrays.asList(
"[field1, field2, field3]", "[field1, field2, field3]", "[field1, field2, field3]"));
assertThat(data.getValuesInColumn("Field Analyzer"))
.isEqualTo(Arrays.asList("{field1=StandardAnalyzer, field2=KeywordAnalyzer}",
"{field1=StandardAnalyzer, field2=KeywordAnalyzer}",
"{field1=StandardAnalyzer, field2=KeywordAnalyzer}"));
assertThat(data.getValuesInColumn("Query Executions")).isEqualTo(Arrays.asList("1", "2", "3"));
assertThat(data.getValuesInColumn("Commits")).isEqualTo(Arrays.asList("10", "20", "30"));
assertThat(data.getValuesInColumn("Updates")).isEqualTo(Arrays.asList("5", "10", "15"));
assertThat(data.getValuesInColumn("Documents")).isEqualTo(Arrays.asList("1", "2", "3"));
assertThat(data.getValuesInColumn("Serializer"))
.isEqualTo(Arrays.asList(HeterogeneousLuceneSerializer.class.getSimpleName(),
HeterogeneousLuceneSerializer.class.getSimpleName(),
HeterogeneousLuceneSerializer.class.getSimpleName()));
}
@Test
public void testCreateIndex() throws Exception {
final ResultCollector mockResultCollector = mock(ResultCollector.class);
final LuceneCreateIndexCommand command =
spy(new LuceneTestCreateIndexCommand(mockCache, null));
final List<CliFunctionResult> cliFunctionResults = new ArrayList<>();
cliFunctionResults
.add(new CliFunctionResult("member1", CliFunctionResult.StatusState.OK, "Index Created"));
cliFunctionResults.add(new CliFunctionResult("member2", CliFunctionResult.StatusState.ERROR,
"Index creation failed"));
cliFunctionResults
.add(new CliFunctionResult("member3", CliFunctionResult.StatusState.OK, "Index Created"));
doReturn(mockResultCollector).when(command).executeFunctionOnAllMembers(
any(LuceneCreateIndexFunction.class), any(LuceneIndexInfo.class));
doReturn(cliFunctionResults).when(mockResultCollector).getResult();
String indexName = "index";
String regionPath = "regionPath";
String[] searchableFields = {"field1", "field2", "field3"};
String[] fieldAnalyzers = {StandardAnalyzer.class.getCanonicalName(),
KeywordAnalyzer.class.getCanonicalName(), StandardAnalyzer.class.getCanonicalName()};
String serializer = PrimitiveSerializer.class.getCanonicalName();
ResultModel result = command.createIndex(indexName, regionPath, searchableFields,
fieldAnalyzers, serializer);
assertThat(result.getStatus()).isEqualTo(Status.OK);
TabularResultModel data = result.getTableSection("lucene-indexes");
assertThat(data.getValuesInColumn("Member"))
.isEqualTo(Arrays.asList("member1", "member2", "member3"));
assertThat(data.getValuesInColumn("Status"))
.isEqualTo(Arrays.asList("Successfully created lucene index",
"Failed: Index creation failed", "Successfully created lucene index"));
}
@Test
public void testDescribeIndex() throws Exception {
final String serverName = "mockServer";
final ResultCollector mockResultCollector = mock(ResultCollector.class, "ResultCollector");
final LuceneDescribeIndexCommand command =
spy(new LuceneTestDescribeIndexCommand(mockCache, null));
String[] searchableFields = {"field1", "field2", "field3"};
Map<String, Analyzer> fieldAnalyzers = new HashMap<>();
fieldAnalyzers.put("field1", new StandardAnalyzer());
fieldAnalyzers.put("field2", new KeywordAnalyzer());
fieldAnalyzers.put("field3", null);
final LuceneIndexStats mockIndexStats = getMockIndexStats(1, 10, 5, 1);
final List<LuceneIndexDetails> indexDetails = new ArrayList<>();
LuceneSerializer serializer = new HeterogeneousLuceneSerializer();
indexDetails.add(createIndexDetails("memberFive", SEPARATOR + "Employees", searchableFields,
fieldAnalyzers, mockIndexStats, LuceneIndexStatus.INITIALIZED, serverName, serializer));
doReturn(mockResultCollector).when(command).executeFunctionOnRegion(
any(LuceneDescribeIndexFunction.class), any(LuceneIndexInfo.class), eq(true));
doReturn(indexDetails).when(mockResultCollector).getResult();
ResultModel result = command.describeIndex("memberFive", SEPARATOR + "Employees");
TabularResultModel data = result.getTableSection("lucene-indexes");
assertThat(data.getValuesInColumn("Index Name"))
.isEqualTo(Collections.singletonList("memberFive"));
assertThat(data.getValuesInColumn("Region Path"))
.isEqualTo(Collections.singletonList(SEPARATOR + "Employees"));
assertThat(data.getValuesInColumn("Indexed Fields"))
.isEqualTo(Collections.singletonList("[field1, field2, field3]"));
assertThat(data.getValuesInColumn("Field Analyzer"))
.isEqualTo(Collections.singletonList("{field1=StandardAnalyzer, field2=KeywordAnalyzer}"));
assertThat(data.getValuesInColumn("Status"))
.isEqualTo(Collections.singletonList("INITIALIZED"));
assertThat(data.getValuesInColumn("Query Executions"))
.isEqualTo(Collections.singletonList("1"));
assertThat(data.getValuesInColumn("Commits")).isEqualTo(Collections.singletonList("10"));
assertThat(data.getValuesInColumn("Updates")).isEqualTo(Collections.singletonList("5"));
assertThat(data.getValuesInColumn("Documents")).isEqualTo(Collections.singletonList("1"));
}
@Test
public void testSearchIndex() throws Exception {
final ResultCollector mockResultCollector = mock(ResultCollector.class, "ResultCollector");
final LuceneSearchIndexCommand command =
spy(new LuceneTestSearchIndexCommand(mockCache, null));
final List<Set<LuceneSearchResults>> queryResultsList = new ArrayList<>();
HashSet<LuceneSearchResults> queryResults = new HashSet<>();
queryResults.add(createQueryResults("A", "Result1", Float.parseFloat("1.3")));
queryResults.add(createQueryResults("B", "Result1", Float.parseFloat("1.2")));
queryResults.add(createQueryResults("C", "Result1", Float.parseFloat("1.1")));
queryResultsList.add(queryResults);
doReturn(mockResultCollector).when(command).executeSearch(any(LuceneQueryInfo.class));
doReturn(queryResultsList).when(mockResultCollector).getResult();
ResultModel result =
command.searchIndex("index", "region", "Result1", "field1", -1, false);
TabularResultModel data = result.getTableSection("lucene-indexes");
assertThat(data.getValuesInColumn("key")).isEqualTo(Arrays.asList("A", "B", "C"));
assertThat(data.getValuesInColumn("value"))
.isEqualTo(Arrays.asList("Result1", "Result1", "Result1"));
assertThat(data.getValuesInColumn("score")).isEqualTo(Arrays.asList("1.3", "1.2", "1.1"));
}
@Test
public void testSearchIndexWithPaging() throws Exception {
final Gfsh mockGfsh = mock(Gfsh.class);
final ResultCollector mockResultCollector = mock(ResultCollector.class, "ResultCollector");
final LuceneSearchIndexCommand command =
spy(new LuceneTestSearchIndexCommand(mockCache, null));
ArgumentCaptor<String> resultCaptor = ArgumentCaptor.forClass(String.class);
LuceneSearchResults result1 = createQueryResults("A", "Result1", Float.parseFloat("1.7"));
LuceneSearchResults result2 = createQueryResults("B", "Result1", Float.parseFloat("1.6"));
LuceneSearchResults result3 = createQueryResults("C", "Result1", Float.parseFloat("1.5"));
LuceneSearchResults result4 = createQueryResults("D", "Result1", Float.parseFloat("1.4"));
LuceneSearchResults result5 = createQueryResults("E", "Result1", Float.parseFloat("1.3"));
LuceneSearchResults result6 = createQueryResults("F", "Result1", Float.parseFloat("1.2"));
LuceneSearchResults result7 = createQueryResults("G", "Result1", Float.parseFloat("1.1"));
final List<Set<LuceneSearchResults>> queryResultsList =
getSearchResults(result1, result2, result3, result4, result5, result6, result7);
doReturn(mockResultCollector).when(command).executeSearch(any(LuceneQueryInfo.class));
doReturn(queryResultsList).when(mockResultCollector).getResult();
doReturn(mockGfsh).when(command).initGfsh();
when(mockGfsh.interact(anyString())).thenReturn("n").thenReturn("n").thenReturn("n")
.thenReturn("n").thenReturn("p").thenReturn("p").thenReturn("p").thenReturn("p")
.thenReturn("p").thenReturn("n").thenReturn("q");
when(command.getPageSize()).thenReturn(2);
LuceneSearchResults[] expectedResults =
new LuceneSearchResults[] {result7, result6, result5, result4, result3, result2, result1};
String expectedPage1 = getPage(expectedResults, new int[] {6, 5});
String expectedPage2 = getPage(expectedResults, new int[] {4, 3});
String expectedPage3 = getPage(expectedResults, new int[] {2, 1});
String expectedPage4 = getPage(expectedResults, new int[] {0});
command.searchIndex("index", "region", "Result1", "field1", -1, false);
verify(mockGfsh, times(20)).printAsInfo(resultCaptor.capture());
List<String> actualPageResults = resultCaptor.getAllValues();
assertThat(actualPageResults.get(0)).isEqualTo(expectedPage1);
assertThat(actualPageResults.get(1)).isEqualTo("\t\tPage 1 of 4");
assertThat(actualPageResults.get(2)).isEqualTo(expectedPage2);
assertThat(actualPageResults.get(3)).isEqualTo("\t\tPage 2 of 4");
assertThat(actualPageResults.get(4)).isEqualTo(expectedPage3);
assertThat(actualPageResults.get(5)).isEqualTo("\t\tPage 3 of 4");
assertThat(actualPageResults.get(6)).isEqualTo(expectedPage4);
assertThat(actualPageResults.get(7)).isEqualTo("\t\tPage 4 of 4");
assertThat(actualPageResults.get(8)).isEqualTo("No more results to display.");
assertThat(actualPageResults.get(9)).isEqualTo(expectedPage4);
assertThat(actualPageResults.get(10)).isEqualTo("\t\tPage 4 of 4");
assertThat(actualPageResults.get(11)).isEqualTo(expectedPage3);
assertThat(actualPageResults.get(12)).isEqualTo("\t\tPage 3 of 4");
assertThat(actualPageResults.get(13)).isEqualTo(expectedPage2);
assertThat(actualPageResults.get(14)).isEqualTo("\t\tPage 2 of 4");
assertThat(actualPageResults.get(15)).isEqualTo(expectedPage1);
assertThat(actualPageResults.get(16)).isEqualTo("\t\tPage 1 of 4");
assertThat(actualPageResults.get(17)).isEqualTo("At the top of the search results.");
assertThat(actualPageResults.get(18)).isEqualTo(expectedPage1);
assertThat(actualPageResults.get(19)).isEqualTo("\t\tPage 1 of 4");
}
@Test
public void testSearchIndexWithKeysOnly() throws Exception {
final ResultCollector mockResultCollector = mock(ResultCollector.class, "ResultCollector");
final LuceneSearchIndexCommand command =
spy(new LuceneTestSearchIndexCommand(mockCache, null));
final List<Set<LuceneSearchResults>> queryResultsList = new ArrayList<>();
HashSet<LuceneSearchResults> queryResults = new HashSet<>();
queryResults.add(createQueryResults("A", "Result1", Float.parseFloat("1.3")));
queryResults.add(createQueryResults("B", "Result1", Float.parseFloat("1.2")));
queryResults.add(createQueryResults("C", "Result1", Float.parseFloat("1.1")));
queryResultsList.add(queryResults);
doReturn(mockResultCollector).when(command).executeSearch(any(LuceneQueryInfo.class));
doReturn(queryResultsList).when(mockResultCollector).getResult();
ResultModel result = command.searchIndex("index", "region", "Result1", "field1", -1, true);
TabularResultModel data = result.getTableSection("lucene-indexes");
assertThat(data.getValuesInColumn("key")).isEqualTo(Arrays.asList("A", "B", "C"));
}
@Test
public void testSearchIndexWhenSearchResultsHaveSameScore() throws Exception {
final ResultCollector mockResultCollector = mock(ResultCollector.class, "ResultCollector");
final LuceneSearchIndexCommand command =
spy(new LuceneTestSearchIndexCommand(mockCache, null));
final List<Set<LuceneSearchResults>> queryResultsList = new ArrayList<>();
HashSet<LuceneSearchResults> queryResults = new HashSet<>();
queryResults.add(createQueryResults("A", "Result1", 1));
queryResults.add(createQueryResults("B", "Result1", 1));
queryResults.add(createQueryResults("C", "Result1", 1));
queryResults.add(createQueryResults("D", "Result1", 1));
queryResults.add(createQueryResults("E", "Result1", 1));
queryResults.add(createQueryResults("F", "Result1", 1));
queryResults.add(createQueryResults("G", "Result1", 1));
queryResults.add(createQueryResults("H", "Result1", 1));
queryResults.add(createQueryResults("I", "Result1", 1));
queryResults.add(createQueryResults("J", "Result1", 1));
queryResults.add(createQueryResults("K", "Result1", 1));
queryResults.add(createQueryResults("L", "Result1", 1));
queryResults.add(createQueryResults("M", "Result1", 1));
queryResults.add(createQueryResults("N", "Result1", 1));
queryResults.add(createQueryResults("P", "Result1", 1));
queryResults.add(createQueryResults("Q", "Result1", 1));
queryResults.add(createQueryResults("R", "Result1", 1));
queryResults.add(createQueryResults("S", "Result1", 1));
queryResults.add(createQueryResults("T", "Result1", 1));
queryResultsList.add(queryResults);
doReturn(mockResultCollector).when(command).executeSearch(any(LuceneQueryInfo.class));
doReturn(queryResultsList).when(mockResultCollector).getResult();
ResultModel result = command.searchIndex("index", "region", "Result1", "field1", -1, true);
TabularResultModel data = result.getTableSection("lucene-indexes");
assertThat(data.getValuesInColumn("key").size()).isEqualTo(queryResults.size());
}
@Test
public void testDestroySingleIndexNoRegionMembers() {
LuceneDestroyIndexCommand command =
spy(new LuceneTestDestroyIndexCommand(mockCache, null));
final List<CliFunctionResult> cliFunctionResults = new ArrayList<>();
String expectedStatus = CliStrings.format(
LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__COULD_NOT_FIND__MEMBERS_GREATER_THAN_VERSION_0,
new Object[] {KnownVersion.GEODE_1_7_0});
cliFunctionResults.add(new CliFunctionResult("member0", CliFunctionResult.StatusState.OK));
doReturn(Collections.emptySet()).when(command).getNormalMembersWithSameOrNewerVersion(any());
ResultModel result = command.destroyIndex("index", "regionPath");
verifyDestroyIndexCommandResult(result, cliFunctionResults, expectedStatus);
}
@Test
@Parameters({"true", "false"})
public void testDestroySingleIndexWithRegionMembers(boolean expectedToSucceed) {
LuceneDestroyIndexCommand command =
spy(new LuceneTestDestroyIndexCommand(mockCache, null));
String indexName = "index";
String regionPath = "regionPath";
Set<DistributedMember> members = new HashSet<>();
DistributedMember mockMember = mock(DistributedMember.class);
when(mockMember.getId()).thenReturn("member0");
members.add(mockMember);
final ResultCollector mockResultCollector = mock(ResultCollector.class);
final List<CliFunctionResult> cliFunctionResults = new ArrayList<>();
String expectedStatus;
if (expectedToSucceed) {
expectedStatus = CliStrings.format(
LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__SUCCESSFULLY_DESTROYED_INDEX_0_FROM_REGION_1,
indexName, regionPath);
cliFunctionResults
.add(new CliFunctionResult(mockMember.getId(), CliFunctionResult.StatusState.OK));
} else {
Exception e = new IllegalStateException("failed");
expectedStatus = e.getMessage();
cliFunctionResults.add(new CliFunctionResult("member0", e, e.getMessage()));
}
doReturn(mockResultCollector).when(command).executeFunction(
any(LuceneDestroyIndexFunction.class), any(LuceneDestroyIndexInfo.class), anySet());
doReturn(cliFunctionResults).when(mockResultCollector).getResult();
doReturn(members).when(command).getNormalMembersWithSameOrNewerVersion(any());
ResultModel result = command.destroyIndex(indexName, regionPath);
verifyDestroyIndexCommandResult(result, cliFunctionResults, expectedStatus);
}
@Test
public void testDestroyAllIndexesNoRegionMembers() {
LuceneDestroyIndexCommand commands =
spy(new LuceneTestDestroyIndexCommand(mockCache, null));
doReturn(Collections.emptySet()).when(commands).getNormalMembersWithSameOrNewerVersion(any());
final List<CliFunctionResult> cliFunctionResults = new ArrayList<>();
String expectedStatus = CliStrings.format(
LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__COULD_NOT_FIND__MEMBERS_GREATER_THAN_VERSION_0,
new Object[] {KnownVersion.GEODE_1_7_0});
cliFunctionResults.add(new CliFunctionResult("member0", CliFunctionResult.StatusState.OK));
ResultModel result = commands.destroyIndex(null, "regionPath");
verifyDestroyIndexCommandResult(result, cliFunctionResults, expectedStatus);
}
@Test
@Parameters({"true", "false"})
public void testDestroyAllIndexesWithRegionMembers(boolean expectedToSucceed) {
LuceneDestroyIndexCommand commands =
spy(new LuceneTestDestroyIndexCommand(mockCache, null));
String indexName = null;
String regionPath = "regionPath";
Set<DistributedMember> members = new HashSet<>();
DistributedMember mockMember = mock(DistributedMember.class);
when(mockMember.getId()).thenReturn("member0");
members.add(mockMember);
final ResultCollector mockResultCollector = mock(ResultCollector.class);
final List<CliFunctionResult> cliFunctionResults = new ArrayList<>();
String expectedStatus;
if (expectedToSucceed) {
expectedStatus = CliStrings.format(
LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__SUCCESSFULLY_DESTROYED_INDEXES_FROM_REGION_0,
new Object[] {regionPath});
cliFunctionResults
.add(new CliFunctionResult(mockMember.getId(), CliFunctionResult.StatusState.OK));
} else {
Exception e = new IllegalStateException("failed");
expectedStatus = e.getMessage();
cliFunctionResults.add(new CliFunctionResult("member0", e, e.getMessage()));
}
doReturn(mockResultCollector).when(commands).executeFunction(
any(LuceneDestroyIndexFunction.class), any(LuceneDestroyIndexInfo.class), anySet());
doReturn(cliFunctionResults).when(mockResultCollector).getResult();
doReturn(members).when(commands).getNormalMembersWithSameOrNewerVersion(any());
ResultModel result = commands.destroyIndex(indexName, regionPath);
verifyDestroyIndexCommandResult(result, cliFunctionResults, expectedStatus);
}
private void verifyDestroyIndexCommandResult(ResultModel result,
List<CliFunctionResult> cliFunctionResults, String expectedStatus) {
assertThat(result.getStatus()).isEqualTo(Status.OK);
TabularResultModel data = result.getTableSection("lucene-indexes");
if (data != null) {
List<String> members = data.getValuesInColumn("Member");
assertThat(cliFunctionResults.size()).isEqualTo(members.size());
// Verify each member
for (int i = 0; i < members.size(); i++) {
assertThat(members.get(i)).isEqualTo("member" + i);
}
// Verify each status
List<String> status = data.getValuesInColumn("Status");
for (String statu : status) {
assertThat(statu).isEqualTo(expectedStatus);
}
} else if (result.getInfoSection("info") != null) {
// Info result. Verify next lines are equal.
assertThat(result.getInfoSection("info").getContent().get(0)).isEqualTo(expectedStatus);
} else {
// Error result. Verify next lines are equal.
assertThat(result.getInfoSection("error").getContent().get(0)).isEqualTo(expectedStatus);
}
}
private String getPage(final LuceneSearchResults[] expectedResults, int[] indexList) {
ResultModel resultModel = new ResultModel();
TabularResultModel data = resultModel.addTable("table");
for (int i : indexList) {
data.accumulate("key", expectedResults[i].getKey());
data.accumulate("value", expectedResults[i].getValue());
data.accumulate("score", expectedResults[i].getScore() + "");
}
return new CommandResult(resultModel).asString();
}
private List<Set<LuceneSearchResults>> getSearchResults(LuceneSearchResults... results) {
final List<Set<LuceneSearchResults>> queryResultsList = new ArrayList<>();
HashSet<LuceneSearchResults> queryResults = new HashSet<>();
Collections.addAll(queryResults, results);
queryResultsList.add(queryResults);
return queryResultsList;
}
private LuceneIndexStats getMockIndexStats(int queries, int commits, int updates, int docs) {
LuceneIndexStats mockIndexStats = mock(LuceneIndexStats.class);
when(mockIndexStats.getQueryExecutions()).thenReturn(queries);
when(mockIndexStats.getCommits()).thenReturn(commits);
when(mockIndexStats.getUpdates()).thenReturn(updates);
when(mockIndexStats.getDocuments()).thenReturn(docs);
return mockIndexStats;
}
private LuceneIndexDetails createIndexDetails(final String indexName, final String regionPath,
final String[] searchableFields, final Map<String, Analyzer> fieldAnalyzers,
LuceneIndexStats indexStats, LuceneIndexStatus status, final String serverName,
LuceneSerializer serializer) {
return new LuceneIndexDetails(indexName, regionPath, searchableFields, fieldAnalyzers,
indexStats, status, serverName, serializer);
}
private LuceneIndexDetails createIndexDetails(final String indexName, final String regionPath,
final String[] searchableFields, final Map<String, Analyzer> fieldAnalyzers,
LuceneIndexStatus status, final String serverName, LuceneSerializer serializer) {
return new LuceneIndexDetails(indexName, regionPath, searchableFields, fieldAnalyzers, null,
status, serverName, serializer);
}
private LuceneSearchResults createQueryResults(final String key, final String value,
final float score) {
return new LuceneSearchResults(key, value, score);
}
private static class LuceneTestListIndexCommand extends LuceneListIndexCommand {
private final Execution functionExecutor;
LuceneTestListIndexCommand(final InternalCache cache, final Execution functionExecutor) {
assert cache != null : "The InternalCache cannot be null!";
setCache(cache);
this.functionExecutor = functionExecutor;
}
@Override
public Set<DistributedMember> getAllMembers() {
return Collections.emptySet();
}
@Override
public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
assertThat(members).isNotNull();
return functionExecutor;
}
}
private static class LuceneTestCreateIndexCommand extends LuceneCreateIndexCommand {
private final Execution functionExecutor;
LuceneTestCreateIndexCommand(final InternalCache cache, final Execution functionExecutor) {
assert cache != null : "The InternalCache cannot be null!";
setCache(cache);
this.functionExecutor = functionExecutor;
}
@Override
public Set<DistributedMember> getAllMembers() {
return Collections.emptySet();
}
@Override
public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
assertThat(members).isNotNull();
return functionExecutor;
}
}
private static class LuceneTestDescribeIndexCommand extends LuceneDescribeIndexCommand {
private final Execution functionExecutor;
LuceneTestDescribeIndexCommand(final InternalCache cache, final Execution functionExecutor) {
assert cache != null : "The InternalCache cannot be null!";
setCache(cache);
this.functionExecutor = functionExecutor;
}
@Override
public Set<DistributedMember> getAllMembers() {
return Collections.emptySet();
}
@Override
public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
assertThat(members).isNotNull();
return functionExecutor;
}
}
private static class LuceneTestSearchIndexCommand extends LuceneSearchIndexCommand {
private final Execution functionExecutor;
LuceneTestSearchIndexCommand(final InternalCache cache, final Execution functionExecutor) {
assert cache != null : "The InternalCache cannot be null!";
setCache(cache);
this.functionExecutor = functionExecutor;
}
@Override
public Set<DistributedMember> getAllMembers() {
return Collections.emptySet();
}
@Override
public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
assertThat(members).isNotNull();
return functionExecutor;
}
}
private static class LuceneTestDestroyIndexCommand extends LuceneDestroyIndexCommand {
private final Execution functionExecutor;
LuceneTestDestroyIndexCommand(final InternalCache cache, final Execution functionExecutor) {
assert cache != null : "The InternalCache cannot be null!";
setCache(cache);
this.functionExecutor = functionExecutor;
}
@Override
public Set<DistributedMember> getAllMembers() {
return Collections.emptySet();
}
@Override
public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
assertThat(members).isNotNull();
return functionExecutor;
}
}
}
|
googleapis/google-cloud-java | 35,728 | java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/SummarizationHelpfulnessInput.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/evaluation_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1;
/**
*
*
* <pre>
* Input for summarization helpfulness metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.SummarizationHelpfulnessInput}
*/
public final class SummarizationHelpfulnessInput extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.SummarizationHelpfulnessInput)
SummarizationHelpfulnessInputOrBuilder {
private static final long serialVersionUID = 0L;
// Use SummarizationHelpfulnessInput.newBuilder() to construct.
private SummarizationHelpfulnessInput(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SummarizationHelpfulnessInput() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SummarizationHelpfulnessInput();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_SummarizationHelpfulnessInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_SummarizationHelpfulnessInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput.class,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput.Builder.class);
}
private int bitField0_;
public static final int METRIC_SPEC_FIELD_NUMBER = 1;
private com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metricSpec_;
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the metricSpec field is set.
*/
@java.lang.Override
public boolean hasMetricSpec() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec getMetricSpec() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec.getDefaultInstance()
: metricSpec_;
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpecOrBuilder
getMetricSpecOrBuilder() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec.getDefaultInstance()
: metricSpec_;
}
public static final int INSTANCE_FIELD_NUMBER = 2;
private com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance_;
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the instance field is set.
*/
@java.lang.Override
public boolean hasInstance() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance getInstance() {
return instance_ == null
? com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance.getDefaultInstance()
: instance_;
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstanceOrBuilder
getInstanceOrBuilder() {
return instance_ == null
? com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance.getDefaultInstance()
: instance_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getMetricSpec());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getInstance());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getMetricSpec());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getInstance());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput other =
(com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput) obj;
if (hasMetricSpec() != other.hasMetricSpec()) return false;
if (hasMetricSpec()) {
if (!getMetricSpec().equals(other.getMetricSpec())) return false;
}
if (hasInstance() != other.hasInstance()) return false;
if (hasInstance()) {
if (!getInstance().equals(other.getInstance())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasMetricSpec()) {
hash = (37 * hash) + METRIC_SPEC_FIELD_NUMBER;
hash = (53 * hash) + getMetricSpec().hashCode();
}
if (hasInstance()) {
hash = (37 * hash) + INSTANCE_FIELD_NUMBER;
hash = (53 * hash) + getInstance().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Input for summarization helpfulness metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.SummarizationHelpfulnessInput}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.SummarizationHelpfulnessInput)
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInputOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_SummarizationHelpfulnessInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_SummarizationHelpfulnessInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput.class,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getMetricSpecFieldBuilder();
getInstanceFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
metricSpec_ = null;
if (metricSpecBuilder_ != null) {
metricSpecBuilder_.dispose();
metricSpecBuilder_ = null;
}
instance_ = null;
if (instanceBuilder_ != null) {
instanceBuilder_.dispose();
instanceBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_SummarizationHelpfulnessInput_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput build() {
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput buildPartial() {
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput result =
new com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.metricSpec_ = metricSpecBuilder_ == null ? metricSpec_ : metricSpecBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.instance_ = instanceBuilder_ == null ? instance_ : instanceBuilder_.build();
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput) {
return mergeFrom((com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput other) {
if (other
== com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput.getDefaultInstance())
return this;
if (other.hasMetricSpec()) {
mergeMetricSpec(other.getMetricSpec());
}
if (other.hasInstance()) {
mergeInstance(other.getInstance());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(getMetricSpecFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getInstanceFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metricSpec_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec.Builder,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpecOrBuilder>
metricSpecBuilder_;
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the metricSpec field is set.
*/
public boolean hasMetricSpec() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec getMetricSpec() {
if (metricSpecBuilder_ == null) {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec.getDefaultInstance()
: metricSpec_;
} else {
return metricSpecBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec value) {
if (metricSpecBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
metricSpec_ = value;
} else {
metricSpecBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec.Builder builderForValue) {
if (metricSpecBuilder_ == null) {
metricSpec_ = builderForValue.build();
} else {
metricSpecBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeMetricSpec(
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec value) {
if (metricSpecBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& metricSpec_ != null
&& metricSpec_
!= com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec
.getDefaultInstance()) {
getMetricSpecBuilder().mergeFrom(value);
} else {
metricSpec_ = value;
}
} else {
metricSpecBuilder_.mergeFrom(value);
}
if (metricSpec_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearMetricSpec() {
bitField0_ = (bitField0_ & ~0x00000001);
metricSpec_ = null;
if (metricSpecBuilder_ != null) {
metricSpecBuilder_.dispose();
metricSpecBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec.Builder
getMetricSpecBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getMetricSpecFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpecOrBuilder
getMetricSpecOrBuilder() {
if (metricSpecBuilder_ != null) {
return metricSpecBuilder_.getMessageOrBuilder();
} else {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec.getDefaultInstance()
: metricSpec_;
}
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec.Builder,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpecOrBuilder>
getMetricSpecFieldBuilder() {
if (metricSpecBuilder_ == null) {
metricSpecBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpec.Builder,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessSpecOrBuilder>(
getMetricSpec(), getParentForChildren(), isClean());
metricSpec_ = null;
}
return metricSpecBuilder_;
}
private com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance.Builder,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstanceOrBuilder>
instanceBuilder_;
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the instance field is set.
*/
public boolean hasInstance() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance getInstance() {
if (instanceBuilder_ == null) {
return instance_ == null
? com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance.getDefaultInstance()
: instance_;
} else {
return instanceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance value) {
if (instanceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
instance_ = value;
} else {
instanceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance.Builder builderForValue) {
if (instanceBuilder_ == null) {
instance_ = builderForValue.build();
} else {
instanceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeInstance(
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance value) {
if (instanceBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& instance_ != null
&& instance_
!= com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance
.getDefaultInstance()) {
getInstanceBuilder().mergeFrom(value);
} else {
instance_ = value;
}
} else {
instanceBuilder_.mergeFrom(value);
}
if (instance_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearInstance() {
bitField0_ = (bitField0_ & ~0x00000002);
instance_ = null;
if (instanceBuilder_ != null) {
instanceBuilder_.dispose();
instanceBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance.Builder
getInstanceBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getInstanceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstanceOrBuilder
getInstanceOrBuilder() {
if (instanceBuilder_ != null) {
return instanceBuilder_.getMessageOrBuilder();
} else {
return instance_ == null
? com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance.getDefaultInstance()
: instance_;
}
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance.Builder,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstanceOrBuilder>
getInstanceFieldBuilder() {
if (instanceBuilder_ == null) {
instanceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstance.Builder,
com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInstanceOrBuilder>(
getInstance(), getParentForChildren(), isClean());
instance_ = null;
}
return instanceBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.SummarizationHelpfulnessInput)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.SummarizationHelpfulnessInput)
private static final com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput();
}
public static com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SummarizationHelpfulnessInput> PARSER =
new com.google.protobuf.AbstractParser<SummarizationHelpfulnessInput>() {
@java.lang.Override
public SummarizationHelpfulnessInput parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<SummarizationHelpfulnessInput> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SummarizationHelpfulnessInput> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.SummarizationHelpfulnessInput getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,811 | java-dlp/proto-google-cloud-dlp-v2/src/main/java/com/google/privacy/dlp/v2/DiscoveryVertexDatasetGenerationCadence.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/privacy/dlp/v2/dlp.proto
// Protobuf Java Version: 3.25.8
package com.google.privacy.dlp.v2;
/**
*
*
* <pre>
* How often existing datasets should have their profiles refreshed.
* New datasets are scanned as quickly as possible depending on system
* capacity.
* </pre>
*
* Protobuf type {@code google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence}
*/
public final class DiscoveryVertexDatasetGenerationCadence
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence)
DiscoveryVertexDatasetGenerationCadenceOrBuilder {
private static final long serialVersionUID = 0L;
// Use DiscoveryVertexDatasetGenerationCadence.newBuilder() to construct.
private DiscoveryVertexDatasetGenerationCadence(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DiscoveryVertexDatasetGenerationCadence() {
refreshFrequency_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new DiscoveryVertexDatasetGenerationCadence();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_DiscoveryVertexDatasetGenerationCadence_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_DiscoveryVertexDatasetGenerationCadence_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence.class,
com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence.Builder.class);
}
private int bitField0_;
public static final int REFRESH_FREQUENCY_FIELD_NUMBER = 1;
private int refreshFrequency_ = 0;
/**
*
*
* <pre>
* If you set this field, profiles are refreshed at this
* frequency regardless of whether the underlying datasets have changed.
* Defaults to never.
* </pre>
*
* <code>.google.privacy.dlp.v2.DataProfileUpdateFrequency refresh_frequency = 1;</code>
*
* @return The enum numeric value on the wire for refreshFrequency.
*/
@java.lang.Override
public int getRefreshFrequencyValue() {
return refreshFrequency_;
}
/**
*
*
* <pre>
* If you set this field, profiles are refreshed at this
* frequency regardless of whether the underlying datasets have changed.
* Defaults to never.
* </pre>
*
* <code>.google.privacy.dlp.v2.DataProfileUpdateFrequency refresh_frequency = 1;</code>
*
* @return The refreshFrequency.
*/
@java.lang.Override
public com.google.privacy.dlp.v2.DataProfileUpdateFrequency getRefreshFrequency() {
com.google.privacy.dlp.v2.DataProfileUpdateFrequency result =
com.google.privacy.dlp.v2.DataProfileUpdateFrequency.forNumber(refreshFrequency_);
return result == null
? com.google.privacy.dlp.v2.DataProfileUpdateFrequency.UNRECOGNIZED
: result;
}
public static final int INSPECT_TEMPLATE_MODIFIED_CADENCE_FIELD_NUMBER = 2;
private com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence
inspectTemplateModifiedCadence_;
/**
*
*
* <pre>
* Governs when to update data profiles when the inspection rules
* defined by the `InspectTemplate` change.
* If not set, changing the template will not cause a data profile to be
* updated.
* </pre>
*
* <code>
* .google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence inspect_template_modified_cadence = 2;
* </code>
*
* @return Whether the inspectTemplateModifiedCadence field is set.
*/
@java.lang.Override
public boolean hasInspectTemplateModifiedCadence() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Governs when to update data profiles when the inspection rules
* defined by the `InspectTemplate` change.
* If not set, changing the template will not cause a data profile to be
* updated.
* </pre>
*
* <code>
* .google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence inspect_template_modified_cadence = 2;
* </code>
*
* @return The inspectTemplateModifiedCadence.
*/
@java.lang.Override
public com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence
getInspectTemplateModifiedCadence() {
return inspectTemplateModifiedCadence_ == null
? com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence.getDefaultInstance()
: inspectTemplateModifiedCadence_;
}
/**
*
*
* <pre>
* Governs when to update data profiles when the inspection rules
* defined by the `InspectTemplate` change.
* If not set, changing the template will not cause a data profile to be
* updated.
* </pre>
*
* <code>
* .google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence inspect_template_modified_cadence = 2;
* </code>
*/
@java.lang.Override
public com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadenceOrBuilder
getInspectTemplateModifiedCadenceOrBuilder() {
return inspectTemplateModifiedCadence_ == null
? com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence.getDefaultInstance()
: inspectTemplateModifiedCadence_;
}
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 (refreshFrequency_
!= com.google.privacy.dlp.v2.DataProfileUpdateFrequency.UPDATE_FREQUENCY_UNSPECIFIED
.getNumber()) {
output.writeEnum(1, refreshFrequency_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getInspectTemplateModifiedCadence());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (refreshFrequency_
!= com.google.privacy.dlp.v2.DataProfileUpdateFrequency.UPDATE_FREQUENCY_UNSPECIFIED
.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, refreshFrequency_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
2, getInspectTemplateModifiedCadence());
}
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.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence)) {
return super.equals(obj);
}
com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence other =
(com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence) obj;
if (refreshFrequency_ != other.refreshFrequency_) return false;
if (hasInspectTemplateModifiedCadence() != other.hasInspectTemplateModifiedCadence())
return false;
if (hasInspectTemplateModifiedCadence()) {
if (!getInspectTemplateModifiedCadence().equals(other.getInspectTemplateModifiedCadence()))
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) + REFRESH_FREQUENCY_FIELD_NUMBER;
hash = (53 * hash) + refreshFrequency_;
if (hasInspectTemplateModifiedCadence()) {
hash = (37 * hash) + INSPECT_TEMPLATE_MODIFIED_CADENCE_FIELD_NUMBER;
hash = (53 * hash) + getInspectTemplateModifiedCadence().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence 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.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence 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.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence
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.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence 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.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence 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>
* How often existing datasets should have their profiles refreshed.
* New datasets are scanned as quickly as possible depending on system
* capacity.
* </pre>
*
* Protobuf type {@code google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence)
com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadenceOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_DiscoveryVertexDatasetGenerationCadence_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_DiscoveryVertexDatasetGenerationCadence_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence.class,
com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence.Builder.class);
}
// Construct using
// com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getInspectTemplateModifiedCadenceFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
refreshFrequency_ = 0;
inspectTemplateModifiedCadence_ = null;
if (inspectTemplateModifiedCadenceBuilder_ != null) {
inspectTemplateModifiedCadenceBuilder_.dispose();
inspectTemplateModifiedCadenceBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_DiscoveryVertexDatasetGenerationCadence_descriptor;
}
@java.lang.Override
public com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence
getDefaultInstanceForType() {
return com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence.getDefaultInstance();
}
@java.lang.Override
public com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence build() {
com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence buildPartial() {
com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence result =
new com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.refreshFrequency_ = refreshFrequency_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.inspectTemplateModifiedCadence_ =
inspectTemplateModifiedCadenceBuilder_ == null
? inspectTemplateModifiedCadence_
: inspectTemplateModifiedCadenceBuilder_.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.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence) {
return mergeFrom((com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence other) {
if (other
== com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence.getDefaultInstance())
return this;
if (other.refreshFrequency_ != 0) {
setRefreshFrequencyValue(other.getRefreshFrequencyValue());
}
if (other.hasInspectTemplateModifiedCadence()) {
mergeInspectTemplateModifiedCadence(other.getInspectTemplateModifiedCadence());
}
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:
{
refreshFrequency_ = input.readEnum();
bitField0_ |= 0x00000001;
break;
} // case 8
case 18:
{
input.readMessage(
getInspectTemplateModifiedCadenceFieldBuilder().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 int refreshFrequency_ = 0;
/**
*
*
* <pre>
* If you set this field, profiles are refreshed at this
* frequency regardless of whether the underlying datasets have changed.
* Defaults to never.
* </pre>
*
* <code>.google.privacy.dlp.v2.DataProfileUpdateFrequency refresh_frequency = 1;</code>
*
* @return The enum numeric value on the wire for refreshFrequency.
*/
@java.lang.Override
public int getRefreshFrequencyValue() {
return refreshFrequency_;
}
/**
*
*
* <pre>
* If you set this field, profiles are refreshed at this
* frequency regardless of whether the underlying datasets have changed.
* Defaults to never.
* </pre>
*
* <code>.google.privacy.dlp.v2.DataProfileUpdateFrequency refresh_frequency = 1;</code>
*
* @param value The enum numeric value on the wire for refreshFrequency to set.
* @return This builder for chaining.
*/
public Builder setRefreshFrequencyValue(int value) {
refreshFrequency_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* If you set this field, profiles are refreshed at this
* frequency regardless of whether the underlying datasets have changed.
* Defaults to never.
* </pre>
*
* <code>.google.privacy.dlp.v2.DataProfileUpdateFrequency refresh_frequency = 1;</code>
*
* @return The refreshFrequency.
*/
@java.lang.Override
public com.google.privacy.dlp.v2.DataProfileUpdateFrequency getRefreshFrequency() {
com.google.privacy.dlp.v2.DataProfileUpdateFrequency result =
com.google.privacy.dlp.v2.DataProfileUpdateFrequency.forNumber(refreshFrequency_);
return result == null
? com.google.privacy.dlp.v2.DataProfileUpdateFrequency.UNRECOGNIZED
: result;
}
/**
*
*
* <pre>
* If you set this field, profiles are refreshed at this
* frequency regardless of whether the underlying datasets have changed.
* Defaults to never.
* </pre>
*
* <code>.google.privacy.dlp.v2.DataProfileUpdateFrequency refresh_frequency = 1;</code>
*
* @param value The refreshFrequency to set.
* @return This builder for chaining.
*/
public Builder setRefreshFrequency(com.google.privacy.dlp.v2.DataProfileUpdateFrequency value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
refreshFrequency_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* If you set this field, profiles are refreshed at this
* frequency regardless of whether the underlying datasets have changed.
* Defaults to never.
* </pre>
*
* <code>.google.privacy.dlp.v2.DataProfileUpdateFrequency refresh_frequency = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearRefreshFrequency() {
bitField0_ = (bitField0_ & ~0x00000001);
refreshFrequency_ = 0;
onChanged();
return this;
}
private com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence
inspectTemplateModifiedCadence_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence,
com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence.Builder,
com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadenceOrBuilder>
inspectTemplateModifiedCadenceBuilder_;
/**
*
*
* <pre>
* Governs when to update data profiles when the inspection rules
* defined by the `InspectTemplate` change.
* If not set, changing the template will not cause a data profile to be
* updated.
* </pre>
*
* <code>
* .google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence inspect_template_modified_cadence = 2;
* </code>
*
* @return Whether the inspectTemplateModifiedCadence field is set.
*/
public boolean hasInspectTemplateModifiedCadence() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Governs when to update data profiles when the inspection rules
* defined by the `InspectTemplate` change.
* If not set, changing the template will not cause a data profile to be
* updated.
* </pre>
*
* <code>
* .google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence inspect_template_modified_cadence = 2;
* </code>
*
* @return The inspectTemplateModifiedCadence.
*/
public com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence
getInspectTemplateModifiedCadence() {
if (inspectTemplateModifiedCadenceBuilder_ == null) {
return inspectTemplateModifiedCadence_ == null
? com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence.getDefaultInstance()
: inspectTemplateModifiedCadence_;
} else {
return inspectTemplateModifiedCadenceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Governs when to update data profiles when the inspection rules
* defined by the `InspectTemplate` change.
* If not set, changing the template will not cause a data profile to be
* updated.
* </pre>
*
* <code>
* .google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence inspect_template_modified_cadence = 2;
* </code>
*/
public Builder setInspectTemplateModifiedCadence(
com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence value) {
if (inspectTemplateModifiedCadenceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
inspectTemplateModifiedCadence_ = value;
} else {
inspectTemplateModifiedCadenceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Governs when to update data profiles when the inspection rules
* defined by the `InspectTemplate` change.
* If not set, changing the template will not cause a data profile to be
* updated.
* </pre>
*
* <code>
* .google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence inspect_template_modified_cadence = 2;
* </code>
*/
public Builder setInspectTemplateModifiedCadence(
com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence.Builder builderForValue) {
if (inspectTemplateModifiedCadenceBuilder_ == null) {
inspectTemplateModifiedCadence_ = builderForValue.build();
} else {
inspectTemplateModifiedCadenceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Governs when to update data profiles when the inspection rules
* defined by the `InspectTemplate` change.
* If not set, changing the template will not cause a data profile to be
* updated.
* </pre>
*
* <code>
* .google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence inspect_template_modified_cadence = 2;
* </code>
*/
public Builder mergeInspectTemplateModifiedCadence(
com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence value) {
if (inspectTemplateModifiedCadenceBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& inspectTemplateModifiedCadence_ != null
&& inspectTemplateModifiedCadence_
!= com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence
.getDefaultInstance()) {
getInspectTemplateModifiedCadenceBuilder().mergeFrom(value);
} else {
inspectTemplateModifiedCadence_ = value;
}
} else {
inspectTemplateModifiedCadenceBuilder_.mergeFrom(value);
}
if (inspectTemplateModifiedCadence_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Governs when to update data profiles when the inspection rules
* defined by the `InspectTemplate` change.
* If not set, changing the template will not cause a data profile to be
* updated.
* </pre>
*
* <code>
* .google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence inspect_template_modified_cadence = 2;
* </code>
*/
public Builder clearInspectTemplateModifiedCadence() {
bitField0_ = (bitField0_ & ~0x00000002);
inspectTemplateModifiedCadence_ = null;
if (inspectTemplateModifiedCadenceBuilder_ != null) {
inspectTemplateModifiedCadenceBuilder_.dispose();
inspectTemplateModifiedCadenceBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Governs when to update data profiles when the inspection rules
* defined by the `InspectTemplate` change.
* If not set, changing the template will not cause a data profile to be
* updated.
* </pre>
*
* <code>
* .google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence inspect_template_modified_cadence = 2;
* </code>
*/
public com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence.Builder
getInspectTemplateModifiedCadenceBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getInspectTemplateModifiedCadenceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Governs when to update data profiles when the inspection rules
* defined by the `InspectTemplate` change.
* If not set, changing the template will not cause a data profile to be
* updated.
* </pre>
*
* <code>
* .google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence inspect_template_modified_cadence = 2;
* </code>
*/
public com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadenceOrBuilder
getInspectTemplateModifiedCadenceOrBuilder() {
if (inspectTemplateModifiedCadenceBuilder_ != null) {
return inspectTemplateModifiedCadenceBuilder_.getMessageOrBuilder();
} else {
return inspectTemplateModifiedCadence_ == null
? com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence.getDefaultInstance()
: inspectTemplateModifiedCadence_;
}
}
/**
*
*
* <pre>
* Governs when to update data profiles when the inspection rules
* defined by the `InspectTemplate` change.
* If not set, changing the template will not cause a data profile to be
* updated.
* </pre>
*
* <code>
* .google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence inspect_template_modified_cadence = 2;
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence,
com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence.Builder,
com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadenceOrBuilder>
getInspectTemplateModifiedCadenceFieldBuilder() {
if (inspectTemplateModifiedCadenceBuilder_ == null) {
inspectTemplateModifiedCadenceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence,
com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadence.Builder,
com.google.privacy.dlp.v2.DiscoveryInspectTemplateModifiedCadenceOrBuilder>(
getInspectTemplateModifiedCadence(), getParentForChildren(), isClean());
inspectTemplateModifiedCadence_ = null;
}
return inspectTemplateModifiedCadenceBuilder_;
}
@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.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence)
}
// @@protoc_insertion_point(class_scope:google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence)
private static final com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence();
}
public static com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DiscoveryVertexDatasetGenerationCadence> PARSER =
new com.google.protobuf.AbstractParser<DiscoveryVertexDatasetGenerationCadence>() {
@java.lang.Override
public DiscoveryVertexDatasetGenerationCadence 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<DiscoveryVertexDatasetGenerationCadence> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DiscoveryVertexDatasetGenerationCadence> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.privacy.dlp.v2.DiscoveryVertexDatasetGenerationCadence
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,594 | java-translate/proto-google-cloud-translate-v3/src/main/java/com/google/cloud/translate/v3/Example.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/translate/v3/automl_translation.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.translate.v3;
/**
*
*
* <pre>
* A sentence pair.
* </pre>
*
* Protobuf type {@code google.cloud.translation.v3.Example}
*/
public final class Example extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.translation.v3.Example)
ExampleOrBuilder {
private static final long serialVersionUID = 0L;
// Use Example.newBuilder() to construct.
private Example(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Example() {
name_ = "";
sourceText_ = "";
targetText_ = "";
usage_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new Example();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_Example_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_Example_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.translate.v3.Example.class,
com.google.cloud.translate.v3.Example.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object name_ = "";
/**
*
*
* <pre>
* Output only. The resource name of the example, in form of
* `projects/{project-number-or-id}/locations/{location_id}/datasets/{dataset_id}/examples/{example_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</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>
* Output only. The resource name of the example, in form of
* `projects/{project-number-or-id}/locations/{location_id}/datasets/{dataset_id}/examples/{example_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</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 SOURCE_TEXT_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object sourceText_ = "";
/**
*
*
* <pre>
* Sentence in source language.
* </pre>
*
* <code>string source_text = 2;</code>
*
* @return The sourceText.
*/
@java.lang.Override
public java.lang.String getSourceText() {
java.lang.Object ref = sourceText_;
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();
sourceText_ = s;
return s;
}
}
/**
*
*
* <pre>
* Sentence in source language.
* </pre>
*
* <code>string source_text = 2;</code>
*
* @return The bytes for sourceText.
*/
@java.lang.Override
public com.google.protobuf.ByteString getSourceTextBytes() {
java.lang.Object ref = sourceText_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
sourceText_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TARGET_TEXT_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object targetText_ = "";
/**
*
*
* <pre>
* Sentence in target language.
* </pre>
*
* <code>string target_text = 3;</code>
*
* @return The targetText.
*/
@java.lang.Override
public java.lang.String getTargetText() {
java.lang.Object ref = targetText_;
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();
targetText_ = s;
return s;
}
}
/**
*
*
* <pre>
* Sentence in target language.
* </pre>
*
* <code>string target_text = 3;</code>
*
* @return The bytes for targetText.
*/
@java.lang.Override
public com.google.protobuf.ByteString getTargetTextBytes() {
java.lang.Object ref = targetText_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
targetText_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int USAGE_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object usage_ = "";
/**
*
*
* <pre>
* Output only. Usage of the sentence pair. Options are TRAIN|VALIDATION|TEST.
* </pre>
*
* <code>string usage = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The usage.
*/
@java.lang.Override
public java.lang.String getUsage() {
java.lang.Object ref = usage_;
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();
usage_ = s;
return s;
}
}
/**
*
*
* <pre>
* Output only. Usage of the sentence pair. Options are TRAIN|VALIDATION|TEST.
* </pre>
*
* <code>string usage = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for usage.
*/
@java.lang.Override
public com.google.protobuf.ByteString getUsageBytes() {
java.lang.Object ref = usage_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
usage_ = 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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(sourceText_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, sourceText_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(targetText_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, targetText_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(usage_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, usage_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(sourceText_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, sourceText_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(targetText_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, targetText_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(usage_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, usage_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.translate.v3.Example)) {
return super.equals(obj);
}
com.google.cloud.translate.v3.Example other = (com.google.cloud.translate.v3.Example) obj;
if (!getName().equals(other.getName())) return false;
if (!getSourceText().equals(other.getSourceText())) return false;
if (!getTargetText().equals(other.getTargetText())) return false;
if (!getUsage().equals(other.getUsage())) 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) + SOURCE_TEXT_FIELD_NUMBER;
hash = (53 * hash) + getSourceText().hashCode();
hash = (37 * hash) + TARGET_TEXT_FIELD_NUMBER;
hash = (53 * hash) + getTargetText().hashCode();
hash = (37 * hash) + USAGE_FIELD_NUMBER;
hash = (53 * hash) + getUsage().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.translate.v3.Example parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3.Example parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3.Example parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3.Example parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3.Example parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3.Example parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3.Example parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3.Example parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.translate.v3.Example parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3.Example parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.translate.v3.Example parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3.Example parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.translate.v3.Example 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 sentence pair.
* </pre>
*
* Protobuf type {@code google.cloud.translation.v3.Example}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.translation.v3.Example)
com.google.cloud.translate.v3.ExampleOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_Example_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_Example_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.translate.v3.Example.class,
com.google.cloud.translate.v3.Example.Builder.class);
}
// Construct using com.google.cloud.translate.v3.Example.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
name_ = "";
sourceText_ = "";
targetText_ = "";
usage_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_Example_descriptor;
}
@java.lang.Override
public com.google.cloud.translate.v3.Example getDefaultInstanceForType() {
return com.google.cloud.translate.v3.Example.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.translate.v3.Example build() {
com.google.cloud.translate.v3.Example result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.translate.v3.Example buildPartial() {
com.google.cloud.translate.v3.Example result =
new com.google.cloud.translate.v3.Example(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.translate.v3.Example result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.name_ = name_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.sourceText_ = sourceText_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.targetText_ = targetText_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.usage_ = usage_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.translate.v3.Example) {
return mergeFrom((com.google.cloud.translate.v3.Example) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.translate.v3.Example other) {
if (other == com.google.cloud.translate.v3.Example.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getSourceText().isEmpty()) {
sourceText_ = other.sourceText_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getTargetText().isEmpty()) {
targetText_ = other.targetText_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getUsage().isEmpty()) {
usage_ = other.usage_;
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:
{
name_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
sourceText_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
targetText_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
usage_ = 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 name_ = "";
/**
*
*
* <pre>
* Output only. The resource name of the example, in form of
* `projects/{project-number-or-id}/locations/{location_id}/datasets/{dataset_id}/examples/{example_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</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>
* Output only. The resource name of the example, in form of
* `projects/{project-number-or-id}/locations/{location_id}/datasets/{dataset_id}/examples/{example_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</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>
* Output only. The resource name of the example, in form of
* `projects/{project-number-or-id}/locations/{location_id}/datasets/{dataset_id}/examples/{example_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</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>
* Output only. The resource name of the example, in form of
* `projects/{project-number-or-id}/locations/{location_id}/datasets/{dataset_id}/examples/{example_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The resource name of the example, in form of
* `projects/{project-number-or-id}/locations/{location_id}/datasets/{dataset_id}/examples/{example_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object sourceText_ = "";
/**
*
*
* <pre>
* Sentence in source language.
* </pre>
*
* <code>string source_text = 2;</code>
*
* @return The sourceText.
*/
public java.lang.String getSourceText() {
java.lang.Object ref = sourceText_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
sourceText_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Sentence in source language.
* </pre>
*
* <code>string source_text = 2;</code>
*
* @return The bytes for sourceText.
*/
public com.google.protobuf.ByteString getSourceTextBytes() {
java.lang.Object ref = sourceText_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
sourceText_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Sentence in source language.
* </pre>
*
* <code>string source_text = 2;</code>
*
* @param value The sourceText to set.
* @return This builder for chaining.
*/
public Builder setSourceText(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
sourceText_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Sentence in source language.
* </pre>
*
* <code>string source_text = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearSourceText() {
sourceText_ = getDefaultInstance().getSourceText();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Sentence in source language.
* </pre>
*
* <code>string source_text = 2;</code>
*
* @param value The bytes for sourceText to set.
* @return This builder for chaining.
*/
public Builder setSourceTextBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
sourceText_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object targetText_ = "";
/**
*
*
* <pre>
* Sentence in target language.
* </pre>
*
* <code>string target_text = 3;</code>
*
* @return The targetText.
*/
public java.lang.String getTargetText() {
java.lang.Object ref = targetText_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
targetText_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Sentence in target language.
* </pre>
*
* <code>string target_text = 3;</code>
*
* @return The bytes for targetText.
*/
public com.google.protobuf.ByteString getTargetTextBytes() {
java.lang.Object ref = targetText_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
targetText_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Sentence in target language.
* </pre>
*
* <code>string target_text = 3;</code>
*
* @param value The targetText to set.
* @return This builder for chaining.
*/
public Builder setTargetText(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
targetText_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Sentence in target language.
* </pre>
*
* <code>string target_text = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearTargetText() {
targetText_ = getDefaultInstance().getTargetText();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Sentence in target language.
* </pre>
*
* <code>string target_text = 3;</code>
*
* @param value The bytes for targetText to set.
* @return This builder for chaining.
*/
public Builder setTargetTextBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
targetText_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object usage_ = "";
/**
*
*
* <pre>
* Output only. Usage of the sentence pair. Options are TRAIN|VALIDATION|TEST.
* </pre>
*
* <code>string usage = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The usage.
*/
public java.lang.String getUsage() {
java.lang.Object ref = usage_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
usage_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Output only. Usage of the sentence pair. Options are TRAIN|VALIDATION|TEST.
* </pre>
*
* <code>string usage = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for usage.
*/
public com.google.protobuf.ByteString getUsageBytes() {
java.lang.Object ref = usage_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
usage_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Output only. Usage of the sentence pair. Options are TRAIN|VALIDATION|TEST.
* </pre>
*
* <code>string usage = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The usage to set.
* @return This builder for chaining.
*/
public Builder setUsage(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
usage_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Usage of the sentence pair. Options are TRAIN|VALIDATION|TEST.
* </pre>
*
* <code>string usage = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return This builder for chaining.
*/
public Builder clearUsage() {
usage_ = getDefaultInstance().getUsage();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Usage of the sentence pair. Options are TRAIN|VALIDATION|TEST.
* </pre>
*
* <code>string usage = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The bytes for usage to set.
* @return This builder for chaining.
*/
public Builder setUsageBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
usage_ = 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.translation.v3.Example)
}
// @@protoc_insertion_point(class_scope:google.cloud.translation.v3.Example)
private static final com.google.cloud.translate.v3.Example DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.translate.v3.Example();
}
public static com.google.cloud.translate.v3.Example getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Example> PARSER =
new com.google.protobuf.AbstractParser<Example>() {
@java.lang.Override
public Example 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<Example> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Example> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.translate.v3.Example getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,625 | java-area120-tables/proto-google-area120-tables-v1alpha1/src/main/java/com/google/area120/tables/v1alpha1/UpdateRowRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/area120/tables/v1alpha1/tables.proto
// Protobuf Java Version: 3.25.8
package com.google.area120.tables.v1alpha1;
/**
*
*
* <pre>
* Request message for TablesService.UpdateRow.
* </pre>
*
* Protobuf type {@code google.area120.tables.v1alpha1.UpdateRowRequest}
*/
public final class UpdateRowRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.area120.tables.v1alpha1.UpdateRowRequest)
UpdateRowRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateRowRequest.newBuilder() to construct.
private UpdateRowRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateRowRequest() {
view_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateRowRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.area120.tables.v1alpha1.TablesProto
.internal_static_google_area120_tables_v1alpha1_UpdateRowRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.area120.tables.v1alpha1.TablesProto
.internal_static_google_area120_tables_v1alpha1_UpdateRowRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.area120.tables.v1alpha1.UpdateRowRequest.class,
com.google.area120.tables.v1alpha1.UpdateRowRequest.Builder.class);
}
private int bitField0_;
public static final int ROW_FIELD_NUMBER = 1;
private com.google.area120.tables.v1alpha1.Row row_;
/**
*
*
* <pre>
* Required. The row to update.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.Row row = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the row field is set.
*/
@java.lang.Override
public boolean hasRow() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The row to update.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.Row row = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The row.
*/
@java.lang.Override
public com.google.area120.tables.v1alpha1.Row getRow() {
return row_ == null ? com.google.area120.tables.v1alpha1.Row.getDefaultInstance() : row_;
}
/**
*
*
* <pre>
* Required. The row to update.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.Row row = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.area120.tables.v1alpha1.RowOrBuilder getRowOrBuilder() {
return row_ == null ? com.google.area120.tables.v1alpha1.Row.getDefaultInstance() : row_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* The list of fields to update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The list of fields to update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* The list of fields to update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
public static final int VIEW_FIELD_NUMBER = 3;
private int view_ = 0;
/**
*
*
* <pre>
* Optional. Column key to use for values in the row.
* Defaults to user entered name.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.View view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The enum numeric value on the wire for view.
*/
@java.lang.Override
public int getViewValue() {
return view_;
}
/**
*
*
* <pre>
* Optional. Column key to use for values in the row.
* Defaults to user entered name.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.View view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The view.
*/
@java.lang.Override
public com.google.area120.tables.v1alpha1.View getView() {
com.google.area120.tables.v1alpha1.View result =
com.google.area120.tables.v1alpha1.View.forNumber(view_);
return result == null ? com.google.area120.tables.v1alpha1.View.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 (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getRow());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getUpdateMask());
}
if (view_ != com.google.area120.tables.v1alpha1.View.VIEW_UNSPECIFIED.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 (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getRow());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
if (view_ != com.google.area120.tables.v1alpha1.View.VIEW_UNSPECIFIED.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.area120.tables.v1alpha1.UpdateRowRequest)) {
return super.equals(obj);
}
com.google.area120.tables.v1alpha1.UpdateRowRequest other =
(com.google.area120.tables.v1alpha1.UpdateRowRequest) obj;
if (hasRow() != other.hasRow()) return false;
if (hasRow()) {
if (!getRow().equals(other.getRow())) return false;
}
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) 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();
if (hasRow()) {
hash = (37 * hash) + ROW_FIELD_NUMBER;
hash = (53 * hash) + getRow().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (37 * hash) + VIEW_FIELD_NUMBER;
hash = (53 * hash) + view_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.area120.tables.v1alpha1.UpdateRowRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.area120.tables.v1alpha1.UpdateRowRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.area120.tables.v1alpha1.UpdateRowRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.area120.tables.v1alpha1.UpdateRowRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.area120.tables.v1alpha1.UpdateRowRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.area120.tables.v1alpha1.UpdateRowRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.area120.tables.v1alpha1.UpdateRowRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.area120.tables.v1alpha1.UpdateRowRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.area120.tables.v1alpha1.UpdateRowRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.area120.tables.v1alpha1.UpdateRowRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.area120.tables.v1alpha1.UpdateRowRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.area120.tables.v1alpha1.UpdateRowRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.area120.tables.v1alpha1.UpdateRowRequest 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 TablesService.UpdateRow.
* </pre>
*
* Protobuf type {@code google.area120.tables.v1alpha1.UpdateRowRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.area120.tables.v1alpha1.UpdateRowRequest)
com.google.area120.tables.v1alpha1.UpdateRowRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.area120.tables.v1alpha1.TablesProto
.internal_static_google_area120_tables_v1alpha1_UpdateRowRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.area120.tables.v1alpha1.TablesProto
.internal_static_google_area120_tables_v1alpha1_UpdateRowRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.area120.tables.v1alpha1.UpdateRowRequest.class,
com.google.area120.tables.v1alpha1.UpdateRowRequest.Builder.class);
}
// Construct using com.google.area120.tables.v1alpha1.UpdateRowRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getRowFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
row_ = null;
if (rowBuilder_ != null) {
rowBuilder_.dispose();
rowBuilder_ = null;
}
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
view_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.area120.tables.v1alpha1.TablesProto
.internal_static_google_area120_tables_v1alpha1_UpdateRowRequest_descriptor;
}
@java.lang.Override
public com.google.area120.tables.v1alpha1.UpdateRowRequest getDefaultInstanceForType() {
return com.google.area120.tables.v1alpha1.UpdateRowRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.area120.tables.v1alpha1.UpdateRowRequest build() {
com.google.area120.tables.v1alpha1.UpdateRowRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.area120.tables.v1alpha1.UpdateRowRequest buildPartial() {
com.google.area120.tables.v1alpha1.UpdateRowRequest result =
new com.google.area120.tables.v1alpha1.UpdateRowRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.area120.tables.v1alpha1.UpdateRowRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.row_ = rowBuilder_ == null ? row_ : rowBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000002;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.view_ = view_;
}
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.area120.tables.v1alpha1.UpdateRowRequest) {
return mergeFrom((com.google.area120.tables.v1alpha1.UpdateRowRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.area120.tables.v1alpha1.UpdateRowRequest other) {
if (other == com.google.area120.tables.v1alpha1.UpdateRowRequest.getDefaultInstance())
return this;
if (other.hasRow()) {
mergeRow(other.getRow());
}
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
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:
{
input.readMessage(getRowFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry);
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 com.google.area120.tables.v1alpha1.Row row_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.area120.tables.v1alpha1.Row,
com.google.area120.tables.v1alpha1.Row.Builder,
com.google.area120.tables.v1alpha1.RowOrBuilder>
rowBuilder_;
/**
*
*
* <pre>
* Required. The row to update.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.Row row = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the row field is set.
*/
public boolean hasRow() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The row to update.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.Row row = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The row.
*/
public com.google.area120.tables.v1alpha1.Row getRow() {
if (rowBuilder_ == null) {
return row_ == null ? com.google.area120.tables.v1alpha1.Row.getDefaultInstance() : row_;
} else {
return rowBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The row to update.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.Row row = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setRow(com.google.area120.tables.v1alpha1.Row value) {
if (rowBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
row_ = value;
} else {
rowBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The row to update.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.Row row = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setRow(com.google.area120.tables.v1alpha1.Row.Builder builderForValue) {
if (rowBuilder_ == null) {
row_ = builderForValue.build();
} else {
rowBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The row to update.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.Row row = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeRow(com.google.area120.tables.v1alpha1.Row value) {
if (rowBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& row_ != null
&& row_ != com.google.area120.tables.v1alpha1.Row.getDefaultInstance()) {
getRowBuilder().mergeFrom(value);
} else {
row_ = value;
}
} else {
rowBuilder_.mergeFrom(value);
}
if (row_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The row to update.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.Row row = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearRow() {
bitField0_ = (bitField0_ & ~0x00000001);
row_ = null;
if (rowBuilder_ != null) {
rowBuilder_.dispose();
rowBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The row to update.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.Row row = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.area120.tables.v1alpha1.Row.Builder getRowBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getRowFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The row to update.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.Row row = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.area120.tables.v1alpha1.RowOrBuilder getRowOrBuilder() {
if (rowBuilder_ != null) {
return rowBuilder_.getMessageOrBuilder();
} else {
return row_ == null ? com.google.area120.tables.v1alpha1.Row.getDefaultInstance() : row_;
}
}
/**
*
*
* <pre>
* Required. The row to update.
* </pre>
*
* <code>.google.area120.tables.v1alpha1.Row row = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.area120.tables.v1alpha1.Row,
com.google.area120.tables.v1alpha1.Row.Builder,
com.google.area120.tables.v1alpha1.RowOrBuilder>
getRowFieldBuilder() {
if (rowBuilder_ == null) {
rowBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.area120.tables.v1alpha1.Row,
com.google.area120.tables.v1alpha1.Row.Builder,
com.google.area120.tables.v1alpha1.RowOrBuilder>(
getRow(), getParentForChildren(), isClean());
row_ = null;
}
return rowBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* The list of fields to update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The list of fields to update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The list of fields to update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The list of fields to update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The list of fields to update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The list of fields to update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The list of fields to update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The list of fields to update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* The list of fields to update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
private int view_ = 0;
/**
*
*
* <pre>
* Optional. Column key to use for values in the row.
* Defaults to user entered name.
* </pre>
*
* <code>
* .google.area120.tables.v1alpha1.View view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The enum numeric value on the wire for view.
*/
@java.lang.Override
public int getViewValue() {
return view_;
}
/**
*
*
* <pre>
* Optional. Column key to use for values in the row.
* Defaults to user entered name.
* </pre>
*
* <code>
* .google.area120.tables.v1alpha1.View view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </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>
* Optional. Column key to use for values in the row.
* Defaults to user entered name.
* </pre>
*
* <code>
* .google.area120.tables.v1alpha1.View view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The view.
*/
@java.lang.Override
public com.google.area120.tables.v1alpha1.View getView() {
com.google.area120.tables.v1alpha1.View result =
com.google.area120.tables.v1alpha1.View.forNumber(view_);
return result == null ? com.google.area120.tables.v1alpha1.View.UNRECOGNIZED : result;
}
/**
*
*
* <pre>
* Optional. Column key to use for values in the row.
* Defaults to user entered name.
* </pre>
*
* <code>
* .google.area120.tables.v1alpha1.View view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param value The view to set.
* @return This builder for chaining.
*/
public Builder setView(com.google.area120.tables.v1alpha1.View value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
view_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Column key to use for values in the row.
* Defaults to user entered name.
* </pre>
*
* <code>
* .google.area120.tables.v1alpha1.View view = 3 [(.google.api.field_behavior) = OPTIONAL];
* </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.area120.tables.v1alpha1.UpdateRowRequest)
}
// @@protoc_insertion_point(class_scope:google.area120.tables.v1alpha1.UpdateRowRequest)
private static final com.google.area120.tables.v1alpha1.UpdateRowRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.area120.tables.v1alpha1.UpdateRowRequest();
}
public static com.google.area120.tables.v1alpha1.UpdateRowRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateRowRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateRowRequest>() {
@java.lang.Override
public UpdateRowRequest 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<UpdateRowRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateRowRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.area120.tables.v1alpha1.UpdateRowRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/directory-studio | 35,875 | plugins/ldifeditor/src/main/java/org/apache/directory/studio/ldifeditor/editor/LdifEditor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldifeditor.editor;
import java.io.File;
import java.util.ResourceBundle;
import org.apache.directory.studio.common.ui.CommonUIUtils;
import org.apache.directory.studio.common.ui.filesystem.PathEditorInput;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyEvent;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyListener;
import org.apache.directory.studio.connection.core.Connection;
import org.apache.directory.studio.connection.core.ConnectionFolder;
import org.apache.directory.studio.connection.core.event.ConnectionEventRegistry;
import org.apache.directory.studio.connection.core.event.ConnectionUpdateListener;
import org.apache.directory.studio.connection.ui.ConnectionUIPlugin;
import org.apache.directory.studio.ldapbrowser.common.BrowserCommonConstants;
import org.apache.directory.studio.ldapbrowser.common.actions.ValueEditorPreferencesAction;
import org.apache.directory.studio.ldapbrowser.common.widgets.search.BrowserConnectionWidget;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.apache.directory.studio.ldifeditor.LdifEditorActivator;
import org.apache.directory.studio.ldifeditor.LdifEditorConstants;
import org.apache.directory.studio.ldifeditor.editor.actions.EditLdifAttributeAction;
import org.apache.directory.studio.ldifeditor.editor.actions.EditLdifRecordAction;
import org.apache.directory.studio.ldifeditor.editor.actions.FormatLdifDocumentAction;
import org.apache.directory.studio.ldifeditor.editor.actions.FormatLdifRecordAction;
import org.apache.directory.studio.ldifeditor.editor.actions.OpenBestValueEditorAction;
import org.apache.directory.studio.ldifeditor.editor.actions.OpenDefaultValueEditorAction;
import org.apache.directory.studio.ldifeditor.editor.actions.OpenValueEditorAction;
import org.apache.directory.studio.ldifeditor.editor.text.LdifPartitionScanner;
import org.apache.directory.studio.ldifparser.model.LdifFile;
import org.apache.directory.studio.utils.ActionUtils;
import org.apache.directory.studio.valueeditors.AbstractDialogValueEditor;
import org.apache.directory.studio.valueeditors.IValueEditor;
import org.apache.directory.studio.valueeditors.ValueEditorManager;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.projection.ProjectionSupport;
import org.eclipse.jface.text.source.projection.ProjectionViewer;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IPathEditorInput;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.contexts.IContextActivation;
import org.eclipse.ui.contexts.IContextService;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.TextEditor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import org.eclipse.ui.texteditor.ContentAssistAction;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
/**
* This class implements the LDIF editor
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class LdifEditor extends TextEditor implements ILdifEditor, ConnectionUpdateListener, IPartListener2
{
private ViewForm control;
private BrowserConnectionWidget browserConnectionWidget;
private ToolBar actionToolBar;
private IToolBarManager actionToolBarManager;
private IBrowserConnection browserConnection;
private ProjectionSupport projectionSupport;
protected LdifOutlinePage outlinePage;
private ValueEditorManager valueEditorManager;
private OpenBestValueEditorAction openBestValueEditorAction;
private OpenValueEditorAction[] openValueEditorActions;
private ValueEditorPreferencesAction valueEditorPreferencesAction;
protected boolean showToolBar = true;
/**
* Creates a new instance of LdifEditor.
*/
public LdifEditor()
{
super();
setSourceViewerConfiguration( new LdifSourceViewerConfiguration( this, true ) );
setDocumentProvider( new LdifDocumentProvider() );
IPreferenceStore editorStore = EditorsUI.getPreferenceStore();
IPreferenceStore browserStore = LdifEditorActivator.getDefault().getPreferenceStore();
IPreferenceStore combinedStore = new ChainedPreferenceStore( new IPreferenceStore[]
{ browserStore, editorStore } );
setPreferenceStore( combinedStore );
setHelpContextId( LdifEditorConstants.PLUGIN_ID + "." + "tools_ldif_editor" ); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#handlePreferenceStoreChanged(org.eclipse.jface.util.PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged( PropertyChangeEvent event )
{
try
{
ISourceViewer sourceViewer = getSourceViewer();
if ( sourceViewer == null )
{
return;
}
int topIndex = getSourceViewer().getTopIndex();
getSourceViewer().getDocument().set( getSourceViewer().getDocument().get() );
getSourceViewer().setTopIndex( topIndex );
}
finally
{
super.handlePreferenceStoreChanged( event );
}
}
/**
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#collectContextMenuPreferencePages()
*/
protected String[] collectContextMenuPreferencePages()
{
String[] ids = super.collectContextMenuPreferencePages();
String[] more = new String[ids.length + 4];
more[0] = LdifEditorConstants.PREFERENCEPAGEID_LDIFEDITOR;
more[1] = LdifEditorConstants.PREFERENCEPAGEID_LDIFEDITOR_CONTENTASSIST;
more[2] = LdifEditorConstants.PREFERENCEPAGEID_LDIFEDITOR_SYNTAXCOLORING;
more[3] = LdifEditorConstants.PREFERENCEPAGEID_LDIFEDITOR_TEMPLATES;
System.arraycopy( ids, 0, more, 4, ids.length );
return more;
}
/**
* Gets the ID of the LDIF Editor
*
* @return
* the ID of the LDIF Editor
*/
public static String getId()
{
return LdifEditorConstants.EDITOR_LDIF_EDITOR;
}
/**
* @see org.eclipse.ui.texteditor.AbstractTextEditor#init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput)
*/
public void init( IEditorSite site, IEditorInput input ) throws PartInitException
{
String className = input.getClass().getName();
File file = null;
if ( input instanceof IPathEditorInput )
{
IPathEditorInput pei = ( IPathEditorInput ) input;
IPath path = pei.getPath();
file = path.toFile();
}
else if ( className.equals( "org.eclipse.ui.internal.editors.text.JavaFileEditorInput" ) //$NON-NLS-1$
|| className.equals( "org.eclipse.ui.ide.FileStoreEditorInput" ) ) //$NON-NLS-1$
// The class 'org.eclipse.ui.internal.editors.text.JavaFileEditorInput'
// is used when opening a file from the menu File > Open... in Eclipse 3.2.x
// The class 'org.eclipse.ui.ide.FileStoreEditorInput' is used when
// opening a file from the menu File > Open... in Eclipse 3.3.x
{
file = new File( input.getToolTipText() );
}
if ( file != null )
{
long fileLength = file.length();
if ( fileLength > ( 1 * 1024 * 1024 ) )
{
MessageDialog.openError( site.getShell(), Messages.getString( "LdifEditor.LDIFFileIsTooBig" ), //$NON-NLS-1$
Messages.getString( "LdifEditor.LDIFFileIsTooBigDescription" ) ); //$NON-NLS-1$
input = new NonExistingLdifEditorInput();
}
}
super.init( site, input );
ConnectionEventRegistry.addConnectionUpdateListener( this, ConnectionUIPlugin.getDefault().getEventRunner() );
getSite().getPage().addPartListener( this );
this.valueEditorManager = new ValueEditorManager( getSite().getShell(), false, false );
}
/**
* @see org.eclipse.ui.editors.text.TextEditor#dispose()
*/
public void dispose()
{
valueEditorManager.dispose();
deactivateGlobalActionHandlers();
ConnectionEventRegistry.removeConnectionUpdateListener( this );
getSite().getPage().removePartListener( this );
super.dispose();
}
/**
* @see org.eclipse.ui.editors.text.TextEditor#getAdapter(java.lang.Class)
*/
public Object getAdapter( Class required )
{
if ( IShowInTargetList.class.equals( required ) )
{
return new IShowInTargetList()
{
public String[] getShowInTargetIds()
{
return new String[]
{ IPageLayout.ID_RES_NAV };
}
};
}
if ( IContentOutlinePage.class.equals( required ) )
{
if ( outlinePage == null || outlinePage.getControl() == null || outlinePage.getControl().isDisposed() )
{
outlinePage = new LdifOutlinePage( this );
}
return outlinePage;
}
if ( ISourceViewer.class.equals( required ) )
{
return getSourceViewer();
}
if ( IAnnotationHover.class.equals( required ) )
{
if ( getSourceViewerConfiguration() != null && getSourceViewer() != null )
return getSourceViewerConfiguration().getAnnotationHover( getSourceViewer() );
}
if ( ITextHover.class.equals( required ) )
{
if ( getSourceViewerConfiguration() != null && getSourceViewer() != null )
return getSourceViewerConfiguration().getTextHover( getSourceViewer(), null );
}
if ( IContentAssistProcessor.class.equals( required ) )
{
if ( getSourceViewerConfiguration() != null && getSourceViewer() != null )
return getSourceViewerConfiguration().getContentAssistant( getSourceViewer() )
.getContentAssistProcessor( LdifPartitionScanner.LDIF_RECORD );
}
if ( projectionSupport != null )
{
Object adapter = projectionSupport.getAdapter( getSourceViewer(), required );
if ( adapter != null )
return adapter;
}
return super.getAdapter( required );
}
/**
* @see org.eclipse.ui.editors.text.TextEditor#editorContextMenuAboutToShow(org.eclipse.jface.action.IMenuManager)
*/
protected void editorContextMenuAboutToShow( IMenuManager menu )
{
super.editorContextMenuAboutToShow( menu );
IContributionItem[] items = menu.getItems();
for ( int i = 0; i < items.length; i++ )
{
if ( items[i] instanceof ActionContributionItem )
{
ActionContributionItem aci = ( ActionContributionItem ) items[i];
if ( aci.getAction() == getAction( ITextEditorActionConstants.SHIFT_LEFT ) )
{
menu.remove( items[i] );
}
if ( aci.getAction() == getAction( ITextEditorActionConstants.SHIFT_RIGHT ) )
{
menu.remove( items[i] );
}
}
}
// add Edit actions
addAction( menu, ITextEditorActionConstants.GROUP_EDIT,
LdifEditorConstants.ACTION_ID_EDIT_ATTRIBUTE_DESCRIPTION );
addAction( menu, ITextEditorActionConstants.GROUP_EDIT, BrowserCommonConstants.ACTION_ID_EDIT_VALUE );
MenuManager valueEditorMenuManager = new MenuManager( Messages.getString( "LdifEditor.EditValueWith" ) ); //$NON-NLS-1$
if ( this.openBestValueEditorAction.isEnabled() )
{
valueEditorMenuManager.add( this.openBestValueEditorAction );
valueEditorMenuManager.add( new Separator() );
}
for ( int i = 0; i < this.openValueEditorActions.length; i++ )
{
this.openValueEditorActions[i].update();
if ( this.openValueEditorActions[i].isEnabled()
&& this.openValueEditorActions[i].getValueEditor().getClass() != this.openBestValueEditorAction
.getValueEditor().getClass()
&& this.openValueEditorActions[i].getValueEditor() instanceof AbstractDialogValueEditor )
{
valueEditorMenuManager.add( this.openValueEditorActions[i] );
}
}
valueEditorMenuManager.add( new Separator() );
valueEditorMenuManager.add( this.valueEditorPreferencesAction );
menu.appendToGroup( ITextEditorActionConstants.GROUP_EDIT, valueEditorMenuManager );
addAction( menu, ITextEditorActionConstants.GROUP_EDIT, LdifEditorConstants.ACTION_ID_EDIT_RECORD );
// add Format actions
MenuManager formatMenuManager = new MenuManager( Messages.getString( "LdifEditor.Format" ) ); //$NON-NLS-1$
addAction( formatMenuManager, LdifEditorConstants.ACTION_ID_FORMAT_LDIF_DOCUMENT );
addAction( formatMenuManager, LdifEditorConstants.ACTION_ID_FORMAT_LDIF_RECORD );
menu.appendToGroup( ITextEditorActionConstants.GROUP_EDIT, formatMenuManager );
}
/**
* @see org.eclipse.ui.editors.text.TextEditor#createActions()
*/
protected void createActions()
{
super.createActions();
// add content assistant
ResourceBundle bundle = LdifEditorActivator.getDefault().getResourceBundle();
IAction action = new ContentAssistAction( bundle, "ldifeditor__contentassistproposal_", this ); //$NON-NLS-1$
action.setActionDefinitionId( ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS );
setAction( "ContentAssistProposal", action ); //$NON-NLS-1$
// add execute action (for tool bar)
if ( actionToolBarManager != null )
{
ExecuteLdifAction executeLdifAction = new ExecuteLdifAction( this );
actionToolBarManager.add( executeLdifAction );
setAction( LdifEditorConstants.ACTION_ID_EXECUTE_LDIF, executeLdifAction );
actionToolBarManager.update( true );
}
// add context menu edit actions
EditLdifAttributeAction editLdifAttributeAction = new EditLdifAttributeAction( this );
setAction( BrowserCommonConstants.ACTION_ID_EDIT_ATTRIBUTE_DESCRIPTION, editLdifAttributeAction );
openBestValueEditorAction = new OpenBestValueEditorAction( this );
IValueEditor[] valueEditors = valueEditorManager.getAllValueEditors();
openValueEditorActions = new OpenValueEditorAction[valueEditors.length];
for ( int i = 0; i < this.openValueEditorActions.length; i++ )
{
openValueEditorActions[i] = new OpenValueEditorAction( this, valueEditors[i] );
}
valueEditorPreferencesAction = new ValueEditorPreferencesAction();
OpenDefaultValueEditorAction openDefaultValueEditorAction = new OpenDefaultValueEditorAction( this,
openBestValueEditorAction );
setAction( BrowserCommonConstants.ACTION_ID_EDIT_VALUE, openDefaultValueEditorAction );
EditLdifRecordAction editRecordAction = new EditLdifRecordAction( this );
setAction( LdifEditorConstants.ACTION_ID_EDIT_RECORD, editRecordAction );
// add context menu format actions
FormatLdifDocumentAction formatDocumentAction = new FormatLdifDocumentAction( this );
setAction( LdifEditorConstants.ACTION_ID_FORMAT_LDIF_DOCUMENT, formatDocumentAction );
FormatLdifRecordAction formatRecordAction = new FormatLdifRecordAction( this );
setAction( LdifEditorConstants.ACTION_ID_FORMAT_LDIF_RECORD, formatRecordAction );
// update cut, copy, paste
IAction cutAction = getAction( ITextEditorActionConstants.CUT );
if ( cutAction != null )
{
cutAction.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
ISharedImages.IMG_TOOL_CUT ) );
}
IAction copyAction = getAction( ITextEditorActionConstants.COPY );
if ( copyAction != null )
{
copyAction.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
ISharedImages.IMG_TOOL_COPY ) );
}
IAction pasteAction = getAction( ITextEditorActionConstants.PASTE );
if ( pasteAction != null )
{
pasteAction.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
ISharedImages.IMG_TOOL_PASTE ) );
}
activateGlobalActionHandlers();
}
/**
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl( Composite parent )
{
setHelpContextId( LdifEditorConstants.PLUGIN_ID + "." + "tools_ldif_editor" ); //$NON-NLS-1$ //$NON-NLS-2$
if ( showToolBar )
{
// create the toolbar (including connection widget and execute button) on top of the editor
Composite composite = new Composite( parent, SWT.NONE );
GridLayout layout = new GridLayout();
layout.marginWidth = 0;
layout.marginHeight = 0;
layout.verticalSpacing = 0;
composite.setLayout( layout );
control = new ViewForm( composite, SWT.NONE );
control.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Composite browserConnectionWidgetControl = BaseWidgetUtils.createColumnContainer( control, 2, 1 );
browserConnectionWidget = new BrowserConnectionWidget();
browserConnectionWidget.createWidget( browserConnectionWidgetControl );
connectionUpdated( null );
browserConnectionWidget.addWidgetModifyListener( new WidgetModifyListener()
{
public void widgetModified( WidgetModifyEvent event )
{
IBrowserConnection browserConnection = browserConnectionWidget.getBrowserConnection();
setConnection( browserConnection );
}
} );
control.setTopLeft( browserConnectionWidgetControl );
// tool bar
actionToolBar = new ToolBar( control, SWT.FLAT | SWT.RIGHT );
actionToolBar.setLayoutData( new GridData( SWT.END, SWT.NONE, true, false ) );
actionToolBarManager = new ToolBarManager( actionToolBar );
control.setTopCenter( actionToolBar );
// local menu
control.setTopRight( null );
// content
Composite editorComposite = new Composite( control, SWT.NONE );
editorComposite.setLayout( new FillLayout() );
GridData data = new GridData( GridData.FILL_BOTH );
data.widthHint = 450;
data.heightHint = 250;
editorComposite.setLayoutData( data );
super.createPartControl( editorComposite );
control.setContent( editorComposite );
}
else
{
super.createPartControl( parent );
}
ProjectionViewer projectionViewer = ( ProjectionViewer ) getSourceViewer();
projectionSupport = new ProjectionSupport( projectionViewer, getAnnotationAccess(), getSharedColors() );
projectionSupport.install();
projectionViewer.doOperation( ProjectionViewer.TOGGLE );
}
/**
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createSourceViewer(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.source.IVerticalRuler, int)
*/
protected ISourceViewer createSourceViewer( Composite parent, IVerticalRuler ruler, int styles )
{
getAnnotationAccess();
getOverviewRuler();
ISourceViewer viewer = new ProjectionViewer( parent, ruler, getOverviewRuler(), true, styles );
getSourceViewerDecorationSupport( viewer );
return viewer;
}
/**
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#configureSourceViewerDecorationSupport(org.eclipse.ui.texteditor.SourceViewerDecorationSupport)
*/
protected void configureSourceViewerDecorationSupport( SourceViewerDecorationSupport support )
{
super.configureSourceViewerDecorationSupport( support );
}
/**
* @see org.apache.directory.studio.ldifeditor.editor.ILdifEditor#getLdifModel()
*/
public LdifFile getLdifModel()
{
IDocumentProvider provider = getDocumentProvider();
if ( provider instanceof LdifDocumentProvider )
{
return ( ( LdifDocumentProvider ) provider ).getLdifModel();
}
else
{
return null;
}
}
/**
* This method is used to notify the LDIF Editor that the Outline Page has been closed.
*/
public void outlinePageClosed()
{
projectionSupport.dispose();
outlinePage = null;
}
/**
* @see org.apache.directory.studio.ldifeditor.editor.ILdifEditor#getConnection()
*/
public IBrowserConnection getConnection()
{
return browserConnection;
}
/**
* Sets the Connection
*
* @param browserConnection
* the browser connection to set
*/
protected void setConnection( IBrowserConnection browserConnection )
{
setConnection( browserConnection, false );
}
/**
* Sets the Connection
*
* @param browserConnection the browser connection to set
* @param updateBrowserConnectionWidget the flag indicating if the browser connection widget
* should be updated
*/
protected void setConnection( IBrowserConnection browserConnection, boolean updateBrowserConnectionWidget )
{
this.browserConnection = browserConnection;
if ( updateBrowserConnectionWidget && ( browserConnectionWidget != null ) )
{
browserConnectionWidget.setBrowserConnection( browserConnection );
}
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionUpdated(org.apache.directory.studio.connection.core.Connection)
*/
public final void connectionUpdated( Connection connection )
{
if ( browserConnectionWidget != null )
{
IBrowserConnection browserConnection = browserConnectionWidget.getBrowserConnection();
if ( browserConnection != null && browserConnection.getConnection().equals( connection ) )
{
setConnection( browserConnection );
browserConnectionWidget.setBrowserConnection( browserConnection );
}
}
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionAdded(org.apache.directory.studio.connection.core.Connection)
*/
public void connectionAdded( Connection connection )
{
connectionUpdated( connection );
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionRemoved(org.apache.directory.studio.connection.core.Connection)
*/
public void connectionRemoved( Connection connection )
{
connectionUpdated( connection );
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionOpened(org.apache.directory.studio.connection.core.Connection)
*/
public void connectionOpened( Connection connection )
{
connectionUpdated( connection );
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionClosed(org.apache.directory.studio.connection.core.Connection)
*/
public void connectionClosed( Connection connection )
{
connectionUpdated( connection );
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionFolderModified(org.apache.directory.studio.connection.core.ConnectionFolder)
*/
public void connectionFolderModified( ConnectionFolder connectionFolder )
{
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionFolderAdded(org.apache.directory.studio.connection.core.ConnectionFolder)
*/
public void connectionFolderAdded( ConnectionFolder connectionFolder )
{
}
/**
* @see org.apache.directory.studio.connection.core.event.ConnectionUpdateListener#connectionFolderRemoved(org.apache.directory.studio.connection.core.ConnectionFolder)
*/
public void connectionFolderRemoved( ConnectionFolder connectionFolder )
{
}
/**
* This implementation checks if the input is of type
* NonExistingLdifEditorInput. In that case doSaveAs() is
* called to prompt for a new file name and location.
*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSave(org.eclipse.core.runtime.IProgressMonitor)
*/
public void doSave( IProgressMonitor progressMonitor )
{
final IEditorInput input = getEditorInput();
if ( input instanceof NonExistingLdifEditorInput )
{
super.doSaveAs();
return;
}
super.doSave( progressMonitor );
}
/**
* The input could be one of the following types:
* - NonExistingLdifEditorInput: New file, not yet saved
* - PathEditorInput: file opened with our internal "Open File.." action
* - FileEditorInput: file is within workspace
* - JavaFileEditorInput: file opend with "Open File..." action from org.eclipse.ui.editor
*
* In RCP the FileDialog appears.
* In IDE the super implementation is called.
* To detect if this plugin runs in IDE the org.eclipse.ui.ide extension point is checked.
*
* @see org.eclipse.ui.editors.text.TextEditor#performSaveAs(org.eclipse.core.runtime.IProgressMonitor)
*/
protected void performSaveAs( IProgressMonitor progressMonitor )
{
// detect IDE or RCP:
// check if perspective org.eclipse.ui.resourcePerspective is available
boolean isIDE = CommonUIUtils.isIDEEnvironment();
if ( isIDE )
{
// Just call super implementation for now
IPreferenceStore store = EditorsUI.getPreferenceStore();
String key = getEditorSite().getId() + ".internal.delegateSaveAs"; // $NON-NLS-1$ //$NON-NLS-1$
store.setValue( key, true );
super.performSaveAs( progressMonitor );
}
else
{
// Open FileDialog
Shell shell = getSite().getShell();
final IEditorInput input = getEditorInput();
IDocumentProvider provider = getDocumentProvider();
final IEditorInput newInput;
FileDialog dialog = new FileDialog( shell, SWT.SAVE );
String path = dialog.open();
if ( path == null )
{
if ( progressMonitor != null )
{
progressMonitor.setCanceled( true );
}
return;
}
// Check whether file exists and if so, confirm overwrite
final File externalFile = new File( path );
if ( externalFile.exists() )
{
MessageDialog overwriteDialog = new MessageDialog(
shell,
Messages.getString( "LdifEditor.Overwrite" ), null, Messages.getString( "LdifEditor.OverwriteQuestion" ), //$NON-NLS-1$ //$NON-NLS-2$
MessageDialog.WARNING, new String[]
{ IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 1 ); // 'No' is the default
if ( overwriteDialog.open() != Window.OK )
{
if ( progressMonitor != null )
{
progressMonitor.setCanceled( true );
return;
}
}
}
IPath iPath = new Path( path );
newInput = new PathEditorInput( iPath );
boolean success = false;
try
{
provider.aboutToChange( newInput );
provider.saveDocument( progressMonitor, newInput, provider.getDocument( input ), true );
success = true;
}
catch ( CoreException x )
{
final IStatus status = x.getStatus();
if ( status == null || status.getSeverity() != IStatus.CANCEL )
{
String title = Messages.getString( "LdifEditor.ErrorInSaveAs" ); //$NON-NLS-1$
String msg = Messages.getString( "LdifEditor.ErrorInSaveAs" ) + x.getMessage(); //$NON-NLS-1$
MessageDialog.openError( shell, title, msg );
}
}
finally
{
provider.changed( newInput );
if ( success )
{
setInput( newInput );
}
}
if ( progressMonitor != null )
{
progressMonitor.setCanceled( !success );
}
}
}
private IContextActivation contextActivation;
/**
* @see org.eclipse.ui.IPartListener2#partDeactivated(org.eclipse.ui.IWorkbenchPartReference)
*/
public void partDeactivated( IWorkbenchPartReference partRef )
{
if ( partRef.getPart( false ) == this && contextActivation != null )
{
deactivateGlobalActionHandlers();
IContextService contextService = ( IContextService ) PlatformUI.getWorkbench().getAdapter(
IContextService.class );
contextService.deactivateContext( contextActivation );
contextActivation = null;
}
}
/**
* @see org.eclipse.ui.IPartListener2#partActivated(org.eclipse.ui.IWorkbenchPartReference)
*/
public void partActivated( IWorkbenchPartReference partRef )
{
if ( partRef.getPart( false ) == this )
{
IContextService contextService = ( IContextService ) PlatformUI.getWorkbench().getAdapter(
IContextService.class );
contextActivation = contextService.activateContext( BrowserCommonConstants.CONTEXT_WINDOWS );
activateGlobalActionHandlers();
}
}
/**
* @see org.eclipse.ui.IPartListener2#partBroughtToTop(org.eclipse.ui.IWorkbenchPartReference)
*/
public void partBroughtToTop( IWorkbenchPartReference partRef )
{
}
/**
* @see org.eclipse.ui.IPartListener2#partClosed(org.eclipse.ui.IWorkbenchPartReference)
*/
public void partClosed( IWorkbenchPartReference partRef )
{
}
/**
* @see org.eclipse.ui.IPartListener2#partHidden(org.eclipse.ui.IWorkbenchPartReference)
*/
public void partHidden( IWorkbenchPartReference partRef )
{
}
/**
* @see org.eclipse.ui.IPartListener2#partInputChanged(org.eclipse.ui.IWorkbenchPartReference)
*/
public void partInputChanged( IWorkbenchPartReference partRef )
{
}
/**
* @see org.eclipse.ui.IPartListener2#partOpened(org.eclipse.ui.IWorkbenchPartReference)
*/
public void partOpened( IWorkbenchPartReference partRef )
{
}
/**
* @see org.eclipse.ui.IPartListener2#partVisible(org.eclipse.ui.IWorkbenchPartReference)
*/
public void partVisible( IWorkbenchPartReference partRef )
{
}
/**
* Activates global action handlers
*/
public void activateGlobalActionHandlers()
{
IAction elaa = getAction( BrowserCommonConstants.ACTION_ID_EDIT_ATTRIBUTE_DESCRIPTION );
ActionUtils.activateActionHandler( elaa );
IAction elva = getAction( BrowserCommonConstants.ACTION_ID_EDIT_VALUE );
ActionUtils.activateActionHandler( elva );
IAction elra = getAction( LdifEditorConstants.ACTION_ID_EDIT_RECORD );
ActionUtils.activateActionHandler( elra );
}
/**
* Deactivates global action handlers
*/
public void deactivateGlobalActionHandlers()
{
IAction elaa = getAction( BrowserCommonConstants.ACTION_ID_EDIT_ATTRIBUTE_DESCRIPTION );
ActionUtils.deactivateActionHandler( elaa );
IAction elva = getAction( BrowserCommonConstants.ACTION_ID_EDIT_VALUE );
ActionUtils.deactivateActionHandler( elva );
IAction elra = getAction( LdifEditorConstants.ACTION_ID_EDIT_RECORD );
ActionUtils.deactivateActionHandler( elra );
}
/**
* Gets the Value Editor Manager
*
* @return
* the Value Editor Manager
*/
public ValueEditorManager getValueEditorManager()
{
return valueEditorManager;
}
}
|
apache/jena | 35,080 | jena-arq/src/test/java/org/apache/jena/sparql/expr/TestFunctions2.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.sparql.expr;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.apache.jena.graph.Node;
import org.apache.jena.shared.PrefixMapping;
import org.apache.jena.sparql.ARQConstants;
import org.apache.jena.sparql.function.FunctionEnvBase;
import org.apache.jena.sparql.util.ExprUtils;
import org.apache.jena.sparql.util.NodeFactoryExtra;
import org.apache.jena.sys.JenaSystem;
public class TestFunctions2
{
static { JenaSystem.init(); }
// Some overlap with TestFunctions except those are direct function calls and these are via SPARQL 1.1 syntax.
// Better too many tests than too few.
static boolean warnOnBadLexicalForms = true;
@BeforeAll public static void beforeClass()
{
warnOnBadLexicalForms = NodeValue.VerboseWarnings;
NodeValue.VerboseWarnings = false;
}
@AfterAll public static void afterClass()
{
NodeValue.VerboseWarnings = warnOnBadLexicalForms;
}
// tests for strings. strlen, substr, strucase, strlcase, contains, concat
// Some overlap with NodeFunctions.
// Tests for IRI(..) are in TestUpdateOperations.insert_with_iri_function_resolution*
// so we can observe the parser effect.
/*
| 'CONCAT' ExpressionList
| SubstringExpression
| 'STRLEN' '(' Expression ')'
| 'UCASE' '(' Expression ')'
| 'LCASE' '(' Expression ')'
| 'ENCODE_FOR_URI' '(' Expression ')'
| 'CONTAINS' '(' Expression ',' Expression ')'
| 'STARTS' '(' Expression ',' Expression ')'
| 'ENDS' '(' Expression ',' Expression ')'
| 'YEAR' '(' Expression ')'
| 'MONTH' '(' Expression ')'
| 'DAY' '(' Expression ')'
| 'HOURS' '(' Expression ')'
| 'MINUTES' '(' Expression ')'
| 'SECONDS' '(' Expression ')'
| 'TIMEZONE' '(' Expression ')'
| 'NOW' NIL
| 'MD5' '(' Expression ')'
| 'SHA1' '(' Expression ')'
| SHA224 '(' Expression ')'
| 'SHA256' '(' Expression ')'
| 'SHA384' '(' Expression ')'
| 'SHA512' '(' Expression ')'
| 'COALESCE' ExpressionList
| 'IF' '(' Expression ',' Expression ',' Expression ')'
| 'STRLANG' '(' Expression ',' Expression ')'
| 'STRDT' '(' Expression ',' Expression ')'
*/
// Note in these tests, the result is written exactly as expected
// Any same value would do - we test for the exact lexical form
// of the implementation.
@Test public void round_01() { test("round(123)", "123"); }
@Test public void round_02() { test("round(123.5)", "'124.0'^^xsd:decimal"); }
@Test public void round_03() { test("round(-0.5e0)", "0.0e0"); }
@Test public void round_04() { test("round(-1.5)", "'-1.0'^^xsd:decimal"); }
@Test public void round_05() { test("round(-0)", "-0"); }
@Test public void abs_01() { test("abs(1)", "1"); }
@Test public void abs_02() { test("abs(1.0)", "1.0"); }
@Test public void abs_03() { test("abs(1.0e0)", "1.0e0"); }
@Test public void abs_04() { test("abs(-1)", "1"); }
@Test public void abs_05() { test("abs(+0)", "0"); }
@Test public void abs_06() { test("abs(-0)", "0"); }
// CEIL
@Test public void ceil_01() { test("ceil(1)", "1"); }
@Test public void ceil_02() { test("ceil(1.0)", "'1.0'^^xsd:decimal"); }
@Test public void ceil_03() { test("ceil(1e0)", "1.0e0"); }
@Test public void ceil_04() { test("ceil(1.5e0)", "2.0e0"); }
@Test public void ceil_05() { test("ceil(-0.9)", "'0.0'^^xsd:decimal"); }
@Test public void ceil_06() { test("ceil(-9)", "-9"); }
@Test public void ceil_07() { test("ceil(-9.5)", "'-9.0'^^xsd:decimal"); }
@Test public void ceil_08() { test("ceil(0)", "0"); }
// FLOOR
@Test public void floor_01() { test("floor(1)", "1"); }
@Test public void floor_02() { test("floor(1.0)", "'1.0'^^xsd:decimal"); }
@Test public void floor_03() { test("floor(1e0)", "1.0e0"); }
@Test public void floor_04() { test("floor(1.5e0)", "1.0e0"); }
@Test public void floor_05() { test("floor(-0.9)", "'-1.0'^^xsd:decimal"); }
@Test public void floor_06() { test("floor(-9)", "-9"); }
@Test public void floor_07() { test("floor(-9.5)", "'-10.0'^^xsd:decimal"); }
@Test public void floor_08() { test("floor(0)", "0"); }
// simple, PLWL, xsd:string.
// CONCAT
@Test public void concat_01() { test("concat('a')", "'a'"); }
@Test public void concat_02() { test("concat('a', 'b')", "'ab'"); }
@Test public void concat_03() { test("concat('a'@en, 'b')", "'ab'"); }
@Test public void concat_04() { test("concat('a'@en, 'b'@en)", "'ab'@en"); }
//@Test public void concat_05() { test("concat('a'^^xsd:string, 'b')", "'ab'^^xsd:string"); }
@Test public void concat_05() { test("concat('a'^^xsd:string, 'b')", "'ab'"); }
@Test public void concat_06() { test("concat('a'^^xsd:string, 'b'^^xsd:string)", "'ab'^^xsd:string"); }
@Test public void concat_07() { test("concat('a'^^xsd:string, 'b'^^xsd:string)", "'ab'^^xsd:string"); }
//@Test public void concat_08() { test("concat('a', 'b'^^xsd:string)", "'ab'^^xsd:string"); }
@Test public void concat_08() { test("concat('a', 'b'^^xsd:string)", "'ab'"); }
@Test public void concat_09() { test("concat('a'@en, 'b'^^xsd:string)", "'ab'"); }
@Test public void concat_10() { test("concat('a'^^xsd:string, 'b'@en)", "'ab'"); }
@Test public void concat_11() { test("concat()", "''"); }
@Test
public void concat_90() { assertThrows(ExprEvalException.class, ()-> test("concat(1)", "1") ); }
@Test
public void concat_91() { test("concat('a'@en, 'b'@fr)", "'ab'"); }
// SUBSTR
@Test public void substr_01() { test("substr('abc',1)", "'abc'"); }
@Test public void substr_02() { test("substr('abc',2)", "'bc'"); }
@Test public void substr_03() { test("substr('abc',2,1)", "'b'"); }
@Test public void substr_04() { test("substr('abc',2,0)", "''"); }
@Test public void substr_05() { test("substr('12345',0,3)", "'12'"); }
@Test public void substr_06() { test("substr('12345',-1,3)", "'1'"); }
// These are the examples in F&O
@Test public void substr_10() { test("substr('motor car', 6)", "' car'"); }
@Test public void substr_11() { test("substr('metadata', 4, 3)", "'ada'"); }
@Test public void substr_12() { test("substr('12345', 1.5, 2.6)", "'234'"); }
@Test public void substr_13() { test("substr('12345', 0, 3)", "'12'"); }
@Test public void substr_14() { test("substr('12345', 5, -3)", "''"); }
@Test public void substr_15() { test("substr('12345', -3, 5)", "'1'"); }
@Test public void substr_16() { test("substr('12345', 0/0E0, 3)", "''"); }
@Test public void substr_17() { test("substr('12345', 1, 0/0E0)", "''"); }
@Test public void substr_18() { test("substr('', 1, 3)", "''"); }
@Test
public void substr_20() { assertThrows(ExprEvalException.class, ()-> test("substr(1, 1, 3)", "''") ); }
@Test
public void substr_21() { assertThrows(ExprEvalException.class, ()-> test("substr('', 'one', 3)", "''") ); }
@Test
public void substr_22() { assertThrows(ExprEvalException.class, ()-> test("substr('', 1, 'three')", "''") ); }
// Codepoint outside UTF-16.
// These are U+0001F46A 👪 - FAMILY
// As surrogate pair: 0xD83D 0xDC6A
// Written here in forms which protect against binary file corruption.
//@Test public void substr_30() { test("substr('👪', 1)", "'👪'"); }
// Written using \-u escapes in SPARQL.
@Test public void substr_30() { test("substr('\\uD83D\\uDC6A', 1)", "'\\uD83D\\uDC6A'"); }
// Same using Java string escapes.
@Test public void substr_30b() { test("substr('\uD83D\uDC6A', 1)", "'\uD83D\uDC6A'"); }
@Test public void substr_31() { test("substr('\\uD83D\\uDC6A', 2)", "''"); }
@Test public void substr_32() { test("substr('ABC\\uD83D\\uDC6ADEF', 4, 1)", "'\\uD83D\\uDC6A'"); }
@Test public void substr_33() { test("substr('\\uD83D\\uDC6A!', -1, 3)", "'\\uD83D\\uDC6A'"); }
@Test public void substr_34() { test("substr('\\uD83D\\uDC6A!', -1, 4)", "'\\uD83D\\uDC6A!'"); }
// STRLEN
@Test public void strlen_01() { test("strlen('abc')", "3"); }
@Test public void strlen_02() { test("strlen('')", "0"); }
// UCASE
@Test public void ucase_01() { test("ucase('abc')", "'ABC'"); }
@Test public void ucase_02() { test("ucase('ABC')", "'ABC'"); }
@Test public void ucase_03() { test("ucase('Ab 123 Cd')", "'AB 123 CD'"); }
@Test public void ucase_04() { test("ucase('')", "''"); }
// LCASE
@Test public void lcase_01() { test("lcase('abc')", "'abc'"); }
@Test public void lcase_02() { test("lcase('ABC')", "'abc'"); }
@Test public void lcase_03() { test("lcase('Ab 123 Cd')", "'ab 123 cd'"); }
@Test public void lcase_04() { test("lcase('')", "''"); }
// ENCODE_FOR_URI
@Test public void encodeURI_01() { test("encode_for_uri('a:b cd/~')", "'a%3Ab%20cd%2F~'"); }
@Test public void encodeURI_02() { test("encode_for_uri('\\n')", "'%0A'"); }
@Test public void encodeURI_03() { test("encode_for_uri('\\t')", "'%09'"); }
@Test public void encodeURI_04() { test("encode_for_uri('abc')", "'abc'"); }
@Test public void encodeURI_05() { test("encode_for_uri('abc'@en)", "'abc'"); }
@Test
public void encodeURI_09() { assertThrows(ExprEvalException.class, ()-> test("encode_for_uri(1234)", "'1234'") ); }
/* Compatibility rules
# pairs of simple literals,
# pairs of xsd:string typed literals
# pairs of plain literals with identical language tags
# pairs of an xsd:string typed literal (arg1 or arg2) and a simple literal (arg2 or arg1)
# pairs of a plain literal with language tag (arg1) and a simple literal (arg2)
# pairs of a plain literal with language tag (arg1) and an xsd:string typed literal (arg2)
*/
// CONTAINS
@Test public void contains_01() { test("contains('abc', 'a')", "true"); }
@Test public void contains_02() { test("contains('abc', 'b')", "true"); }
@Test public void contains_03() { test("contains('ABC', 'a')", "false"); }
@Test public void contains_04() { test("contains('abc', '')", "true"); }
@Test public void contains_05() { test("contains('', '')", "true"); }
@Test public void contains_06() { test("contains('', 'a')", "false"); }
@Test public void contains_07() { test("contains('12345', '34')", "true"); }
@Test public void contains_08() { test("contains('12345', '123456')", "false"); }
@Test public void contains_10() { test("contains('abc', 'a'^^xsd:string)", "true"); }
@Test
public void contains_11() { assertThrows(ExprEvalException.class, ()-> test("contains('abc', 'a'@en)", "true") ); }
@Test public void contains_12() { test("contains('abc'@en, 'a')", "true"); }
@Test public void contains_13() { test("contains('abc'@en, 'a'^^xsd:string)", "true"); }
@Test public void contains_14() { test("contains('abc'@en, 'a'@en)", "true"); }
@Test
public void contains_15() { assertThrows(ExprEvalException.class, ()-> test("contains('abc'@en, 'a'@fr)", "true") ); }
@Test public void contains_16() { test("contains('abc'^^xsd:string, 'a')", "true"); }
@Test
public void contains_17() { assertThrows(ExprEvalException.class, ()-> test("contains('abc'^^xsd:string, 'a'@en)", "true") ); }
@Test public void contains_18() { test("contains('abc'^^xsd:string, 'a'^^xsd:string)", "true"); }
@Test
public void contains_20() { assertThrows(ExprEvalException.class, ()-> test("contains(1816, 'a'^^xsd:string)", "true") ); }
@Test
public void contains_21() { assertThrows(ExprEvalException.class, ()-> test("contains('abc', 1066)", "true") ); }
@Test public void strstarts_01() { test("strstarts('abc', 'a')", "true"); }
@Test public void strstarts_02() { test("strstarts('abc', 'b')", "false"); }
@Test public void strstarts_03() { test("strstarts('ABC', 'a')", "false"); }
@Test public void strstarts_04() { test("strstarts('abc', '')", "true"); }
@Test public void strstarts_05() { test("strstarts('', '')", "true"); }
@Test public void strstarts_06() { test("strstarts('', 'a')", "false"); }
@Test public void strstarts_10() { test("strstarts('abc', 'a'^^xsd:string)", "true"); }
@Test
public void strstarts_11() { assertThrows(ExprEvalException.class, ()-> test("strstarts('abc', 'a'@en)", "true") ); }
@Test public void strstarts_12() { test("strstarts('abc'@en, 'a')", "true"); }
@Test public void strstarts_13() { test("strstarts('abc'@en, 'a'^^xsd:string)", "true"); }
@Test public void strstarts_14() { test("strstarts('abc'@en, 'a'@en)", "true"); }
@Test
public void strstarts_15() { assertThrows(ExprEvalException.class, ()-> test("strstarts('abc'@en, 'a'@fr)", "true") ); }
@Test public void strstarts_16() { test("strstarts('abc'^^xsd:string, 'a')", "true"); }
@Test
public void strstarts_17() { assertThrows(ExprEvalException.class, ()-> test("strstarts('abc'^^xsd:string, 'a'@en)", "true") ); }
@Test public void strstarts_18() { test("strstarts('abc'^^xsd:string, 'a'^^xsd:string)", "true"); }
@Test
public void strstarts_20() { assertThrows(ExprEvalException.class, ()-> test("strstarts(1816, 'a'^^xsd:string)", "true") ); }
@Test
public void strstarts_21() { assertThrows(ExprEvalException.class, ()-> test("strstarts('abc', 1066)", "true") ); }
// STRENDS
@Test public void strends_01() { test("strends('abc', 'c')", "true"); }
@Test public void strends_02() { test("strends('abc', 'b')", "false"); }
@Test public void strends_03() { test("strends('ABC', 'c')", "false"); }
@Test public void strends_04() { test("strends('abc', '')", "true"); }
@Test public void strends_05() { test("strends('', '')", "true"); }
@Test public void strends_06() { test("strends('', 'a')", "false"); }
@Test public void strends_10() { test("strends('abc', 'c'^^xsd:string)", "true"); }
@Test
public void strends11() { assertThrows(ExprEvalException.class, ()-> test("strends('abc', 'c'@en)", "true") ); }
@Test public void strends_12() { test("strends('abc'@en, 'c')", "true"); }
@Test public void strends_13() { test("strends('abc'@en, 'c'^^xsd:string)", "true"); }
@Test public void strends_14() { test("strends('abc'@en, 'c'@en)", "true"); }
@Test
public void strends_15() { assertThrows(ExprEvalException.class, ()-> test("strends('abc'@en, 'c'@fr)", "true") ); }
@Test public void strends_16() { test("strends('abc'^^xsd:string, 'bc')", "true"); }
@Test
public void strends_17() { assertThrows(ExprEvalException.class, ()-> test("strends('abc'^^xsd:string, 'a'@en)", "true") ); }
@Test public void strends_18() { test("strends('abc'^^xsd:string, 'abc'^^xsd:string)", "true"); }
@Test
public void strends_20() { assertThrows(ExprEvalException.class, ()-> test("strends(1816, '6'^^xsd:string)", "true") ); }
@Test
public void strends_21() { assertThrows(ExprEvalException.class, ()-> test("strends('abc', 1066)", "true") ); }
// YEAR
@Test public void year_01() { test("year('2010-12-24T16:24:01.123'^^xsd:dateTime)", "2010"); }
@Test public void year_02() { test("year('2010-12-24'^^xsd:date)", "2010"); }
@Test public void year_03() { test("year('2010'^^xsd:gYear)", "2010"); }
@Test public void year_04() { test("year('2010-12'^^xsd:gYearMonth)", "2010"); }
@Test
public void year_05() { assertThrows(ExprEvalException.class, ()-> test("year('--12'^^xsd:gMonth)", "2010") ); }
@Test
public void year_06() { assertThrows(ExprEvalException.class, ()-> test("year('--12-24'^^xsd:gMonthDay)", "2010") ); }
@Test
public void year_07() { assertThrows(ExprEvalException.class, ()-> test("year('---24'^^xsd:gDay)", "2010") ); }
@Test public void year_11() { test("year('2010-12-24T16:24:01.123Z'^^xsd:dateTime)", "2010"); }
@Test public void year_12() { test("year('2010-12-24Z'^^xsd:date)", "2010"); }
@Test public void year_13() { test("year('2010Z'^^xsd:gYear)", "2010"); }
@Test public void year_14() { test("year('2010-12Z'^^xsd:gYearMonth)", "2010"); }
@Test
public void year_15() { assertThrows(ExprEvalException.class, ()-> test("year('--12Z'^^xsd:gMonth)", "2010") ); }
@Test
public void year_16() { assertThrows(ExprEvalException.class, ()-> test("year('--12-24Z'^^xsd:gMonthDay)", "2010") ); }
@Test
public void year_17() { assertThrows(ExprEvalException.class, ()-> test("year('---24Z'^^xsd:gDay)", "2010") ); }
@Test public void year_21() { test("year('2010-12-24T16:24:01.123-08:00'^^xsd:dateTime)", "2010"); }
@Test public void year_22() { test("year('2010-12-24-08:00'^^xsd:date)", "2010"); }
@Test public void year_23() { test("year('2010-08:00'^^xsd:gYear)", "2010"); }
@Test public void year_24() { test("year('2010-12-08:00'^^xsd:gYearMonth)", "2010"); }
@Test
public void year_25() { assertThrows(ExprEvalException.class, ()-> test("year('--12-08:00'^^xsd:gMonth)", "2010") ); }
@Test
public void year_26() { assertThrows(ExprEvalException.class, ()-> test("year('--12-24-08:00'^^xsd:gMonthDay)", "2010") ); }
@Test
public void year_27() { assertThrows(ExprEvalException.class, ()-> test("year('---24-08:00'^^xsd:gDay)", "2010") ); }
@Test public void year_dur_01() { test("year('P1Y2M3DT4H5M6S'^^xsd:duration)", "1"); }
// MONTH
@Test public void month_01() { test("month('2010-12-24T16:24:01.123'^^xsd:dateTime)", "12"); }
@Test public void month_02() { test("month('2010-12-24'^^xsd:date)", "12"); }
@Test
public void month_03() { assertThrows(ExprEvalException.class, ()-> test("month('2010'^^xsd:gYear)", "12") ); }
@Test public void month_04() { test("month('2010-12'^^xsd:gYearMonth)", "12"); }
@Test public void month_05() { test("month('--12'^^xsd:gMonth)", "12"); }
@Test public void month_06() { test("month('--12-24'^^xsd:gMonthDay)", "12"); }
@Test
public void month_07() { assertThrows(ExprEvalException.class, ()-> test("month('---24'^^xsd:gDay)", "12") ); }
@Test public void month_11() { test("month('2010-12-24T16:24:01.123Z'^^xsd:dateTime)", "12"); }
@Test public void month_12() { test("month('2010-12-24Z'^^xsd:date)", "12"); }
@Test
public void month_13() { assertThrows(ExprEvalException.class, ()-> test("month('2010Z'^^xsd:gYear)", "12") ); }
@Test public void month_14() { test("month('2010-12Z'^^xsd:gYearMonth)", "12"); }
@Test public void month_15() { test("month('--12Z'^^xsd:gMonth)", "12"); }
@Test public void month_16() { test("month('--12-24Z'^^xsd:gMonthDay)", "12"); }
@Test
public void month_17() { assertThrows(ExprEvalException.class, ()-> test("month('---24Z'^^xsd:gDay)", "12") ); }
@Test public void month_21() { test("month('2010-12-24T16:24:01.123-08:00'^^xsd:dateTime)", "12"); }
@Test public void month_22() { test("month('2010-12-24-08:00'^^xsd:date)", "12"); }
@Test
public void month_23() { assertThrows(ExprEvalException.class, ()-> test("month('2010-08:00'^^xsd:gYear)", "12") ); }
@Test public void month_24() { test("month('2010-12-08:00'^^xsd:gYearMonth)", "12"); }
@Test public void month_25() { test("month('--12-08:00'^^xsd:gMonth)", "12"); }
public void month_26() { test("month('--12-24-08:00'^^xsd:gMonthDay)", "12"); }
@Test
public void month_27() { assertThrows(ExprEvalException.class, ()-> test("month('---24-08:00'^^xsd:gDay)", "12") ); }
@Test public void month_dur_01() { test("month('P1Y2M3DT4H5M6S'^^xsd:duration)", "2"); }
// DAY
@Test public void day_01() { test("day('2010-12-24T16:24:01.123'^^xsd:dateTime)", "24"); }
@Test public void day_02() { test("day('2010-12-24'^^xsd:date)", "24"); }
@Test
public void day_03() { assertThrows(ExprEvalException.class, ()-> test("day('2010'^^xsd:gYear)", "24") ); }
@Test
public void day_04() { assertThrows(ExprEvalException.class, ()-> test("day('2010-12'^^xsd:gYearMonth)", "24") ); }
@Test
public void day_05() { assertThrows(ExprEvalException.class, ()-> test("day('--12'^^xsd:gMonth)", "24") ); }
@Test public void day_06() { test("day('--12-24'^^xsd:gMonthDay)", "24"); }
@Test public void day_07() { test("day('---24'^^xsd:gDay)", "24"); }
@Test public void day_11() { test("day('2010-12-24T16:24:01.123Z'^^xsd:dateTime)", "24"); }
@Test public void day_12() { test("day('2010-12-24Z'^^xsd:date)", "24"); }
@Test
public void day_13() { assertThrows(ExprEvalException.class, ()-> test("day('2010Z'^^xsd:gYear)", "24") ); }
@Test
public void day_14() { assertThrows(ExprEvalException.class, ()-> test("day('2010-12Z'^^xsd:gYearMonth)", "24") ); }
@Test
public void day_15() { assertThrows(ExprEvalException.class, ()-> test("day('--12Z'^^xsd:gMonth)", "24") ); }
@Test public void day_16() { test("day('--12-24Z'^^xsd:gMonthDay)", "24"); }
@Test public void day_17() { test("day('---24Z'^^xsd:gDay)", "24"); }
@Test public void day_21() { test("day('2010-12-24T16:24:01.123-08:00'^^xsd:dateTime)", "24"); }
@Test public void day_22() { test("day('2010-12-24-08:00'^^xsd:date)", "24"); }
@Test
public void day_23() { assertThrows(ExprEvalException.class, ()-> test("day('2010-08:00'^^xsd:gYear)", "24") ); }
@Test
public void day_24() { assertThrows(ExprEvalException.class, ()-> test("day('2010-12-08:00'^^xsd:gYearMonth)", "24") ); }
@Test
public void day_25() { assertThrows(ExprEvalException.class, ()-> test("day('--12-08:00'^^xsd:gMonth)", "24") ); }
@Test public void day_26() { test("day('--12-24-08:00'^^xsd:gMonthDay)", "24"); }
@Test public void day_27() { test("day('---24-08:00'^^xsd:gDay)", "24"); }
@Test public void day_dur_01() { test("day('P1Y2M3DT4H5M6S'^^xsd:duration)", "3"); }
// HOURS
@Test public void hours_01() { test("hours('2010-12-24T16:24:01.123'^^xsd:dateTime)", "16"); }
@Test
public void hours_02() { assertThrows(ExprEvalException.class, ()-> test("hours('2010-12-24'^^xsd:date)", "16") ); }
@Test public void hours_03() { test("hours('16:24:01'^^xsd:time)", "16"); }
@Test public void hours_10() { test("hours('2010-12-24T16:24:01.123Z'^^xsd:dateTime)", "16"); }
@Test public void hours_11() { test("hours('16:24:24Z'^^xsd:time)", "16"); }
@Test public void hours_20() { test("hours('2010-12-24T16:24:01.123-08:00'^^xsd:dateTime)", "16"); }
@Test public void hours_21() { test("hours('16:24:24-08:00'^^xsd:time)", "16"); }
@Test public void hours_dur_01() { test("hours('P1Y2M3DT4H5M6S'^^xsd:duration)", "4"); }
// MINUTES
@Test public void minutes_01() { test("minutes('2010-12-24T16:24:01.123'^^xsd:dateTime)", "24"); }
@Test
public void minutes_02() { assertThrows(ExprEvalException.class, ()-> test("minutes('2010-12-24'^^xsd:date)", "") ); }
@Test public void minutes_03() { test("minutes('16:24:01'^^xsd:time)", "24"); }
@Test public void minutes_10() { test("minutes('2010-12-24T16:24:01.123Z'^^xsd:dateTime)", "24"); }
@Test public void minutes_11() { test("minutes('16:24:01.1Z'^^xsd:time)", "24"); }
@Test public void minutes_20() { test("minutes('2010-12-24T16:24:01.123-08:00'^^xsd:dateTime)", "24"); }
@Test public void minutes_21() { test("minutes('16:24:01.01-08:00'^^xsd:time)", "24"); }
@Test public void minutes_dur_01() { test("minutes('P1Y2M3DT4H5M6S'^^xsd:duration)", "5"); }
// SECONDS
@Test public void seconds_01() { test("seconds('2010-12-24T16:24:01.123'^^xsd:dateTime)", "01.123"); }
@Test
public void seconds_02() { assertThrows(ExprEvalException.class, ()-> test("seconds('2010-12-24'^^xsd:date)", "") ); }
@Test public void seconds_03() { test("seconds('16:24:01'^^xsd:time)", "'01'^^xsd:decimal"); }
@Test public void seconds_10() { test("seconds('2010-12-24T16:24:31.123Z'^^xsd:dateTime)", "31.123"); }
@Test public void seconds_11() { test("seconds('16:24:01.1Z'^^xsd:time)", "'01.1'^^xsd:decimal"); }
@Test public void seconds_20() { test("seconds('2010-12-24T16:24:35.123-08:00'^^xsd:dateTime)", "35.123"); }
@Test public void seconds_21() { test("seconds('16:24:01.01-08:00'^^xsd:time)", "'01.01'^^xsd:decimal"); }
@Test public void seconds_dur_01() { test("seconds('P1Y2M3DT4H5M6S'^^xsd:duration)", "'6.0'^^xsd:decimal"); }
// TIMEZONE
@Test public void timezone_01() { test("timezone('2010-12-24T16:24:35.123Z'^^xsd:dateTime)", "'PT0S'^^xsd:dayTimeDuration"); }
@Test public void timezone_02() { test("timezone('2010-12-24T16:24:35.123-08:00'^^xsd:dateTime)", "'-PT8H'^^xsd:dayTimeDuration"); }
@Test public void timezone_03() { test("timezone('2010-12-24T16:24:35.123+01:00'^^xsd:dateTime)", "'PT1H'^^xsd:dayTimeDuration"); }
@Test public void timezone_04() { test("timezone('2010-12-24T16:24:35.123-00:00'^^xsd:dateTime)", "'-PT0S'^^xsd:dayTimeDuration"); }
@Test public void timezone_05() { test("timezone('2010-12-24T16:24:35.123+00:00'^^xsd:dateTime)", "'PT0S'^^xsd:dayTimeDuration"); }
@Test
public void timezone_09() { assertThrows(ExprEvalException.class, ()-> test("timezone('2010-12-24T16:24:35'^^xsd:dateTime)", "'PT0S'^^xsd:dayTimeDuration") ); }
@Test
public void timezone_10() { assertThrows(ExprEvalException.class, ()-> test("timezone(2010)", "'PT0S'^^xsd:dayTimeDuration") ); }
@Test
public void timezone_11() { assertThrows(ExprEvalException.class, ()-> test("timezone('2010-junk'^^xsd:gYear)", "'PT0S'^^xsd:dayTimeDuration") ); }
// General "adjust-to-timezone"
@Test public void adjust_1() {
test("adjust(xsd:dateTime('2022-12-21T05:05:07'), '-PT10H'^^xsd:duration)", "'2022-12-21T05:05:07-10:00'^^xsd:dateTime");
}
@Test
public void adjust_2() {
assertThrows(ExprEvalException.class, ()->
test("adjust('2022-12-21T05:05:07', 'PT08H'^^xsd:duration)", "'2022-12-21T05:05:07+08:00'^^xsd:dateTime")
);
}
// General "adjust-to-timezone"
@Test public void adjust_3() {
test("adjust(xsd:date('2022-12-21'), 'PT1H'^^xsd:duration)", "'2022-12-21+01:00'^^xsd:date");
}
@Test public void adjust_4() {
test("adjust(xsd:dateTime('2022-12-21T05:05:07'))", "'2022-12-21T05:05:07Z'^^xsd:dateTime");
}
// TZ
@Test public void tz_01() { test("tz('2010-12-24T16:24:35.123Z'^^xsd:dateTime)", "'Z'"); }
@Test public void tz_02() { test("tz('2010-12-24T16:24:35.123-08:00'^^xsd:dateTime)", "'-08:00'"); }
@Test public void tz_03() { test("tz('2010-12-24T16:24:35.123+01:00'^^xsd:dateTime)", "'+01:00'"); }
@Test public void tz_04() { test("tz('2010-12-24T16:24:35.123-00:00'^^xsd:dateTime)", "'-00:00'"); }
@Test public void tz_05() { test("tz('2010-12-24T16:24:35.123+00:00'^^xsd:dateTime)", "'+00:00'"); }
@Test public void tz_06() { test("tz('2010-12-24T16:24:35.123'^^xsd:dateTime)", "''"); }
@Test
public void tz_10() { assertThrows(ExprEvalException.class, ()-> test("tz(2010)", "''") ); }
@Test
public void tz_11() { assertThrows(ExprEvalException.class, ()-> test("tz('2010-junk'^^xsd:gYear)", "''") ); }
// NOW
//@Test public void now_01() { test("now() > '2010-12-24T16:24:35.123-08:00'^^xsd:dateTime", "true"); }
// MD5
@Test public void md5_01() { test("md5('abcd')","'e2fc714c4727ee9395f324cd2e7f331f'"); }
@Test public void md5_02() { test("md5('abcd'^^xsd:string)","'e2fc714c4727ee9395f324cd2e7f331f'"); }
@Test
public void md5_03() { assertThrows(ExprEvalException.class, ()-> test("md5('abcd'@en)","'e2fc714c4727ee9395f324cd2e7f331f'") ); }
@Test
public void md5_04() { assertThrows(ExprEvalException.class, ()-> test("md5(1234)","'e2fc714c4727ee9395f324cd2e7f331f'") ); }
// SHA1
@Test public void sha1_01() { test("sha1('abcd')","'81fe8bfe87576c3ecb22426f8e57847382917acf'"); }
@Test public void sha1_02() { test("sha1('abcd'^^xsd:string)","'81fe8bfe87576c3ecb22426f8e57847382917acf'"); }
@Test
public void sha1_03() { assertThrows(ExprEvalException.class, ()-> test("sha1('abcd'@en)","'81fe8bfe87576c3ecb22426f8e57847382917acf'") ); }
@Test
public void sha1_04() { assertThrows(ExprEvalException.class, ()-> test("sha1(123)","'81fe8bfe87576c3ecb22426f8e57847382917acf'") ); }
// SHA224
// @Test public void sha224_01() { test("sha224('abcd')","'e2fc714c4727ee9395f324cd2e7f331f'"); }
//
// @Test
// public void sha224_02() { assertThrows(ExprEvalException.class, ()-> test("sha224('abcd'^^xsd:string)","'e2fc714c4727ee9395f324cd2e7f331f'") ); }
//
// @Test
// public void sha224_03() { assertThrows(ExprEvalException.class, ()-> test("sha224('abcd'@en)","'e2fc714c4727ee9395f324cd2e7f331f'") ); }
//
// @Test
// public void sha224_04() { assertThrows(ExprEvalException.class, ()-> test("sha224(1234)","'e2fc714c4727ee9395f324cd2e7f331f'") ); }
// SHA256
@Test public void sha256_01() { test("sha256('abcd')","'88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589'"); }
@Test public void sha256_02() { test("sha256('abcd'^^xsd:string)","'88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589'"); }
@Test
public void sha256_03() { assertThrows(ExprEvalException.class, ()-> test("sha256('abcd'@en)","'88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589'") ); }
@Test
public void sha256_04() { assertThrows(ExprEvalException.class, ()-> test("sha256(<uri>)","'88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589'") ); }
// SHA384
@Test public void sha384_01() { test("sha384('abcd')","'1165b3406ff0b52a3d24721f785462ca2276c9f454a116c2b2ba20171a7905ea5a026682eb659c4d5f115c363aa3c79b'"); }
@Test public void sha384_02() { test("sha384('abcd'^^xsd:string)","'1165b3406ff0b52a3d24721f785462ca2276c9f454a116c2b2ba20171a7905ea5a026682eb659c4d5f115c363aa3c79b'"); }
@Test
public void sha384_03() { assertThrows(ExprEvalException.class, ()-> test("sha384('abcd'@en)","'1165b3406ff0b52a3d24721f785462ca2276c9f454a116c2b2ba20171a7905ea5a026682eb659c4d5f115c363aa3c79b'") ); }
@Test
public void sha384_04() { assertThrows(ExprEvalException.class, ()-> test("sha384(123.45)","'1165b3406ff0b52a3d24721f785462ca2276c9f454a116c2b2ba20171a7905ea5a026682eb659c4d5f115c363aa3c79b'") ); }
// SHA512
@Test public void sha512_01() { test("sha512('abcd')","'d8022f2060ad6efd297ab73dcc5355c9b214054b0d1776a136a669d26a7d3b14f73aa0d0ebff19ee333368f0164b6419a96da49e3e481753e7e96b716bdccb6f'"); }
@Test public void sha512_02() { test("sha512('abcd'^^xsd:string)","'d8022f2060ad6efd297ab73dcc5355c9b214054b0d1776a136a669d26a7d3b14f73aa0d0ebff19ee333368f0164b6419a96da49e3e481753e7e96b716bdccb6f'"); }
@Test
public void sha512_03() { assertThrows(ExprEvalException.class, ()-> test("md5('abcd'@en)","'d8022f2060ad6efd297ab73dcc5355c9b214054b0d1776a136a669d26a7d3b14f73aa0d0ebff19ee333368f0164b6419a96da49e3e481753e7e96b716bdccb6f'") ); }
@Test
public void sha512_04() { assertThrows(ExprEvalException.class, ()-> test("md5(0.0e0)","'d8022f2060ad6efd297ab73dcc5355c9b214054b0d1776a136a669d26a7d3b14f73aa0d0ebff19ee333368f0164b6419a96da49e3e481753e7e96b716bdccb6f'") ); }
// --------
private static PrefixMapping pmap = ARQConstants.getGlobalPrefixMap();
private static void test(String string, String result) {
Expr expr = ExprUtils.parse(string, pmap);
NodeValue nv = expr.eval(null, new FunctionEnvBase());
Node r = NodeFactoryExtra.parseNode(result);
NodeValue nvr = NodeValue.makeNode(r);
assertTrue(NodeValue.sameValueAs(nvr, nv), "Not same value: Expected: " + nvr + " : Actual = " + nv);
// test result must be lexical form exact.
assertEquals(r, nv.asNode());
}
}
|
googleapis/google-cloud-java | 35,667 | java-securitycentermanagement/proto-google-cloud-securitycentermanagement-v1/src/main/java/com/google/cloud/securitycentermanagement/v1/ListEventThreatDetectionCustomModulesRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/securitycentermanagement/v1/security_center_management.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.securitycentermanagement.v1;
/**
*
*
* <pre>
* Request message for
* [SecurityCenterManagement.ListEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEventThreatDetectionCustomModules].
* </pre>
*
* Protobuf type {@code
* google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest}
*/
public final class ListEventThreatDetectionCustomModulesRequest
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest)
ListEventThreatDetectionCustomModulesRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListEventThreatDetectionCustomModulesRequest.newBuilder() to construct.
private ListEventThreatDetectionCustomModulesRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListEventThreatDetectionCustomModulesRequest() {
parent_ = "";
pageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListEventThreatDetectionCustomModulesRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ListEventThreatDetectionCustomModulesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ListEventThreatDetectionCustomModulesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest.class,
com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Optional. The maximum number of modules to return. The service may return
* fewer than this value. If unspecified, at most 10 modules will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj
instanceof
com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest)) {
return super.equals(obj);
}
com.google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest
other =
(com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest)
obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest
prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request message for
* [SecurityCenterManagement.ListEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListEventThreatDetectionCustomModules].
* </pre>
*
* Protobuf type {@code
* google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest)
com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ListEventThreatDetectionCustomModulesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ListEventThreatDetectionCustomModulesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest.class,
com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest.Builder.class);
}
// Construct using
// com.google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ListEventThreatDetectionCustomModulesRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest
getDefaultInstanceForType() {
return com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest
build() {
com.google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest
result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest
buildPartial() {
com.google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest
result =
new com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest
result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other
instanceof
com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest) {
return mergeFrom(
(com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest)
other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest
other) {
if (other
== com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Optional. The maximum number of modules to return. The service may return
* fewer than this value. If unspecified, at most 10 modules will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Optional. The maximum number of modules to return. The service may return
* fewer than this value. If unspecified, at most 10 modules will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The maximum number of modules to return. The service may return
* fewer than this value. If unspecified, at most 10 modules will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest)
private static final com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest();
}
public static com.google.cloud.securitycentermanagement.v1
.ListEventThreatDetectionCustomModulesRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListEventThreatDetectionCustomModulesRequest>
PARSER =
new com.google.protobuf.AbstractParser<ListEventThreatDetectionCustomModulesRequest>() {
@java.lang.Override
public ListEventThreatDetectionCustomModulesRequest 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<ListEventThreatDetectionCustomModulesRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListEventThreatDetectionCustomModulesRequest>
getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.securitycentermanagement.v1.ListEventThreatDetectionCustomModulesRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/uima-uimaj | 35,801 | uimaj-core/src/main/java/org/apache/uima/cas/impl/CASSerializer.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.uima.cas.impl;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import org.apache.uima.UimaSerializable;
import org.apache.uima.cas.CASRuntimeException;
import org.apache.uima.cas.CommonArrayFS;
import org.apache.uima.cas.Marker;
import org.apache.uima.cas.impl.CASImpl.FsChange;
import org.apache.uima.cas.impl.SlotKinds.SlotKind;
import org.apache.uima.internal.util.Misc;
import org.apache.uima.internal.util.Obj2IntIdentityHashMap;
import org.apache.uima.internal.util.function.Consumer_T_withIOException;
import org.apache.uima.jcas.cas.BooleanArray;
import org.apache.uima.jcas.cas.ByteArray;
import org.apache.uima.jcas.cas.DoubleArray;
import org.apache.uima.jcas.cas.FSArray;
import org.apache.uima.jcas.cas.FloatArray;
import org.apache.uima.jcas.cas.IntegerArray;
import org.apache.uima.jcas.cas.LongArray;
import org.apache.uima.jcas.cas.ShortArray;
import org.apache.uima.jcas.cas.StringArray;
import org.apache.uima.jcas.cas.TOP;
import org.apache.uima.util.CasIOUtils;
// @formatter:off
/**
* This object has 2 purposes.
* - it can hold a collection of individually Java-object-serializable objects representing a CAS +
* the list of FS's indexed in the CAS
*
* - it has special methods (versions of addCAS) to do a custom binary serialization (no compression) of a CAS + lists
* of its indexed FSs.
*
* One use of this class follows this form:
*
* 1) create an instance of this class
* 2) add a Cas to it (via addCAS methods)
* 3) use the instance of this class as the argument to anObjectOutputStream.writeObject(anInstanceOfThisClass)
* In UIMA this is done in the SerializationUtils class; it appears to be used for Vinci service adapters.
*
* There are also custom serialization methods that serialize to outputStreams.
*
* The format of the serialized data is in one of several formats:
* normal Java object serialization / custom binary serialization
*
* The custom binary serialization is in several formats:
* full / delta:
* full - the entire cas
* delta - only differences from a previous "mark" are serialized
*
* This class only does uncompressed forms of custom binary serialization.
*
* This class is for internal use. Some of the serialized formats are readable by the C++
* implementation, and used for efficiently transferring CASes between Java frameworks and other ones.
* Others are used with Vinci to communicate to remote annotators.
*
* To serialize the type definition and index specifications for a CAS
*
* @see org.apache.uima.cas.impl.CASMgrSerializer
*/
// @formatter:on
public class CASSerializer implements Serializable {
static final long serialVersionUID = -7972011651957420295L;
static class AddrPlusValue {
final int addr; // heap or aux heap addr
final long value; // boolean, byte, short, long, double value
AddrPlusValue(int addr, long value) {
this.addr = addr;
this.value = value;
}
}
// The heap itself.
public int[] heapArray = null;
// Heap metadata. This is not strictly required, the heap can be
// deserialized
// without. Must be null if not used.
public int[] heapMetaData = null;
// The string table for strings that are feature structure values. Note that
// the 0th position in the string table should be null and will be ignored.
public String[] stringTable;
// Special encoding of fs pseudo-addrs and counts by view incl. sofa and view counts
public int[] fsIndex;
public byte[] byteHeapArray;
public short[] shortHeapArray;
public long[] longHeapArray;
/**
* Constructor for CASSerializer.
*/
public CASSerializer() {
}
/**
* Serialize CAS data without heap-internal meta data. Currently used for serialization to C++.
*
* @param casImpl
* The CAS to be serialized.
*/
public void addNoMetaData(CASImpl casImpl) {
addCAS(casImpl, false);
}
/**
* Add the CAS to be serialized. Note that we need the implementation here, the interface is not
* enough.
*
* @param cas
* The CAS to be serialized.
*/
public void addCAS(CASImpl cas) {
addCAS(cas, true);
}
/**
* Add the CAS to be serialized.
*
* @param cas
* The CAS to be serialized.
* @param addMetaData
* - true to include metadata
*/
public void addCAS(CASImpl cas, boolean addMetaData) {
synchronized (cas.svd) {
BinaryCasSerDes bcsd = cas.getBinaryCasSerDes();
// next call runs the setup, which scans all the reachables
final CommonSerDesSequential csds = BinaryCasSerDes4.getCsds(cas.getBaseCAS(), false); // saves
// the
// csds
// in
// the
// cas
bcsd.scanAllFSsForBinarySerialization(null, csds); // no mark
fsIndex = bcsd.getIndexedFSs(csds.fs2addr); // must follow scanAll...
if (addMetaData) {
// some details about current main-heap specifications
// not required to deserialize
// not sent for C++
// is 7 words long
// not serialized by custom serializers, only by Java object serialization
int heapsz = bcsd.heap.getCellsUsed();
heapMetaData = new int[] { Heap.getRoundedSize(heapsz), // a bit more than the size of
// the used heap
heapsz, // the position of the next (unused) slot in the heap
heapsz, 0, 0, 1024, // initial size
0 };
}
copyHeapsToArrays(bcsd);
}
}
private void outputStringHeap(DataOutputStream dos, CASImpl cas,
StringHeapDeserializationHelper shdh, BinaryCasSerDes bcsd) throws IOException {
// output the strings
// compute the number of total size of data in stringHeap
// total size = char buffer length + length of strings in the string list;
int stringHeapLength = shdh.charHeapPos;
int stringListLength = 0;
for (int i = 0; i < shdh.refHeap.length; i += 3) {
int ref = shdh.refHeap[i + StringHeapDeserializationHelper.STRING_LIST_ADDR_OFFSET];
// this is a string in the string list
// get length and add to total string heap length
if (ref != 0) {
// terminate each string with a null
stringListLength += 1 + bcsd.stringHeap.getStringForCode(ref).length();
}
}
int stringTotalLength = stringHeapLength + stringListLength;
if (stringHeapLength == 0 && stringListLength > 0) {
// nothing from stringHeap
// add 1 for the null at the beginning
stringTotalLength += 1;
}
dos.writeInt(stringTotalLength);
// write the data in the stringheap, if there is any
if (stringTotalLength > 0) {
if (shdh.charHeapPos > 0) {
dos.writeChars(String.valueOf(shdh.charHeap, 0, shdh.charHeapPos));
} else {
// no stringheap data
// if there is data in the string lists, write a leading 0
if (stringListLength > 0) {
dos.writeChar(0);
}
}
// word alignment
if (stringTotalLength % 2 != 0) {
dos.writeChar(0);
}
}
// write out the string ref heap
// each reference consist of a offset into stringheap and a length
int refheapsz = ((shdh.refHeap.length - StringHeapDeserializationHelper.FIRST_CELL_REF)
/ StringHeapDeserializationHelper.REF_HEAP_CELL_SIZE) * 2;
refheapsz++;
dos.writeInt(refheapsz);
dos.writeInt(0);
for (int i = StringHeapDeserializationHelper.FIRST_CELL_REF; i < shdh.refHeap.length; i += 3) {
dos.writeInt(shdh.refHeap[i + StringHeapDeserializationHelper.CHAR_HEAP_POINTER_OFFSET]);
dos.writeInt(shdh.refHeap[i + StringHeapDeserializationHelper.CHAR_HEAP_STRLEN_OFFSET]);
}
}
void addTsiCAS(CASImpl cas, OutputStream ostream) {
}
// @formatter:off
/**
* Serializes the CAS data and writes it to the output stream.
* ---------------------------------------------------------------------
* Blob Format Element
* Size Number of Description
* (bytes) Elements
* ------------ --------- --------------------------------
* 4 1 Blob key = "UIMA" in utf-8
* 4 1 Version (currently = 1)
* 4 1 size of 32-bit FS Heap array = s32H
* 4 s32H 32-bit FS heap array
* 4 1 size of 16-bit string Heap array = sSH
* 2 sSH 16-bit string heap array
* 4 1 size of string Ref Heap zrray = sSRH
* 4 2*sSRH string ref offsets and lengths
* 4 1 size of FS index array = sFSI
* 4 sFSI FS index array
* 4 1 size of 8-bit Heap array = s8H
* 1 s8H 8-bit Heap array
* 4 1 size of 16-bit Heap array = s16H
* 2 s16H 16-bit Heap array
* 4 1 size of 64-bit Heap array = s64H
* 8 s64H 64-bit Heap array
* ---------------------------------------------------------------------
*
* @param cas
* The CAS to be serialized. ostream The output stream.
* @param ostream
* -
*/
// @formatter:on
public void addCAS(CASImpl cas, OutputStream ostream) {
addCAS(cas, ostream, false);
}
public void addCAS(CASImpl cas, OutputStream ostream, boolean includeTsi) {
synchronized (cas.svd) {
final BinaryCasSerDes bcsd = cas.getBinaryCasSerDes();
// next call runs the setup, which scans all the reachables
// these may have changed since this was previously computed due to updates in the CAS
final CommonSerDesSequential csds = BinaryCasSerDes4.getCsds(cas.getBaseCAS(), false); // saves
// the
// csds
// in
// the
// cas,
// used
// for
// possible
// future
// delta
// deser
bcsd.scanAllFSsForBinarySerialization(null, csds); // no mark
try {
DataOutputStream dos = new DataOutputStream(ostream);
// get the indexed FSs for all views
fsIndex = bcsd.getIndexedFSs(csds.fs2addr);
// output the key and version number
CommonSerDes.createHeader().seqVer(2) // 0 original, 1 UIMA-4743 2 for uima v3
.typeSystemIndexDefIncluded(includeTsi).v3().write(dos);
if (includeTsi) {
CasIOUtils.writeTypeSystem(cas, ostream, true);
}
// output the FS heap
final int heapSize = bcsd.heap.getCellsUsed();
dos.writeInt(heapSize);
// writing the 0th (null) element, because that's what V2 did
final int[] vs = bcsd.heap.heap;
for (int i = 0; i < heapSize; i++) {
dos.writeInt(vs[i]);
}
// output the strings
StringHeapDeserializationHelper shdh = bcsd.stringHeap.serialize();
outputStringHeap(dos, cas, shdh, bcsd);
// // compute the number of total size of data in stringHeap
// // total size = char buffer length + length of strings in the string list;
// int stringHeapLength = shdh.charHeapPos;
// int stringListLength = 0;
// for (int i = 0; i < shdh.refHeap.length; i += 3) {
// int ref = shdh.refHeap[i + StringHeapDeserializationHelper.STRING_LIST_ADDR_OFFSET];
// // this is a string in the string list
// // get length and add to total string heap length
// if (ref != 0) {
// // terminate each string with a null
// stringListLength += 1 + cas.getStringHeap().getStringForCode(ref).length();
// }
// }
//
// int stringTotalLength = stringHeapLength + stringListLength;
// if (stringHeapLength == 0 && stringListLength > 0) {
// // nothing from stringHeap
// // add 1 for the null at the beginning
// stringTotalLength += 1;
// }
// dos.writeInt(stringTotalLength);
//
// // write the data in the stringheap, if there is any
// if (stringTotalLength > 0) {
// if (shdh.charHeapPos > 0) {
// dos.writeChars(String.valueOf(shdh.charHeap, 0, shdh.charHeapPos));
// } else {
// // no stringheap data
// // if there is data in the string lists, write a leading 0
// if (stringListLength > 0) {
// dos.writeChar(0);
// }
// }
//
// // word alignment
// if (stringTotalLength % 2 != 0) {
// dos.writeChar(0);
// }
// }
//
// // write out the string ref heap
// // each reference consist of a offset into stringheap and a length
// int refheapsz = ((shdh.refHeap.length - StringHeapDeserializationHelper.FIRST_CELL_REF) /
// StringHeapDeserializationHelper.REF_HEAP_CELL_SIZE) * 2;
// refheapsz++;
// dos.writeInt(refheapsz);
// dos.writeInt(0);
// for (int i = StringHeapDeserializationHelper.FIRST_CELL_REF; i < shdh.refHeap.length; i
// += 3) {
// dos.writeInt(shdh.refHeap[i + StringHeapDeserializationHelper.CHAR_HEAP_POINTER_OFFSET]);
// dos.writeInt(shdh.refHeap[i + StringHeapDeserializationHelper.CHAR_HEAP_STRLEN_OFFSET]);
// }
// output the index FSs
dos.writeInt(fsIndex.length);
for (int i = 0; i < fsIndex.length; i++) {
dos.writeInt(fsIndex[i]);
}
// 8bit heap
final int byteheapsz = bcsd.byteHeap.getSize();
dos.writeInt(byteheapsz);
dos.write(bcsd.byteHeap.heap, 0, byteheapsz);
// word alignment
int align = (4 - (byteheapsz % 4)) % 4;
for (int i = 0; i < align; i++) {
dos.writeByte(0);
}
// 16bit heap
final int shortheapsz = bcsd.shortHeap.getSize();
dos.writeInt(shortheapsz);
final short[] sh = bcsd.shortHeap.heap;
for (int i = 0; i < shortheapsz; i++) {
dos.writeShort(sh[i]);
}
// word alignment
if (shortheapsz % 2 != 0) {
dos.writeShort(0);
}
// 64bit heap
int longheapsz = bcsd.longHeap.getSize();
dos.writeInt(longheapsz);
final long[] lh = bcsd.longHeap.heap;
for (int i = 0; i < longheapsz; i++) {
dos.writeLong(lh[i]);
}
} catch (IOException e) {
throw new CASRuntimeException(CASRuntimeException.BLOB_SERIALIZATION, e.getMessage());
}
bcsd.setHeapExtents();
// non delta serialization
csds.setHeapEnd(bcsd.nextHeapAddrAfterMark);
}
}
// @formatter:off
/**
* Serializes only new and modified FS and index operations made after the tracking mark is
* created. Serializes CAS data in binary Delta format described below and writes it to the output
* stream.
*
* ElementSize NumberOfElements Description
* ----------- ---------------- ---------------------------------------------------------
* 4 1 Blob key = "UIMA" in utf-8 (byte order flag)
* 4 1 Version (1 = complete cas, 2 = delta cas)
* 4 1 size of 32-bit heap array = s32H
* 4 s32H 32-bit FS heap array (new elements)
* 4 1 size of 16-bit string Heap array = sSH
* 2 sSH 16-bit string heap array (new strings)
* 4 1 size of string Ref Heap array = sSRH
* 4 2*sSRH string ref offsets and lengths (for new strings)
* 4 1 number of modified, preexisting 32-bit modified FS heap elements = sM32H
* 4 2*sM32H 32-bit heap offset and value (preexisting cells modified)
* 4 1 size of FS index array = sFSI
* 4 sFSI FS index array in Delta format
* 4 1 size of 8-bit Heap array = s8H
* 1 s8H 8-bit Heap array (new elements)
* 4 1 size of 16-bit Heap array = s16H
* 2 s16H 16-bit Heap array (new elements)
* 4 1 size of 64-bit Heap array = s64H
* 8 s64H 64-bit Heap array (new elements)
* 4 1 number of modified, preexisting 8-bit heap elements = sM8H
* 4 sM8H 8-bit heap offsets (preexisting cells modified)
* 1 sM8H 8-bit heap values (preexisting cells modified)
* 4 1 number of modified, preexisting 16-bit heap elements = sM16H
* 4 sM16H 16-bit heap offsets (preexisting cells modified)
* 2 sM16H 16-bit heap values (preexisting cells modified)
* 4 1 number of modified, preexisting 64-bit heap elements = sM64H
* 4 sM64H 64-bit heap offsets (preexisting cells modified)
* 2 sM64H 64-bit heap values (preexisting cells modified)
*
*
* @param cas
* -
* @param ostream
* -
* @param trackingMark
* -
*/
// @formatter:on
public void addCAS(CASImpl cas, OutputStream ostream, Marker trackingMark) {
if (!trackingMark.isValid()) {
throw new CASRuntimeException(CASRuntimeException.INVALID_MARKER, "Invalid Marker.");
}
MarkerImpl mark = (MarkerImpl) trackingMark;
synchronized (cas.svd) {
final BinaryCasSerDes bcsd = cas.getBinaryCasSerDes();
// next call runs the setup, which scans all the reachables
final CommonSerDesSequential csds = BinaryCasSerDes4.getCsds(cas.getBaseCAS(), true); // saves
// the
// csds
// in
// the
// cas
// because the output is only the new elements, this populates the arrays with only the new
// elements
// Note: all heaps reserve slot 0 for null, real data starts at position 1
List<TOP> all = bcsd.scanAllFSsForBinarySerialization(mark, csds);
// if (csds.getHeapEnd() == 0) {
// System.out.println("debug");
// }
final Obj2IntIdentityHashMap<TOP> fs2auxOffset = new Obj2IntIdentityHashMap<>(TOP.class,
TOP._singleton);
int byteOffset = 1;
int shortOffset = 1;
int longOffset = 1;
// scan all below mark and set up maps from aux array FSs to the offset to where the array
// starts in the modelled aux heap
for (TOP fs : all) {
if (trackingMark.isNew(fs)) {
break;
}
if (fs instanceof CommonArrayFS) {
CommonArrayFS<?> ca = (CommonArrayFS<?>) fs;
SlotKind kind = fs._getTypeImpl().getComponentSlotKind();
switch (kind) {
case Slot_BooleanRef:
case Slot_ByteRef:
fs2auxOffset.put(fs, byteOffset);
byteOffset += ca.size();
break;
case Slot_ShortRef:
fs2auxOffset.put(fs, shortOffset);
shortOffset += ca.size();
break;
case Slot_LongRef:
case Slot_DoubleRef:
fs2auxOffset.put(fs, longOffset);
longOffset += ca.size();
break;
default:
} // end of switch
} // end of if commonarray
else { // fs has feature slots
// model long and double refs which use up the long aux heap for 1 cell
TypeImpl ti = fs._getTypeImpl();
longOffset += ti.getNbrOfLongOrDoubleFeatures();
}
} // end of for
try {
DataOutputStream dos = new DataOutputStream(ostream);
// get the indexed FSs
fsIndex = bcsd.getDeltaIndexedFSs(mark, csds.fs2addr);
CommonSerDes.createHeader().delta().seqVer(2) // 1 for UIMA-4743 2 for uima v3
.v3().write(dos);
// output the new FS heap cells
final int heapSize = bcsd.heap.getCellsUsed() - 1; // first entry (null) is not written
// Write heap - either the entire heap, or for delta, just the new part
dos.writeInt(heapSize);
final int[] vs = bcsd.heap.heap;
for (int i = 1; i <= heapSize; i++) { // <= because heapsize is 1 less than cells used, but
// we start at index 1
dos.writeInt(vs[i]);
}
// convert v3 change-logging to v2 form, setting the chgXX-addr and chgXX-values lists.
// we do this before the strings or aux arrays are written out, because this
// could make additions to those.
// addresses are in terms of modeled v2 arrays, as absolute addr in the aux arrays, and
// values
List<AddrPlusValue> chgMainAvs = new ArrayList<>();
List<AddrPlusValue> chgByteAvs = new ArrayList<>();
List<AddrPlusValue> chgShortAvs = new ArrayList<>();
List<AddrPlusValue> chgLongAvs = new ArrayList<>();
scanModifications(bcsd, csds, cas.getModifiedFSList(), fs2auxOffset, chgMainAvs, chgByteAvs,
chgShortAvs, chgLongAvs);
// output the new strings
StringHeapDeserializationHelper shdh = bcsd.stringHeap.serialize(1);
outputStringHeap(dos, cas, shdh, bcsd);
// output modified FS Heap cells
// this is output in a way that is the total number of slots changed ==
// the sum over all fsChanges of
// for each fsChange, the number of slots (heap-sited-array or feature) modified
final int modHeapSize = chgMainAvs.size();
dos.writeInt(modHeapSize); // num modified
for (AddrPlusValue av : chgMainAvs) {
dos.writeInt(av.addr);
dos.writeInt((int) av.value);
}
// output the index FSs
dos.writeInt(fsIndex.length);
for (int i = 0; i < fsIndex.length; i++) {
dos.writeInt(fsIndex[i]);
}
// 8bit heap new
int byteheapsz = bcsd.byteHeap.getSize() - 1;
dos.writeInt(byteheapsz);
dos.write(bcsd.byteHeap.heap, 1, byteheapsz); // byte 0 not used
// word alignment
int align = (4 - (byteheapsz % 4)) % 4;
for (int i = 0; i < align; i++) {
dos.writeByte(0);
}
// 16bit heap new
int shortheapsz = bcsd.shortHeap.getSize() - 1;
dos.writeInt(shortheapsz);
for (int i = 1; i <= shortheapsz; i++) { // <= in test because we're starting at 1
dos.writeShort(bcsd.shortHeap.heap[i]);
}
// word alignment
if (shortheapsz % 2 != 0) {
dos.writeShort(0);
}
// 64bit heap new
int longheapsz = bcsd.longHeap.getSize() - 1;
dos.writeInt(longheapsz);
for (int i = 1; i <= longheapsz; i++) {
dos.writeLong(bcsd.longHeap.heap[i]);
}
// 8bit heap modified cells
writeMods(chgByteAvs, dos, av -> dos.writeByte((byte) av.value));
// word alignment
align = (4 - (chgByteAvs.size() % 4)) % 4;
for (int i = 0; i < align; i++) {
dos.writeByte(0);
}
// 16bit heap modified cells
writeMods(chgShortAvs, dos, av -> dos.writeShort((short) av.value));
// word alignment
if (chgShortAvs.size() % 2 != 0) {
dos.writeShort(0);
}
// 64bit heap modified cells
writeMods(chgLongAvs, dos, av -> dos.writeLong(av.value));
} catch (IOException e) {
throw new CASRuntimeException(CASRuntimeException.BLOB_SERIALIZATION, e.getMessage());
}
}
}
private void writeMods(List<AddrPlusValue> avs, DataOutputStream dos,
Consumer_T_withIOException<AddrPlusValue> writeValue) throws IOException {
int size = avs.size();
dos.writeInt(size);
for (AddrPlusValue av : avs) {
dos.writeInt(av.addr);
}
for (AddrPlusValue av : avs) {
writeValue.accept(av);
}
}
/**
* The offset in the modeled heaps:
*
* @param index
* the 0-based index into the array
* @param fs
* the feature structure representing the array
* @return the addr into an aux array or main heap
*/
private static int convertArrayIndexToAuxHeapAddr(BinaryCasSerDes bcsd, int index, TOP fs,
Obj2IntIdentityHashMap<TOP> fs2auxOffset) {
int offset = fs2auxOffset.get(fs);
assert offset > 0;
return offset;
}
private static int convertArrayIndexToMainHeapAddr(int index, TOP fs,
Obj2IntIdentityHashMap<TOP> fs2addr) {
return fs2addr.get(fs) + 2 + index;
}
/**
* Scan the v3 fsChange info and produce v2 style info into chgXxxAddr, chgXxxValue
*
* A pre-scan approach is needed in order to write the number of modifications preceding the write
* of the values (which unfortunately were written to the same stream in V2).
*
* @param bcsd
* holds the model needed for v2 aux arrays
* @param chgMainAvs
* an ordered collection of changed addresses as an array for the main heap
* @param chgByteAvs
* an ordered collection of changed addresses as an array for the aux byte heap
* @param chgShortAvs
* an ordered collection of changed addresses as an array for the aus short heap
* @param chgLongAvs
* an ordered collection of changed addresses as an array for the aux long heap
*/
static void scanModifications(BinaryCasSerDes bcsd, CommonSerDesSequential csds,
FsChange[] fssModified, Obj2IntIdentityHashMap<TOP> fs2auxOffset,
List<AddrPlusValue> chgMainAvs, List<AddrPlusValue> chgByteAvs,
List<AddrPlusValue> chgShortAvs, List<AddrPlusValue> chgLongAvs) {
// scan the sorted mods to precompute the various change items:
// changed main heap: addr and new slot value
// for aux heaps: new values.
// Note: the changed main heap values point to these (and also to new string values)
// -- for byte (and boolean), short, long
// for aux heaps: changed (updated) values: the addr(s) followed by the values
final Obj2IntIdentityHashMap<TOP> fs2addr = csds.fs2addr;
for (FsChange fsChange : fssModified) {
final TOP fs = fsChange.fs;
final TypeImpl type = fs._getTypeImpl();
if (fsChange.arrayUpdates != null) {
switch (type.getComponentSlotKind()) {
case Slot_BooleanRef:
fsChange.arrayUpdates.forAllInts(index -> {
chgByteAvs.add(new AddrPlusValue(
convertArrayIndexToAuxHeapAddr(bcsd, index, fs, fs2auxOffset),
((BooleanArray) fs).get(index) ? 1 : 0));
});
break;
case Slot_ByteRef:
fsChange.arrayUpdates.forAllInts(index -> {
chgByteAvs.add(new AddrPlusValue(
convertArrayIndexToAuxHeapAddr(bcsd, index, fs, fs2auxOffset),
((ByteArray) fs).get(index)));
});
break;
case Slot_ShortRef:
fsChange.arrayUpdates.forAllInts(index -> {
chgShortAvs.add(new AddrPlusValue(
convertArrayIndexToAuxHeapAddr(bcsd, index, fs, fs2auxOffset),
((ShortArray) fs).get(index)));
});
break;
case Slot_LongRef:
fsChange.arrayUpdates.forAllInts(index -> {
chgLongAvs.add(new AddrPlusValue(
convertArrayIndexToAuxHeapAddr(bcsd, index, fs, fs2auxOffset),
((LongArray) fs).get(index)));
});
break;
case Slot_DoubleRef:
fsChange.arrayUpdates.forAllInts(index -> {
chgLongAvs.add(new AddrPlusValue(
convertArrayIndexToAuxHeapAddr(bcsd, index, fs, fs2auxOffset),
CASImpl.double2long(((DoubleArray) fs).get(index))));
});
break;
// heap stored arrays
case Slot_Int:
fsChange.arrayUpdates.forAllInts(index -> {
chgMainAvs.add(new AddrPlusValue(convertArrayIndexToMainHeapAddr(index, fs, fs2addr),
((IntegerArray) fs).get(index)));
});
break;
case Slot_Float:
fsChange.arrayUpdates.forAllInts(index -> {
chgMainAvs.add(new AddrPlusValue(convertArrayIndexToMainHeapAddr(index, fs, fs2addr),
CASImpl.float2int(((FloatArray) fs).get(index))));
});
break;
case Slot_StrRef:
fsChange.arrayUpdates.forAllInts(index -> {
int v = bcsd.nextStringHeapAddrAfterMark
+ bcsd.stringHeap.addString(((StringArray) fs).get(index));
chgMainAvs.add(
new AddrPlusValue(convertArrayIndexToMainHeapAddr(index, fs, fs2addr), v));
});
break;
case Slot_HeapRef:
fsChange.arrayUpdates.forAllInts(index -> {
TOP tgtFs = (TOP) ((FSArray<?>) fs).get(index);
chgMainAvs.add(new AddrPlusValue(convertArrayIndexToMainHeapAddr(index, fs, fs2addr),
fs2addr.get(tgtFs)));
});
break;
default:
Misc.internalError();
} // end of switch
} else { // end of if-array
// 1 or more features modified
if (fs instanceof UimaSerializable uimaSerializable) {
uimaSerializable._save_to_cas_data();
}
BitSet fm = fsChange.featuresModified;
int offset = fm.nextSetBit(0);
while (offset >= 0) {
int addr = csds.fs2addr.get(fs) + offset + 1; // skip over type code);
int value = 0;
FeatureImpl feat = type.getFeatureImpls()[offset];
switch (feat.getSlotKind()) {
case Slot_Boolean:
value = fs._getBooleanValueNc(feat) ? 1 : 0;
break;
case Slot_Byte:
value = fs._getByteValueNc(feat);
break;
case Slot_Short:
value = fs._getShortValueNc(feat);
break;
case Slot_Int:
value = fs._getIntValueNc(feat);
break;
case Slot_Float:
value = CASImpl.float2int(fs._getFloatValueNc(feat));
break;
case Slot_LongRef: {
value = bcsd.nextLongHeapAddrAfterMark
+ bcsd.longHeap.addLong(fs._getLongValueNc(feat));
break;
}
case Slot_DoubleRef: {
value = bcsd.nextLongHeapAddrAfterMark
+ bcsd.longHeap.addLong(CASImpl.double2long(fs._getDoubleValueNc(feat)));
break;
}
case Slot_StrRef: {
value = bcsd.nextStringHeapAddrAfterMark
+ bcsd.stringHeap.addString(fs._getStringValueNc(feat));
break;
}
case Slot_HeapRef:
value = fs2addr.get(fs._getFeatureValueNc(feat));
break;
default:
Misc.internalError();
} // end of switch
chgMainAvs.add(new AddrPlusValue(addr, value));
offset = fm.nextSetBit(offset + 1);
} // loop over changed feature offsets
} // end of features-modified case
} // end of for all fsChanges
}
// /**
// * Serialize with compression
// * Target is not constrained to the C++ format
// * For non delta serialization, pass marker with 0 as values
// * @throws IOException
// */
//
// public void serialize(CASImpl cas, OutputStream ostream, Marker marker) throws IOException {
// if (marker != null && !marker.isValid() ) {
// CASRuntimeException exception = new CASRuntimeException(
// CASRuntimeException.INVALID_MARKER, new String[] { "Invalid Marker." });
// throw exception;
// }
// MarkerImpl mark = (MarkerImpl) marker;
// DataOutputStream dos = new DataOutputStream(ostream);
//
// this.fsIndex = cas.getDeltaIndexedFSs(mark);
// outputVersion(3 , dos);
//
// // output the new FS heap cells
// final int heapSize = cas.getHeap().getCellsUsed() - mark.nextFSId);
// compressHeapOut(dos, cas, heapSize, mark)
//
// // output the new strings
//
// }
int[] getHeapMetadata() {
return heapMetaData;
}
int[] getHeapArray() {
return heapArray;
}
String[] getStringTable() {
return stringTable;
}
int[] getFSIndex() {
return fsIndex;
}
byte[] getByteArray() {
return byteHeapArray;
}
short[] getShortArray() {
return shortHeapArray;
}
long[] getLongArray() {
return longHeapArray;
}
private void copyHeapsToArrays(BinaryCasSerDes bcsd) {
heapArray = bcsd.heap.toArray();
byteHeapArray = bcsd.byteHeap.toArray();
shortHeapArray = bcsd.shortHeap.toArray();
longHeapArray = bcsd.longHeap.toArray();
stringTable = bcsd.stringHeap.toArray();
}
}
|
googleads/google-ads-java | 35,957 | google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/resources/ListingGroupFilterDimensionPath.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v19/resources/asset_group_listing_group_filter.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v19.resources;
/**
* <pre>
* The path defining of dimensions defining a listing group filter.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath}
*/
public final class ListingGroupFilterDimensionPath extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath)
ListingGroupFilterDimensionPathOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListingGroupFilterDimensionPath.newBuilder() to construct.
private ListingGroupFilterDimensionPath(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListingGroupFilterDimensionPath() {
dimensions_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new ListingGroupFilterDimensionPath();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v19_resources_ListingGroupFilterDimensionPath_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v19_resources_ListingGroupFilterDimensionPath_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath.class, com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath.Builder.class);
}
public static final int DIMENSIONS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.ads.googleads.v19.resources.ListingGroupFilterDimension> dimensions_;
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.util.List<com.google.ads.googleads.v19.resources.ListingGroupFilterDimension> getDimensionsList() {
return dimensions_;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionOrBuilder>
getDimensionsOrBuilderList() {
return dimensions_;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public int getDimensionsCount() {
return dimensions_.size();
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v19.resources.ListingGroupFilterDimension getDimensions(int index) {
return dimensions_.get(index);
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionOrBuilder getDimensionsOrBuilder(
int index) {
return dimensions_.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 < dimensions_.size(); i++) {
output.writeMessage(1, dimensions_.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 < dimensions_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, dimensions_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath)) {
return super.equals(obj);
}
com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath other = (com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath) obj;
if (!getDimensionsList()
.equals(other.getDimensionsList())) 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 (getDimensionsCount() > 0) {
hash = (37 * hash) + DIMENSIONS_FIELD_NUMBER;
hash = (53 * hash) + getDimensionsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath 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 path defining of dimensions defining a listing group filter.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath)
com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPathOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v19_resources_ListingGroupFilterDimensionPath_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v19_resources_ListingGroupFilterDimensionPath_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath.class, com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath.Builder.class);
}
// Construct using com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (dimensionsBuilder_ == null) {
dimensions_ = java.util.Collections.emptyList();
} else {
dimensions_ = null;
dimensionsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v19.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v19_resources_ListingGroupFilterDimensionPath_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath getDefaultInstanceForType() {
return com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath build() {
com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath buildPartial() {
com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath result = new com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartialRepeatedFields(com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath result) {
if (dimensionsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
dimensions_ = java.util.Collections.unmodifiableList(dimensions_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.dimensions_ = dimensions_;
} else {
result.dimensions_ = dimensionsBuilder_.build();
}
}
private void buildPartial0(com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath result) {
int from_bitField0_ = bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath) {
return mergeFrom((com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath other) {
if (other == com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath.getDefaultInstance()) return this;
if (dimensionsBuilder_ == null) {
if (!other.dimensions_.isEmpty()) {
if (dimensions_.isEmpty()) {
dimensions_ = other.dimensions_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureDimensionsIsMutable();
dimensions_.addAll(other.dimensions_);
}
onChanged();
}
} else {
if (!other.dimensions_.isEmpty()) {
if (dimensionsBuilder_.isEmpty()) {
dimensionsBuilder_.dispose();
dimensionsBuilder_ = null;
dimensions_ = other.dimensions_;
bitField0_ = (bitField0_ & ~0x00000001);
dimensionsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getDimensionsFieldBuilder() : null;
} else {
dimensionsBuilder_.addAllMessages(other.dimensions_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
com.google.ads.googleads.v19.resources.ListingGroupFilterDimension m =
input.readMessage(
com.google.ads.googleads.v19.resources.ListingGroupFilterDimension.parser(),
extensionRegistry);
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.add(m);
} else {
dimensionsBuilder_.addMessage(m);
}
break;
} // case 10
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.ads.googleads.v19.resources.ListingGroupFilterDimension> dimensions_ =
java.util.Collections.emptyList();
private void ensureDimensionsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
dimensions_ = new java.util.ArrayList<com.google.ads.googleads.v19.resources.ListingGroupFilterDimension>(dimensions_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v19.resources.ListingGroupFilterDimension, com.google.ads.googleads.v19.resources.ListingGroupFilterDimension.Builder, com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionOrBuilder> dimensionsBuilder_;
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public java.util.List<com.google.ads.googleads.v19.resources.ListingGroupFilterDimension> getDimensionsList() {
if (dimensionsBuilder_ == null) {
return java.util.Collections.unmodifiableList(dimensions_);
} else {
return dimensionsBuilder_.getMessageList();
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public int getDimensionsCount() {
if (dimensionsBuilder_ == null) {
return dimensions_.size();
} else {
return dimensionsBuilder_.getCount();
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v19.resources.ListingGroupFilterDimension getDimensions(int index) {
if (dimensionsBuilder_ == null) {
return dimensions_.get(index);
} else {
return dimensionsBuilder_.getMessage(index);
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder setDimensions(
int index, com.google.ads.googleads.v19.resources.ListingGroupFilterDimension value) {
if (dimensionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDimensionsIsMutable();
dimensions_.set(index, value);
onChanged();
} else {
dimensionsBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder setDimensions(
int index, com.google.ads.googleads.v19.resources.ListingGroupFilterDimension.Builder builderForValue) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.set(index, builderForValue.build());
onChanged();
} else {
dimensionsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addDimensions(com.google.ads.googleads.v19.resources.ListingGroupFilterDimension value) {
if (dimensionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDimensionsIsMutable();
dimensions_.add(value);
onChanged();
} else {
dimensionsBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addDimensions(
int index, com.google.ads.googleads.v19.resources.ListingGroupFilterDimension value) {
if (dimensionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDimensionsIsMutable();
dimensions_.add(index, value);
onChanged();
} else {
dimensionsBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addDimensions(
com.google.ads.googleads.v19.resources.ListingGroupFilterDimension.Builder builderForValue) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.add(builderForValue.build());
onChanged();
} else {
dimensionsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addDimensions(
int index, com.google.ads.googleads.v19.resources.ListingGroupFilterDimension.Builder builderForValue) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.add(index, builderForValue.build());
onChanged();
} else {
dimensionsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addAllDimensions(
java.lang.Iterable<? extends com.google.ads.googleads.v19.resources.ListingGroupFilterDimension> values) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, dimensions_);
onChanged();
} else {
dimensionsBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder clearDimensions() {
if (dimensionsBuilder_ == null) {
dimensions_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
dimensionsBuilder_.clear();
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder removeDimensions(int index) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.remove(index);
onChanged();
} else {
dimensionsBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v19.resources.ListingGroupFilterDimension.Builder getDimensionsBuilder(
int index) {
return getDimensionsFieldBuilder().getBuilder(index);
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionOrBuilder getDimensionsOrBuilder(
int index) {
if (dimensionsBuilder_ == null) {
return dimensions_.get(index); } else {
return dimensionsBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public java.util.List<? extends com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionOrBuilder>
getDimensionsOrBuilderList() {
if (dimensionsBuilder_ != null) {
return dimensionsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(dimensions_);
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v19.resources.ListingGroupFilterDimension.Builder addDimensionsBuilder() {
return getDimensionsFieldBuilder().addBuilder(
com.google.ads.googleads.v19.resources.ListingGroupFilterDimension.getDefaultInstance());
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v19.resources.ListingGroupFilterDimension.Builder addDimensionsBuilder(
int index) {
return getDimensionsFieldBuilder().addBuilder(
index, com.google.ads.googleads.v19.resources.ListingGroupFilterDimension.getDefaultInstance());
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public java.util.List<com.google.ads.googleads.v19.resources.ListingGroupFilterDimension.Builder>
getDimensionsBuilderList() {
return getDimensionsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v19.resources.ListingGroupFilterDimension, com.google.ads.googleads.v19.resources.ListingGroupFilterDimension.Builder, com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionOrBuilder>
getDimensionsFieldBuilder() {
if (dimensionsBuilder_ == null) {
dimensionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v19.resources.ListingGroupFilterDimension, com.google.ads.googleads.v19.resources.ListingGroupFilterDimension.Builder, com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionOrBuilder>(
dimensions_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
dimensions_ = null;
}
return dimensionsBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath)
private static final com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath();
}
public static com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListingGroupFilterDimensionPath>
PARSER = new com.google.protobuf.AbstractParser<ListingGroupFilterDimensionPath>() {
@java.lang.Override
public ListingGroupFilterDimensionPath 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<ListingGroupFilterDimensionPath> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListingGroupFilterDimensionPath> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v19.resources.ListingGroupFilterDimensionPath getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 35,957 | google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/resources/ListingGroupFilterDimensionPath.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v20/resources/asset_group_listing_group_filter.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v20.resources;
/**
* <pre>
* The path defining of dimensions defining a listing group filter.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath}
*/
public final class ListingGroupFilterDimensionPath extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath)
ListingGroupFilterDimensionPathOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListingGroupFilterDimensionPath.newBuilder() to construct.
private ListingGroupFilterDimensionPath(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListingGroupFilterDimensionPath() {
dimensions_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new ListingGroupFilterDimensionPath();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v20_resources_ListingGroupFilterDimensionPath_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v20_resources_ListingGroupFilterDimensionPath_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath.class, com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath.Builder.class);
}
public static final int DIMENSIONS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.ads.googleads.v20.resources.ListingGroupFilterDimension> dimensions_;
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.util.List<com.google.ads.googleads.v20.resources.ListingGroupFilterDimension> getDimensionsList() {
return dimensions_;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionOrBuilder>
getDimensionsOrBuilderList() {
return dimensions_;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public int getDimensionsCount() {
return dimensions_.size();
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v20.resources.ListingGroupFilterDimension getDimensions(int index) {
return dimensions_.get(index);
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionOrBuilder getDimensionsOrBuilder(
int index) {
return dimensions_.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 < dimensions_.size(); i++) {
output.writeMessage(1, dimensions_.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 < dimensions_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, dimensions_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath)) {
return super.equals(obj);
}
com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath other = (com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath) obj;
if (!getDimensionsList()
.equals(other.getDimensionsList())) 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 (getDimensionsCount() > 0) {
hash = (37 * hash) + DIMENSIONS_FIELD_NUMBER;
hash = (53 * hash) + getDimensionsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath 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 path defining of dimensions defining a listing group filter.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath)
com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPathOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v20_resources_ListingGroupFilterDimensionPath_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v20_resources_ListingGroupFilterDimensionPath_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath.class, com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath.Builder.class);
}
// Construct using com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (dimensionsBuilder_ == null) {
dimensions_ = java.util.Collections.emptyList();
} else {
dimensions_ = null;
dimensionsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v20.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v20_resources_ListingGroupFilterDimensionPath_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath getDefaultInstanceForType() {
return com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath build() {
com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath buildPartial() {
com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath result = new com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartialRepeatedFields(com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath result) {
if (dimensionsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
dimensions_ = java.util.Collections.unmodifiableList(dimensions_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.dimensions_ = dimensions_;
} else {
result.dimensions_ = dimensionsBuilder_.build();
}
}
private void buildPartial0(com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath result) {
int from_bitField0_ = bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath) {
return mergeFrom((com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath other) {
if (other == com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath.getDefaultInstance()) return this;
if (dimensionsBuilder_ == null) {
if (!other.dimensions_.isEmpty()) {
if (dimensions_.isEmpty()) {
dimensions_ = other.dimensions_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureDimensionsIsMutable();
dimensions_.addAll(other.dimensions_);
}
onChanged();
}
} else {
if (!other.dimensions_.isEmpty()) {
if (dimensionsBuilder_.isEmpty()) {
dimensionsBuilder_.dispose();
dimensionsBuilder_ = null;
dimensions_ = other.dimensions_;
bitField0_ = (bitField0_ & ~0x00000001);
dimensionsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getDimensionsFieldBuilder() : null;
} else {
dimensionsBuilder_.addAllMessages(other.dimensions_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
com.google.ads.googleads.v20.resources.ListingGroupFilterDimension m =
input.readMessage(
com.google.ads.googleads.v20.resources.ListingGroupFilterDimension.parser(),
extensionRegistry);
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.add(m);
} else {
dimensionsBuilder_.addMessage(m);
}
break;
} // case 10
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.ads.googleads.v20.resources.ListingGroupFilterDimension> dimensions_ =
java.util.Collections.emptyList();
private void ensureDimensionsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
dimensions_ = new java.util.ArrayList<com.google.ads.googleads.v20.resources.ListingGroupFilterDimension>(dimensions_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v20.resources.ListingGroupFilterDimension, com.google.ads.googleads.v20.resources.ListingGroupFilterDimension.Builder, com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionOrBuilder> dimensionsBuilder_;
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public java.util.List<com.google.ads.googleads.v20.resources.ListingGroupFilterDimension> getDimensionsList() {
if (dimensionsBuilder_ == null) {
return java.util.Collections.unmodifiableList(dimensions_);
} else {
return dimensionsBuilder_.getMessageList();
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public int getDimensionsCount() {
if (dimensionsBuilder_ == null) {
return dimensions_.size();
} else {
return dimensionsBuilder_.getCount();
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v20.resources.ListingGroupFilterDimension getDimensions(int index) {
if (dimensionsBuilder_ == null) {
return dimensions_.get(index);
} else {
return dimensionsBuilder_.getMessage(index);
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder setDimensions(
int index, com.google.ads.googleads.v20.resources.ListingGroupFilterDimension value) {
if (dimensionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDimensionsIsMutable();
dimensions_.set(index, value);
onChanged();
} else {
dimensionsBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder setDimensions(
int index, com.google.ads.googleads.v20.resources.ListingGroupFilterDimension.Builder builderForValue) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.set(index, builderForValue.build());
onChanged();
} else {
dimensionsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addDimensions(com.google.ads.googleads.v20.resources.ListingGroupFilterDimension value) {
if (dimensionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDimensionsIsMutable();
dimensions_.add(value);
onChanged();
} else {
dimensionsBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addDimensions(
int index, com.google.ads.googleads.v20.resources.ListingGroupFilterDimension value) {
if (dimensionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDimensionsIsMutable();
dimensions_.add(index, value);
onChanged();
} else {
dimensionsBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addDimensions(
com.google.ads.googleads.v20.resources.ListingGroupFilterDimension.Builder builderForValue) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.add(builderForValue.build());
onChanged();
} else {
dimensionsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addDimensions(
int index, com.google.ads.googleads.v20.resources.ListingGroupFilterDimension.Builder builderForValue) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.add(index, builderForValue.build());
onChanged();
} else {
dimensionsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addAllDimensions(
java.lang.Iterable<? extends com.google.ads.googleads.v20.resources.ListingGroupFilterDimension> values) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, dimensions_);
onChanged();
} else {
dimensionsBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder clearDimensions() {
if (dimensionsBuilder_ == null) {
dimensions_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
dimensionsBuilder_.clear();
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder removeDimensions(int index) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.remove(index);
onChanged();
} else {
dimensionsBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v20.resources.ListingGroupFilterDimension.Builder getDimensionsBuilder(
int index) {
return getDimensionsFieldBuilder().getBuilder(index);
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionOrBuilder getDimensionsOrBuilder(
int index) {
if (dimensionsBuilder_ == null) {
return dimensions_.get(index); } else {
return dimensionsBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public java.util.List<? extends com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionOrBuilder>
getDimensionsOrBuilderList() {
if (dimensionsBuilder_ != null) {
return dimensionsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(dimensions_);
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v20.resources.ListingGroupFilterDimension.Builder addDimensionsBuilder() {
return getDimensionsFieldBuilder().addBuilder(
com.google.ads.googleads.v20.resources.ListingGroupFilterDimension.getDefaultInstance());
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v20.resources.ListingGroupFilterDimension.Builder addDimensionsBuilder(
int index) {
return getDimensionsFieldBuilder().addBuilder(
index, com.google.ads.googleads.v20.resources.ListingGroupFilterDimension.getDefaultInstance());
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public java.util.List<com.google.ads.googleads.v20.resources.ListingGroupFilterDimension.Builder>
getDimensionsBuilderList() {
return getDimensionsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v20.resources.ListingGroupFilterDimension, com.google.ads.googleads.v20.resources.ListingGroupFilterDimension.Builder, com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionOrBuilder>
getDimensionsFieldBuilder() {
if (dimensionsBuilder_ == null) {
dimensionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v20.resources.ListingGroupFilterDimension, com.google.ads.googleads.v20.resources.ListingGroupFilterDimension.Builder, com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionOrBuilder>(
dimensions_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
dimensions_ = null;
}
return dimensionsBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath)
private static final com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath();
}
public static com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListingGroupFilterDimensionPath>
PARSER = new com.google.protobuf.AbstractParser<ListingGroupFilterDimensionPath>() {
@java.lang.Override
public ListingGroupFilterDimensionPath 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<ListingGroupFilterDimensionPath> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListingGroupFilterDimensionPath> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v20.resources.ListingGroupFilterDimensionPath getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 35,957 | google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/resources/ListingGroupFilterDimensionPath.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v21/resources/asset_group_listing_group_filter.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v21.resources;
/**
* <pre>
* The path defining of dimensions defining a listing group filter.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath}
*/
public final class ListingGroupFilterDimensionPath extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath)
ListingGroupFilterDimensionPathOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListingGroupFilterDimensionPath.newBuilder() to construct.
private ListingGroupFilterDimensionPath(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListingGroupFilterDimensionPath() {
dimensions_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new ListingGroupFilterDimensionPath();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v21_resources_ListingGroupFilterDimensionPath_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v21_resources_ListingGroupFilterDimensionPath_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath.class, com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath.Builder.class);
}
public static final int DIMENSIONS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.ads.googleads.v21.resources.ListingGroupFilterDimension> dimensions_;
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.util.List<com.google.ads.googleads.v21.resources.ListingGroupFilterDimension> getDimensionsList() {
return dimensions_;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionOrBuilder>
getDimensionsOrBuilderList() {
return dimensions_;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public int getDimensionsCount() {
return dimensions_.size();
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v21.resources.ListingGroupFilterDimension getDimensions(int index) {
return dimensions_.get(index);
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionOrBuilder getDimensionsOrBuilder(
int index) {
return dimensions_.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 < dimensions_.size(); i++) {
output.writeMessage(1, dimensions_.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 < dimensions_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, dimensions_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath)) {
return super.equals(obj);
}
com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath other = (com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath) obj;
if (!getDimensionsList()
.equals(other.getDimensionsList())) 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 (getDimensionsCount() > 0) {
hash = (37 * hash) + DIMENSIONS_FIELD_NUMBER;
hash = (53 * hash) + getDimensionsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath 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 path defining of dimensions defining a listing group filter.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath)
com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPathOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v21_resources_ListingGroupFilterDimensionPath_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v21_resources_ListingGroupFilterDimensionPath_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath.class, com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath.Builder.class);
}
// Construct using com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (dimensionsBuilder_ == null) {
dimensions_ = java.util.Collections.emptyList();
} else {
dimensions_ = null;
dimensionsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v21.resources.AssetGroupListingGroupFilterProto.internal_static_google_ads_googleads_v21_resources_ListingGroupFilterDimensionPath_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath getDefaultInstanceForType() {
return com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath build() {
com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath buildPartial() {
com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath result = new com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartialRepeatedFields(com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath result) {
if (dimensionsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
dimensions_ = java.util.Collections.unmodifiableList(dimensions_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.dimensions_ = dimensions_;
} else {
result.dimensions_ = dimensionsBuilder_.build();
}
}
private void buildPartial0(com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath result) {
int from_bitField0_ = bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath) {
return mergeFrom((com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath other) {
if (other == com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath.getDefaultInstance()) return this;
if (dimensionsBuilder_ == null) {
if (!other.dimensions_.isEmpty()) {
if (dimensions_.isEmpty()) {
dimensions_ = other.dimensions_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureDimensionsIsMutable();
dimensions_.addAll(other.dimensions_);
}
onChanged();
}
} else {
if (!other.dimensions_.isEmpty()) {
if (dimensionsBuilder_.isEmpty()) {
dimensionsBuilder_.dispose();
dimensionsBuilder_ = null;
dimensions_ = other.dimensions_;
bitField0_ = (bitField0_ & ~0x00000001);
dimensionsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getDimensionsFieldBuilder() : null;
} else {
dimensionsBuilder_.addAllMessages(other.dimensions_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
com.google.ads.googleads.v21.resources.ListingGroupFilterDimension m =
input.readMessage(
com.google.ads.googleads.v21.resources.ListingGroupFilterDimension.parser(),
extensionRegistry);
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.add(m);
} else {
dimensionsBuilder_.addMessage(m);
}
break;
} // case 10
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.ads.googleads.v21.resources.ListingGroupFilterDimension> dimensions_ =
java.util.Collections.emptyList();
private void ensureDimensionsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
dimensions_ = new java.util.ArrayList<com.google.ads.googleads.v21.resources.ListingGroupFilterDimension>(dimensions_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v21.resources.ListingGroupFilterDimension, com.google.ads.googleads.v21.resources.ListingGroupFilterDimension.Builder, com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionOrBuilder> dimensionsBuilder_;
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public java.util.List<com.google.ads.googleads.v21.resources.ListingGroupFilterDimension> getDimensionsList() {
if (dimensionsBuilder_ == null) {
return java.util.Collections.unmodifiableList(dimensions_);
} else {
return dimensionsBuilder_.getMessageList();
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public int getDimensionsCount() {
if (dimensionsBuilder_ == null) {
return dimensions_.size();
} else {
return dimensionsBuilder_.getCount();
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v21.resources.ListingGroupFilterDimension getDimensions(int index) {
if (dimensionsBuilder_ == null) {
return dimensions_.get(index);
} else {
return dimensionsBuilder_.getMessage(index);
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder setDimensions(
int index, com.google.ads.googleads.v21.resources.ListingGroupFilterDimension value) {
if (dimensionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDimensionsIsMutable();
dimensions_.set(index, value);
onChanged();
} else {
dimensionsBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder setDimensions(
int index, com.google.ads.googleads.v21.resources.ListingGroupFilterDimension.Builder builderForValue) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.set(index, builderForValue.build());
onChanged();
} else {
dimensionsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addDimensions(com.google.ads.googleads.v21.resources.ListingGroupFilterDimension value) {
if (dimensionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDimensionsIsMutable();
dimensions_.add(value);
onChanged();
} else {
dimensionsBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addDimensions(
int index, com.google.ads.googleads.v21.resources.ListingGroupFilterDimension value) {
if (dimensionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDimensionsIsMutable();
dimensions_.add(index, value);
onChanged();
} else {
dimensionsBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addDimensions(
com.google.ads.googleads.v21.resources.ListingGroupFilterDimension.Builder builderForValue) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.add(builderForValue.build());
onChanged();
} else {
dimensionsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addDimensions(
int index, com.google.ads.googleads.v21.resources.ListingGroupFilterDimension.Builder builderForValue) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.add(index, builderForValue.build());
onChanged();
} else {
dimensionsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder addAllDimensions(
java.lang.Iterable<? extends com.google.ads.googleads.v21.resources.ListingGroupFilterDimension> values) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, dimensions_);
onChanged();
} else {
dimensionsBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder clearDimensions() {
if (dimensionsBuilder_ == null) {
dimensions_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
dimensionsBuilder_.clear();
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder removeDimensions(int index) {
if (dimensionsBuilder_ == null) {
ensureDimensionsIsMutable();
dimensions_.remove(index);
onChanged();
} else {
dimensionsBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v21.resources.ListingGroupFilterDimension.Builder getDimensionsBuilder(
int index) {
return getDimensionsFieldBuilder().getBuilder(index);
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionOrBuilder getDimensionsOrBuilder(
int index) {
if (dimensionsBuilder_ == null) {
return dimensions_.get(index); } else {
return dimensionsBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public java.util.List<? extends com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionOrBuilder>
getDimensionsOrBuilderList() {
if (dimensionsBuilder_ != null) {
return dimensionsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(dimensions_);
}
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v21.resources.ListingGroupFilterDimension.Builder addDimensionsBuilder() {
return getDimensionsFieldBuilder().addBuilder(
com.google.ads.googleads.v21.resources.ListingGroupFilterDimension.getDefaultInstance());
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public com.google.ads.googleads.v21.resources.ListingGroupFilterDimension.Builder addDimensionsBuilder(
int index) {
return getDimensionsFieldBuilder().addBuilder(
index, com.google.ads.googleads.v21.resources.ListingGroupFilterDimension.getDefaultInstance());
}
/**
* <pre>
* Output only. The complete path of dimensions through the listing group
* filter hierarchy (excluding the root node) to this listing group filter.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.resources.ListingGroupFilterDimension dimensions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public java.util.List<com.google.ads.googleads.v21.resources.ListingGroupFilterDimension.Builder>
getDimensionsBuilderList() {
return getDimensionsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v21.resources.ListingGroupFilterDimension, com.google.ads.googleads.v21.resources.ListingGroupFilterDimension.Builder, com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionOrBuilder>
getDimensionsFieldBuilder() {
if (dimensionsBuilder_ == null) {
dimensionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v21.resources.ListingGroupFilterDimension, com.google.ads.googleads.v21.resources.ListingGroupFilterDimension.Builder, com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionOrBuilder>(
dimensions_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
dimensions_ = null;
}
return dimensionsBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath)
private static final com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath();
}
public static com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListingGroupFilterDimensionPath>
PARSER = new com.google.protobuf.AbstractParser<ListingGroupFilterDimensionPath>() {
@java.lang.Override
public ListingGroupFilterDimensionPath 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<ListingGroupFilterDimensionPath> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListingGroupFilterDimensionPath> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v21.resources.ListingGroupFilterDimensionPath getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,653 | java-appengine-admin/proto-google-cloud-appengine-admin-v1/src/main/java/com/google/appengine/v1/ListAuthorizedDomainsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/appengine/v1/appengine.proto
// Protobuf Java Version: 3.25.8
package com.google.appengine.v1;
/**
*
*
* <pre>
* Response message for `AuthorizedDomains.ListAuthorizedDomains`.
* </pre>
*
* Protobuf type {@code google.appengine.v1.ListAuthorizedDomainsResponse}
*/
public final class ListAuthorizedDomainsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.appengine.v1.ListAuthorizedDomainsResponse)
ListAuthorizedDomainsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListAuthorizedDomainsResponse.newBuilder() to construct.
private ListAuthorizedDomainsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListAuthorizedDomainsResponse() {
domains_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListAuthorizedDomainsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListAuthorizedDomainsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListAuthorizedDomainsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.appengine.v1.ListAuthorizedDomainsResponse.class,
com.google.appengine.v1.ListAuthorizedDomainsResponse.Builder.class);
}
public static final int DOMAINS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.appengine.v1.AuthorizedDomain> domains_;
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.appengine.v1.AuthorizedDomain> getDomainsList() {
return domains_;
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.appengine.v1.AuthorizedDomainOrBuilder>
getDomainsOrBuilderList() {
return domains_;
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
@java.lang.Override
public int getDomainsCount() {
return domains_.size();
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
@java.lang.Override
public com.google.appengine.v1.AuthorizedDomain getDomains(int index) {
return domains_.get(index);
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
@java.lang.Override
public com.google.appengine.v1.AuthorizedDomainOrBuilder getDomainsOrBuilder(int index) {
return domains_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < domains_.size(); i++) {
output.writeMessage(1, domains_.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 < domains_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, domains_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.appengine.v1.ListAuthorizedDomainsResponse)) {
return super.equals(obj);
}
com.google.appengine.v1.ListAuthorizedDomainsResponse other =
(com.google.appengine.v1.ListAuthorizedDomainsResponse) obj;
if (!getDomainsList().equals(other.getDomainsList())) 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 (getDomainsCount() > 0) {
hash = (37 * hash) + DOMAINS_FIELD_NUMBER;
hash = (53 * hash) + getDomainsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.appengine.v1.ListAuthorizedDomainsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.appengine.v1.ListAuthorizedDomainsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.appengine.v1.ListAuthorizedDomainsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.appengine.v1.ListAuthorizedDomainsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.appengine.v1.ListAuthorizedDomainsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.appengine.v1.ListAuthorizedDomainsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.appengine.v1.ListAuthorizedDomainsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.appengine.v1.ListAuthorizedDomainsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.appengine.v1.ListAuthorizedDomainsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.appengine.v1.ListAuthorizedDomainsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.appengine.v1.ListAuthorizedDomainsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.appengine.v1.ListAuthorizedDomainsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.appengine.v1.ListAuthorizedDomainsResponse 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 `AuthorizedDomains.ListAuthorizedDomains`.
* </pre>
*
* Protobuf type {@code google.appengine.v1.ListAuthorizedDomainsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.appengine.v1.ListAuthorizedDomainsResponse)
com.google.appengine.v1.ListAuthorizedDomainsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListAuthorizedDomainsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListAuthorizedDomainsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.appengine.v1.ListAuthorizedDomainsResponse.class,
com.google.appengine.v1.ListAuthorizedDomainsResponse.Builder.class);
}
// Construct using com.google.appengine.v1.ListAuthorizedDomainsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (domainsBuilder_ == null) {
domains_ = java.util.Collections.emptyList();
} else {
domains_ = null;
domainsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListAuthorizedDomainsResponse_descriptor;
}
@java.lang.Override
public com.google.appengine.v1.ListAuthorizedDomainsResponse getDefaultInstanceForType() {
return com.google.appengine.v1.ListAuthorizedDomainsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.appengine.v1.ListAuthorizedDomainsResponse build() {
com.google.appengine.v1.ListAuthorizedDomainsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.appengine.v1.ListAuthorizedDomainsResponse buildPartial() {
com.google.appengine.v1.ListAuthorizedDomainsResponse result =
new com.google.appengine.v1.ListAuthorizedDomainsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.appengine.v1.ListAuthorizedDomainsResponse result) {
if (domainsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
domains_ = java.util.Collections.unmodifiableList(domains_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.domains_ = domains_;
} else {
result.domains_ = domainsBuilder_.build();
}
}
private void buildPartial0(com.google.appengine.v1.ListAuthorizedDomainsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.appengine.v1.ListAuthorizedDomainsResponse) {
return mergeFrom((com.google.appengine.v1.ListAuthorizedDomainsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.appengine.v1.ListAuthorizedDomainsResponse other) {
if (other == com.google.appengine.v1.ListAuthorizedDomainsResponse.getDefaultInstance())
return this;
if (domainsBuilder_ == null) {
if (!other.domains_.isEmpty()) {
if (domains_.isEmpty()) {
domains_ = other.domains_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureDomainsIsMutable();
domains_.addAll(other.domains_);
}
onChanged();
}
} else {
if (!other.domains_.isEmpty()) {
if (domainsBuilder_.isEmpty()) {
domainsBuilder_.dispose();
domainsBuilder_ = null;
domains_ = other.domains_;
bitField0_ = (bitField0_ & ~0x00000001);
domainsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getDomainsFieldBuilder()
: null;
} else {
domainsBuilder_.addAllMessages(other.domains_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.appengine.v1.AuthorizedDomain m =
input.readMessage(
com.google.appengine.v1.AuthorizedDomain.parser(), extensionRegistry);
if (domainsBuilder_ == null) {
ensureDomainsIsMutable();
domains_.add(m);
} else {
domainsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.appengine.v1.AuthorizedDomain> domains_ =
java.util.Collections.emptyList();
private void ensureDomainsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
domains_ = new java.util.ArrayList<com.google.appengine.v1.AuthorizedDomain>(domains_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.appengine.v1.AuthorizedDomain,
com.google.appengine.v1.AuthorizedDomain.Builder,
com.google.appengine.v1.AuthorizedDomainOrBuilder>
domainsBuilder_;
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public java.util.List<com.google.appengine.v1.AuthorizedDomain> getDomainsList() {
if (domainsBuilder_ == null) {
return java.util.Collections.unmodifiableList(domains_);
} else {
return domainsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public int getDomainsCount() {
if (domainsBuilder_ == null) {
return domains_.size();
} else {
return domainsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public com.google.appengine.v1.AuthorizedDomain getDomains(int index) {
if (domainsBuilder_ == null) {
return domains_.get(index);
} else {
return domainsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public Builder setDomains(int index, com.google.appengine.v1.AuthorizedDomain value) {
if (domainsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDomainsIsMutable();
domains_.set(index, value);
onChanged();
} else {
domainsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public Builder setDomains(
int index, com.google.appengine.v1.AuthorizedDomain.Builder builderForValue) {
if (domainsBuilder_ == null) {
ensureDomainsIsMutable();
domains_.set(index, builderForValue.build());
onChanged();
} else {
domainsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public Builder addDomains(com.google.appengine.v1.AuthorizedDomain value) {
if (domainsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDomainsIsMutable();
domains_.add(value);
onChanged();
} else {
domainsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public Builder addDomains(int index, com.google.appengine.v1.AuthorizedDomain value) {
if (domainsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDomainsIsMutable();
domains_.add(index, value);
onChanged();
} else {
domainsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public Builder addDomains(com.google.appengine.v1.AuthorizedDomain.Builder builderForValue) {
if (domainsBuilder_ == null) {
ensureDomainsIsMutable();
domains_.add(builderForValue.build());
onChanged();
} else {
domainsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public Builder addDomains(
int index, com.google.appengine.v1.AuthorizedDomain.Builder builderForValue) {
if (domainsBuilder_ == null) {
ensureDomainsIsMutable();
domains_.add(index, builderForValue.build());
onChanged();
} else {
domainsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public Builder addAllDomains(
java.lang.Iterable<? extends com.google.appengine.v1.AuthorizedDomain> values) {
if (domainsBuilder_ == null) {
ensureDomainsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, domains_);
onChanged();
} else {
domainsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public Builder clearDomains() {
if (domainsBuilder_ == null) {
domains_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
domainsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public Builder removeDomains(int index) {
if (domainsBuilder_ == null) {
ensureDomainsIsMutable();
domains_.remove(index);
onChanged();
} else {
domainsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public com.google.appengine.v1.AuthorizedDomain.Builder getDomainsBuilder(int index) {
return getDomainsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public com.google.appengine.v1.AuthorizedDomainOrBuilder getDomainsOrBuilder(int index) {
if (domainsBuilder_ == null) {
return domains_.get(index);
} else {
return domainsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public java.util.List<? extends com.google.appengine.v1.AuthorizedDomainOrBuilder>
getDomainsOrBuilderList() {
if (domainsBuilder_ != null) {
return domainsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(domains_);
}
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public com.google.appengine.v1.AuthorizedDomain.Builder addDomainsBuilder() {
return getDomainsFieldBuilder()
.addBuilder(com.google.appengine.v1.AuthorizedDomain.getDefaultInstance());
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public com.google.appengine.v1.AuthorizedDomain.Builder addDomainsBuilder(int index) {
return getDomainsFieldBuilder()
.addBuilder(index, com.google.appengine.v1.AuthorizedDomain.getDefaultInstance());
}
/**
*
*
* <pre>
* The authorized domains belonging to the user.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedDomain domains = 1;</code>
*/
public java.util.List<com.google.appengine.v1.AuthorizedDomain.Builder>
getDomainsBuilderList() {
return getDomainsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.appengine.v1.AuthorizedDomain,
com.google.appengine.v1.AuthorizedDomain.Builder,
com.google.appengine.v1.AuthorizedDomainOrBuilder>
getDomainsFieldBuilder() {
if (domainsBuilder_ == null) {
domainsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.appengine.v1.AuthorizedDomain,
com.google.appengine.v1.AuthorizedDomain.Builder,
com.google.appengine.v1.AuthorizedDomainOrBuilder>(
domains_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
domains_ = null;
}
return domainsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.appengine.v1.ListAuthorizedDomainsResponse)
}
// @@protoc_insertion_point(class_scope:google.appengine.v1.ListAuthorizedDomainsResponse)
private static final com.google.appengine.v1.ListAuthorizedDomainsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.appengine.v1.ListAuthorizedDomainsResponse();
}
public static com.google.appengine.v1.ListAuthorizedDomainsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListAuthorizedDomainsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListAuthorizedDomainsResponse>() {
@java.lang.Override
public ListAuthorizedDomainsResponse 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<ListAuthorizedDomainsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListAuthorizedDomainsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.appengine.v1.ListAuthorizedDomainsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,739 | java-api-gateway/proto-google-cloud-api-gateway-v1/src/main/java/com/google/cloud/apigateway/v1/UpdateApiConfigRequest.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/apigateway/v1/apigateway.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.apigateway.v1;
/**
*
*
* <pre>
* Request message for ApiGatewayService.UpdateApiConfig
* </pre>
*
* Protobuf type {@code google.cloud.apigateway.v1.UpdateApiConfigRequest}
*/
public final class UpdateApiConfigRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.apigateway.v1.UpdateApiConfigRequest)
UpdateApiConfigRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateApiConfigRequest.newBuilder() to construct.
private UpdateApiConfigRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateApiConfigRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateApiConfigRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_UpdateApiConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_UpdateApiConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.apigateway.v1.UpdateApiConfigRequest.class,
com.google.cloud.apigateway.v1.UpdateApiConfigRequest.Builder.class);
}
private int bitField0_;
public static final int UPDATE_MASK_FIELD_NUMBER = 1;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* ApiConfig 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;</code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* ApiConfig 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;</code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* ApiConfig 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;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
public static final int API_CONFIG_FIELD_NUMBER = 2;
private com.google.cloud.apigateway.v1.ApiConfig apiConfig_;
/**
*
*
* <pre>
* Required. API Config resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.ApiConfig api_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the apiConfig field is set.
*/
@java.lang.Override
public boolean hasApiConfig() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. API Config resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.ApiConfig api_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The apiConfig.
*/
@java.lang.Override
public com.google.cloud.apigateway.v1.ApiConfig getApiConfig() {
return apiConfig_ == null
? com.google.cloud.apigateway.v1.ApiConfig.getDefaultInstance()
: apiConfig_;
}
/**
*
*
* <pre>
* Required. API Config resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.ApiConfig api_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.apigateway.v1.ApiConfigOrBuilder getApiConfigOrBuilder() {
return apiConfig_ == null
? com.google.cloud.apigateway.v1.ApiConfig.getDefaultInstance()
: apiConfig_;
}
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, getApiConfig());
}
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, getApiConfig());
}
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.apigateway.v1.UpdateApiConfigRequest)) {
return super.equals(obj);
}
com.google.cloud.apigateway.v1.UpdateApiConfigRequest other =
(com.google.cloud.apigateway.v1.UpdateApiConfigRequest) obj;
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (hasApiConfig() != other.hasApiConfig()) return false;
if (hasApiConfig()) {
if (!getApiConfig().equals(other.getApiConfig())) 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 (hasApiConfig()) {
hash = (37 * hash) + API_CONFIG_FIELD_NUMBER;
hash = (53 * hash) + getApiConfig().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.apigateway.v1.UpdateApiConfigRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigateway.v1.UpdateApiConfigRequest 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.apigateway.v1.UpdateApiConfigRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigateway.v1.UpdateApiConfigRequest 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.apigateway.v1.UpdateApiConfigRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigateway.v1.UpdateApiConfigRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.apigateway.v1.UpdateApiConfigRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.apigateway.v1.UpdateApiConfigRequest 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.apigateway.v1.UpdateApiConfigRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.apigateway.v1.UpdateApiConfigRequest 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.apigateway.v1.UpdateApiConfigRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.apigateway.v1.UpdateApiConfigRequest 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.apigateway.v1.UpdateApiConfigRequest 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 ApiGatewayService.UpdateApiConfig
* </pre>
*
* Protobuf type {@code google.cloud.apigateway.v1.UpdateApiConfigRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.apigateway.v1.UpdateApiConfigRequest)
com.google.cloud.apigateway.v1.UpdateApiConfigRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_UpdateApiConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_UpdateApiConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.apigateway.v1.UpdateApiConfigRequest.class,
com.google.cloud.apigateway.v1.UpdateApiConfigRequest.Builder.class);
}
// Construct using com.google.cloud.apigateway.v1.UpdateApiConfigRequest.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();
getApiConfigFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
apiConfig_ = null;
if (apiConfigBuilder_ != null) {
apiConfigBuilder_.dispose();
apiConfigBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_UpdateApiConfigRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.apigateway.v1.UpdateApiConfigRequest getDefaultInstanceForType() {
return com.google.cloud.apigateway.v1.UpdateApiConfigRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.apigateway.v1.UpdateApiConfigRequest build() {
com.google.cloud.apigateway.v1.UpdateApiConfigRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.apigateway.v1.UpdateApiConfigRequest buildPartial() {
com.google.cloud.apigateway.v1.UpdateApiConfigRequest result =
new com.google.cloud.apigateway.v1.UpdateApiConfigRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.apigateway.v1.UpdateApiConfigRequest 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.apiConfig_ = apiConfigBuilder_ == null ? apiConfig_ : apiConfigBuilder_.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.apigateway.v1.UpdateApiConfigRequest) {
return mergeFrom((com.google.cloud.apigateway.v1.UpdateApiConfigRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.apigateway.v1.UpdateApiConfigRequest other) {
if (other == com.google.cloud.apigateway.v1.UpdateApiConfigRequest.getDefaultInstance())
return this;
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
if (other.hasApiConfig()) {
mergeApiConfig(other.getApiConfig());
}
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(getApiConfigFieldBuilder().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>
* Field mask is used to specify the fields to be overwritten in the
* ApiConfig 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;</code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* ApiConfig 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;</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>
* Field mask is used to specify the fields to be overwritten in the
* ApiConfig 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;</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>
* Field mask is used to specify the fields to be overwritten in the
* ApiConfig 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;</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>
* Field mask is used to specify the fields to be overwritten in the
* ApiConfig 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;</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>
* Field mask is used to specify the fields to be overwritten in the
* ApiConfig 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;</code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000001);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* ApiConfig 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;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* ApiConfig 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;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* ApiConfig 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;</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.apigateway.v1.ApiConfig apiConfig_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.apigateway.v1.ApiConfig,
com.google.cloud.apigateway.v1.ApiConfig.Builder,
com.google.cloud.apigateway.v1.ApiConfigOrBuilder>
apiConfigBuilder_;
/**
*
*
* <pre>
* Required. API Config resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.ApiConfig api_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the apiConfig field is set.
*/
public boolean hasApiConfig() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. API Config resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.ApiConfig api_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The apiConfig.
*/
public com.google.cloud.apigateway.v1.ApiConfig getApiConfig() {
if (apiConfigBuilder_ == null) {
return apiConfig_ == null
? com.google.cloud.apigateway.v1.ApiConfig.getDefaultInstance()
: apiConfig_;
} else {
return apiConfigBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. API Config resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.ApiConfig api_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setApiConfig(com.google.cloud.apigateway.v1.ApiConfig value) {
if (apiConfigBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
apiConfig_ = value;
} else {
apiConfigBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. API Config resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.ApiConfig api_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setApiConfig(com.google.cloud.apigateway.v1.ApiConfig.Builder builderForValue) {
if (apiConfigBuilder_ == null) {
apiConfig_ = builderForValue.build();
} else {
apiConfigBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. API Config resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.ApiConfig api_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeApiConfig(com.google.cloud.apigateway.v1.ApiConfig value) {
if (apiConfigBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& apiConfig_ != null
&& apiConfig_ != com.google.cloud.apigateway.v1.ApiConfig.getDefaultInstance()) {
getApiConfigBuilder().mergeFrom(value);
} else {
apiConfig_ = value;
}
} else {
apiConfigBuilder_.mergeFrom(value);
}
if (apiConfig_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. API Config resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.ApiConfig api_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearApiConfig() {
bitField0_ = (bitField0_ & ~0x00000002);
apiConfig_ = null;
if (apiConfigBuilder_ != null) {
apiConfigBuilder_.dispose();
apiConfigBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. API Config resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.ApiConfig api_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.apigateway.v1.ApiConfig.Builder getApiConfigBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getApiConfigFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. API Config resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.ApiConfig api_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.apigateway.v1.ApiConfigOrBuilder getApiConfigOrBuilder() {
if (apiConfigBuilder_ != null) {
return apiConfigBuilder_.getMessageOrBuilder();
} else {
return apiConfig_ == null
? com.google.cloud.apigateway.v1.ApiConfig.getDefaultInstance()
: apiConfig_;
}
}
/**
*
*
* <pre>
* Required. API Config resource.
* </pre>
*
* <code>
* .google.cloud.apigateway.v1.ApiConfig api_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.apigateway.v1.ApiConfig,
com.google.cloud.apigateway.v1.ApiConfig.Builder,
com.google.cloud.apigateway.v1.ApiConfigOrBuilder>
getApiConfigFieldBuilder() {
if (apiConfigBuilder_ == null) {
apiConfigBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.apigateway.v1.ApiConfig,
com.google.cloud.apigateway.v1.ApiConfig.Builder,
com.google.cloud.apigateway.v1.ApiConfigOrBuilder>(
getApiConfig(), getParentForChildren(), isClean());
apiConfig_ = null;
}
return apiConfigBuilder_;
}
@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.apigateway.v1.UpdateApiConfigRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.apigateway.v1.UpdateApiConfigRequest)
private static final com.google.cloud.apigateway.v1.UpdateApiConfigRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.apigateway.v1.UpdateApiConfigRequest();
}
public static com.google.cloud.apigateway.v1.UpdateApiConfigRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateApiConfigRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateApiConfigRequest>() {
@java.lang.Override
public UpdateApiConfigRequest 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<UpdateApiConfigRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateApiConfigRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.apigateway.v1.UpdateApiConfigRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,919 | java-discoveryengine/google-cloud-discoveryengine/src/main/java/com/google/cloud/discoveryengine/v1/stub/HttpJsonDataStoreServiceStub.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.discoveryengine.v1.stub;
import static com.google.cloud.discoveryengine.v1.DataStoreServiceClient.ListDataStoresPagedResponse;
import com.google.api.HttpRule;
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.httpjson.longrunning.stub.HttpJsonOperationsStub;
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.discoveryengine.v1.CreateDataStoreMetadata;
import com.google.cloud.discoveryengine.v1.CreateDataStoreRequest;
import com.google.cloud.discoveryengine.v1.DataStore;
import com.google.cloud.discoveryengine.v1.DeleteDataStoreMetadata;
import com.google.cloud.discoveryengine.v1.DeleteDataStoreRequest;
import com.google.cloud.discoveryengine.v1.GetDataStoreRequest;
import com.google.cloud.discoveryengine.v1.ListDataStoresRequest;
import com.google.cloud.discoveryengine.v1.ListDataStoresResponse;
import com.google.cloud.discoveryengine.v1.UpdateDataStoreRequest;
import com.google.common.collect.ImmutableMap;
import com.google.longrunning.Operation;
import com.google.protobuf.Empty;
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 DataStoreService service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@Generated("by gapic-generator-java")
public class HttpJsonDataStoreServiceStub extends DataStoreServiceStub {
private static final TypeRegistry typeRegistry =
TypeRegistry.newBuilder()
.add(DeleteDataStoreMetadata.getDescriptor())
.add(Empty.getDescriptor())
.add(DataStore.getDescriptor())
.add(CreateDataStoreMetadata.getDescriptor())
.build();
private static final ApiMethodDescriptor<CreateDataStoreRequest, Operation>
createDataStoreMethodDescriptor =
ApiMethodDescriptor.<CreateDataStoreRequest, Operation>newBuilder()
.setFullMethodName("google.cloud.discoveryengine.v1.DataStoreService/CreateDataStore")
.setHttpMethod("POST")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<CreateDataStoreRequest>newBuilder()
.setPath(
"/v1/{parent=projects/*/locations/*}/dataStores",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<CreateDataStoreRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "parent", request.getParent());
return fields;
})
.setAdditionalPaths(
"/v1/{parent=projects/*/locations/*/collections/*}/dataStores")
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<CreateDataStoreRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(
fields, "cmekConfigName", request.getCmekConfigName());
serializer.putQueryParam(
fields,
"createAdvancedSiteSearch",
request.getCreateAdvancedSiteSearch());
serializer.putQueryParam(
fields, "dataStoreId", request.getDataStoreId());
serializer.putQueryParam(
fields, "disableCmek", request.getDisableCmek());
serializer.putQueryParam(
fields,
"skipDefaultSchemaCreation",
request.getSkipDefaultSchemaCreation());
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(
request ->
ProtoRestSerializer.create()
.toBody("dataStore", request.getDataStore(), true))
.build())
.setResponseParser(
ProtoMessageResponseParser.<Operation>newBuilder()
.setDefaultInstance(Operation.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.setOperationSnapshotFactory(
(CreateDataStoreRequest request, Operation response) ->
HttpJsonOperationSnapshot.create(response))
.build();
private static final ApiMethodDescriptor<GetDataStoreRequest, DataStore>
getDataStoreMethodDescriptor =
ApiMethodDescriptor.<GetDataStoreRequest, DataStore>newBuilder()
.setFullMethodName("google.cloud.discoveryengine.v1.DataStoreService/GetDataStore")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<GetDataStoreRequest>newBuilder()
.setPath(
"/v1/{name=projects/*/locations/*/dataStores/*}",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<GetDataStoreRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "name", request.getName());
return fields;
})
.setAdditionalPaths(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*}")
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<GetDataStoreRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<DataStore>newBuilder()
.setDefaultInstance(DataStore.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<ListDataStoresRequest, ListDataStoresResponse>
listDataStoresMethodDescriptor =
ApiMethodDescriptor.<ListDataStoresRequest, ListDataStoresResponse>newBuilder()
.setFullMethodName("google.cloud.discoveryengine.v1.DataStoreService/ListDataStores")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<ListDataStoresRequest>newBuilder()
.setPath(
"/v1/{parent=projects/*/locations/*}/dataStores",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<ListDataStoresRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "parent", request.getParent());
return fields;
})
.setAdditionalPaths(
"/v1/{parent=projects/*/locations/*/collections/*}/dataStores")
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<ListDataStoresRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "filter", request.getFilter());
serializer.putQueryParam(fields, "pageSize", request.getPageSize());
serializer.putQueryParam(fields, "pageToken", request.getPageToken());
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<ListDataStoresResponse>newBuilder()
.setDefaultInstance(ListDataStoresResponse.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<DeleteDataStoreRequest, Operation>
deleteDataStoreMethodDescriptor =
ApiMethodDescriptor.<DeleteDataStoreRequest, Operation>newBuilder()
.setFullMethodName("google.cloud.discoveryengine.v1.DataStoreService/DeleteDataStore")
.setHttpMethod("DELETE")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<DeleteDataStoreRequest>newBuilder()
.setPath(
"/v1/{name=projects/*/locations/*/dataStores/*}",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<DeleteDataStoreRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "name", request.getName());
return fields;
})
.setAdditionalPaths(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*}")
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<DeleteDataStoreRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<Operation>newBuilder()
.setDefaultInstance(Operation.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.setOperationSnapshotFactory(
(DeleteDataStoreRequest request, Operation response) ->
HttpJsonOperationSnapshot.create(response))
.build();
private static final ApiMethodDescriptor<UpdateDataStoreRequest, DataStore>
updateDataStoreMethodDescriptor =
ApiMethodDescriptor.<UpdateDataStoreRequest, DataStore>newBuilder()
.setFullMethodName("google.cloud.discoveryengine.v1.DataStoreService/UpdateDataStore")
.setHttpMethod("PATCH")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<UpdateDataStoreRequest>newBuilder()
.setPath(
"/v1/{dataStore.name=projects/*/locations/*/dataStores/*}",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<UpdateDataStoreRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(
fields, "dataStore.name", request.getDataStore().getName());
return fields;
})
.setAdditionalPaths(
"/v1/{dataStore.name=projects/*/locations/*/collections/*/dataStores/*}")
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<UpdateDataStoreRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "updateMask", request.getUpdateMask());
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(
request ->
ProtoRestSerializer.create()
.toBody("dataStore", request.getDataStore(), true))
.build())
.setResponseParser(
ProtoMessageResponseParser.<DataStore>newBuilder()
.setDefaultInstance(DataStore.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private final UnaryCallable<CreateDataStoreRequest, Operation> createDataStoreCallable;
private final OperationCallable<CreateDataStoreRequest, DataStore, CreateDataStoreMetadata>
createDataStoreOperationCallable;
private final UnaryCallable<GetDataStoreRequest, DataStore> getDataStoreCallable;
private final UnaryCallable<ListDataStoresRequest, ListDataStoresResponse> listDataStoresCallable;
private final UnaryCallable<ListDataStoresRequest, ListDataStoresPagedResponse>
listDataStoresPagedCallable;
private final UnaryCallable<DeleteDataStoreRequest, Operation> deleteDataStoreCallable;
private final OperationCallable<DeleteDataStoreRequest, Empty, DeleteDataStoreMetadata>
deleteDataStoreOperationCallable;
private final UnaryCallable<UpdateDataStoreRequest, DataStore> updateDataStoreCallable;
private final BackgroundResource backgroundResources;
private final HttpJsonOperationsStub httpJsonOperationsStub;
private final HttpJsonStubCallableFactory callableFactory;
public static final HttpJsonDataStoreServiceStub create(DataStoreServiceStubSettings settings)
throws IOException {
return new HttpJsonDataStoreServiceStub(settings, ClientContext.create(settings));
}
public static final HttpJsonDataStoreServiceStub create(ClientContext clientContext)
throws IOException {
return new HttpJsonDataStoreServiceStub(
DataStoreServiceStubSettings.newHttpJsonBuilder().build(), clientContext);
}
public static final HttpJsonDataStoreServiceStub create(
ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException {
return new HttpJsonDataStoreServiceStub(
DataStoreServiceStubSettings.newHttpJsonBuilder().build(), clientContext, callableFactory);
}
/**
* Constructs an instance of HttpJsonDataStoreServiceStub, 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 HttpJsonDataStoreServiceStub(
DataStoreServiceStubSettings settings, ClientContext clientContext) throws IOException {
this(settings, clientContext, new HttpJsonDataStoreServiceCallableFactory());
}
/**
* Constructs an instance of HttpJsonDataStoreServiceStub, 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 HttpJsonDataStoreServiceStub(
DataStoreServiceStubSettings settings,
ClientContext clientContext,
HttpJsonStubCallableFactory callableFactory)
throws IOException {
this.callableFactory = callableFactory;
this.httpJsonOperationsStub =
HttpJsonOperationsStub.create(
clientContext,
callableFactory,
typeRegistry,
ImmutableMap.<String, HttpRule>builder()
.put(
"google.longrunning.Operations.CancelOperation",
HttpRule.newBuilder()
.setPost("/v1/{name=projects/*/operations/*}:cancel")
.addAdditionalBindings(
HttpRule.newBuilder()
.setPost(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setPost(
"/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}:cancel")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setPost(
"/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel")
.build())
.build())
.put(
"google.longrunning.Operations.GetOperation",
HttpRule.newBuilder()
.setGet("/v1/{name=projects/*/operations/*}")
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataConnector/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/dataStores/*/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/identityMappingStores/*/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet("/v1/{name=projects/*/locations/*/operations/*}")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet("/v1/{name=projects/*/operations/*}")
.build())
.build())
.put(
"google.longrunning.Operations.ListOperations",
HttpRule.newBuilder()
.setGet("/v1/{name=projects/*}/operations")
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataConnector}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/collections/*}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet("/v1/{name=projects/*/locations/*/dataStores/*}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet(
"/v1/{name=projects/*/locations/*/identityMappingStores/*}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet("/v1/{name=projects/*/locations/*}/operations")
.build())
.addAdditionalBindings(
HttpRule.newBuilder()
.setGet("/v1/{name=projects/*}/operations")
.build())
.build())
.build());
HttpJsonCallSettings<CreateDataStoreRequest, Operation> createDataStoreTransportSettings =
HttpJsonCallSettings.<CreateDataStoreRequest, Operation>newBuilder()
.setMethodDescriptor(createDataStoreMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
HttpJsonCallSettings<GetDataStoreRequest, DataStore> getDataStoreTransportSettings =
HttpJsonCallSettings.<GetDataStoreRequest, DataStore>newBuilder()
.setMethodDescriptor(getDataStoreMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
HttpJsonCallSettings<ListDataStoresRequest, ListDataStoresResponse>
listDataStoresTransportSettings =
HttpJsonCallSettings.<ListDataStoresRequest, ListDataStoresResponse>newBuilder()
.setMethodDescriptor(listDataStoresMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
HttpJsonCallSettings<DeleteDataStoreRequest, Operation> deleteDataStoreTransportSettings =
HttpJsonCallSettings.<DeleteDataStoreRequest, Operation>newBuilder()
.setMethodDescriptor(deleteDataStoreMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
HttpJsonCallSettings<UpdateDataStoreRequest, DataStore> updateDataStoreTransportSettings =
HttpJsonCallSettings.<UpdateDataStoreRequest, DataStore>newBuilder()
.setMethodDescriptor(updateDataStoreMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("data_store.name", String.valueOf(request.getDataStore().getName()));
return builder.build();
})
.build();
this.createDataStoreCallable =
callableFactory.createUnaryCallable(
createDataStoreTransportSettings, settings.createDataStoreSettings(), clientContext);
this.createDataStoreOperationCallable =
callableFactory.createOperationCallable(
createDataStoreTransportSettings,
settings.createDataStoreOperationSettings(),
clientContext,
httpJsonOperationsStub);
this.getDataStoreCallable =
callableFactory.createUnaryCallable(
getDataStoreTransportSettings, settings.getDataStoreSettings(), clientContext);
this.listDataStoresCallable =
callableFactory.createUnaryCallable(
listDataStoresTransportSettings, settings.listDataStoresSettings(), clientContext);
this.listDataStoresPagedCallable =
callableFactory.createPagedCallable(
listDataStoresTransportSettings, settings.listDataStoresSettings(), clientContext);
this.deleteDataStoreCallable =
callableFactory.createUnaryCallable(
deleteDataStoreTransportSettings, settings.deleteDataStoreSettings(), clientContext);
this.deleteDataStoreOperationCallable =
callableFactory.createOperationCallable(
deleteDataStoreTransportSettings,
settings.deleteDataStoreOperationSettings(),
clientContext,
httpJsonOperationsStub);
this.updateDataStoreCallable =
callableFactory.createUnaryCallable(
updateDataStoreTransportSettings, settings.updateDataStoreSettings(), clientContext);
this.backgroundResources =
new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
@InternalApi
public static List<ApiMethodDescriptor> getMethodDescriptors() {
List<ApiMethodDescriptor> methodDescriptors = new ArrayList<>();
methodDescriptors.add(createDataStoreMethodDescriptor);
methodDescriptors.add(getDataStoreMethodDescriptor);
methodDescriptors.add(listDataStoresMethodDescriptor);
methodDescriptors.add(deleteDataStoreMethodDescriptor);
methodDescriptors.add(updateDataStoreMethodDescriptor);
return methodDescriptors;
}
public HttpJsonOperationsStub getHttpJsonOperationsStub() {
return httpJsonOperationsStub;
}
@Override
public UnaryCallable<CreateDataStoreRequest, Operation> createDataStoreCallable() {
return createDataStoreCallable;
}
@Override
public OperationCallable<CreateDataStoreRequest, DataStore, CreateDataStoreMetadata>
createDataStoreOperationCallable() {
return createDataStoreOperationCallable;
}
@Override
public UnaryCallable<GetDataStoreRequest, DataStore> getDataStoreCallable() {
return getDataStoreCallable;
}
@Override
public UnaryCallable<ListDataStoresRequest, ListDataStoresResponse> listDataStoresCallable() {
return listDataStoresCallable;
}
@Override
public UnaryCallable<ListDataStoresRequest, ListDataStoresPagedResponse>
listDataStoresPagedCallable() {
return listDataStoresPagedCallable;
}
@Override
public UnaryCallable<DeleteDataStoreRequest, Operation> deleteDataStoreCallable() {
return deleteDataStoreCallable;
}
@Override
public OperationCallable<DeleteDataStoreRequest, Empty, DeleteDataStoreMetadata>
deleteDataStoreOperationCallable() {
return deleteDataStoreOperationCallable;
}
@Override
public UnaryCallable<UpdateDataStoreRequest, DataStore> updateDataStoreCallable() {
return updateDataStoreCallable;
}
@Override
public final void close() {
try {
backgroundResources.close();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to close resource", e);
}
}
@Override
public void shutdown() {
backgroundResources.shutdown();
}
@Override
public boolean isShutdown() {
return backgroundResources.isShutdown();
}
@Override
public boolean isTerminated() {
return backgroundResources.isTerminated();
}
@Override
public void shutdownNow() {
backgroundResources.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return backgroundResources.awaitTermination(duration, unit);
}
}
|
apache/iotdb | 35,800 | iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/AbstractMemTable.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iotdb.db.storageengine.dataregion.memtable;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.commons.exception.IllegalPathException;
import org.apache.iotdb.commons.path.AlignedFullPath;
import org.apache.iotdb.commons.path.IFullPath;
import org.apache.iotdb.commons.path.NonAlignedFullPath;
import org.apache.iotdb.commons.path.PartialPath;
import org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
import org.apache.iotdb.db.exception.WriteProcessException;
import org.apache.iotdb.db.exception.query.QueryProcessException;
import org.apache.iotdb.db.queryengine.execution.fragment.QueryContext;
import org.apache.iotdb.db.queryengine.plan.analyze.cache.schema.DataNodeDevicePathCache;
import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertRowNode;
import org.apache.iotdb.db.queryengine.plan.planner.plan.node.write.InsertTabletNode;
import org.apache.iotdb.db.schemaengine.schemaregion.utils.ResourceByPathUtils;
import org.apache.iotdb.db.storageengine.dataregion.flush.FlushStatus;
import org.apache.iotdb.db.storageengine.dataregion.flush.NotifyFlushMemTable;
import org.apache.iotdb.db.storageengine.dataregion.modification.ModEntry;
import org.apache.iotdb.db.storageengine.dataregion.read.filescan.IChunkHandle;
import org.apache.iotdb.db.storageengine.dataregion.read.filescan.impl.MemAlignedChunkHandleImpl;
import org.apache.iotdb.db.storageengine.dataregion.read.filescan.impl.MemChunkHandleImpl;
import org.apache.iotdb.db.storageengine.dataregion.wal.buffer.IWALByteBufferView;
import org.apache.iotdb.db.storageengine.dataregion.wal.utils.WALWriteUtils;
import org.apache.iotdb.db.utils.MemUtils;
import org.apache.iotdb.db.utils.ModificationUtils;
import org.apache.tsfile.enums.TSDataType;
import org.apache.tsfile.file.metadata.ChunkMetadata;
import org.apache.tsfile.file.metadata.IChunkMetadata;
import org.apache.tsfile.file.metadata.IDeviceID;
import org.apache.tsfile.file.metadata.IDeviceID.Deserializer;
import org.apache.tsfile.file.metadata.enums.CompressionType;
import org.apache.tsfile.file.metadata.enums.TSEncoding;
import org.apache.tsfile.file.metadata.statistics.TimeStatistics;
import org.apache.tsfile.read.common.TimeRange;
import org.apache.tsfile.read.filter.basic.Filter;
import org.apache.tsfile.utils.BitMap;
import org.apache.tsfile.utils.Pair;
import org.apache.tsfile.utils.ReadWriteIOUtils;
import org.apache.tsfile.write.schema.IMeasurementSchema;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
public abstract class AbstractMemTable implements IMemTable {
/** Each memTable node has a unique int value identifier, init when recovering wal. */
public static final AtomicLong memTableIdCounter = new AtomicLong(-1);
private static final int FIXED_SERIALIZED_SIZE = Byte.BYTES + 2 * Integer.BYTES + 6 * Long.BYTES;
/** DeviceId -> chunkGroup(MeasurementId -> chunk). */
private final Map<IDeviceID, IWritableMemChunkGroup> memTableMap;
private static final DeviceIDFactory deviceIDFactory = DeviceIDFactory.getInstance();
private boolean shouldFlush = false;
private volatile FlushStatus flushStatus = FlushStatus.WORKING;
/** Memory size of data points, including TEXT values. */
private long memSize = 0;
/**
* Memory usage of all TVLists memory usage regardless of whether these TVLists are full,
* including TEXT values.
*/
private long tvListRamCost = 0;
private int seriesNumber = 0;
private long totalPointsNum = 0;
private long totalPointsNumThreshold = 0;
private long maxPlanIndex = Long.MIN_VALUE;
private long minPlanIndex = Long.MAX_VALUE;
private final long memTableId = memTableIdCounter.incrementAndGet();
private final long createdTime = System.currentTimeMillis();
/** this time is updated by the timed flush, same as createdTime when the feature is disabled. */
private long updateTime = createdTime;
/**
* check whether this memTable has been updated since last timed flush check, update updateTime
* when changed
*/
private long lastTotalPointsNum = totalPointsNum;
private String database;
private String dataRegionId;
protected AbstractMemTable() {
this.database = null;
this.dataRegionId = null;
this.memTableMap = new HashMap<>();
}
protected AbstractMemTable(String database, String dataRegionId) {
this.database = database;
this.dataRegionId = dataRegionId;
this.memTableMap = new HashMap<>();
}
protected AbstractMemTable(
String database, String dataRegionId, Map<IDeviceID, IWritableMemChunkGroup> memTableMap) {
this.database = database;
this.dataRegionId = dataRegionId;
this.memTableMap = memTableMap;
}
@Override
public Map<IDeviceID, IWritableMemChunkGroup> getMemTableMap() {
return memTableMap;
}
/**
* Create this MemChunk if it's not exist.
*
* @param deviceId device id
* @param schemaList measurement schemaList
* @return this MemChunkGroup
*/
private IWritableMemChunkGroup createMemChunkGroupIfNotExistAndGet(
IDeviceID deviceId, List<IMeasurementSchema> schemaList) {
IWritableMemChunkGroup memChunkGroup =
memTableMap.computeIfAbsent(deviceId, k -> new WritableMemChunkGroup());
for (IMeasurementSchema schema : schemaList) {
if (schema != null && !memChunkGroup.contains(schema.getMeasurementName())) {
seriesNumber++;
}
}
return memChunkGroup;
}
private IWritableMemChunkGroup createAlignedMemChunkGroupIfNotExistAndGet(
IDeviceID deviceId, List<IMeasurementSchema> schemaList) {
IWritableMemChunkGroup memChunkGroup =
memTableMap.computeIfAbsent(
deviceId,
k -> {
seriesNumber += schemaList.size();
return new AlignedWritableMemChunkGroup(
schemaList.stream().filter(Objects::nonNull).collect(Collectors.toList()),
k.isTableModel());
});
for (IMeasurementSchema schema : schemaList) {
if (schema != null && !memChunkGroup.contains(schema.getMeasurementName())) {
seriesNumber++;
}
}
return memChunkGroup;
}
@Override
public int insert(InsertRowNode insertRowNode) {
String[] measurements = insertRowNode.getMeasurements();
Object[] values = insertRowNode.getValues();
List<IMeasurementSchema> schemaList = new ArrayList<>();
List<TSDataType> dataTypes = new ArrayList<>();
int nullPointsNumber = 0;
for (int i = 0; i < insertRowNode.getMeasurements().length; i++) {
// Use measurements[i] to ignore failed partial insert
if (measurements[i] == null || values[i] == null) {
if (values[i] == null) {
nullPointsNumber++;
}
schemaList.add(null);
} else {
IMeasurementSchema schema = insertRowNode.getMeasurementSchemas()[i];
schemaList.add(schema);
dataTypes.add(schema.getType());
}
}
memSize += MemUtils.getRowRecordSize(dataTypes, values);
write(insertRowNode.getDeviceID(), schemaList, insertRowNode.getTime(), values);
int pointsInserted =
insertRowNode.getMeasurements().length
- insertRowNode.getFailedMeasurementNumber()
- (IoTDBDescriptor.getInstance().getConfig().isIncludeNullValueInWriteThroughputMetric()
? 0
: nullPointsNumber);
totalPointsNum += pointsInserted;
return pointsInserted;
}
@Override
public int insertAlignedRow(InsertRowNode insertRowNode) {
String[] measurements = insertRowNode.getMeasurements();
Object[] values = insertRowNode.getValues();
List<IMeasurementSchema> schemaList = new ArrayList<>();
List<TSDataType> dataTypes = new ArrayList<>();
int nullPointsNumber = 0;
for (int i = 0; i < insertRowNode.getMeasurements().length; i++) {
// Use measurements[i] to ignore failed partial insert
if (measurements[i] == null
|| values[i] == null
|| insertRowNode.getColumnCategories() != null
&& insertRowNode.getColumnCategories()[i] != TsTableColumnCategory.FIELD) {
if (values[i] == null) {
nullPointsNumber++;
}
schemaList.add(null);
continue;
}
IMeasurementSchema schema = insertRowNode.getMeasurementSchemas()[i];
schemaList.add(schema);
dataTypes.add(schema.getType());
}
if (schemaList.isEmpty()) {
return 0;
}
memSize +=
MemUtils.getAlignedRowRecordSize(dataTypes, values, insertRowNode.getColumnCategories());
writeAlignedRow(insertRowNode.getDeviceID(), schemaList, insertRowNode.getTime(), values);
int pointsInserted =
insertRowNode.getMeasurementColumnCnt()
- insertRowNode.getFailedMeasurementNumber()
- (IoTDBDescriptor.getInstance().getConfig().isIncludeNullValueInWriteThroughputMetric()
? 0
: nullPointsNumber);
totalPointsNum += pointsInserted;
return pointsInserted;
}
@Override
public int insertTablet(InsertTabletNode insertTabletNode, int start, int end)
throws WriteProcessException {
try {
int nullPointsNumber = computeTabletNullPointsNumber(insertTabletNode, start, end);
writeTabletNode(insertTabletNode, start, end);
memSize += MemUtils.getTabletSize(insertTabletNode, start, end);
int pointsInserted =
((insertTabletNode.getDataTypes().length - insertTabletNode.getFailedMeasurementNumber())
* (end - start))
- (IoTDBDescriptor.getInstance()
.getConfig()
.isIncludeNullValueInWriteThroughputMetric()
? 0
: nullPointsNumber);
totalPointsNum += pointsInserted;
return pointsInserted;
} catch (RuntimeException e) {
throw new WriteProcessException(e);
}
}
@Override
public int insertAlignedTablet(
InsertTabletNode insertTabletNode, int start, int end, TSStatus[] results)
throws WriteProcessException {
try {
int nullPointsNumber = computeTabletNullPointsNumber(insertTabletNode, start, end);
writeAlignedTablet(insertTabletNode, start, end, results);
// TODO-Table: what is the relation between this and TsFileProcessor.checkMemCost
memSize += MemUtils.getAlignedTabletSize(insertTabletNode, start, end, results);
int pointsInserted =
((insertTabletNode.getMeasurementColumnCnt()
- insertTabletNode.getFailedMeasurementNumber())
* (end - start))
- (IoTDBDescriptor.getInstance()
.getConfig()
.isIncludeNullValueInWriteThroughputMetric()
? 0
: nullPointsNumber);
totalPointsNum += pointsInserted;
return pointsInserted;
} catch (RuntimeException e) {
throw new WriteProcessException(e);
}
}
private static int computeTabletNullPointsNumber(
InsertTabletNode insertTabletNode, int start, int end) {
Object[] values = insertTabletNode.getBitMaps();
int nullPointsNumber = 0;
if (values != null) {
for (int i = 0; i < insertTabletNode.getMeasurements().length; i++) {
BitMap bitMap = (BitMap) values[i];
if (bitMap != null && !bitMap.isAllUnmarked()) {
for (int j = start; j < end; j++) {
if (bitMap.isMarked(j)) {
nullPointsNumber++;
}
}
}
}
}
return nullPointsNumber;
}
@Override
public void write(
IDeviceID deviceId,
List<IMeasurementSchema> schemaList,
long insertTime,
Object[] objectValue) {
IWritableMemChunkGroup memChunkGroup =
createMemChunkGroupIfNotExistAndGet(deviceId, schemaList);
memChunkGroup.writeRow(insertTime, objectValue, schemaList);
}
@Override
public void writeAlignedRow(
IDeviceID deviceId,
List<IMeasurementSchema> schemaList,
long insertTime,
Object[] objectValue) {
IWritableMemChunkGroup memChunkGroup =
createAlignedMemChunkGroupIfNotExistAndGet(deviceId, schemaList);
memChunkGroup.writeRow(insertTime, objectValue, schemaList);
}
public void writeTabletNode(InsertTabletNode insertTabletNode, int start, int end) {
List<IMeasurementSchema> schemaList = new ArrayList<>();
for (int i = 0; i < insertTabletNode.getMeasurementSchemas().length; i++) {
if (insertTabletNode.getColumns()[i] == null) {
schemaList.add(null);
} else {
schemaList.add(insertTabletNode.getMeasurementSchemas()[i]);
}
}
IWritableMemChunkGroup memChunkGroup =
createMemChunkGroupIfNotExistAndGet(insertTabletNode.getDeviceID(), schemaList);
memChunkGroup.writeTablet(
insertTabletNode.getTimes(),
insertTabletNode.getColumns(),
insertTabletNode.getBitMaps(),
schemaList,
start,
end,
null);
}
public void writeAlignedTablet(
InsertTabletNode insertTabletNode, int start, int end, TSStatus[] results) {
List<IMeasurementSchema> schemaList = new ArrayList<>();
for (int i = 0; i < insertTabletNode.getMeasurementSchemas().length; i++) {
if (insertTabletNode.getColumns()[i] == null
|| (insertTabletNode.getColumnCategories() != null
&& insertTabletNode.getColumnCategories()[i] != TsTableColumnCategory.FIELD)) {
schemaList.add(null);
} else {
schemaList.add(insertTabletNode.getMeasurementSchemas()[i]);
}
}
if (schemaList.isEmpty()) {
return;
}
final List<Pair<IDeviceID, Integer>> deviceEndOffsetPair =
insertTabletNode.splitByDevice(start, end);
int splitStart = start;
for (Pair<IDeviceID, Integer> pair : deviceEndOffsetPair) {
final IDeviceID deviceID = pair.left;
int splitEnd = pair.right;
IWritableMemChunkGroup memChunkGroup =
createAlignedMemChunkGroupIfNotExistAndGet(deviceID, schemaList);
memChunkGroup.writeTablet(
insertTabletNode.getTimes(),
insertTabletNode.getColumns(),
insertTabletNode.getBitMaps(),
schemaList,
splitStart,
splitEnd,
results);
splitStart = splitEnd;
}
}
@Override
public boolean chunkNotExist(IDeviceID deviceId, String measurement) {
IWritableMemChunkGroup memChunkGroup = memTableMap.get(deviceId);
if (null == memChunkGroup) {
return true;
}
return !memChunkGroup.contains(measurement);
}
@Override
public IWritableMemChunk getWritableMemChunk(IDeviceID deviceId, String measurement) {
IWritableMemChunkGroup memChunkGroup = memTableMap.get(deviceId);
if (null == memChunkGroup) {
return null;
}
return memChunkGroup.getWritableMemChunk(measurement);
}
@Override
public int getSeriesNumber() {
return seriesNumber;
}
@Override
public long getTotalPointsNum() {
return totalPointsNum;
}
@Override
public long size() {
long sum = 0;
for (IWritableMemChunkGroup writableMemChunkGroup : memTableMap.values()) {
sum += writableMemChunkGroup.count();
}
return sum;
}
@Override
public long memSize() {
return memSize;
}
@Override
public void clear() {
memTableMap.clear();
memSize = 0;
seriesNumber = 0;
totalPointsNum = 0;
totalPointsNumThreshold = 0;
tvListRamCost = 0;
maxPlanIndex = 0;
minPlanIndex = 0;
}
@Override
public boolean isEmpty() {
return memTableMap.isEmpty();
}
@Override
public ReadOnlyMemChunk query(
QueryContext context,
IFullPath fullPath,
long ttlLowerBound,
List<Pair<ModEntry, IMemTable>> modsToMemtable,
Filter globalTimeFilter)
throws IOException, QueryProcessException {
return ResourceByPathUtils.getResourceInstance(fullPath)
.getReadOnlyMemChunkFromMemTable(
context, this, modsToMemtable, ttlLowerBound, globalTimeFilter);
}
@Override
public void queryForSeriesRegionScan(
IFullPath fullPath,
long ttlLowerBound,
Map<String, List<IChunkMetadata>> chunkMetaDataMap,
Map<String, List<IChunkHandle>> memChunkHandleMap,
List<Pair<ModEntry, IMemTable>> modsToMemTabled) {
IDeviceID deviceID = fullPath.getDeviceId();
if (fullPath instanceof NonAlignedFullPath) {
String measurementId = ((NonAlignedFullPath) fullPath).getMeasurement();
// check If MemTable Contains this path
if (!memTableMap.containsKey(deviceID)
|| !memTableMap.get(deviceID).contains(measurementId)) {
return;
}
List<TimeRange> deletionList = new ArrayList<>();
if (modsToMemTabled != null) {
deletionList =
ModificationUtils.constructDeletionList(
fullPath.getDeviceId(), measurementId, this, modsToMemTabled, ttlLowerBound);
}
getMemChunkHandleFromMemTable(
deviceID, measurementId, chunkMetaDataMap, memChunkHandleMap, deletionList);
} else {
// check If MemTable Contains this path
if (!memTableMap.containsKey(deviceID)) {
return;
}
List<List<TimeRange>> deletionList = new ArrayList<>();
if (modsToMemTabled != null) {
deletionList =
ModificationUtils.constructDeletionList(
deviceID,
((AlignedFullPath) fullPath).getMeasurementList(),
this,
modsToMemTabled,
ttlLowerBound);
}
getMemAlignedChunkHandleFromMemTable(
deviceID,
((AlignedFullPath) fullPath).getSchemaList(),
chunkMetaDataMap,
memChunkHandleMap,
deletionList);
}
}
@Override
public void queryForDeviceRegionScan(
IDeviceID deviceID,
boolean isAligned,
long ttlLowerBound,
Map<String, List<IChunkMetadata>> chunkMetadataMap,
Map<String, List<IChunkHandle>> memChunkHandleMap,
List<Pair<ModEntry, IMemTable>> modsToMemTabled) {
Map<IDeviceID, IWritableMemChunkGroup> memTableMap = getMemTableMap();
// check If MemTable Contains this path
if (!memTableMap.containsKey(deviceID)) {
return;
}
IWritableMemChunkGroup writableMemChunkGroup = memTableMap.get(deviceID);
if (isAligned) {
getMemAlignedChunkHandleFromMemTable(
deviceID,
(AlignedWritableMemChunkGroup) writableMemChunkGroup,
chunkMetadataMap,
memChunkHandleMap,
ttlLowerBound,
modsToMemTabled);
} else {
getMemChunkHandleFromMemTable(
deviceID,
(WritableMemChunkGroup) writableMemChunkGroup,
chunkMetadataMap,
memChunkHandleMap,
ttlLowerBound,
modsToMemTabled);
}
}
private void getMemChunkHandleFromMemTable(
IDeviceID deviceID,
String measurementId,
Map<String, List<IChunkMetadata>> chunkMetadataMap,
Map<String, List<IChunkHandle>> memChunkHandleMap,
List<TimeRange> deletionList) {
WritableMemChunk memChunk =
(WritableMemChunk) memTableMap.get(deviceID).getMemChunkMap().get(measurementId);
long[] timestamps = memChunk.getFilteredTimestamp(deletionList);
chunkMetadataMap
.computeIfAbsent(measurementId, k -> new ArrayList<>())
.add(
buildChunkMetaDataForMemoryChunk(
measurementId,
timestamps[0],
timestamps[timestamps.length - 1],
Collections.emptyList()));
memChunkHandleMap
.computeIfAbsent(measurementId, k -> new ArrayList<>())
.add(new MemChunkHandleImpl(deviceID, measurementId, timestamps));
}
private void getMemAlignedChunkHandleFromMemTable(
IDeviceID deviceID,
List<IMeasurementSchema> schemaList,
Map<String, List<IChunkMetadata>> chunkMetadataList,
Map<String, List<IChunkHandle>> memChunkHandleMap,
List<List<TimeRange>> deletionList) {
AlignedWritableMemChunk alignedMemChunk =
((AlignedWritableMemChunkGroup) memTableMap.get(deviceID)).getAlignedMemChunk();
boolean containsMeasurement = false;
for (IMeasurementSchema measurementSchema : schemaList) {
if (alignedMemChunk.containsMeasurement(measurementSchema.getMeasurementName())) {
containsMeasurement = true;
break;
}
}
if (!containsMeasurement) {
return;
}
List<BitMap> bitMaps = new ArrayList<>();
long[] timestamps = alignedMemChunk.getFilteredTimestamp(deletionList, bitMaps, true);
buildAlignedMemChunkHandle(
deviceID,
timestamps,
bitMaps,
deletionList,
schemaList,
chunkMetadataList,
memChunkHandleMap);
}
private void getMemAlignedChunkHandleFromMemTable(
IDeviceID deviceID,
AlignedWritableMemChunkGroup writableMemChunkGroup,
Map<String, List<IChunkMetadata>> chunkMetadataList,
Map<String, List<IChunkHandle>> memChunkHandleMap,
long ttlLowerBound,
List<Pair<ModEntry, IMemTable>> modsToMemTabled) {
AlignedWritableMemChunk memChunk = writableMemChunkGroup.getAlignedMemChunk();
List<IMeasurementSchema> schemaList = memChunk.getSchemaList();
List<List<TimeRange>> deletionList = new ArrayList<>();
if (modsToMemTabled != null) {
for (IMeasurementSchema schema : schemaList) {
deletionList.add(
ModificationUtils.constructDeletionList(
deviceID, schema.getMeasurementName(), this, modsToMemTabled, ttlLowerBound));
}
}
List<BitMap> bitMaps = new ArrayList<>();
long[] timestamps = memChunk.getFilteredTimestamp(deletionList, bitMaps, true);
buildAlignedMemChunkHandle(
deviceID,
timestamps,
bitMaps,
deletionList,
schemaList,
chunkMetadataList,
memChunkHandleMap);
}
private void getMemChunkHandleFromMemTable(
IDeviceID deviceID,
WritableMemChunkGroup writableMemChunkGroup,
Map<String, List<IChunkMetadata>> chunkMetadataMap,
Map<String, List<IChunkHandle>> memChunkHandleMap,
long ttlLowerBound,
List<Pair<ModEntry, IMemTable>> modsToMemTabled) {
for (Entry<String, IWritableMemChunk> entry :
writableMemChunkGroup.getMemChunkMap().entrySet()) {
String measurementId = entry.getKey();
WritableMemChunk writableMemChunk = (WritableMemChunk) entry.getValue();
List<TimeRange> deletionList = new ArrayList<>();
if (modsToMemTabled != null) {
deletionList =
ModificationUtils.constructDeletionList(
deviceID, measurementId, this, modsToMemTabled, ttlLowerBound);
}
long[] timestamps = writableMemChunk.getFilteredTimestamp(deletionList);
chunkMetadataMap
.computeIfAbsent(measurementId, k -> new ArrayList<>())
.add(
buildChunkMetaDataForMemoryChunk(
measurementId,
timestamps[0],
timestamps[timestamps.length - 1],
Collections.emptyList()));
memChunkHandleMap
.computeIfAbsent(measurementId, k -> new ArrayList<>())
.add(new MemChunkHandleImpl(deviceID, measurementId, timestamps));
}
}
private void buildAlignedMemChunkHandle(
IDeviceID deviceID,
long[] timestamps,
List<BitMap> bitMaps,
List<List<TimeRange>> deletionList,
List<IMeasurementSchema> schemaList,
Map<String, List<IChunkMetadata>> chunkMetadataList,
Map<String, List<IChunkHandle>> chunkHandleMap) {
for (int column = 0; column < schemaList.size(); column++) {
String measurement = schemaList.get(column).getMeasurementName();
List<TimeRange> deletion =
deletionList == null || deletionList.isEmpty()
? Collections.emptyList()
: deletionList.get(column);
long[] startEndTime = calculateStartEndTime(timestamps, bitMaps, column);
chunkMetadataList
.computeIfAbsent(measurement, k -> new ArrayList<>())
.add(
buildChunkMetaDataForMemoryChunk(
measurement, startEndTime[0], startEndTime[1], deletion));
chunkHandleMap
.computeIfAbsent(measurement, k -> new ArrayList<>())
.add(
new MemAlignedChunkHandleImpl(
deviceID, measurement, timestamps, bitMaps, column, startEndTime));
}
}
private long[] calculateStartEndTime(long[] timestamps, List<BitMap> bitMaps, int column) {
if (bitMaps.isEmpty()) {
return new long[] {timestamps[0], timestamps[timestamps.length - 1]};
}
long startTime = -1, endTime = -1;
for (int i = 0; i < timestamps.length; i++) {
if (!bitMaps.get(i).isMarked(column)) {
startTime = timestamps[i];
break;
}
}
for (int i = timestamps.length - 1; i >= 0; i--) {
if (!bitMaps.get(i).isMarked(column)) {
endTime = timestamps[i];
break;
}
}
return new long[] {startTime, endTime};
}
private IChunkMetadata buildChunkMetaDataForMemoryChunk(
String measurement, long startTime, long endTime, List<TimeRange> deletionList) {
TimeStatistics timeStatistics = new TimeStatistics();
timeStatistics.setStartTime(startTime);
timeStatistics.setEndTime(endTime);
// ChunkMetaData for memory is only used to get time statistics, the dataType is irrelevant.
IChunkMetadata chunkMetadata =
new ChunkMetadata(
measurement,
TSDataType.UNKNOWN,
TSEncoding.PLAIN,
CompressionType.UNCOMPRESSED,
0,
timeStatistics);
for (TimeRange timeRange : deletionList) {
chunkMetadata.insertIntoSortedDeletions(timeRange);
}
return chunkMetadata;
}
@Override
public long delete(ModEntry modEntry) {
List<Pair<IDeviceID, IWritableMemChunkGroup>> targetDeviceList = new ArrayList<>();
for (Entry<IDeviceID, IWritableMemChunkGroup> entry : memTableMap.entrySet()) {
if (modEntry.affects(entry.getKey())) {
targetDeviceList.add(new Pair<>(entry.getKey(), entry.getValue()));
}
}
long pointDeleted = 0;
for (Pair<IDeviceID, IWritableMemChunkGroup> pair : targetDeviceList) {
if (modEntry.affectsAll(pair.left)) {
pointDeleted += pair.right.deleteTime(modEntry);
} else {
pointDeleted += pair.right.delete(modEntry);
}
if (pair.right.isEmpty()) {
memTableMap.remove(pair.left).release();
}
}
return pointDeleted;
}
@Override
public void addTVListRamCost(long cost) {
this.tvListRamCost += cost;
}
@Override
public void releaseTVListRamCost(long cost) {
this.tvListRamCost -= cost;
}
@Override
public long getTVListsRamCost() {
return tvListRamCost;
}
@Override
public void addTextDataSize(long textDataSize) {
this.memSize += textDataSize;
}
@Override
public void releaseTextDataSize(long textDataSize) {
this.memSize -= textDataSize;
}
@Override
public void setShouldFlush() {
shouldFlush = true;
}
@Override
public boolean shouldFlush() {
return shouldFlush;
}
@Override
public void release() {
for (Entry<IDeviceID, IWritableMemChunkGroup> entry : memTableMap.entrySet()) {
entry.getValue().release();
}
}
@Override
public long getMaxPlanIndex() {
return maxPlanIndex;
}
@Override
public long getMinPlanIndex() {
return minPlanIndex;
}
@Override
public long getMemTableId() {
return memTableId;
}
@Override
public long getCreatedTime() {
return createdTime;
}
/** Check whether updated since last get method */
@Override
public long getUpdateTime() {
if (lastTotalPointsNum != totalPointsNum) {
lastTotalPointsNum = totalPointsNum;
updateTime = System.currentTimeMillis();
}
return updateTime;
}
@Override
public FlushStatus getFlushStatus() {
return flushStatus;
}
@Override
public void setFlushStatus(FlushStatus flushStatus) {
this.flushStatus = flushStatus;
}
/** Notice: this method is concurrent unsafe. */
@Override
public int serializedSize() {
if (isSignalMemTable()) {
return Byte.BYTES;
}
int size = FIXED_SERIALIZED_SIZE;
for (Map.Entry<IDeviceID, IWritableMemChunkGroup> entry : memTableMap.entrySet()) {
size += entry.getKey().serializedSize();
size += Byte.BYTES;
size += entry.getValue().serializedSize();
}
return size;
}
/** Notice: this method is concurrent unsafe. */
@Override
public void serializeToWAL(IWALByteBufferView buffer) {
if (isSignalMemTable()) {
WALWriteUtils.write(isSignalMemTable(), buffer);
return;
}
// marker for multi-tvlist mem chunk
WALWriteUtils.write((byte) -1, buffer);
buffer.putInt(seriesNumber);
buffer.putLong(memSize);
buffer.putLong(tvListRamCost);
buffer.putLong(totalPointsNum);
buffer.putLong(totalPointsNumThreshold);
buffer.putLong(maxPlanIndex);
buffer.putLong(minPlanIndex);
buffer.putInt(memTableMap.size());
for (Map.Entry<IDeviceID, IWritableMemChunkGroup> entry : memTableMap.entrySet()) {
try {
entry.getKey().serialize(buffer);
} catch (IOException e) {
throw new RuntimeException(e);
}
IWritableMemChunkGroup memChunkGroup = entry.getValue();
WALWriteUtils.write(memChunkGroup instanceof AlignedWritableMemChunkGroup, buffer);
memChunkGroup.serializeToWAL(buffer);
}
}
protected void deserialize(DataInputStream stream, boolean multiTvListInMemChunk)
throws IOException {
seriesNumber = stream.readInt();
memSize = stream.readLong();
tvListRamCost = stream.readLong();
totalPointsNum = stream.readLong();
totalPointsNumThreshold = stream.readLong();
maxPlanIndex = stream.readLong();
minPlanIndex = stream.readLong();
int memTableMapSize = stream.readInt();
for (int i = 0; i < memTableMapSize; ++i) {
IDeviceID deviceID = Deserializer.DEFAULT_DESERIALIZER.deserializeFrom(stream);
boolean isAligned = ReadWriteIOUtils.readBool(stream);
IWritableMemChunkGroup memChunkGroup;
if (multiTvListInMemChunk) {
if (isAligned) {
memChunkGroup = AlignedWritableMemChunkGroup.deserialize(stream, deviceID.isTableModel());
} else {
memChunkGroup = WritableMemChunkGroup.deserialize(stream);
}
} else {
if (isAligned) {
memChunkGroup =
AlignedWritableMemChunkGroup.deserializeSingleTVListMemChunks(
stream, deviceID.isTableModel());
} else {
memChunkGroup = WritableMemChunkGroup.deserializeSingleTVListMemChunks(stream);
}
}
memTableMap.put(deviceID, memChunkGroup);
}
}
public void deserializeFromOldMemTableSnapshot(
DataInputStream stream, boolean multiTvListInMemChunk) throws IOException {
seriesNumber = stream.readInt();
memSize = stream.readLong();
tvListRamCost = stream.readLong();
totalPointsNum = stream.readLong();
totalPointsNumThreshold = stream.readLong();
maxPlanIndex = stream.readLong();
minPlanIndex = stream.readLong();
int memTableMapSize = stream.readInt();
for (int i = 0; i < memTableMapSize; ++i) {
PartialPath devicePath;
try {
devicePath =
DataNodeDevicePathCache.getInstance()
.getPartialPath(ReadWriteIOUtils.readString(stream));
} catch (IllegalPathException e) {
throw new IllegalArgumentException("Cannot deserialize OldMemTableSnapshot", e);
}
IDeviceID deviceID = deviceIDFactory.getDeviceID(devicePath);
boolean isAligned = ReadWriteIOUtils.readBool(stream);
IWritableMemChunkGroup memChunkGroup;
if (multiTvListInMemChunk) {
if (isAligned) {
memChunkGroup = AlignedWritableMemChunkGroup.deserialize(stream, deviceID.isTableModel());
} else {
memChunkGroup = WritableMemChunkGroup.deserialize(stream);
}
} else {
if (isAligned) {
memChunkGroup =
AlignedWritableMemChunkGroup.deserializeSingleTVListMemChunks(
stream, deviceID.isTableModel());
} else {
memChunkGroup = WritableMemChunkGroup.deserializeSingleTVListMemChunks(stream);
}
}
memTableMap.put(deviceID, memChunkGroup);
}
}
@Override
public Map<IDeviceID, Long> getMaxTime() {
Map<IDeviceID, Long> latestTimeForEachDevice = new HashMap<>();
for (Entry<IDeviceID, IWritableMemChunkGroup> entry : memTableMap.entrySet()) {
if (entry.getValue().count() > 0 && !entry.getValue().isEmpty()) {
latestTimeForEachDevice.put(entry.getKey(), entry.getValue().getMaxTime());
}
}
return latestTimeForEachDevice;
}
public static class Factory {
private Factory() {
// Empty constructor
}
public static IMemTable create(DataInputStream stream) throws IOException {
byte marker = ReadWriteIOUtils.readByte(stream);
boolean isSignal = marker == 1;
IMemTable memTable;
if (isSignal) {
memTable = new NotifyFlushMemTable();
} else {
// database will be updated when deserialize
PrimitiveMemTable primitiveMemTable = new PrimitiveMemTable();
primitiveMemTable.deserialize(stream, marker == -1);
memTable = primitiveMemTable;
}
return memTable;
}
public static IMemTable createFromOldMemTableSnapshot(DataInputStream stream)
throws IOException {
byte marker = ReadWriteIOUtils.readByte(stream);
boolean isSignal = marker == 1;
IMemTable memTable;
if (isSignal) {
memTable = new NotifyFlushMemTable();
} else {
// database will be updated when deserialize
PrimitiveMemTable primitiveMemTable = new PrimitiveMemTable();
primitiveMemTable.deserializeFromOldMemTableSnapshot(stream, marker == -1);
memTable = primitiveMemTable;
}
return memTable;
}
}
@Override
public String getDatabase() {
return database;
}
@Override
public String getDataRegionId() {
return dataRegionId;
}
@Override
public void setDatabaseAndDataRegionId(String database, String dataRegionId) {
this.database = database;
this.dataRegionId = dataRegionId;
}
}
|
googleapis/google-cloud-java | 35,661 | java-monitoring/proto-google-cloud-monitoring-v3/src/main/java/com/google/monitoring/v3/QueryErrorList.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/v3/metric_service.proto
// Protobuf Java Version: 3.25.8
package com.google.monitoring.v3;
/**
*
*
* <pre>
* This is an error detail intended to be used with INVALID_ARGUMENT errors.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.QueryErrorList}
*/
public final class QueryErrorList extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.monitoring.v3.QueryErrorList)
QueryErrorListOrBuilder {
private static final long serialVersionUID = 0L;
// Use QueryErrorList.newBuilder() to construct.
private QueryErrorList(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private QueryErrorList() {
errors_ = java.util.Collections.emptyList();
errorSummary_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new QueryErrorList();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.MetricServiceProto
.internal_static_google_monitoring_v3_QueryErrorList_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.MetricServiceProto
.internal_static_google_monitoring_v3_QueryErrorList_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.QueryErrorList.class,
com.google.monitoring.v3.QueryErrorList.Builder.class);
}
public static final int ERRORS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.monitoring.v3.QueryError> errors_;
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.monitoring.v3.QueryError> getErrorsList() {
return errors_;
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.monitoring.v3.QueryErrorOrBuilder>
getErrorsOrBuilderList() {
return errors_;
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
@java.lang.Override
public int getErrorsCount() {
return errors_.size();
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.QueryError getErrors(int index) {
return errors_.get(index);
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.QueryErrorOrBuilder getErrorsOrBuilder(int index) {
return errors_.get(index);
}
public static final int ERROR_SUMMARY_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object errorSummary_ = "";
/**
*
*
* <pre>
* A summary of all the errors.
* </pre>
*
* <code>string error_summary = 2;</code>
*
* @return The errorSummary.
*/
@java.lang.Override
public java.lang.String getErrorSummary() {
java.lang.Object ref = errorSummary_;
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();
errorSummary_ = s;
return s;
}
}
/**
*
*
* <pre>
* A summary of all the errors.
* </pre>
*
* <code>string error_summary = 2;</code>
*
* @return The bytes for errorSummary.
*/
@java.lang.Override
public com.google.protobuf.ByteString getErrorSummaryBytes() {
java.lang.Object ref = errorSummary_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
errorSummary_ = 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 < errors_.size(); i++) {
output.writeMessage(1, errors_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(errorSummary_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, errorSummary_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < errors_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, errors_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(errorSummary_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, errorSummary_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.monitoring.v3.QueryErrorList)) {
return super.equals(obj);
}
com.google.monitoring.v3.QueryErrorList other = (com.google.monitoring.v3.QueryErrorList) obj;
if (!getErrorsList().equals(other.getErrorsList())) return false;
if (!getErrorSummary().equals(other.getErrorSummary())) 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 (getErrorsCount() > 0) {
hash = (37 * hash) + ERRORS_FIELD_NUMBER;
hash = (53 * hash) + getErrorsList().hashCode();
}
hash = (37 * hash) + ERROR_SUMMARY_FIELD_NUMBER;
hash = (53 * hash) + getErrorSummary().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.monitoring.v3.QueryErrorList parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.QueryErrorList parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.QueryErrorList parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.QueryErrorList parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.QueryErrorList parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.QueryErrorList parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.QueryErrorList parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.QueryErrorList parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.QueryErrorList parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.QueryErrorList parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.QueryErrorList parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.QueryErrorList parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.monitoring.v3.QueryErrorList prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* This is an error detail intended to be used with INVALID_ARGUMENT errors.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.QueryErrorList}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.monitoring.v3.QueryErrorList)
com.google.monitoring.v3.QueryErrorListOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.MetricServiceProto
.internal_static_google_monitoring_v3_QueryErrorList_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.MetricServiceProto
.internal_static_google_monitoring_v3_QueryErrorList_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.QueryErrorList.class,
com.google.monitoring.v3.QueryErrorList.Builder.class);
}
// Construct using com.google.monitoring.v3.QueryErrorList.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (errorsBuilder_ == null) {
errors_ = java.util.Collections.emptyList();
} else {
errors_ = null;
errorsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
errorSummary_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.monitoring.v3.MetricServiceProto
.internal_static_google_monitoring_v3_QueryErrorList_descriptor;
}
@java.lang.Override
public com.google.monitoring.v3.QueryErrorList getDefaultInstanceForType() {
return com.google.monitoring.v3.QueryErrorList.getDefaultInstance();
}
@java.lang.Override
public com.google.monitoring.v3.QueryErrorList build() {
com.google.monitoring.v3.QueryErrorList result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.monitoring.v3.QueryErrorList buildPartial() {
com.google.monitoring.v3.QueryErrorList result =
new com.google.monitoring.v3.QueryErrorList(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(com.google.monitoring.v3.QueryErrorList result) {
if (errorsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
errors_ = java.util.Collections.unmodifiableList(errors_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.errors_ = errors_;
} else {
result.errors_ = errorsBuilder_.build();
}
}
private void buildPartial0(com.google.monitoring.v3.QueryErrorList result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.errorSummary_ = errorSummary_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.monitoring.v3.QueryErrorList) {
return mergeFrom((com.google.monitoring.v3.QueryErrorList) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.monitoring.v3.QueryErrorList other) {
if (other == com.google.monitoring.v3.QueryErrorList.getDefaultInstance()) return this;
if (errorsBuilder_ == null) {
if (!other.errors_.isEmpty()) {
if (errors_.isEmpty()) {
errors_ = other.errors_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureErrorsIsMutable();
errors_.addAll(other.errors_);
}
onChanged();
}
} else {
if (!other.errors_.isEmpty()) {
if (errorsBuilder_.isEmpty()) {
errorsBuilder_.dispose();
errorsBuilder_ = null;
errors_ = other.errors_;
bitField0_ = (bitField0_ & ~0x00000001);
errorsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getErrorsFieldBuilder()
: null;
} else {
errorsBuilder_.addAllMessages(other.errors_);
}
}
}
if (!other.getErrorSummary().isEmpty()) {
errorSummary_ = other.errorSummary_;
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.v3.QueryError m =
input.readMessage(
com.google.monitoring.v3.QueryError.parser(), extensionRegistry);
if (errorsBuilder_ == null) {
ensureErrorsIsMutable();
errors_.add(m);
} else {
errorsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
errorSummary_ = 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.v3.QueryError> errors_ =
java.util.Collections.emptyList();
private void ensureErrorsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
errors_ = new java.util.ArrayList<com.google.monitoring.v3.QueryError>(errors_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.monitoring.v3.QueryError,
com.google.monitoring.v3.QueryError.Builder,
com.google.monitoring.v3.QueryErrorOrBuilder>
errorsBuilder_;
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public java.util.List<com.google.monitoring.v3.QueryError> getErrorsList() {
if (errorsBuilder_ == null) {
return java.util.Collections.unmodifiableList(errors_);
} else {
return errorsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public int getErrorsCount() {
if (errorsBuilder_ == null) {
return errors_.size();
} else {
return errorsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public com.google.monitoring.v3.QueryError getErrors(int index) {
if (errorsBuilder_ == null) {
return errors_.get(index);
} else {
return errorsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public Builder setErrors(int index, com.google.monitoring.v3.QueryError value) {
if (errorsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureErrorsIsMutable();
errors_.set(index, value);
onChanged();
} else {
errorsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public Builder setErrors(
int index, com.google.monitoring.v3.QueryError.Builder builderForValue) {
if (errorsBuilder_ == null) {
ensureErrorsIsMutable();
errors_.set(index, builderForValue.build());
onChanged();
} else {
errorsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public Builder addErrors(com.google.monitoring.v3.QueryError value) {
if (errorsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureErrorsIsMutable();
errors_.add(value);
onChanged();
} else {
errorsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public Builder addErrors(int index, com.google.monitoring.v3.QueryError value) {
if (errorsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureErrorsIsMutable();
errors_.add(index, value);
onChanged();
} else {
errorsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public Builder addErrors(com.google.monitoring.v3.QueryError.Builder builderForValue) {
if (errorsBuilder_ == null) {
ensureErrorsIsMutable();
errors_.add(builderForValue.build());
onChanged();
} else {
errorsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public Builder addErrors(
int index, com.google.monitoring.v3.QueryError.Builder builderForValue) {
if (errorsBuilder_ == null) {
ensureErrorsIsMutable();
errors_.add(index, builderForValue.build());
onChanged();
} else {
errorsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public Builder addAllErrors(
java.lang.Iterable<? extends com.google.monitoring.v3.QueryError> values) {
if (errorsBuilder_ == null) {
ensureErrorsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, errors_);
onChanged();
} else {
errorsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public Builder clearErrors() {
if (errorsBuilder_ == null) {
errors_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
errorsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public Builder removeErrors(int index) {
if (errorsBuilder_ == null) {
ensureErrorsIsMutable();
errors_.remove(index);
onChanged();
} else {
errorsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public com.google.monitoring.v3.QueryError.Builder getErrorsBuilder(int index) {
return getErrorsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public com.google.monitoring.v3.QueryErrorOrBuilder getErrorsOrBuilder(int index) {
if (errorsBuilder_ == null) {
return errors_.get(index);
} else {
return errorsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public java.util.List<? extends com.google.monitoring.v3.QueryErrorOrBuilder>
getErrorsOrBuilderList() {
if (errorsBuilder_ != null) {
return errorsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(errors_);
}
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public com.google.monitoring.v3.QueryError.Builder addErrorsBuilder() {
return getErrorsFieldBuilder()
.addBuilder(com.google.monitoring.v3.QueryError.getDefaultInstance());
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public com.google.monitoring.v3.QueryError.Builder addErrorsBuilder(int index) {
return getErrorsFieldBuilder()
.addBuilder(index, com.google.monitoring.v3.QueryError.getDefaultInstance());
}
/**
*
*
* <pre>
* Errors in parsing the time series query language text. The number of errors
* in the response may be limited.
* </pre>
*
* <code>repeated .google.monitoring.v3.QueryError errors = 1;</code>
*/
public java.util.List<com.google.monitoring.v3.QueryError.Builder> getErrorsBuilderList() {
return getErrorsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.monitoring.v3.QueryError,
com.google.monitoring.v3.QueryError.Builder,
com.google.monitoring.v3.QueryErrorOrBuilder>
getErrorsFieldBuilder() {
if (errorsBuilder_ == null) {
errorsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.monitoring.v3.QueryError,
com.google.monitoring.v3.QueryError.Builder,
com.google.monitoring.v3.QueryErrorOrBuilder>(
errors_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
errors_ = null;
}
return errorsBuilder_;
}
private java.lang.Object errorSummary_ = "";
/**
*
*
* <pre>
* A summary of all the errors.
* </pre>
*
* <code>string error_summary = 2;</code>
*
* @return The errorSummary.
*/
public java.lang.String getErrorSummary() {
java.lang.Object ref = errorSummary_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
errorSummary_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A summary of all the errors.
* </pre>
*
* <code>string error_summary = 2;</code>
*
* @return The bytes for errorSummary.
*/
public com.google.protobuf.ByteString getErrorSummaryBytes() {
java.lang.Object ref = errorSummary_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
errorSummary_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A summary of all the errors.
* </pre>
*
* <code>string error_summary = 2;</code>
*
* @param value The errorSummary to set.
* @return This builder for chaining.
*/
public Builder setErrorSummary(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
errorSummary_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A summary of all the errors.
* </pre>
*
* <code>string error_summary = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearErrorSummary() {
errorSummary_ = getDefaultInstance().getErrorSummary();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A summary of all the errors.
* </pre>
*
* <code>string error_summary = 2;</code>
*
* @param value The bytes for errorSummary to set.
* @return This builder for chaining.
*/
public Builder setErrorSummaryBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
errorSummary_ = 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.v3.QueryErrorList)
}
// @@protoc_insertion_point(class_scope:google.monitoring.v3.QueryErrorList)
private static final com.google.monitoring.v3.QueryErrorList DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.monitoring.v3.QueryErrorList();
}
public static com.google.monitoring.v3.QueryErrorList getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<QueryErrorList> PARSER =
new com.google.protobuf.AbstractParser<QueryErrorList>() {
@java.lang.Override
public QueryErrorList 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<QueryErrorList> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<QueryErrorList> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.monitoring.v3.QueryErrorList getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
openjdk/jdk8 | 33,495 | jdk/test/java/util/Formatter/BasicBigDecimal.java | /*
* Copyright (c) 2003, 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.
*
* 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.
*/
/* Type-specific source code for unit test
*
* Regenerate the BasicX classes via genBasic.sh whenever this file changes.
* We check in the generated source files so that the test tree can be used
* independently of the rest of the source tree.
*/
// -- This file was mechanically generated: Do not edit! -- //
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormatSymbols;
import java.util.*;
import static java.util.Calendar.*;
public class BasicBigDecimal extends Basic {
private static void test(String fs, String exp, Object ... args) {
Formatter f = new Formatter(new StringBuilder(), Locale.US);
f.format(fs, args);
ck(fs, exp, f.toString());
}
private static void test(Locale l, String fs, String exp, Object ... args)
{
Formatter f = new Formatter(new StringBuilder(), l);
f.format(fs, args);
ck(fs, exp, f.toString());
}
private static void test(String fs, Object ... args) {
Formatter f = new Formatter(new StringBuilder(), Locale.US);
f.format(fs, args);
ck(fs, "fail", f.toString());
}
private static void test(String fs) {
Formatter f = new Formatter(new StringBuilder(), Locale.US);
f.format(fs, "fail");
ck(fs, "fail", f.toString());
}
private static void testSysOut(String fs, String exp, Object ... args) {
FileOutputStream fos = null;
FileInputStream fis = null;
try {
PrintStream saveOut = System.out;
fos = new FileOutputStream("testSysOut");
System.setOut(new PrintStream(fos));
System.out.format(Locale.US, fs, args);
fos.close();
fis = new FileInputStream("testSysOut");
byte [] ba = new byte[exp.length()];
int len = fis.read(ba);
String got = new String(ba);
if (len != ba.length)
fail(fs, exp, got);
ck(fs, exp, got);
System.setOut(saveOut);
} catch (FileNotFoundException ex) {
fail(fs, ex.getClass());
} catch (IOException ex) {
fail(fs, ex.getClass());
} finally {
try {
if (fos != null)
fos.close();
if (fis != null)
fis.close();
} catch (IOException ex) {
fail(fs, ex.getClass());
}
}
}
private static void tryCatch(String fs, Class<?> ex) {
boolean caught = false;
try {
test(fs);
} catch (Throwable x) {
if (ex.isAssignableFrom(x.getClass()))
caught = true;
}
if (!caught)
fail(fs, ex);
else
pass();
}
private static void tryCatch(String fs, Class<?> ex, Object ... args) {
boolean caught = false;
try {
test(fs, args);
} catch (Throwable x) {
if (ex.isAssignableFrom(x.getClass()))
caught = true;
}
if (!caught)
fail(fs, ex);
else
pass();
}
private static BigDecimal create(double v) {
return new BigDecimal(v);
}
private static BigDecimal negate(BigDecimal v) {
return v.negate();
}
private static BigDecimal mult(BigDecimal v, double mul) {
return v.multiply(new BigDecimal(mul));
}
private static BigDecimal recip(BigDecimal v) {
return BigDecimal.ONE.divide(v);
}
public static void test() {
TimeZone.setDefault(TimeZone.getTimeZone("GMT-0800"));
// Any characters not explicitly defined as conversions, date/time
// conversion suffixes, or flags are illegal and are reserved for
// future extensions. Use of such a character in a format string will
// cause an UnknownFormatConversionException or
// UnknownFormatFlagsException to be thrown.
tryCatch("%q", UnknownFormatConversionException.class);
tryCatch("%t&", UnknownFormatConversionException.class);
tryCatch("%&d", UnknownFormatConversionException.class);
tryCatch("%^b", UnknownFormatConversionException.class);
//---------------------------------------------------------------------
// Formatter.java class javadoc examples
//---------------------------------------------------------------------
test(Locale.FRANCE, "e = %+10.4f", "e = +2,7183", Math.E);
test("%4$2s %3$2s %2$2s %1$2s", " d c b a", "a", "b", "c", "d");
test("Amount gained or lost since last statement: $ %,(.2f",
"Amount gained or lost since last statement: $ (6,217.58)",
(new BigDecimal("-6217.58")));
Calendar c = new GregorianCalendar(1969, JULY, 20, 16, 17, 0);
testSysOut("Local time: %tT", "Local time: 16:17:00", c);
test("Unable to open file '%1$s': %2$s",
"Unable to open file 'food': No such file or directory",
"food", "No such file or directory");
Calendar duke = new GregorianCalendar(1995, MAY, 23, 19, 48, 34);
duke.set(Calendar.MILLISECOND, 584);
test("Duke's Birthday: %1$tB %1$te, %1$tY",
"Duke's Birthday: May 23, 1995",
duke);
test("Duke's Birthday: %1$tB %1$te, %1$tY",
"Duke's Birthday: May 23, 1995",
duke.getTime());
test("Duke's Birthday: %1$tB %1$te, %1$tY",
"Duke's Birthday: May 23, 1995",
duke.getTimeInMillis());
test("%4$s %3$s %2$s %1$s %4$s %3$s %2$s %1$s",
"d c b a d c b a", "a", "b", "c", "d");
test("%s %s %<s %<s", "a b b b", "a", "b", "c", "d");
test("%s %s %s %s", "a b c d", "a", "b", "c", "d");
test("%2$s %s %<s %s", "b a a b", "a", "b", "c", "d");
//---------------------------------------------------------------------
// %b
//
// General conversion applicable to any argument.
//---------------------------------------------------------------------
test("%b", "true", true);
test("%b", "false", false);
test("%B", "TRUE", true);
test("%B", "FALSE", false);
test("%b", "true", Boolean.TRUE);
test("%b", "false", Boolean.FALSE);
test("%B", "TRUE", Boolean.TRUE);
test("%B", "FALSE", Boolean.FALSE);
test("%14b", " true", true);
test("%-14b", "true ", true);
test("%5.1b", " f", false);
test("%-5.1b", "f ", false);
test("%b", "true", "foo");
test("%b", "false", (Object)null);
// Boolean.java hardcodes the Strings for "true" and "false", so no
// localization is possible.
test(Locale.FRANCE, "%b", "true", true);
test(Locale.FRANCE, "%b", "false", false);
// If you pass in a single array to a varargs method, the compiler
// uses it as the array of arguments rather than treating it as a
// single array-type argument.
test("%b", "false", (Object[])new String[2]);
test("%b", "true", new String[2], new String[2]);
int [] ia = { 1, 2, 3 };
test("%b", "true", ia);
//---------------------------------------------------------------------
// %b - errors
//---------------------------------------------------------------------
tryCatch("%#b", FormatFlagsConversionMismatchException.class);
tryCatch("%-b", MissingFormatWidthException.class);
// correct or side-effect of implementation?
tryCatch("%.b", UnknownFormatConversionException.class);
tryCatch("%,b", FormatFlagsConversionMismatchException.class);
//---------------------------------------------------------------------
// %c
//
// General conversion applicable to any argument.
//---------------------------------------------------------------------
test("%c", "i", 'i');
test("%C", "I", 'i');
test("%4c", " i", 'i');
test("%-4c", "i ", 'i');
test("%4C", " I", 'i');
test("%-4C", "I ", 'i');
test("%c", "i", new Character('i'));
test("%c", "H", (byte) 72);
test("%c", "i", (short) 105);
test("%c", "!", (int) 33);
test("%c", "\u007F", Byte.MAX_VALUE);
test("%c", new String(Character.toChars(Short.MAX_VALUE)),
Short.MAX_VALUE);
test("%c", "null", (Object) null);
//---------------------------------------------------------------------
// %c - errors
//---------------------------------------------------------------------
tryCatch("%c", IllegalFormatConversionException.class,
Boolean.TRUE);
tryCatch("%c", IllegalFormatConversionException.class,
(float) 0.1);
tryCatch("%c", IllegalFormatConversionException.class,
new Object());
tryCatch("%c", IllegalFormatCodePointException.class,
Byte.MIN_VALUE);
tryCatch("%c", IllegalFormatCodePointException.class,
Short.MIN_VALUE);
tryCatch("%c", IllegalFormatCodePointException.class,
Integer.MIN_VALUE);
tryCatch("%c", IllegalFormatCodePointException.class,
Integer.MAX_VALUE);
tryCatch("%#c", FormatFlagsConversionMismatchException.class);
tryCatch("%,c", FormatFlagsConversionMismatchException.class);
tryCatch("%(c", FormatFlagsConversionMismatchException.class);
tryCatch("%$c", UnknownFormatConversionException.class);
tryCatch("%.2c", IllegalFormatPrecisionException.class);
//---------------------------------------------------------------------
// %s
//
// General conversion applicable to any argument.
//---------------------------------------------------------------------
test("%s", "Hello, Duke", "Hello, Duke");
test("%S", "HELLO, DUKE", "Hello, Duke");
test("%20S", " HELLO, DUKE", "Hello, Duke");
test("%20s", " Hello, Duke", "Hello, Duke");
test("%-20s", "Hello, Duke ", "Hello, Duke");
test("%-20.5s", "Hello ", "Hello, Duke");
test("%s", "null", (Object)null);
StringBuffer sb = new StringBuffer("foo bar");
test("%s", sb.toString(), sb);
test("%S", sb.toString().toUpperCase(), sb);
//---------------------------------------------------------------------
// %s - errors
//---------------------------------------------------------------------
tryCatch("%-s", MissingFormatWidthException.class);
tryCatch("%--s", DuplicateFormatFlagsException.class);
tryCatch("%#s", FormatFlagsConversionMismatchException.class, 0);
tryCatch("%#s", FormatFlagsConversionMismatchException.class, 0.5f);
tryCatch("%#s", FormatFlagsConversionMismatchException.class, "hello");
tryCatch("%#s", FormatFlagsConversionMismatchException.class, null);
//---------------------------------------------------------------------
// %h
//
// General conversion applicable to any argument.
//---------------------------------------------------------------------
test("%h", Integer.toHexString("Hello, Duke".hashCode()),
"Hello, Duke");
test("%10h", " ddf63471", "Hello, Duke");
test("%-10h", "ddf63471 ", "Hello, Duke");
test("%-10H", "DDF63471 ", "Hello, Duke");
test("%10h", " 402e0000", 15.0);
test("%10H", " 402E0000", 15.0);
//---------------------------------------------------------------------
// %h - errors
//---------------------------------------------------------------------
tryCatch("%#h", FormatFlagsConversionMismatchException.class);
//---------------------------------------------------------------------
// flag/conversion errors
//---------------------------------------------------------------------
tryCatch("%F", UnknownFormatConversionException.class);
tryCatch("%#g", FormatFlagsConversionMismatchException.class);
//---------------------------------------------------------------------
// %s - BigDecimal
//---------------------------------------------------------------------
BigDecimal one = BigDecimal.ONE;
BigDecimal ten = BigDecimal.TEN;
BigDecimal pi = new BigDecimal(Math.PI);
BigDecimal piToThe300 = pi.pow(300);
test("%s", "3.141592653589793115997963468544185161590576171875", pi);
//---------------------------------------------------------------------
// flag/conversion errors
//---------------------------------------------------------------------
tryCatch("%d", IllegalFormatConversionException.class, one);
tryCatch("%,.4e", FormatFlagsConversionMismatchException.class, one);
//---------------------------------------------------------------------
// %e
//
// Floating-point conversions applicable to float, double, and
// BigDecimal.
//---------------------------------------------------------------------
test("%e", "null", (Object)null);
//---------------------------------------------------------------------
// %e - float and double
//---------------------------------------------------------------------
// double PI = 3.141 592 653 589 793 238 46;
test("%e", "3.141593e+00", pi);
test("%.0e", "1e+01", ten);
test("%#.0e", "1.e+01", ten);
test("%E", "3.141593E+00", pi);
test("%10.3e", " 3.142e+00", pi);
test("%10.3e", "-3.142e+00", negate(pi));
test("%010.3e", "03.142e+00", pi);
test("%010.3e", "-3.142e+00", negate(pi));
test("%-12.3e", "3.142e+00 ", pi);
test("%-12.3e", "-3.142e+00 ", negate(pi));
test("%.3e", "3.142e+00", pi);
test("%.3e", "-3.142e+00", negate(pi));
test("%.3e", "3.142e+06", mult(pi, 1000000.0));
test("%.3e", "-3.142e+06", mult(pi, -1000000.0));
test(Locale.FRANCE, "%e", "3,141593e+00", pi);
// double PI^300
// = 13962455701329742638131355433930076081862072808 ... e+149
//---------------------------------------------------------------------
// %e - BigDecimal
//---------------------------------------------------------------------
test("%.3e", "1.396e+149", piToThe300);
test("%.3e", "-1.396e+149", piToThe300.negate());
test("%.3e", "1.000e-100", recip(ten.pow(100)));
test("%.3e", "-1.000e-100", negate(recip(ten.pow(100))));
test("%3.0e", "1e-06", new BigDecimal("0.000001"));
test("%3.0e", "1e-05", new BigDecimal("0.00001"));
test("%3.0e", "1e-04", new BigDecimal("0.0001"));
test("%3.0e", "1e-03", new BigDecimal("0.001"));
test("%3.0e", "1e-02", new BigDecimal("0.01"));
test("%3.0e", "1e-01", new BigDecimal("0.1"));
test("%3.0e", "9e-01", new BigDecimal("0.9"));
test("%3.1e", "9.0e-01", new BigDecimal("0.9"));
test("%3.0e", "1e+00", new BigDecimal("1.00"));
test("%3.0e", "1e+01", new BigDecimal("10.00"));
test("%3.0e", "1e+02", new BigDecimal("99.19"));
test("%3.1e", "9.9e+01", new BigDecimal("99.19"));
test("%3.0e", "1e+02", new BigDecimal("99.99"));
test("%3.0e", "1e+02", new BigDecimal("100.00"));
test("%#3.0e", "1.e+03", new BigDecimal("1000.00"));
test("%3.0e", "1e+04", new BigDecimal("10000.00"));
test("%3.0e", "1e+05", new BigDecimal("100000.00"));
test("%3.0e", "1e+06", new BigDecimal("1000000.00"));
test("%3.0e", "1e+07", new BigDecimal("10000000.00"));
test("%3.0e", "1e+08", new BigDecimal("100000000.00"));
test("%10.3e", " 1.000e+00", one);
test("%+.3e", "+3.142e+00", pi);
test("%+.3e", "-3.142e+00", negate(pi));
test("% .3e", " 3.142e+00", pi);
test("% .3e", "-3.142e+00", negate(pi));
test("%#.0e", "3.e+00", create(3.0));
test("%#.0e", "-3.e+00", create(-3.0));
test("%.0e", "3e+00", create(3.0));
test("%.0e", "-3e+00", create(-3.0));
test("%(.4e", "3.1416e+06", mult(pi, 1000000.0));
test("%(.4e", "(3.1416e+06)", mult(pi, -1000000.0));
//---------------------------------------------------------------------
// %e - boundary problems
//---------------------------------------------------------------------
test("%3.0e", "1e-06", 0.000001);
test("%3.0e", "1e-05", 0.00001);
test("%3.0e", "1e-04", 0.0001);
test("%3.0e", "1e-03", 0.001);
test("%3.0e", "1e-02", 0.01);
test("%3.0e", "1e-01", 0.1);
test("%3.0e", "9e-01", 0.9);
test("%3.1e", "9.0e-01", 0.9);
test("%3.0e", "1e+00", 1.00);
test("%3.0e", "1e+01", 10.00);
test("%3.0e", "1e+02", 99.19);
test("%3.1e", "9.9e+01", 99.19);
test("%3.0e", "1e+02", 99.99);
test("%3.0e", "1e+02", 100.00);
test("%#3.0e", "1.e+03", 1000.00);
test("%3.0e", "1e+04", 10000.00);
test("%3.0e", "1e+05", 100000.00);
test("%3.0e", "1e+06", 1000000.00);
test("%3.0e", "1e+07", 10000000.00);
test("%3.0e", "1e+08", 100000000.00);
//---------------------------------------------------------------------
// %f
//
// Floating-point conversions applicable to float, double, and
// BigDecimal.
//---------------------------------------------------------------------
test("%f", "null", (Object)null);
test("%f", "3.141593", pi);
test(Locale.FRANCE, "%f", "3,141593", pi);
test("%10.3f", " 3.142", pi);
test("%10.3f", " -3.142", negate(pi));
test("%010.3f", "000003.142", pi);
test("%010.3f", "-00003.142", negate(pi));
test("%-10.3f", "3.142 ", pi);
test("%-10.3f", "-3.142 ", negate(pi));
test("%.3f", "3.142", pi);
test("%.3f", "-3.142", negate(pi));
test("%+.3f", "+3.142", pi);
test("%+.3f", "-3.142", negate(pi));
test("% .3f", " 3.142", pi);
test("% .3f", "-3.142", negate(pi));
test("%#.0f", "3.", create(3.0));
test("%#.0f", "-3.", create(-3.0));
test("%.0f", "3", create(3.0));
test("%.0f", "-3", create(-3.0));
test("%.3f", "10.000", ten);
test("%.3f", "1.000", one);
test("%10.3f", " 1.000", one);
//---------------------------------------------------------------------
// %f - boundary problems
//---------------------------------------------------------------------
test("%3.0f", " 0", 0.000001);
test("%3.0f", " 0", 0.00001);
test("%3.0f", " 0", 0.0001);
test("%3.0f", " 0", 0.001);
test("%3.0f", " 0", 0.01);
test("%3.0f", " 0", 0.1);
test("%3.0f", " 1", 0.9);
test("%3.1f", "0.9", 0.9);
test("%3.0f", " 1", 1.00);
test("%3.0f", " 10", 10.00);
test("%3.0f", " 99", 99.19);
test("%3.1f", "99.2", 99.19);
test("%3.0f", "100", 99.99);
test("%3.0f", "100", 100.00);
test("%#3.0f", "1000.", 1000.00);
test("%3.0f", "10000", 10000.00);
test("%3.0f", "100000", 100000.00);
test("%3.0f", "1000000", 1000000.00);
test("%3.0f", "10000000", 10000000.00);
test("%3.0f", "100000000", 100000000.00);
//---------------------------------------------------------------------
// %f - BigDecimal
//---------------------------------------------------------------------
test("%4.0f", " 99", new BigDecimal("99.19"));
test("%4.1f", "99.2", new BigDecimal("99.19"));
BigDecimal val = new BigDecimal("99.95");
test("%4.0f", " 100", val);
test("%#4.0f", "100.", val);
test("%4.1f", "100.0", val);
test("%4.2f", "99.95", val);
test("%4.3f", "99.950", val);
val = new BigDecimal(".99");
test("%4.1f", " 1.0", val);
test("%4.2f", "0.99", val);
test("%4.3f", "0.990", val);
// #6476425
val = new BigDecimal("0.00001");
test("%.0f", "0", val);
test("%.1f", "0.0", val);
test("%.2f", "0.00", val);
test("%.3f", "0.000", val);
test("%.4f", "0.0000", val);
test("%.5f", "0.00001", val);
val = new BigDecimal("1.00001");
test("%.0f", "1", val);
test("%.1f", "1.0", val);
test("%.2f", "1.00", val);
test("%.3f", "1.000", val);
test("%.4f", "1.0000", val);
test("%.5f", "1.00001", val);
val = new BigDecimal("1.23456");
test("%.0f", "1", val);
test("%.1f", "1.2", val);
test("%.2f", "1.23", val);
test("%.3f", "1.235", val);
test("%.4f", "1.2346", val);
test("%.5f", "1.23456", val);
test("%.6f", "1.234560", val);
val = new BigDecimal("9.99999");
test("%.0f", "10", val);
test("%.1f", "10.0", val);
test("%.2f", "10.00", val);
test("%.3f", "10.000", val);
test("%.4f", "10.0000", val);
test("%.5f", "9.99999", val);
test("%.6f", "9.999990", val);
val = new BigDecimal("1.99999");
test("%.0f", "2", val);
test("%.1f", "2.0", val);
test("%.2f", "2.00", val);
test("%.3f", "2.000", val);
test("%.4f", "2.0000", val);
test("%.5f", "1.99999", val);
test("%.6f", "1.999990", val);
val = new BigDecimal(0.9996);
test("%.0f", "1", val);
test("%.1f", "1.0", val);
test("%.2f", "1.00", val);
test("%.3f", "1.000", val);
test("%.4f", "0.9996", val);
test("%.5f", "0.99960", val);
test("%.6f", "0.999600", val);
//---------------------------------------------------------------------
// %f - float, double, Double, BigDecimal
//---------------------------------------------------------------------
test("%.3f", "3141592.654", mult(pi, 1000000.0));
test("%.3f", "-3141592.654", mult(pi, -1000000.0));
test("%,.4f", "3,141,592.6536", mult(pi, 1000000.0));
test(Locale.FRANCE, "%,.4f", "3\u00a0141\u00a0592,6536", mult(pi, 1000000.0));
test("%,.4f", "-3,141,592.6536", mult(pi, -1000000.0));
test("%(.4f", "3141592.6536", mult(pi, 1000000.0));
test("%(.4f", "(3141592.6536)", mult(pi, -1000000.0));
test("%(,.4f", "3,141,592.6536", mult(pi, 1000000.0));
test("%(,.4f", "(3,141,592.6536)", mult(pi, -1000000.0));
//---------------------------------------------------------------------
// %g
//
// Floating-point conversions applicable to float, double, and
// BigDecimal.
//---------------------------------------------------------------------
test("%g", "null", (Object)null);
test("%g", "3.14159", pi);
test(Locale.FRANCE, "%g", "3,14159", pi);
test("%.0g", "1e+01", ten);
test("%G", "3.14159", pi);
test("%10.3g", " 3.14", pi);
test("%10.3g", " -3.14", negate(pi));
test("%010.3g", "0000003.14", pi);
test("%010.3g", "-000003.14", negate(pi));
test("%-12.3g", "3.14 ", pi);
test("%-12.3g", "-3.14 ", negate(pi));
test("%.3g", "3.14", pi);
test("%.3g", "-3.14", negate(pi));
test("%.3g", "3.14e+08", mult(pi, 100000000.0));
test("%.3g", "-3.14e+08", mult(pi, -100000000.0));
test("%.3g", "1.00e-05", recip(create(100000.0)));
test("%.3g", "-1.00e-05", recip(create(-100000.0)));
test("%.0g", "-1e-05", recip(create(-100000.0)));
test("%.0g", "1e+05", create(100000.0));
test("%.3G", "1.00E-05", recip(create(100000.0)));
test("%.3G", "-1.00E-05", recip(create(-100000.0)));
test("%.1g", "-0", -0.0);
test("%3.0g", " -0", -0.0);
test("%.1g", "0", 0.0);
test("%3.0g", " 0", 0.0);
test("%.1g", "0", +0.0);
test("%3.0g", " 0", +0.0);
test("%3.0g", "1e-06", 0.000001);
test("%3.0g", "1e-05", 0.00001);
test("%3.0g", "1e-05", 0.0000099);
test("%3.1g", "1e-05", 0.0000099);
test("%3.2g", "9.9e-06", 0.0000099);
test("%3.0g", "0.0001", 0.0001);
test("%3.0g", "9e-05", 0.00009);
test("%3.0g", "0.0001", 0.000099);
test("%3.1g", "0.0001", 0.000099);
test("%3.2g", "9.9e-05", 0.000099);
test("%3.0g", "0.001", 0.001);
test("%3.0g", "0.001", 0.00099);
test("%3.1g", "0.001", 0.00099);
test("%3.2g", "0.00099", 0.00099);
test("%3.3g", "0.00100", 0.001);
test("%3.4g", "0.001000", 0.001);
test("%3.0g", "0.01", 0.01);
test("%3.0g", "0.1", 0.1);
test("%3.0g", "0.9", 0.9);
test("%3.1g", "0.9", 0.9);
test("%3.0g", " 1", 1.00);
test("%3.2g", " 10", 10.00);
test("%3.0g", "1e+01", 10.00);
test("%3.0g", "1e+02", 99.19);
test("%3.1g", "1e+02", 99.19);
test("%3.2g", " 99", 99.19);
test("%3.0g", "1e+02", 99.9);
test("%3.1g", "1e+02", 99.9);
test("%3.2g", "1.0e+02", 99.9);
test("%3.0g", "1e+02", 99.99);
test("%3.0g", "1e+02", 100.00);
test("%3.0g", "1e+03", 999.9);
test("%3.1g", "1e+03", 999.9);
test("%3.2g", "1.0e+03", 999.9);
test("%3.3g", "1.00e+03", 999.9);
test("%3.4g", "999.9", 999.9);
test("%3.4g", "1000", 999.99);
test("%3.0g", "1e+03", 1000.00);
test("%3.0g", "1e+04", 10000.00);
test("%3.0g", "1e+05", 100000.00);
test("%3.0g", "1e+06", 1000000.00);
test("%3.0g", "1e+07", 10000000.00);
test("%3.9g", "100000000", 100000000.00);
test("%3.10g", "100000000.0", 100000000.00);
tryCatch("%#3.0g", FormatFlagsConversionMismatchException.class, 1000.00);
// double PI^300
// = 13962455701329742638131355433930076081862072808 ... e+149
//---------------------------------------------------------------------
// %g - BigDecimal
//---------------------------------------------------------------------
test("%.3g", "1.40e+149", piToThe300);
test("%.3g", "-1.40e+149", piToThe300.negate());
test(Locale.FRANCE, "%.3g", "-1,40e+149", piToThe300.negate());
test("%.3g", "1.00e-100", recip(ten.pow(100)));
test("%.3g", "-1.00e-100", negate(recip(ten.pow(100))));
test("%3.0g", "1e-06", new BigDecimal("0.000001"));
test("%3.0g", "1e-05", new BigDecimal("0.00001"));
test("%3.0g", "0.0001", new BigDecimal("0.0001"));
test("%3.0g", "0.001", new BigDecimal("0.001"));
test("%3.3g", "0.00100", new BigDecimal("0.001"));
test("%3.4g", "0.001000", new BigDecimal("0.001"));
test("%3.0g", "0.01", new BigDecimal("0.01"));
test("%3.0g", "0.1", new BigDecimal("0.1"));
test("%3.0g", "0.9", new BigDecimal("0.9"));
test("%3.1g", "0.9", new BigDecimal("0.9"));
test("%3.0g", " 1", new BigDecimal("1.00"));
test("%3.2g", " 10", new BigDecimal("10.00"));
test("%3.0g", "1e+01", new BigDecimal("10.00"));
test("%3.0g", "1e+02", new BigDecimal("99.19"));
test("%3.1g", "1e+02", new BigDecimal("99.19"));
test("%3.2g", " 99", new BigDecimal("99.19"));
test("%3.0g", "1e+02", new BigDecimal("99.99"));
test("%3.0g", "1e+02", new BigDecimal("100.00"));
test("%3.0g", "1e+03", new BigDecimal("1000.00"));
test("%3.0g", "1e+04", new BigDecimal("10000.00"));
test("%3.0g", "1e+05", new BigDecimal("100000.00"));
test("%3.0g", "1e+06", new BigDecimal("1000000.00"));
test("%3.0g", "1e+07", new BigDecimal("10000000.00"));
test("%3.9g", "100000000", new BigDecimal("100000000.00"));
test("%3.10g", "100000000.0", new BigDecimal("100000000.00"));
test("%.3g", "10.0", ten);
test("%.3g", "1.00", one);
test("%10.3g", " 1.00", one);
test("%+10.3g", " +3.14", pi);
test("%+10.3g", " -3.14", negate(pi));
test("% .3g", " 3.14", pi);
test("% .3g", "-3.14", negate(pi));
test("%.0g", "3", create(3.0));
test("%.0g", "-3", create(-3.0));
test("%(.4g", "3.142e+08", mult(pi, 100000000.0));
test("%(.4g", "(3.142e+08)", mult(pi, -100000000.0));
test("%,.11g", "3,141,592.6536", mult(pi, 1000000.0));
test("%(,.11g", "(3,141,592.6536)", mult(pi, -1000000.0));
//---------------------------------------------------------------------
// %f, %e, %g, %a - Boundaries
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// %t
//
// Date/Time conversions applicable to Calendar, Date, and long.
//---------------------------------------------------------------------
test("%tA", "null", (Object)null);
test("%TA", "NULL", (Object)null);
//---------------------------------------------------------------------
// %t - errors
//---------------------------------------------------------------------
tryCatch("%t", UnknownFormatConversionException.class);
tryCatch("%T", UnknownFormatConversionException.class);
tryCatch("%tP", UnknownFormatConversionException.class);
tryCatch("%TP", UnknownFormatConversionException.class);
tryCatch("%.5tB", IllegalFormatPrecisionException.class);
tryCatch("%#tB", FormatFlagsConversionMismatchException.class);
tryCatch("%-tB", MissingFormatWidthException.class);
//---------------------------------------------------------------------
// %n
//---------------------------------------------------------------------
test("%n", System.getProperty("line.separator"), (Object)null);
test("%n", System.getProperty("line.separator"), "");
tryCatch("%,n", IllegalFormatFlagsException.class);
tryCatch("%.n", UnknownFormatConversionException.class);
tryCatch("%5.n", UnknownFormatConversionException.class);
tryCatch("%5n", IllegalFormatWidthException.class);
tryCatch("%.7n", IllegalFormatPrecisionException.class);
tryCatch("%<n", IllegalFormatFlagsException.class);
//---------------------------------------------------------------------
// %%
//---------------------------------------------------------------------
test("%%", "%", (Object)null);
test("%%", "%", "");
tryCatch("%%%", UnknownFormatConversionException.class);
// perhaps an IllegalFormatArgumentIndexException should be defined?
tryCatch("%<%", IllegalFormatFlagsException.class);
}
}
|
apache/marmotta | 35,919 | commons/marmotta-sesame-tools/marmotta-util-facading/src/main/java/org/apache/marmotta/commons/sesame/facading/impl/FacadingInvocationHandler.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.marmotta.commons.sesame.facading.impl;
import org.apache.marmotta.commons.sesame.facading.annotations.RDF;
import org.apache.marmotta.commons.sesame.facading.annotations.RDFInverse;
import org.apache.marmotta.commons.sesame.facading.annotations.RDFPropertyBuilder;
import org.apache.marmotta.commons.sesame.facading.api.Facading;
import org.apache.marmotta.commons.sesame.facading.api.FacadingPredicateBuilder;
import org.apache.marmotta.commons.sesame.facading.model.Facade;
import org.apache.marmotta.commons.sesame.facading.util.FacadeUtils;
import org.apache.marmotta.commons.util.DateUtils;
import org.joda.time.DateTime;
import org.openrdf.model.*;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.*;
import java.util.*;
/**
* This class implements an invocation handler to be used for proxy classes that delegate to a
* content item and to data in the triple store. It has to be constructed using the triple store
* implementation as parameter. Interfaces that make use of this invocation handler need to extend
* the {@link Facade} interface.
*
* @author Sebastian Schaffert <sschaffert@apache.org>
* @author Jakob Frank <jakob@apache.org>
*/
class FacadingInvocationHandler implements InvocationHandler {
public enum OPERATOR {
GET(false, 0, "get"),
SET(true, 1, "set"),
ADD(true, 1, "add"),
DEL(true, 0, "del", "delete", "remove", "rm"),
HAS(false, 0, "has", "is");
private static final String[] PX, SPX;
static {
LinkedList<String> ops = new LinkedList<>();
for (OPERATOR op : OPERATOR.values()) {
Collections.addAll(ops, op.prefixes);
}
PX = ops.toArray(new String[ops.size()]);
SPX = ops.toArray(new String[ops.size()]);
Arrays.sort(SPX, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.length() - o1.length();
}
});
}
final String[] prefixes;
final int numArgs;
final boolean writeOp;
OPERATOR(boolean isWriteOp, int args, String... strings) {
this.writeOp = isWriteOp;
this.numArgs = args;
this.prefixes = strings;
}
@Override
public String toString() {
return prefixes[0];
}
public static String[] getOperatorPrefixes() {
return PX;
}
public static String[] getLengthSortedOperatorPrefixes() {
return SPX;
}
public static OPERATOR getOperator(Method m) {
for (OPERATOR op : values()) {
for (String px : op.prefixes) {
if (m.getName().startsWith(px)) {
final int numP = m.getParameterTypes().length;
if (numP == op.numArgs || numP == op.numArgs + 1) { return op; }
}
}
}
return valueOf(m.getName());
}
}
private final RepositoryConnection connection;
private final Facading facadingService;
private final Class<? extends Facade> declaredFacade;
private final FacadingPredicateBuilder propBuilder;
private final Resource delegate;
private final URI context;
private final HashMap<String, Object> fieldCache;
private final Logger log;
/**
* Indicates if the cache is used, by default is false.
*/
private boolean useCache;
public FacadingInvocationHandler(Resource item, URI context, Class<? extends Facade> facade, Facading facadingService, RepositoryConnection connection) {
this.log = LoggerFactory.getLogger(facade.getName() + "!" + this.getClass().getSimpleName() + "@" + item.stringValue());
this.delegate = item;
this.facadingService = facadingService;
this.declaredFacade = facade;
this.connection = connection;
if (declaredFacade.isAnnotationPresent(RDFPropertyBuilder.class)) {
final Class<? extends FacadingPredicateBuilder> bClass = declaredFacade.getAnnotation(RDFPropertyBuilder.class).value();
FacadingPredicateBuilder _b = null;
try {
// Look for a no-arg Constructor
_b = bClass.getConstructor().newInstance();
} catch (NoSuchMethodException e) {
// If there is no no-arg Constructor, try static getInstance()
try {
for (Method m : bClass.getMethods()) {
if (Modifier.isStatic(m.getModifiers()) && "getInstance".equals(m.getName()) && m.getParameterTypes().length == 0) {
_b = (FacadingPredicateBuilder) m.invoke(null);
break;
}
}
if (_b == null) { throw new IllegalArgumentException("Could not find no-arg Constructor or static no-arg factory-method 'getInstance' for "
+ bClass.getName()); }
} catch (Exception e1) {
throw new IllegalArgumentException("Could not load instance of " + bClass.getSimpleName() + " from static factory 'getInstance()': "
+ e.getMessage(), e);
}
} catch (Exception e) {
throw new IllegalArgumentException("Could not create instance of " + bClass.getSimpleName() + ": " + e.getMessage(), e);
}
this.propBuilder = _b;
} else {
this.propBuilder = null;
}
if (context != null) {
this.context = context;
} else {
// FIXME
this.context = null;
}
fieldCache = new HashMap<>();
// disable cache, it does not work well with deleted triples ...
useCache = false;
}
/**
* Indicates if the cache is allow or not.
*
* @return the useCache true if the cache is done.
*/
public boolean isUseCache() {
return useCache;
}
/**
* Used to enable/disable the cache mechanism.
*
* @param useCache
* true foe enable cache, false - no cache.
*/
public void setUseCache(boolean useCache) {
this.useCache = useCache;
}
/**
* @return the item
*/
public Resource getDelegate() {
return delegate;
}
/**
* Invoke the invocation handler for the given proxy object, method, and arguments. In order to
* execute the passed method, this method does the following: - if the method has a
* <code>RDF</code> annotation or if it is a setter and the corresponding getter has a
* <code>RDF</code> annotation, we try to retrieve the appropriate value by querying the triple
* store and converting the triple store data to the return type of the method; if the return
* type is again an interface
*
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method,
* java.lang.Object[])
* @see org.apache.marmotta.commons.sesame.facading.annotations.RDF
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws InstantiationException, IllegalAccessException, RepositoryException {
if (!connection.isOpen()) { throw new IllegalAccessException("the connection is already closed, cannot access proxy methods."); }
if (!connection.isActive()) { throw new IllegalAccessException("no active transaction, cannot access triple-store."); }
// handle default methods:
if (FacadingInvocationHelper.checkMethodSig(method, "hashCode")) {
return delegate.hashCode();
} else if (FacadingInvocationHelper.checkMethodSig(method, "equals", 1)) {
final Object other = args[0];
return other != null && other.getClass().equals(proxy.getClass()) && other.hashCode() == proxy.hashCode();
} else if (FacadingInvocationHelper.checkMethodSig(method, "toString")) {
return declaredFacade.getSimpleName() + " with delegate to " + delegate.toString();
} else if (FacadingInvocationHelper.checkMethodSig(method, "getDelegate")) { return delegate; }
// caching
final String fieldName = FacadingInvocationHelper.getBaseName(method);
if (useCache && method.getName().startsWith("get")) {
if (fieldCache.get(fieldName) != null) { return fieldCache.get(fieldName); }
}
final FacadingPredicate fp = getFacadingPredicate(method);
// distinguish getters and setters and more...
switch (OPERATOR.getOperator(method)) {
case GET:
return handleGet(method, args, fp);
case SET:
return handleSet(method, args, fp);
case ADD:
return handleAdd(method, args, fp);
case DEL:
return handleDel(method, args, fp);
case HAS:
return handleHas(method, args, fp);
default:
throw new IllegalArgumentException("Unsupported method: " + method.getName());
}
}
private FacadingPredicate getFacadingPredicate(Method method) throws IllegalArgumentException {
final String[] rdf_property;
final boolean inverse;
// look for RDF annotation and extract the property from it; if not on the getter, look
// for the corresponding setter and check whether it has a @RDF annotation; if neither has,
// throw an IllegalArgumentException
RDF rdf = FacadingInvocationHelper.getAnnotation(method, RDF.class);
if (rdf != null) {
rdf_property = rdf.value();
inverse = false;
return new FacadingPredicate(inverse, rdf_property);
} else {
RDFInverse rdfi = FacadingInvocationHelper.getAnnotation(method, RDFInverse.class);
if (rdfi != null) {
rdf_property = rdfi.value();
inverse = true;
return new FacadingPredicate(inverse, rdf_property);
} else {
if (propBuilder != null) {
String fName = FacadingInvocationHelper.getBaseName(method);
if (fName.length() > 1) {
fName = fName.substring(0, 1).toLowerCase(Locale.ENGLISH) + fName.substring(1);
}
return propBuilder.getFacadingPredicate(fName, declaredFacade, method);
} else {
throw new IllegalArgumentException("Could not find facading predicate for " + method.getName() + " in " + declaredFacade.getName());
}
}
}
}
private Boolean handleHas(Method method, Object[] args, FacadingPredicate predicate) throws RepositoryException {
final Locale loc;
if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(Locale.class)) {
loc = (Locale) args[0];
} else {
loc = null;
}
if (predicate.isInverse()) {
if (loc != null) { throw new IllegalArgumentException("@RDFInverse not supported for language tagged properties"); }
else {
for (String p : predicate.getProperties()) {
final URI prop = connection.getValueFactory().createURI(p);
final RepositoryResult<Statement> result = connection.getStatements(null, prop, delegate, true, context);
try {
if (result.hasNext()) { return true; }
} finally {
result.close();
}
}
}
} else {
for (String p : predicate.getProperties()) {
final URI prop = connection.getValueFactory().createURI(p);
final RepositoryResult<Statement> result = connection.getStatements(delegate, prop, null, true, context);
try {
if (loc == null) {
if (result.hasNext()) { return true; }
} else {
while (result.hasNext()) {
final Value o = result.next().getObject();
if (FacadingInvocationHelper.checkLocale(loc, o)) { return true; }
}
}
} finally {
result.close();
}
}
}
return false;
}
private Object handleDel(Method method, Object[] args, FacadingPredicate predicate) throws RepositoryException {
final Locale loc;
if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(Locale.class)) {
loc = (Locale) args[0];
} else {
loc = null;
}
delProperties(predicate, loc);
return null;
}
private Object handleAdd(Method method, Object[] args, FacadingPredicate predicate) throws RepositoryException, IllegalArgumentException {
final Locale loc;
if (method.getParameterTypes().length == 2 && method.getParameterTypes()[1].equals(Locale.class)) {
loc = (Locale) args[1];
} else {
loc = null;
}
final Class<?> paramType = method.getParameterTypes()[0];
addProperties(method, args, predicate.getProperties(), predicate.isInverse(), loc, paramType);
return null;
}
private Object handleSet(Method method, Object[] args, FacadingPredicate predicate)
throws RepositoryException, IllegalArgumentException {
final Locale loc;
if (method.getParameterTypes().length == 2 && method.getParameterTypes()[1].equals(Locale.class)) {
loc = (Locale) args[1];
} else {
loc = null;
}
// add to cache
if (useCache) {
fieldCache.put(FacadingInvocationHelper.getBaseName(method), args[0]);
}
// This is SET, so delete all previous properties
delProperties(predicate, loc);
// *** set the value of a certain RDF property
final Class<?> paramType = method.getParameterTypes()[0];
addProperties(method, args, predicate.getProperties(), predicate.isInverse(), loc, paramType);
return null;
}
private void addProperties(Method method, Object[] args, final String[] rdf_property, final boolean inverse, final Locale loc, final Class<?> paramType)
throws RepositoryException, IllegalArgumentException {
if (args[0] == null || "".equals(args[0])) {
// nop;
} else if (FacadeUtils.isBaseType(paramType) && !inverse) {
for (String v : rdf_property) {
final URI prop = connection.getValueFactory().createURI(v);
connection.add(delegate, prop, createLiteral(args[0], loc), context);
}
} else if (FacadeUtils.isValue(paramType) && !inverse) {
for (String v : rdf_property) {
final URI prop = connection.getValueFactory().createURI(v);
// create a new triple for this property, subject, and object
connection.add(delegate, prop, (Value) args[0], context);
}
} else if (FacadeUtils.isResource(paramType) && inverse) {
for (String v : rdf_property) {
final URI prop = connection.getValueFactory().createURI(v);
// create a new triple for this property, subject, and object
connection.add((Resource) args[0], prop, delegate, context);
}
} else if (FacadeUtils.isFacade(paramType) && !inverse) {
for (String v : rdf_property) {
final URI prop = connection.getValueFactory().createURI(v);
// create a new triple for this property, subject, and object
connection.add(delegate, prop, ((Facade) args[0]).getDelegate(), context);
}
} else if (FacadeUtils.isFacade(paramType) && inverse) {
for (String v : rdf_property) {
final URI prop = connection.getValueFactory().createURI(v);
// create a new triple for this property, subject, and object
connection.add(((Facade) args[0]).getDelegate(), prop, delegate, context);
}
} else if (FacadeUtils.isCollection(paramType)) {
for (String v : rdf_property) {
final Collection<?> c = (Collection<?>) args[0];
final URI prop = connection.getValueFactory().createURI(v);
// add each of the elements in the collection as new triple with prop
for (final Object o : c) {
if (o == null) {
// skip
} else if (FacadeUtils.isBaseType(o.getClass()) && !inverse) {
connection.add(delegate, prop, createLiteral(o, loc), context);
} else if (FacadeUtils.isFacade(o.getClass()) && !inverse) {
connection.add(delegate, prop, ((Facade) o).getDelegate(), context);
} else if (FacadeUtils.isFacade(o.getClass()) && inverse) {
connection.add(((Facade) o).getDelegate(), prop, delegate, context);
} else if (FacadeUtils.isValue(o.getClass()) && !inverse) {
connection.add(delegate, prop, (Value) o, context);
} else if (FacadeUtils.isResource(o.getClass()) && inverse) {
connection.add((Resource) o, prop, delegate, context);
} else if (inverse) {
throw new IllegalArgumentException("method " + method.getName() + ": @RDFInverse not supported for parameter type "
+ paramType.getName());
} else {
throw new IllegalArgumentException("the type " + o.getClass().getName() + " is not supported in collections");
}
}
}
} else if (inverse) {
throw new IllegalArgumentException("method " + method.getName() + ": @RDFInverse not supported for parameter type " + paramType.getName());
} else {
throw new IllegalArgumentException("method " + method.getName() + ": unsupported parameter type " + paramType.getName());
}
}
private void delProperties(final FacadingPredicate predicate, final Locale loc) throws RepositoryException {
for (String v : predicate.getProperties()) {
final URI prop = connection.getValueFactory().createURI(v);
if (!predicate.isInverse() && loc == null) {
// remove all properties prop that have this subject;
connection.remove(delegate, prop, null, context);
} else if (predicate.isInverse() && loc == null) {
// remove all properties prop that have this object;
connection.remove((Resource) null, prop, delegate, context);
} else if (!predicate.isInverse() && loc != null) {
final RepositoryResult<Statement> statements = connection.getStatements(delegate, prop, null, false, context);
try {
while (statements.hasNext()) {
final Statement s = statements.next();
if (FacadingInvocationHelper.checkLocale(loc, s.getObject())) {
connection.remove(s);
}
}
} finally {
statements.close();
}
} else if (predicate.isInverse() && loc != null) { throw new IllegalArgumentException("A combination of @RDFInverse and a Literal is not possible");
}
}
}
private Object handleGet(Method method, Object[] args, FacadingPredicate predicate) throws IllegalAccessException, InstantiationException,
RepositoryException {
final Locale loc;
if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(Locale.class)) {
loc = (Locale) args[0];
} else {
loc = null;
}
// *** get the value of a certain RDF property ***
final Class<?> returnType = method.getReturnType();
final Type typeOfGeneric = method.getGenericReturnType();
// we believe that the result is universal for each property
// and therefore just return the result for the firstly defined property
final Object result = transform(returnType, typeOfGeneric, delegate, predicate.getProperties()[0], loc, predicate.isInverse());
if (useCache) {
fieldCache.put(FacadingInvocationHelper.getBaseName(method), result);
}
return result;
}
/**
* Helper method to transform the object reachable via rdf_property from r to the given
* returnType; if the returnType is a collection, it is also necessary to provide the generic
* type. The KiWiEntityManager is used for further querying.<br>
* Please note that if the <code>returnType</code>is a collection you <b>must</b> use a concrete
* class (e.g. <code>java.util.ArrayList</code>) not an abstract class or interface.
*
* @param <C>
* @param returnType
* @param typeOfGeneric
* @param rdf_property
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
private <C, D extends Facade> C transform(Class<C> returnType, Type typeOfGeneric, Resource entity, String rdf_property, Locale loc, boolean inverse)
throws IllegalAccessException, InstantiationException, RepositoryException {
// should not happen actually
if (entity == null) { return null; }
if (FacadeUtils.isBaseType(returnType) && !inverse) {
/*
* if the return type is string or primitive, get the literal value of the property and
* transform it appropriately
*/
final URI property = connection.getValueFactory().createURI(rdf_property);
final String value = getProperty(entity, property, loc, context);
try {
// transformation to appropriate primitive type
return FacadeUtils.transformToBaseType(value, returnType);
} catch (final IllegalArgumentException ex) {
return null;
}
} else if (FacadeUtils.isValue(returnType) && !inverse) {
return queryOutgoingSingle(entity, rdf_property, returnType);
} else if (FacadeUtils.isValue(returnType) && inverse) {
return queryIncomingSingle(entity, rdf_property, returnType);
} else if (FacadeUtils.isFacade(returnType) && !inverse) {
/*
* for KiWi entities, we retrieve the resource that is targeted by this property (by
* using getObject) and create a query on the triple store using createQuery() and the
* resource's uri that returns the result in the appropriate type (can e.g. be again a
* proxy using this invocation handler!)
*/
Resource object = queryOutgoingSingle(entity, rdf_property, Resource.class);
if (object != null) {
return returnType.cast(facadingService.createFacade(object, returnType.asSubclass(Facade.class), context));
} else {
return null;
}
} else if (FacadeUtils.isFacade(returnType) && inverse) {
/*
* for KiWi entities, we retrieve the resource that is targeted by this property (by
* using getObject) and create a query on the triple store using createQuery() and the
* resource's uri that returns the result in the appropriate type (can e.g. be again a
* proxy using this invocation handler!)
*/
Resource subject = queryIncomingSingle(entity, rdf_property, Resource.class);
if (subject != null) {
return returnType.cast(facadingService.createFacade(subject, returnType.asSubclass(Facade.class), context));
} else {
return null;
}
} else if (FacadeUtils.isCollection(returnType)) {
/*
* if we have a collection, we try to infer the generic type of its contents and use
* this to generate values; if the generic type is a kiwi entity, we issue a createQuery
* to the tripleStore to retrieve the corresponding values; if the generic type is a
* base type, we transform the results to the base type and query for literals
*/
if (typeOfGeneric instanceof ParameterizedType) {
final ParameterizedType t = (ParameterizedType) typeOfGeneric;
final Class<?> tCls = (Class<?>) t.getActualTypeArguments()[0];
@SuppressWarnings("rawtypes")
final Class<? extends Collection> collectionType = returnType.asSubclass(Collection.class);
if (FacadeUtils.isFacade(tCls) && !inverse) {
return returnType.cast(FacadingInvocationHelper.createCollection(
collectionType,
facadingService.createFacade(queryOutgoingAll(entity, rdf_property, Resource.class), tCls.asSubclass(Facade.class), context)));
} else if (FacadeUtils.isFacade(tCls) && inverse) {
return returnType.cast(FacadingInvocationHelper.createCollection(
collectionType,
facadingService.createFacade(queryIncomingAll(entity, rdf_property, Resource.class), tCls.asSubclass(Facade.class), context)));
} else if (FacadeUtils.isValue(tCls) && !inverse) {
return returnType.cast(FacadingInvocationHelper.createCollection(
collectionType,
queryOutgoingAll(entity, rdf_property, tCls.asSubclass(Value.class))));
} else if (FacadeUtils.isValue(tCls) && inverse) {
return returnType.cast(FacadingInvocationHelper.createCollection(
collectionType,
queryIncomingAll(entity, rdf_property, tCls.asSubclass(Value.class))));
} else if (inverse) {
throw new IllegalArgumentException("@RDFInverse not supported for mappings of type " + rdf_property);
} else if (FacadeUtils.isBaseType(tCls)) {
final Collection<Object> result = FacadingInvocationHelper.createCollection(collectionType, Collections.<Object> emptyList());
final URI property = connection.getValueFactory().createURI(rdf_property);
for (final String s : getProperties(entity, property, loc, context)) {
result.add(FacadeUtils.transformToBaseType(s, tCls));
}
return returnType.cast(result);
} else {
throw new IllegalArgumentException("return type is using generic type " + tCls.getName()
+ ", which is not supported in RDF-based collections; please use either Java primitive types or KiWi Entities in KiWiFacades");
}
} else {
throw new IllegalArgumentException("return type is unparametrized collection type " + returnType.getName()
+ ", which is not supported; please use an explicit type parameter in Facades");
}
} else if (inverse) {
throw new IllegalArgumentException("@RDFInverse not supported for mappings of type " + rdf_property);
} else {
throw new IllegalArgumentException("unsupported return type " + returnType.getName());
}
}
/**
* Return the single object of type C that is reachable from entity by rdf_property. Returns
* null if there is no such object or if the type of the object does not match the type passed
* as argument.
*
*/
private <C> C queryOutgoingSingle(Resource entity, String rdf_property, Class<C> returnType) throws RepositoryException {
URI property = connection.getValueFactory().createURI(rdf_property);
RepositoryResult<Statement> triples = connection.getStatements(entity, property, null, false);
try {
if (triples.hasNext()) {
Statement triple = triples.next();
Value object = triple.getObject();
if (returnType.isInstance(object)) {
return returnType.cast(object);
} else {
log.error("cannot cast retrieved object {} for property {} to return type {}", object, rdf_property, returnType);
return null;
}
} else {
return null;
}
} finally {
triples.close();
}
}
/**
* Return the single subject of type C that can reach entity by rdf_property. Returns null if
* there is no such object or if the type of the object does not match the type passed as
* argument.
*
*/
private <C> C queryIncomingSingle(Resource entity, String rdf_property, Class<C> returnType) throws RepositoryException {
URI property = connection.getValueFactory().createURI(rdf_property);
RepositoryResult<Statement> triples = connection.getStatements(null, property, entity, false);
try {
if (triples.hasNext()) {
Statement triple = triples.next();
Value subject = triple.getSubject();
if (returnType.isInstance(subject)) {
return returnType.cast(subject);
} else {
log.error("cannot cast retrieved object {} for property {} to return type {}", subject, rdf_property, returnType);
return null;
}
} else {
return null;
}
} finally {
triples.close();
}
}
/**
* Return the all objects of type C that are reachable from entity by rdf_property. Returns
* empty set if there is no such object or if the type of the object does not match the type
* passed as argument.
*
*/
private <C> Set<C> queryOutgoingAll(Resource entity, String rdf_property, Class<C> returnType) throws RepositoryException {
final URI property = connection.getValueFactory().createURI(rdf_property);
final Set<C> dupSet = new LinkedHashSet<>();
final RepositoryResult<Statement> triples = connection.getStatements(entity, property, null, false);
try {
while (triples.hasNext()) {
Statement triple = triples.next();
if (returnType.isInstance(triple.getObject())) {
dupSet.add(returnType.cast(triple.getObject()));
}
}
} finally {
triples.close();
}
return dupSet;
}
/**
* Return the all objects of type C that are can reach the entity by rdf_property. Returns empty
* set if there is no such object or if the type of the object does not match the type passed as
* argument.
*
*/
private <C> Set<C> queryIncomingAll(Resource entity, String rdf_property, Class<C> returnType) throws RepositoryException {
final URI property = connection.getValueFactory().createURI(rdf_property);
final Set<C> dupSet = new LinkedHashSet<>();
final RepositoryResult<Statement> triples = connection.getStatements(null, property, entity, false);
try {
while (triples.hasNext()) {
Statement triple = triples.next();
if (returnType.isInstance(triple.getSubject())) {
dupSet.add(returnType.cast(triple.getSubject()));
}
}
} finally {
triples.close();
}
return dupSet;
}
private Value createLiteral(Object o, Locale loc) {
if (o instanceof Date) {
return connection.getValueFactory().createLiteral(DateUtils.getXMLCalendar((Date) o));
} else if (o instanceof DateTime) {
return connection.getValueFactory().createLiteral(DateUtils.getXMLCalendar((DateTime) o));
} else if (Integer.class.isAssignableFrom(o.getClass())) {
return connection.getValueFactory().createLiteral((Integer) o);
} else if (Long.class.isAssignableFrom(o.getClass())) {
return connection.getValueFactory().createLiteral((Long) o);
} else if (Double.class.isAssignableFrom(o.getClass())) {
return connection.getValueFactory().createLiteral((Double) o);
} else if (Float.class.isAssignableFrom(o.getClass())) {
return connection.getValueFactory().createLiteral((Float) o);
} else if (Boolean.class.isAssignableFrom(o.getClass())) {
return connection.getValueFactory().createLiteral((Boolean) o);
} else if (loc != null) {
return connection.getValueFactory().createLiteral(o.toString(), loc.getLanguage());
} else {
return connection.getValueFactory().createLiteral(o.toString());
}
}
private Set<String> getProperties(Resource entity, URI property, Locale loc, URI context) throws RepositoryException {
final String lang = loc == null ? null : loc.getLanguage().toLowerCase();
final Set<String> values = new HashSet<>();
final RepositoryResult<Statement> candidates = connection.getStatements(entity, property, null, false, context);
try {
while (candidates.hasNext()) {
Statement triple = candidates.next();
if (triple.getObject() instanceof Literal) {
Literal l = (Literal) triple.getObject();
if (lang == null || lang.equals(l.getLanguage())) {
values.add(l.stringValue());
}
}
}
} finally {
candidates.close();
}
return values;
}
private String getProperty(Resource entity, URI property, Locale loc, URI context) throws RepositoryException {
Set<String> values = getProperties(entity, property, loc, context);
if (values.size() > 0) {
return values.iterator().next();
} else {
return null;
}
}
}
|
apache/hadoop-common | 35,339 | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/test/java/org/apache/hadoop/mapreduce/v2/hs/webapp/TestHsWebServicesJobs.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapreduce.v2.hs.webapp;
import static org.apache.hadoop.yarn.util.StringHelper.join;
import static org.apache.hadoop.yarn.util.StringHelper.ujoin;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.StringReader;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.v2.api.records.AMInfo;
import org.apache.hadoop.mapreduce.v2.api.records.JobId;
import org.apache.hadoop.mapreduce.v2.app.AppContext;
import org.apache.hadoop.mapreduce.v2.app.job.Job;
import org.apache.hadoop.mapreduce.v2.hs.HistoryContext;
import org.apache.hadoop.mapreduce.v2.hs.MockHistoryContext;
import org.apache.hadoop.mapreduce.v2.util.MRApps;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.webapp.GenericExceptionHandler;
import org.apache.hadoop.yarn.webapp.WebApp;
import org.apache.hadoop.yarn.webapp.WebServicesTestUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.ClientResponse.Status;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;
/**
* Test the history server Rest API for getting jobs, a specific job, job
* counters, and job attempts.
*
* /ws/v1/history/mapreduce/jobs /ws/v1/history/mapreduce/jobs/{jobid}
* /ws/v1/history/mapreduce/jobs/{jobid}/counters
* /ws/v1/history/mapreduce/jobs/{jobid}/jobattempts
*/
public class TestHsWebServicesJobs extends JerseyTest {
private static Configuration conf = new Configuration();
private static MockHistoryContext appContext;
private static HsWebApp webApp;
private Injector injector = Guice.createInjector(new ServletModule() {
@Override
protected void configureServlets() {
appContext = new MockHistoryContext(0, 1, 2, 1, false);
webApp = mock(HsWebApp.class);
when(webApp.name()).thenReturn("hsmockwebapp");
bind(JAXBContextResolver.class);
bind(HsWebServices.class);
bind(GenericExceptionHandler.class);
bind(WebApp.class).toInstance(webApp);
bind(AppContext.class).toInstance(appContext);
bind(HistoryContext.class).toInstance(appContext);
bind(Configuration.class).toInstance(conf);
serve("/*").with(GuiceContainer.class);
}
});
public class GuiceServletConfig extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return injector;
}
}
@Before
@Override
public void setUp() throws Exception {
super.setUp();
}
public TestHsWebServicesJobs() {
super(new WebAppDescriptor.Builder(
"org.apache.hadoop.mapreduce.v2.hs.webapp")
.contextListenerClass(GuiceServletConfig.class)
.filterClass(com.google.inject.servlet.GuiceFilter.class)
.contextPath("jersey-guice-filter").servletPath("/").build());
}
@Test
public void testJobs() throws JSONException, Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject jobs = json.getJSONObject("jobs");
JSONArray arr = jobs.getJSONArray("job");
assertEquals("incorrect number of elements", 1, arr.length());
JSONObject info = arr.getJSONObject(0);
Job job = appContext.getPartialJob(MRApps.toJobID(info.getString("id")));
VerifyJobsUtils.verifyHsJobPartial(info, job);
}
@Test
public void testJobsSlash() throws JSONException, Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs/").accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject jobs = json.getJSONObject("jobs");
JSONArray arr = jobs.getJSONArray("job");
assertEquals("incorrect number of elements", 1, arr.length());
JSONObject info = arr.getJSONObject(0);
Job job = appContext.getPartialJob(MRApps.toJobID(info.getString("id")));
VerifyJobsUtils.verifyHsJobPartial(info, job);
}
@Test
public void testJobsDefault() throws JSONException, Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject jobs = json.getJSONObject("jobs");
JSONArray arr = jobs.getJSONArray("job");
assertEquals("incorrect number of elements", 1, arr.length());
JSONObject info = arr.getJSONObject(0);
Job job = appContext.getPartialJob(MRApps.toJobID(info.getString("id")));
VerifyJobsUtils.verifyHsJobPartial(info, job);
}
@Test
public void testJobsXML() throws Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").accept(MediaType.APPLICATION_XML)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
String xml = response.getEntity(String.class);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document dom = db.parse(is);
NodeList jobs = dom.getElementsByTagName("jobs");
assertEquals("incorrect number of elements", 1, jobs.getLength());
NodeList job = dom.getElementsByTagName("job");
assertEquals("incorrect number of elements", 1, job.getLength());
verifyHsJobPartialXML(job, appContext);
}
public void verifyHsJobPartialXML(NodeList nodes, MockHistoryContext appContext) {
assertEquals("incorrect number of elements", 1, nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
Job job = appContext.getPartialJob(MRApps.toJobID(WebServicesTestUtils
.getXmlString(element, "id")));
assertNotNull("Job not found - output incorrect", job);
VerifyJobsUtils.verifyHsJobGeneric(job,
WebServicesTestUtils.getXmlString(element, "id"),
WebServicesTestUtils.getXmlString(element, "user"),
WebServicesTestUtils.getXmlString(element, "name"),
WebServicesTestUtils.getXmlString(element, "state"),
WebServicesTestUtils.getXmlString(element, "queue"),
WebServicesTestUtils.getXmlLong(element, "startTime"),
WebServicesTestUtils.getXmlLong(element, "finishTime"),
WebServicesTestUtils.getXmlInt(element, "mapsTotal"),
WebServicesTestUtils.getXmlInt(element, "mapsCompleted"),
WebServicesTestUtils.getXmlInt(element, "reducesTotal"),
WebServicesTestUtils.getXmlInt(element, "reducesCompleted"));
}
}
public void verifyHsJobXML(NodeList nodes, AppContext appContext) {
assertEquals("incorrect number of elements", 1, nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
Job job = appContext.getJob(MRApps.toJobID(WebServicesTestUtils
.getXmlString(element, "id")));
assertNotNull("Job not found - output incorrect", job);
VerifyJobsUtils.verifyHsJobGeneric(job,
WebServicesTestUtils.getXmlString(element, "id"),
WebServicesTestUtils.getXmlString(element, "user"),
WebServicesTestUtils.getXmlString(element, "name"),
WebServicesTestUtils.getXmlString(element, "state"),
WebServicesTestUtils.getXmlString(element, "queue"),
WebServicesTestUtils.getXmlLong(element, "startTime"),
WebServicesTestUtils.getXmlLong(element, "finishTime"),
WebServicesTestUtils.getXmlInt(element, "mapsTotal"),
WebServicesTestUtils.getXmlInt(element, "mapsCompleted"),
WebServicesTestUtils.getXmlInt(element, "reducesTotal"),
WebServicesTestUtils.getXmlInt(element, "reducesCompleted"));
// restricted access fields - if security and acls set
VerifyJobsUtils.verifyHsJobGenericSecure(job,
WebServicesTestUtils.getXmlBoolean(element, "uberized"),
WebServicesTestUtils.getXmlString(element, "diagnostics"),
WebServicesTestUtils.getXmlLong(element, "avgMapTime"),
WebServicesTestUtils.getXmlLong(element, "avgReduceTime"),
WebServicesTestUtils.getXmlLong(element, "avgShuffleTime"),
WebServicesTestUtils.getXmlLong(element, "avgMergeTime"),
WebServicesTestUtils.getXmlInt(element, "failedReduceAttempts"),
WebServicesTestUtils.getXmlInt(element, "killedReduceAttempts"),
WebServicesTestUtils.getXmlInt(element, "successfulReduceAttempts"),
WebServicesTestUtils.getXmlInt(element, "failedMapAttempts"),
WebServicesTestUtils.getXmlInt(element, "killedMapAttempts"),
WebServicesTestUtils.getXmlInt(element, "successfulMapAttempts"));
}
}
@Test
public void testJobId() throws JSONException, Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId)
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject info = json.getJSONObject("job");
VerifyJobsUtils.verifyHsJob(info, appContext.getJob(id));
}
}
@Test
public void testJobIdSlash() throws JSONException, Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId + "/")
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject info = json.getJSONObject("job");
VerifyJobsUtils.verifyHsJob(info, appContext.getJob(id));
}
}
@Test
public void testJobIdDefault() throws JSONException, Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject info = json.getJSONObject("job");
VerifyJobsUtils.verifyHsJob(info, appContext.getJob(id));
}
}
@Test
public void testJobIdNonExist() throws JSONException, Exception {
WebResource r = resource();
try {
r.path("ws").path("v1").path("history").path("mapreduce").path("jobs")
.path("job_0_1234").get(JSONObject.class);
fail("should have thrown exception on invalid uri");
} catch (UniformInterfaceException ue) {
ClientResponse response = ue.getResponse();
assertEquals(Status.NOT_FOUND, response.getClientResponseStatus());
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject msg = response.getEntity(JSONObject.class);
JSONObject exception = msg.getJSONObject("RemoteException");
assertEquals("incorrect number of elements", 3, exception.length());
String message = exception.getString("message");
String type = exception.getString("exception");
String classname = exception.getString("javaClassName");
WebServicesTestUtils.checkStringMatch("exception message",
"java.lang.Exception: job, job_0_1234, is not found", message);
WebServicesTestUtils.checkStringMatch("exception type",
"NotFoundException", type);
WebServicesTestUtils.checkStringMatch("exception classname",
"org.apache.hadoop.yarn.webapp.NotFoundException", classname);
}
}
@Test
public void testJobIdInvalid() throws JSONException, Exception {
WebResource r = resource();
try {
r.path("ws").path("v1").path("history").path("mapreduce").path("jobs")
.path("job_foo").accept(MediaType.APPLICATION_JSON)
.get(JSONObject.class);
fail("should have thrown exception on invalid uri");
} catch (UniformInterfaceException ue) {
ClientResponse response = ue.getResponse();
assertEquals(Status.NOT_FOUND, response.getClientResponseStatus());
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject msg = response.getEntity(JSONObject.class);
JSONObject exception = msg.getJSONObject("RemoteException");
assertEquals("incorrect number of elements", 3, exception.length());
String message = exception.getString("message");
String type = exception.getString("exception");
String classname = exception.getString("javaClassName");
verifyJobIdInvalid(message, type, classname);
}
}
// verify the exception output default is JSON
@Test
public void testJobIdInvalidDefault() throws JSONException, Exception {
WebResource r = resource();
try {
r.path("ws").path("v1").path("history").path("mapreduce").path("jobs")
.path("job_foo").get(JSONObject.class);
fail("should have thrown exception on invalid uri");
} catch (UniformInterfaceException ue) {
ClientResponse response = ue.getResponse();
assertEquals(Status.NOT_FOUND, response.getClientResponseStatus());
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject msg = response.getEntity(JSONObject.class);
JSONObject exception = msg.getJSONObject("RemoteException");
assertEquals("incorrect number of elements", 3, exception.length());
String message = exception.getString("message");
String type = exception.getString("exception");
String classname = exception.getString("javaClassName");
verifyJobIdInvalid(message, type, classname);
}
}
// test that the exception output works in XML
@Test
public void testJobIdInvalidXML() throws JSONException, Exception {
WebResource r = resource();
try {
r.path("ws").path("v1").path("history").path("mapreduce").path("jobs")
.path("job_foo").accept(MediaType.APPLICATION_XML)
.get(JSONObject.class);
fail("should have thrown exception on invalid uri");
} catch (UniformInterfaceException ue) {
ClientResponse response = ue.getResponse();
assertEquals(Status.NOT_FOUND, response.getClientResponseStatus());
assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
String msg = response.getEntity(String.class);
System.out.println(msg);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(msg));
Document dom = db.parse(is);
NodeList nodes = dom.getElementsByTagName("RemoteException");
Element element = (Element) nodes.item(0);
String message = WebServicesTestUtils.getXmlString(element, "message");
String type = WebServicesTestUtils.getXmlString(element, "exception");
String classname = WebServicesTestUtils.getXmlString(element,
"javaClassName");
verifyJobIdInvalid(message, type, classname);
}
}
private void verifyJobIdInvalid(String message, String type, String classname) {
WebServicesTestUtils.checkStringMatch("exception message",
"java.lang.Exception: JobId string : job_foo is not properly formed",
message);
WebServicesTestUtils.checkStringMatch("exception type",
"NotFoundException", type);
WebServicesTestUtils.checkStringMatch("exception classname",
"org.apache.hadoop.yarn.webapp.NotFoundException", classname);
}
@Test
public void testJobIdInvalidBogus() throws JSONException, Exception {
WebResource r = resource();
try {
r.path("ws").path("v1").path("history").path("mapreduce").path("jobs")
.path("bogusfoo").get(JSONObject.class);
fail("should have thrown exception on invalid uri");
} catch (UniformInterfaceException ue) {
ClientResponse response = ue.getResponse();
assertEquals(Status.NOT_FOUND, response.getClientResponseStatus());
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject msg = response.getEntity(JSONObject.class);
JSONObject exception = msg.getJSONObject("RemoteException");
assertEquals("incorrect number of elements", 3, exception.length());
String message = exception.getString("message");
String type = exception.getString("exception");
String classname = exception.getString("javaClassName");
WebServicesTestUtils.checkStringMatch("exception message",
"java.lang.Exception: JobId string : "
+ "bogusfoo is not properly formed", message);
WebServicesTestUtils.checkStringMatch("exception type",
"NotFoundException", type);
WebServicesTestUtils.checkStringMatch("exception classname",
"org.apache.hadoop.yarn.webapp.NotFoundException", classname);
}
}
@Test
public void testJobIdXML() throws Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId)
.accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
String xml = response.getEntity(String.class);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document dom = db.parse(is);
NodeList job = dom.getElementsByTagName("job");
verifyHsJobXML(job, appContext);
}
}
@Test
public void testJobCounters() throws JSONException, Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId).path("counters")
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject info = json.getJSONObject("jobCounters");
verifyHsJobCounters(info, appContext.getJob(id));
}
}
@Test
public void testJobCountersSlash() throws JSONException, Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId).path("counters/")
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject info = json.getJSONObject("jobCounters");
verifyHsJobCounters(info, appContext.getJob(id));
}
}
@Test
public void testJobCountersForKilledJob() throws Exception {
WebResource r = resource();
appContext = new MockHistoryContext(0, 1, 1, 1, true);
injector = Guice.createInjector(new ServletModule() {
@Override
protected void configureServlets() {
webApp = mock(HsWebApp.class);
when(webApp.name()).thenReturn("hsmockwebapp");
bind(JAXBContextResolver.class);
bind(HsWebServices.class);
bind(GenericExceptionHandler.class);
bind(WebApp.class).toInstance(webApp);
bind(AppContext.class).toInstance(appContext);
bind(HistoryContext.class).toInstance(appContext);
bind(Configuration.class).toInstance(conf);
serve("/*").with(GuiceContainer.class);
}
});
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId).path("counters/")
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject info = json.getJSONObject("jobCounters");
WebServicesTestUtils.checkStringMatch("id", MRApps.toString(id),
info.getString("id"));
assertTrue("Job shouldn't contain any counters", info.length() == 1);
}
}
@Test
public void testJobCountersDefault() throws JSONException, Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId).path("counters/")
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject info = json.getJSONObject("jobCounters");
verifyHsJobCounters(info, appContext.getJob(id));
}
}
@Test
public void testJobCountersXML() throws Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId).path("counters")
.accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
String xml = response.getEntity(String.class);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document dom = db.parse(is);
NodeList info = dom.getElementsByTagName("jobCounters");
verifyHsJobCountersXML(info, appContext.getJob(id));
}
}
public void verifyHsJobCounters(JSONObject info, Job job)
throws JSONException {
assertEquals("incorrect number of elements", 2, info.length());
WebServicesTestUtils.checkStringMatch("id", MRApps.toString(job.getID()),
info.getString("id"));
// just do simple verification of fields - not data is correct
// in the fields
JSONArray counterGroups = info.getJSONArray("counterGroup");
for (int i = 0; i < counterGroups.length(); i++) {
JSONObject counterGroup = counterGroups.getJSONObject(i);
String name = counterGroup.getString("counterGroupName");
assertTrue("name not set", (name != null && !name.isEmpty()));
JSONArray counters = counterGroup.getJSONArray("counter");
for (int j = 0; j < counters.length(); j++) {
JSONObject counter = counters.getJSONObject(j);
String counterName = counter.getString("name");
assertTrue("counter name not set",
(counterName != null && !counterName.isEmpty()));
long mapValue = counter.getLong("mapCounterValue");
assertTrue("mapCounterValue >= 0", mapValue >= 0);
long reduceValue = counter.getLong("reduceCounterValue");
assertTrue("reduceCounterValue >= 0", reduceValue >= 0);
long totalValue = counter.getLong("totalCounterValue");
assertTrue("totalCounterValue >= 0", totalValue >= 0);
}
}
}
public void verifyHsJobCountersXML(NodeList nodes, Job job) {
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
assertNotNull("Job not found - output incorrect", job);
WebServicesTestUtils.checkStringMatch("id", MRApps.toString(job.getID()),
WebServicesTestUtils.getXmlString(element, "id"));
// just do simple verification of fields - not data is correct
// in the fields
NodeList groups = element.getElementsByTagName("counterGroup");
for (int j = 0; j < groups.getLength(); j++) {
Element counters = (Element) groups.item(j);
assertNotNull("should have counters in the web service info", counters);
String name = WebServicesTestUtils.getXmlString(counters,
"counterGroupName");
assertTrue("name not set", (name != null && !name.isEmpty()));
NodeList counterArr = counters.getElementsByTagName("counter");
for (int z = 0; z < counterArr.getLength(); z++) {
Element counter = (Element) counterArr.item(z);
String counterName = WebServicesTestUtils.getXmlString(counter,
"name");
assertTrue("counter name not set",
(counterName != null && !counterName.isEmpty()));
long mapValue = WebServicesTestUtils.getXmlLong(counter,
"mapCounterValue");
assertTrue("mapCounterValue not >= 0", mapValue >= 0);
long reduceValue = WebServicesTestUtils.getXmlLong(counter,
"reduceCounterValue");
assertTrue("reduceCounterValue >= 0", reduceValue >= 0);
long totalValue = WebServicesTestUtils.getXmlLong(counter,
"totalCounterValue");
assertTrue("totalCounterValue >= 0", totalValue >= 0);
}
}
}
}
@Test
public void testJobAttempts() throws JSONException, Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId).path("jobattempts")
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject info = json.getJSONObject("jobAttempts");
verifyHsJobAttempts(info, appContext.getJob(id));
}
}
@Test
public void testJobAttemptsSlash() throws JSONException, Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId).path("jobattempts/")
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject info = json.getJSONObject("jobAttempts");
verifyHsJobAttempts(info, appContext.getJob(id));
}
}
@Test
public void testJobAttemptsDefault() throws JSONException, Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId).path("jobattempts")
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
JSONObject info = json.getJSONObject("jobAttempts");
verifyHsJobAttempts(info, appContext.getJob(id));
}
}
@Test
public void testJobAttemptsXML() throws Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId).path("jobattempts")
.accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
String xml = response.getEntity(String.class);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document dom = db.parse(is);
NodeList attempts = dom.getElementsByTagName("jobAttempts");
assertEquals("incorrect number of elements", 1, attempts.getLength());
NodeList info = dom.getElementsByTagName("jobAttempt");
verifyHsJobAttemptsXML(info, appContext.getJob(id));
}
}
public void verifyHsJobAttempts(JSONObject info, Job job)
throws JSONException {
JSONArray attempts = info.getJSONArray("jobAttempt");
assertEquals("incorrect number of elements", 2, attempts.length());
for (int i = 0; i < attempts.length(); i++) {
JSONObject attempt = attempts.getJSONObject(i);
verifyHsJobAttemptsGeneric(job, attempt.getString("nodeHttpAddress"),
attempt.getString("nodeId"), attempt.getInt("id"),
attempt.getLong("startTime"), attempt.getString("containerId"),
attempt.getString("logsLink"));
}
}
public void verifyHsJobAttemptsXML(NodeList nodes, Job job) {
assertEquals("incorrect number of elements", 2, nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
verifyHsJobAttemptsGeneric(job,
WebServicesTestUtils.getXmlString(element, "nodeHttpAddress"),
WebServicesTestUtils.getXmlString(element, "nodeId"),
WebServicesTestUtils.getXmlInt(element, "id"),
WebServicesTestUtils.getXmlLong(element, "startTime"),
WebServicesTestUtils.getXmlString(element, "containerId"),
WebServicesTestUtils.getXmlString(element, "logsLink"));
}
}
public void verifyHsJobAttemptsGeneric(Job job, String nodeHttpAddress,
String nodeId, int id, long startTime, String containerId, String logsLink) {
boolean attemptFound = false;
for (AMInfo amInfo : job.getAMInfos()) {
if (amInfo.getAppAttemptId().getAttemptId() == id) {
attemptFound = true;
String nmHost = amInfo.getNodeManagerHost();
int nmHttpPort = amInfo.getNodeManagerHttpPort();
int nmPort = amInfo.getNodeManagerPort();
WebServicesTestUtils.checkStringMatch("nodeHttpAddress", nmHost + ":"
+ nmHttpPort, nodeHttpAddress);
WebServicesTestUtils.checkStringMatch("nodeId",
NodeId.newInstance(nmHost, nmPort).toString(), nodeId);
assertTrue("startime not greater than 0", startTime > 0);
WebServicesTestUtils.checkStringMatch("containerId", amInfo
.getContainerId().toString(), containerId);
String localLogsLink = join(
"hsmockwebapp",
ujoin("logs", nodeId, containerId, MRApps.toString(job.getID()),
job.getUserName()));
assertTrue("logsLink", logsLink.contains(localLogsLink));
}
}
assertTrue("attempt: " + id + " was not found", attemptFound);
}
}
|
apache/orc | 35,860 | java/core/src/java/org/apache/orc/impl/mask/RedactMaskFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.orc.impl.mask;
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.DecimalColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.DoubleColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.LongColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.TimestampColumnVector;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.io.Text;
import org.apache.orc.DataMask;
import org.apache.orc.TypeDescription;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;
import java.util.SortedMap;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
/**
* Masking strategy that hides most string and numeric values based on unicode
* character categories.
* <p>
* Masking Parameters:
* character replacements: string of 10 characters one per group below
* letter, upper case (default X)
* letter, lower case (default x)
* number, digit (default 9)
* symbol (default $)
* punctuation (default .)
* separator (default no masking)
* letter, other (default ª)
* mark (default ः)
* number, other (default ²)
* other (default )
* <p>
* time replacements: string of 6 numbers or _ one per field below
* year (0 to 4000, default no masking)
* month (1 to 12, default 1)
* date (1 to 31, default 1)
* hour (0 to 23, default 0)
* minute (0 to 59, default 0)
* second (0 to 59, default 0)
* <p>
* Parameters use "_" for preserve original.
*/
public class RedactMaskFactory extends MaskFactory {
/**
* The value to indicate that the value should be preserved.
*/
private static final int UNMASKED_CHAR = "_".codePointAt(0);
private static final int UNMASKED_DATE = -1;
// The default replacements for each character category.
// I picked a character in the same category so that the masking is
// idempotent. For non-ascii characters, I mostly picked the first example.
private static final int DEFAULT_LETTER_UPPER = "X".codePointAt(0);
private static final int DEFAULT_LETTER_LOWER = "x".codePointAt(0);
private static final int DEFAULT_NUMBER_DIGIT = 9;
private static final int DEFAULT_NUMBER_DIGIT_CP =
Integer.toString(DEFAULT_NUMBER_DIGIT).codePointAt(0);
private static final int DEFAULT_SYMBOL = "$".codePointAt(0);
private static final int DEFAULT_PUNCTUATION = ".".codePointAt(0);
private static final int DEFAULT_SEPARATOR = UNMASKED_CHAR;
private static final int DEFAULT_LETTER_OTHER = "\u00AA".codePointAt(0);
private static final int DEFAULT_MARK = "\u0903".codePointAt(0);
private static final int DEFAULT_NUMBER_OTHER = "\u00B2".codePointAt(0);
private static final int DEFAULT_OTHER = "\u06DD".codePointAt(0);
// The replacement codepoint for each character category. We use codepoints
// here so that we don't have to worry about handling long UTF characters
// as special cases.
private final int UPPER_REPLACEMENT;
private final int LOWER_REPLACEMENT;
private final int OTHER_LETTER_REPLACEMENT;
private final int MARK_REPLACEMENT;
private final int DIGIT_CP_REPLACEMENT;
private final int OTHER_NUMBER_REPLACEMENT;
private final int SYMBOL_REPLACEMENT;
private final int PUNCTUATION_REPLACEMENT;
private final int SEPARATOR_REPLACEMENT;
private final int OTHER_REPLACEMENT;
// numeric replacement
private final int DIGIT_REPLACEMENT;
// time replacement
private final int YEAR_REPLACEMENT;
private final int MONTH_REPLACEMENT;
private final int DATE_REPLACEMENT;
private final int HOUR_REPLACEMENT;
private final int MINUTE_REPLACEMENT;
private final int SECOND_REPLACEMENT;
private final boolean maskDate;
private final boolean maskTimestamp;
// index tuples that are not to be masked
private final SortedMap<Integer,Integer> unmaskIndexRanges = new TreeMap<>();
public RedactMaskFactory(String... params) {
ByteBuffer param = params.length < 1 ? ByteBuffer.allocate(0) :
ByteBuffer.wrap(params[0].getBytes(StandardCharsets.UTF_8));
UPPER_REPLACEMENT = getNextCodepoint(param, DEFAULT_LETTER_UPPER);
LOWER_REPLACEMENT = getNextCodepoint(param, DEFAULT_LETTER_LOWER);
DIGIT_CP_REPLACEMENT = getNextCodepoint(param, DEFAULT_NUMBER_DIGIT_CP);
DIGIT_REPLACEMENT = getReplacementDigit(DIGIT_CP_REPLACEMENT);
SYMBOL_REPLACEMENT = getNextCodepoint(param, DEFAULT_SYMBOL);
PUNCTUATION_REPLACEMENT = getNextCodepoint(param, DEFAULT_PUNCTUATION);
SEPARATOR_REPLACEMENT = getNextCodepoint(param, DEFAULT_SEPARATOR);
OTHER_LETTER_REPLACEMENT = getNextCodepoint(param, DEFAULT_LETTER_OTHER);
MARK_REPLACEMENT = getNextCodepoint(param, DEFAULT_MARK);
OTHER_NUMBER_REPLACEMENT = getNextCodepoint(param, DEFAULT_NUMBER_OTHER);
OTHER_REPLACEMENT = getNextCodepoint(param, DEFAULT_OTHER);
String[] timeParams;
if (params.length < 2 || params[1].isBlank()) {
timeParams = null;
} else {
timeParams = params[1].split("\\W+");
}
YEAR_REPLACEMENT = getDateParam(timeParams, 0, UNMASKED_DATE, 4000);
MONTH_REPLACEMENT = getDateParam(timeParams, 1, 1, 12);
DATE_REPLACEMENT = getDateParam(timeParams, 2, 1, 31);
HOUR_REPLACEMENT = getDateParam(timeParams, 3, 0, 23);
MINUTE_REPLACEMENT = getDateParam(timeParams, 4, 0, 59);
SECOND_REPLACEMENT = getDateParam(timeParams, 5, 0, 59);
maskDate = (YEAR_REPLACEMENT != UNMASKED_DATE) ||
(MONTH_REPLACEMENT != UNMASKED_DATE) ||
(DATE_REPLACEMENT != UNMASKED_DATE);
maskTimestamp = maskDate || (HOUR_REPLACEMENT != UNMASKED_DATE) ||
(MINUTE_REPLACEMENT != UNMASKED_DATE) ||
(SECOND_REPLACEMENT != UNMASKED_DATE);
/* un-mask range */
if(!(params.length < 3 || params[2].isBlank())) {
String[] unmaskIndexes = params[2].split(",");
for(int i=0; i < unmaskIndexes.length; i++ ) {
String[] pair = unmaskIndexes[i].trim().split(":");
unmaskIndexRanges.put(Integer.parseInt(pair[0]), Integer.parseInt(pair[1]));
}
}
}
@Override
protected DataMask buildBooleanMask(TypeDescription schema) {
if (DIGIT_CP_REPLACEMENT == UNMASKED_CHAR) {
return new LongIdentity();
} else {
return new BooleanRedactConverter();
}
}
@Override
protected DataMask buildLongMask(TypeDescription schema) {
if (DIGIT_CP_REPLACEMENT == UNMASKED_CHAR) {
return new LongIdentity();
} else {
return new LongRedactConverter(schema.getCategory());
}
}
@Override
protected DataMask buildDecimalMask(TypeDescription schema) {
if (DIGIT_CP_REPLACEMENT == UNMASKED_CHAR) {
return new DecimalIdentity();
} else {
return new DecimalRedactConverter();
}
}
@Override
protected DataMask buildDoubleMask(TypeDescription schema) {
if (DIGIT_CP_REPLACEMENT == UNMASKED_CHAR) {
return new DoubleIdentity();
} else {
return new DoubleRedactConverter();
}
}
@Override
protected DataMask buildStringMask(TypeDescription schema) {
return new StringConverter();
}
@Override
protected DataMask buildDateMask(TypeDescription schema) {
if (maskDate) {
return new DateRedactConverter();
} else {
return new LongIdentity();
}
}
@Override
protected DataMask buildTimestampMask(TypeDescription schema) {
if (maskTimestamp) {
return new TimestampRedactConverter();
} else {
return new TimestampIdentity();
}
}
@Override
protected DataMask buildBinaryMask(TypeDescription schema) {
return new NullifyMask();
}
class LongRedactConverter implements DataMask {
final long mask;
LongRedactConverter(TypeDescription.Category category) {
switch (category) {
case BYTE:
mask = 0xff;
break;
case SHORT:
mask = 0xffff;
break;
case INT:
mask = 0xffff_ffff;
break;
default:
case LONG:
mask = -1;
break;
}
}
@Override
public void maskData(ColumnVector original, ColumnVector masked, int start,
int length) {
LongColumnVector target = (LongColumnVector) masked;
LongColumnVector source = (LongColumnVector) original;
target.noNulls = original.noNulls;
target.isRepeating = original.isRepeating;
if (original.isRepeating) {
target.vector[0] = maskLong(source.vector[0]) & mask;
target.isNull[0] = source.isNull[0];
} else {
for(int r = start; r < start + length; ++r) {
target.vector[r] = maskLong(source.vector[r]) & mask;
target.isNull[r] = source.isNull[r];
}
}
}
}
class BooleanRedactConverter implements DataMask {
@Override
public void maskData(ColumnVector original, ColumnVector masked, int start,
int length) {
LongColumnVector target = (LongColumnVector) masked;
LongColumnVector source = (LongColumnVector) original;
target.noNulls = original.noNulls;
target.isRepeating = original.isRepeating;
if (original.isRepeating) {
target.vector[0] = DIGIT_REPLACEMENT == 0 ? 0 : 1;
target.isNull[0] = source.isNull[0];
} else {
for(int r = start; r < start + length; ++r) {
target.vector[r] = DIGIT_REPLACEMENT == 0 ? 0 : 1;
target.isNull[r] = source.isNull[r];
}
}
}
}
class DoubleRedactConverter implements DataMask {
@Override
public void maskData(ColumnVector original, ColumnVector masked, int start,
int length) {
DoubleColumnVector target = (DoubleColumnVector) masked;
DoubleColumnVector source = (DoubleColumnVector) original;
target.noNulls = original.noNulls;
target.isRepeating = original.isRepeating;
if (original.isRepeating) {
target.vector[0] = maskDouble(source.vector[0]);
target.isNull[0] = source.isNull[0];
} else {
for(int r = start; r < start + length; ++r) {
target.vector[r] = maskDouble(source.vector[r]);
target.isNull[r] = source.isNull[r];
}
}
}
}
class StringConverter implements DataMask {
@Override
public void maskData(ColumnVector original, ColumnVector masked, int start,
int length) {
BytesColumnVector target = (BytesColumnVector) masked;
BytesColumnVector source = (BytesColumnVector) original;
target.noNulls = original.noNulls;
target.isRepeating = original.isRepeating;
if (original.isRepeating) {
target.isNull[0] = source.isNull[0];
if (target.noNulls || !target.isNull[0]) {
maskString(source, 0, target);
}
} else {
for(int r = start; r < start + length; ++r) {
target.isNull[r] = source.isNull[r];
if (target.noNulls || !target.isNull[r]) {
maskString(source, r, target);
}
}
}
}
}
class DecimalRedactConverter implements DataMask {
@Override
public void maskData(ColumnVector original, ColumnVector masked, int start,
int length) {
DecimalColumnVector target = (DecimalColumnVector) masked;
DecimalColumnVector source = (DecimalColumnVector) original;
target.noNulls = original.noNulls;
target.isRepeating = original.isRepeating;
target.scale = source.scale;
target.precision = source.precision;
if (original.isRepeating) {
target.isNull[0] = source.isNull[0];
if (target.noNulls || !target.isNull[0]) {
target.vector[0].set(maskDecimal(source.vector[0]));
}
} else {
for(int r = start; r < start + length; ++r) {
target.isNull[r] = source.isNull[r];
if (target.noNulls || !target.isNull[r]) {
target.vector[r].set(maskDecimal(source.vector[r]));
}
}
}
}
}
class TimestampRedactConverter implements DataMask {
@Override
public void maskData(ColumnVector original, ColumnVector masked, int start,
int length) {
TimestampColumnVector target = (TimestampColumnVector) masked;
TimestampColumnVector source = (TimestampColumnVector) original;
target.noNulls = original.noNulls;
target.isRepeating = original.isRepeating;
if (original.isRepeating) {
target.isNull[0] = source.isNull[0];
if (target.noNulls || !target.isNull[0]) {
target.time[0] = maskTime(source.time[0]);
target.nanos[0] = 0;
}
} else {
for(int r = start; r < start + length; ++r) {
target.isNull[r] = source.isNull[r];
if (target.noNulls || !target.isNull[r]) {
target.time[r] = maskTime(source.time[r]);
target.nanos[r] = 0;
}
}
}
}
}
class DateRedactConverter implements DataMask {
@Override
public void maskData(ColumnVector original, ColumnVector masked, int start,
int length) {
LongColumnVector target = (LongColumnVector) masked;
LongColumnVector source = (LongColumnVector) original;
target.noNulls = original.noNulls;
target.isRepeating = original.isRepeating;
if (original.isRepeating) {
target.isNull[0] = source.isNull[0];
if (target.noNulls || !target.isNull[0]) {
target.vector[0] = maskDate((int) source.vector[0]);
}
} else {
for(int r = start; r < start + length; ++r) {
target.isNull[r] = source.isNull[r];
if (target.noNulls || !target.isNull[r]) {
target.vector[r] = maskDate((int) source.vector[r]);
}
}
}
}
}
/**
* Get the next code point from the ByteBuffer. Moves the position in the
* ByteBuffer forward to the next code point.
* @param param the source of bytes
* @param defaultValue if there are no bytes left, use this value
* @return the code point that was found at the front of the buffer.
*/
static int getNextCodepoint(ByteBuffer param, int defaultValue) {
if (param.remaining() == 0) {
return defaultValue;
} else {
return Text.bytesToCodePoint(param);
}
}
/**
* Get the replacement digit. This routine supports non-ASCII values for the
* replacement. For example, if the user gives one of "7", "७", "〧" or "፯"
* the value is 7.
* @param digitCodePoint the code point that is replacing digits
* @return the number from 0 to 9 to use as the numeric replacement
*/
static int getReplacementDigit(int digitCodePoint) {
int dig = Character.getNumericValue(digitCodePoint);
if (dig >= 0 && dig <= 9) {
return dig;
} else {
return DEFAULT_NUMBER_DIGIT;
}
}
static int getDateParam(String[] dateParams, int posn,
int myDefault, int max) {
if (dateParams != null && posn < dateParams.length) {
if (dateParams[posn].codePointAt(0) == UNMASKED_CHAR) {
return UNMASKED_DATE;
} else {
int result = Integer.parseInt(dateParams[posn]);
if (result >= -1 && result <= max) {
return result;
} else {
throw new IllegalArgumentException("Invalid date parameter " + posn +
" of " + dateParams[posn] + " greater than " + max);
}
}
} else {
return myDefault;
}
}
/**
* Replace each digit in value with DIGIT_REPLACEMENT scaled to the matching
* number of digits.
* @param value the number to mask
* @return the masked value
*/
public long maskLong(long value) {
/* check whether unmasking range provided */
if (!unmaskIndexRanges.isEmpty()) {
return maskLongWithUnmasking(value);
}
long base;
if (DIGIT_REPLACEMENT == 0) {
return 0;
} else if (value >= 0) {
base = 1;
} else {
base = -1;
// make sure Long.MIN_VALUE doesn't overflow
if (value == Long.MIN_VALUE) {
value = Long.MAX_VALUE;
} else {
value = -value;
}
}
if (value < 100_000_000L) {
if (value < 10_000L) {
if (value < 100L) {
if (value < 10L) {
base *= 1;
} else {
base *= 11;
}
} else if (value < 1_000L) {
base *= 111;
} else {
base *= 1_111;
}
} else if (value < 1_000_000L) {
if (value < 100_000L) {
base *= 11_111;
} else {
base *= 111_111;
}
} else if (value < 10_000_000L) {
base *= 1_111_111;
} else {
base *= 11_111_111;
}
} else if (value < 10_000_000_000_000_000L) {
if (value < 1_000_000_000_000L) {
if (value < 10_000_000_000L) {
if (value < 1_000_000_000L) {
base *= 111_111_111;
} else {
base *= 1_111_111_111;
}
} else if (value < 100_000_000_000L) {
base *= 11_111_111_111L;
} else {
base *= 111_111_111_111L;
}
} else if (value < 100_000_000_000_000L) {
if (value < 10_000_000_000_000L) {
base *= 1_111_111_111_111L;
} else {
base *= 11_111_111_111_111L;
}
} else if (value < 1_000_000_000_000_000L) {
base *= 111_111_111_111_111L;
} else {
base *= 1_111_111_111_111_111L;
}
} else if (value < 100_000_000_000_000_000L) {
base *= 11_111_111_111_111_111L;
// If the digit is 9, it would overflow at 19 digits, so use 18.
} else if (value < 1_000_000_000_000_000_000L || DIGIT_REPLACEMENT == 9) {
base *= 111_111_111_111_111_111L;
} else {
base *= 1_111_111_111_111_111_111L;
}
return DIGIT_REPLACEMENT * base;
}
private static final double[] DOUBLE_POWER_10 = new double[]{
1e-308, 1e-307, 1e-306, 1e-305, 1e-304, 1e-303, 1e-302, 1e-301, 1e-300,
1e-299, 1e-298, 1e-297, 1e-296, 1e-295, 1e-294, 1e-293, 1e-292, 1e-291,
1e-290, 1e-289, 1e-288, 1e-287, 1e-286, 1e-285, 1e-284, 1e-283, 1e-282,
1e-281, 1e-280, 1e-279, 1e-278, 1e-277, 1e-276, 1e-275, 1e-274, 1e-273,
1e-272, 1e-271, 1e-270, 1e-269, 1e-268, 1e-267, 1e-266, 1e-265, 1e-264,
1e-263, 1e-262, 1e-261, 1e-260, 1e-259, 1e-258, 1e-257, 1e-256, 1e-255,
1e-254, 1e-253, 1e-252, 1e-251, 1e-250, 1e-249, 1e-248, 1e-247, 1e-246,
1e-245, 1e-244, 1e-243, 1e-242, 1e-241, 1e-240, 1e-239, 1e-238, 1e-237,
1e-236, 1e-235, 1e-234, 1e-233, 1e-232, 1e-231, 1e-230, 1e-229, 1e-228,
1e-227, 1e-226, 1e-225, 1e-224, 1e-223, 1e-222, 1e-221, 1e-220, 1e-219,
1e-218, 1e-217, 1e-216, 1e-215, 1e-214, 1e-213, 1e-212, 1e-211, 1e-210,
1e-209, 1e-208, 1e-207, 1e-206, 1e-205, 1e-204, 1e-203, 1e-202, 1e-201,
1e-200, 1e-199, 1e-198, 1e-197, 1e-196, 1e-195, 1e-194, 1e-193, 1e-192,
1e-191, 1e-190, 1e-189, 1e-188, 1e-187, 1e-186, 1e-185, 1e-184, 1e-183,
1e-182, 1e-181, 1e-180, 1e-179, 1e-178, 1e-177, 1e-176, 1e-175, 1e-174,
1e-173, 1e-172, 1e-171, 1e-170, 1e-169, 1e-168, 1e-167, 1e-166, 1e-165,
1e-164, 1e-163, 1e-162, 1e-161, 1e-160, 1e-159, 1e-158, 1e-157, 1e-156,
1e-155, 1e-154, 1e-153, 1e-152, 1e-151, 1e-150, 1e-149, 1e-148, 1e-147,
1e-146, 1e-145, 1e-144, 1e-143, 1e-142, 1e-141, 1e-140, 1e-139, 1e-138,
1e-137, 1e-136, 1e-135, 1e-134, 1e-133, 1e-132, 1e-131, 1e-130, 1e-129,
1e-128, 1e-127, 1e-126, 1e-125, 1e-124, 1e-123, 1e-122, 1e-121, 1e-120,
1e-119, 1e-118, 1e-117, 1e-116, 1e-115, 1e-114, 1e-113, 1e-112, 1e-111,
1e-110, 1e-109, 1e-108, 1e-107, 1e-106, 1e-105, 1e-104, 1e-103, 1e-102,
1e-101, 1e-100, 1e-99, 1e-98, 1e-97, 1e-96, 1e-95, 1e-94, 1e-93,
1e-92, 1e-91, 1e-90, 1e-89, 1e-88, 1e-87, 1e-86, 1e-85, 1e-84,
1e-83, 1e-82, 1e-81, 1e-80, 1e-79, 1e-78, 1e-77, 1e-76, 1e-75,
1e-74, 1e-73, 1e-72, 1e-71, 1e-70, 1e-69, 1e-68, 1e-67, 1e-66,
1e-65, 1e-64, 1e-63, 1e-62, 1e-61, 1e-60, 1e-59, 1e-58, 1e-57,
1e-56, 1e-55, 1e-54, 1e-53, 1e-52, 1e-51, 1e-50, 1e-49, 1e-48,
1e-47, 1e-46, 1e-45, 1e-44, 1e-43, 1e-42, 1e-41, 1e-40, 1e-39,
1e-38, 1e-37, 1e-36, 1e-35, 1e-34, 1e-33, 1e-32, 1e-31, 1e-30,
1e-29, 1e-28, 1e-27, 1e-26, 1e-25, 1e-24, 1e-23, 1e-22, 1e-21,
1e-20, 1e-19, 1e-18, 1e-17, 1e-16, 1e-15, 1e-14, 1e-13, 1e-12,
1e-11, 1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3,
1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6,
1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15,
1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22, 1e23, 1e24,
1e25, 1e26, 1e27, 1e28, 1e29, 1e30, 1e31, 1e32, 1e33,
1e34, 1e35, 1e36, 1e37, 1e38, 1e39, 1e40, 1e41, 1e42,
1e43, 1e44, 1e45, 1e46, 1e47, 1e48, 1e49, 1e50, 1e51,
1e52, 1e53, 1e54, 1e55, 1e56, 1e57, 1e58, 1e59, 1e60,
1e61, 1e62, 1e63, 1e64, 1e65, 1e66, 1e67, 1e68, 1e69,
1e70, 1e71, 1e72, 1e73, 1e74, 1e75, 1e76, 1e77, 1e78,
1e79, 1e80, 1e81, 1e82, 1e83, 1e84, 1e85, 1e86, 1e87,
1e88, 1e89, 1e90, 1e91, 1e92, 1e93, 1e94, 1e95, 1e96,
1e97, 1e98, 1e99, 1e100, 1e101, 1e102, 1e103, 1e104, 1e105,
1e106, 1e107, 1e108, 1e109, 1e110, 1e111, 1e112, 1e113, 1e114,
1e115, 1e116, 1e117, 1e118, 1e119, 1e120, 1e121, 1e122, 1e123,
1e124, 1e125, 1e126, 1e127, 1e128, 1e129, 1e130, 1e131, 1e132,
1e133, 1e134, 1e135, 1e136, 1e137, 1e138, 1e139, 1e140, 1e141,
1e142, 1e143, 1e144, 1e145, 1e146, 1e147, 1e148, 1e149, 1e150,
1e151, 1e152, 1e153, 1e154, 1e155, 1e156, 1e157, 1e158, 1e159,
1e160, 1e161, 1e162, 1e163, 1e164, 1e165, 1e166, 1e167, 1e168,
1e169, 1e170, 1e171, 1e172, 1e173, 1e174, 1e175, 1e176, 1e177,
1e178, 1e179, 1e180, 1e181, 1e182, 1e183, 1e184, 1e185, 1e186,
1e187, 1e188, 1e189, 1e190, 1e191, 1e192, 1e193, 1e194, 1e195,
1e196, 1e197, 1e198, 1e199, 1e200, 1e201, 1e202, 1e203, 1e204,
1e205, 1e206, 1e207, 1e208, 1e209, 1e210, 1e211, 1e212, 1e213,
1e214, 1e215, 1e216, 1e217, 1e218, 1e219, 1e220, 1e221, 1e222,
1e223, 1e224, 1e225, 1e226, 1e227, 1e228, 1e229, 1e230, 1e231,
1e232, 1e233, 1e234, 1e235, 1e236, 1e237, 1e238, 1e239, 1e240,
1e241, 1e242, 1e243, 1e244, 1e245, 1e246, 1e247, 1e248, 1e249,
1e250, 1e251, 1e252, 1e253, 1e254, 1e255, 1e256, 1e257, 1e258,
1e259, 1e260, 1e261, 1e262, 1e263, 1e264, 1e265, 1e266, 1e267,
1e268, 1e269, 1e270, 1e271, 1e272, 1e273, 1e274, 1e275, 1e276,
1e277, 1e278, 1e279, 1e280, 1e281, 1e282, 1e283, 1e284, 1e285,
1e286, 1e287, 1e288, 1e289, 1e290, 1e291, 1e292, 1e293, 1e294,
1e295, 1e296, 1e297, 1e298, 1e299, 1e300, 1e301, 1e302, 1e303,
1e304, 1e305, 1e306, 1e307};
/**
* Replace each digit in value with digit.
* @param value the number to mask
* @return the
*/
public double maskDouble(double value) {
/* check whether unmasking range provided */
if (!unmaskIndexRanges.isEmpty()) {
return maskDoubleWIthUnmasking(value);
}
double base;
// It seems better to mask 0 to 9.99999 rather than 9.99999e-308.
if (value == 0 || DIGIT_REPLACEMENT == 0) {
return DIGIT_REPLACEMENT * 1.11111;
} else if (value > 0) {
base = 1.11111;
} else {
base = -1.11111;
value = -value;
}
int posn = Arrays.binarySearch(DOUBLE_POWER_10, value);
if (posn < -DOUBLE_POWER_10.length - 2) {
posn = DOUBLE_POWER_10.length - 1;
} else if (posn == -1) {
posn = 0;
} else if (posn < 0) {
posn = -posn -2;
}
return DIGIT_REPLACEMENT * base * DOUBLE_POWER_10[posn];
}
private final Calendar scratch = Calendar.getInstance();
/**
* Given the requested masking parameters, redact the given time
* @param millis the original time
* @return the millis after it has been masked
*/
long maskTime(long millis) {
scratch.setTimeInMillis(millis);
if (YEAR_REPLACEMENT != UNMASKED_DATE) {
scratch.set(Calendar.YEAR, YEAR_REPLACEMENT);
}
if (MONTH_REPLACEMENT != UNMASKED_DATE) {
scratch.set(Calendar.MONTH, MONTH_REPLACEMENT - 1);
}
if (DATE_REPLACEMENT != UNMASKED_DATE) {
scratch.set(Calendar.DATE, DATE_REPLACEMENT);
}
if (HOUR_REPLACEMENT != UNMASKED_DATE) {
if (HOUR_REPLACEMENT >= 12) {
scratch.set(Calendar.HOUR, HOUR_REPLACEMENT - 12);
scratch.set(Calendar.AM_PM, Calendar.PM);
} else {
scratch.set(Calendar.HOUR, HOUR_REPLACEMENT);
scratch.set(Calendar.AM_PM, Calendar.AM);
}
}
if (MINUTE_REPLACEMENT != UNMASKED_DATE) {
scratch.set(Calendar.MINUTE, MINUTE_REPLACEMENT);
}
if (SECOND_REPLACEMENT != UNMASKED_DATE) {
scratch.set(Calendar.SECOND, SECOND_REPLACEMENT);
scratch.set(Calendar.MILLISECOND, 0);
}
return scratch.getTimeInMillis();
}
private static final long MILLIS_PER_DAY = TimeUnit.DAYS.toMillis(1);
private final Calendar utcScratch =
Calendar.getInstance(TimeZone.getTimeZone("UTC"));
/**
* Given a date as the number of days since epoch (1 Jan 1970),
* mask the date given the parameters.
* @param daysSinceEpoch the number of days after epoch
* @return the number of days after epoch when masked
*/
int maskDate(int daysSinceEpoch) {
utcScratch.setTimeInMillis(daysSinceEpoch * MILLIS_PER_DAY);
if (YEAR_REPLACEMENT != UNMASKED_DATE) {
utcScratch.set(Calendar.YEAR, YEAR_REPLACEMENT);
}
if (MONTH_REPLACEMENT != UNMASKED_DATE) {
utcScratch.set(Calendar.MONTH, MONTH_REPLACEMENT - 1);
}
if (DATE_REPLACEMENT != UNMASKED_DATE) {
utcScratch.set(Calendar.DATE, DATE_REPLACEMENT);
}
return (int) (utcScratch.getTimeInMillis() / MILLIS_PER_DAY);
}
/**
* Mask a decimal.
* This is painfully slow because it converts to a string and then back to
* a decimal. Until HiveDecimalWritable gives us more access, this is
* the best tradeoff between developer time, functionality, and run time.
* @param source the value to mask
* @return the masked value.
*/
HiveDecimalWritable maskDecimal(HiveDecimalWritable source) {
return new HiveDecimalWritable(maskNumericString(source.toString()));
}
/**
* Given a UTF code point, find the replacement codepoint
* @param codepoint a UTF character
* @return the replacement codepoint
*/
int getReplacement(int codepoint) {
switch (Character.getType(codepoint)) {
case Character.UPPERCASE_LETTER:
return UPPER_REPLACEMENT;
case Character.LOWERCASE_LETTER:
return LOWER_REPLACEMENT;
case Character.TITLECASE_LETTER:
case Character.MODIFIER_LETTER:
case Character.OTHER_LETTER:
return OTHER_LETTER_REPLACEMENT;
case Character.NON_SPACING_MARK:
case Character.ENCLOSING_MARK:
case Character.COMBINING_SPACING_MARK:
return MARK_REPLACEMENT;
case Character.DECIMAL_DIGIT_NUMBER:
return DIGIT_CP_REPLACEMENT;
case Character.LETTER_NUMBER:
case Character.OTHER_NUMBER:
return OTHER_NUMBER_REPLACEMENT;
case Character.SPACE_SEPARATOR:
case Character.LINE_SEPARATOR:
case Character.PARAGRAPH_SEPARATOR:
return SEPARATOR_REPLACEMENT;
case Character.MATH_SYMBOL:
case Character.CURRENCY_SYMBOL:
case Character.MODIFIER_SYMBOL:
case Character.OTHER_SYMBOL:
return SYMBOL_REPLACEMENT;
case Character.DASH_PUNCTUATION:
case Character.START_PUNCTUATION:
case Character.END_PUNCTUATION:
case Character.CONNECTOR_PUNCTUATION:
case Character.OTHER_PUNCTUATION:
return PUNCTUATION_REPLACEMENT;
default:
return OTHER_REPLACEMENT;
}
}
/**
* Get the number of bytes for each codepoint
* @param codepoint the codepoint to check
* @return the number of bytes
*/
static int getCodepointLength(int codepoint) {
if (codepoint < 0) {
throw new IllegalArgumentException("Illegal codepoint " + codepoint);
} else if (codepoint < 0x80) {
return 1;
} else if (codepoint < 0x7ff) {
return 2;
} else if (codepoint < 0xffff) {
return 3;
} else if (codepoint < 0x10FFFF) {
return 4;
} else {
throw new IllegalArgumentException("Illegal codepoint " + codepoint);
}
}
/**
* Write the give codepoint to the buffer.
* @param codepoint the codepoint to write
* @param buffer the buffer to write into
* @param offset the first offset to use
* @param length the number of bytes that will be used
*/
static void writeCodepoint(int codepoint, byte[] buffer, int offset,
int length) {
switch (length) {
case 1:
buffer[offset] = (byte) codepoint;
break;
case 2:
buffer[offset] = (byte)(0xC0 | codepoint >> 6);
buffer[offset+1] = (byte)(0x80 | (codepoint & 0x3f));
break;
case 3:
buffer[offset] = (byte)(0xE0 | codepoint >> 12);
buffer[offset+1] = (byte)(0x80 | ((codepoint >> 6) & 0x3f));
buffer[offset+2] = (byte)(0x80 | (codepoint & 0x3f));
break;
case 4:
buffer[offset] = (byte)(0xF0 | codepoint >> 18);
buffer[offset+1] = (byte)(0x80 | ((codepoint >> 12) & 0x3f));
buffer[offset+2] = (byte)(0x80 | ((codepoint >> 6) & 0x3f));
buffer[offset+3] = (byte)(0x80 | (codepoint & 0x3f));
break;
default:
throw new IllegalArgumentException("Invalid length for codepoint " +
codepoint + " = " + length);
}
}
/**
* Mask a string by finding the character category of each character
* and replacing it with the matching literal.
* @param source the source column vector
* @param row the value index
* @param target the target column vector
*/
void maskString(BytesColumnVector source, int row, BytesColumnVector target) {
int expectedBytes = source.length[row];
ByteBuffer sourceBytes = ByteBuffer.wrap(source.vector[row],
source.start[row], source.length[row]);
// ensure we have enough space, if the masked data is the same size
target.ensureValPreallocated(expectedBytes);
byte[] outputBuffer = target.getValPreallocatedBytes();
int outputOffset = target.getValPreallocatedStart();
int outputStart = outputOffset;
int index = 0;
while (sourceBytes.remaining() > 0) {
int cp = Text.bytesToCodePoint(sourceBytes);
// Find the replacement for the current character.
int replacement = getReplacement(cp);
if (replacement == UNMASKED_CHAR || isIndexInUnmaskRange(index, source.length[row])) {
replacement = cp;
}
// increment index
index++;
int len = getCodepointLength(replacement);
// If the translation will overflow the buffer, we need to resize.
// This will only happen when the masked size is larger than the original.
if (len + outputOffset > outputBuffer.length) {
// Revise estimate how much we are going to need now. We are maximally
// pesamistic here so that we don't have to expand again for this value.
int currentOutputStart = outputStart;
int currentOutputLength = outputOffset - currentOutputStart;
expectedBytes = currentOutputLength + len + sourceBytes.remaining() * 4;
// Expand the buffer to fit the new estimate
target.ensureValPreallocated(expectedBytes);
// Copy over the bytes we've already written for this value and move
// the pointers to the new output buffer.
byte[] oldBuffer = outputBuffer;
outputBuffer = target.getValPreallocatedBytes();
outputOffset = target.getValPreallocatedStart();
outputStart = outputOffset;
System.arraycopy(oldBuffer, currentOutputStart, outputBuffer,
outputOffset, currentOutputLength);
outputOffset += currentOutputLength;
}
// finally copy the bytes
writeCodepoint(replacement, outputBuffer, outputOffset, len);
outputOffset += len;
}
target.setValPreallocated(row, outputOffset - outputStart);
}
static final long OVERFLOW_REPLACEMENT = 111_111_111_111_111_111L;
/**
* A function that masks longs when there are unmasked ranges.
* @param value the original value
* @return the masked value
*/
long maskLongWithUnmasking(long value) throws IndexOutOfBoundsException {
try {
return Long.parseLong(maskNumericString(Long.toString(value)));
} catch (NumberFormatException nfe) {
return OVERFLOW_REPLACEMENT * DIGIT_REPLACEMENT;
}
}
/**
* A function that masks doubles when there are unmasked ranges.
* @param value original value
* @return masked value
*/
double maskDoubleWIthUnmasking(final double value) {
try {
return Double.parseDouble(maskNumericString(Double.toString(value)));
} catch (NumberFormatException nfe) {
return OVERFLOW_REPLACEMENT * DIGIT_REPLACEMENT;
}
}
/**
* Mask the given stringified numeric value excluding the unmask range.
* Non-digit characters are passed through on the assumption they are
* markers (eg. one of ",.ef").
* @param value the original value.
*/
String maskNumericString(final String value) {
StringBuilder result = new StringBuilder();
final int length = value.codePointCount(0, value.length());
for(int c=0; c < length; ++c) {
int cp = value.codePointAt(c);
if (isIndexInUnmaskRange(c, length) ||
Character.getType(cp) != Character.DECIMAL_DIGIT_NUMBER) {
result.appendCodePoint(cp);
} else {
result.appendCodePoint(DIGIT_CP_REPLACEMENT);
}
}
return result.toString();
}
/**
* Given an index and length of a string
* find out whether it is in a given un-mask range.
* @param index the character point index
* @param length the length of the string in character points
* @return true if the index is in un-mask range else false.
*/
private boolean isIndexInUnmaskRange(final int index, final int length) {
for(final Map.Entry<Integer, Integer> pair : unmaskIndexRanges.entrySet()) {
int start;
int end;
if(pair.getKey() >= 0) {
// for positive indexes
start = pair.getKey();
} else {
// for negative indexes
start = length + pair.getKey();
}
if(pair.getValue() >= 0) {
// for positive indexes
end = pair.getValue();
} else {
// for negative indexes
end = length + pair.getValue();
}
// if the given index is in range
if(index >= start && index <= end ) {
return true;
}
}
return false;
}
}
|
googleapis/google-cloud-java | 35,671 | java-securitycenter/proto-google-cloud-securitycenter-v1/src/main/java/com/google/cloud/securitycenter/v1/ListEffectiveEventThreatDetectionCustomModulesRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/securitycenter/v1/securitycenter_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.securitycenter.v1;
/**
*
*
* <pre>
* Request to list effective Event Threat Detection custom modules.
* </pre>
*
* Protobuf type {@code
* google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest}
*/
public final class ListEffectiveEventThreatDetectionCustomModulesRequest
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest)
ListEffectiveEventThreatDetectionCustomModulesRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListEffectiveEventThreatDetectionCustomModulesRequest.newBuilder() to construct.
private ListEffectiveEventThreatDetectionCustomModulesRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListEffectiveEventThreatDetectionCustomModulesRequest() {
parent_ = "";
pageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListEffectiveEventThreatDetectionCustomModulesRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_ListEffectiveEventThreatDetectionCustomModulesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_ListEffectiveEventThreatDetectionCustomModulesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest
.class,
com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest
.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Name of the parent to list custom modules for.
*
* Its format is:
*
* * `organizations/{organization}/eventThreatDetectionSettings`.
* * `folders/{folder}/eventThreatDetectionSettings`.
* * `projects/{project}/eventThreatDetectionSettings`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Name of the parent to list custom modules for.
*
* Its format is:
*
* * `organizations/{organization}/eventThreatDetectionSettings`.
* * `folders/{folder}/eventThreatDetectionSettings`.
* * `projects/{project}/eventThreatDetectionSettings`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A page token, received from a previous
* `ListEffectiveEventThreatDetectionCustomModules` call. Provide this to
* retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* `ListEffectiveEventThreatDetectionCustomModules` must match the call that
* provided the page token.
* </pre>
*
* <code>string page_token = 2;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A page token, received from a previous
* `ListEffectiveEventThreatDetectionCustomModules` call. Provide this to
* retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* `ListEffectiveEventThreatDetectionCustomModules` must match the call that
* provided the page token.
* </pre>
*
* <code>string page_token = 2;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 3;
private int pageSize_ = 0;
/**
*
*
* <pre>
* The maximum number of modules to return. The service may return fewer than
* this value.
* If unspecified, at most 10 configs will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 3;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
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(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, pageToken_);
}
if (pageSize_ != 0) {
output.writeInt32(3, pageSize_);
}
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(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, pageToken_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, pageSize_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj
instanceof
com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest)) {
return super.equals(obj);
}
com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest other =
(com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest)
obj;
if (!getParent().equals(other.getParent())) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest
prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request to list effective Event Threat Detection custom modules.
* </pre>
*
* Protobuf type {@code
* google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest)
com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_ListEffectiveEventThreatDetectionCustomModulesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_ListEffectiveEventThreatDetectionCustomModulesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest.class,
com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest.Builder.class);
}
// Construct using
// com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageToken_ = "";
pageSize_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_ListEffectiveEventThreatDetectionCustomModulesRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest
getDefaultInstanceForType() {
return com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest
build() {
com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest
result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest
buildPartial() {
com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest
result =
new com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest
result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageSize_ = pageSize_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other
instanceof
com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest) {
return mergeFrom(
(com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest)
other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest
other) {
if (other
== com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
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:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000004;
break;
} // case 24
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Name of the parent to list custom modules for.
*
* Its format is:
*
* * `organizations/{organization}/eventThreatDetectionSettings`.
* * `folders/{folder}/eventThreatDetectionSettings`.
* * `projects/{project}/eventThreatDetectionSettings`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Name of the parent to list custom modules for.
*
* Its format is:
*
* * `organizations/{organization}/eventThreatDetectionSettings`.
* * `folders/{folder}/eventThreatDetectionSettings`.
* * `projects/{project}/eventThreatDetectionSettings`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Name of the parent to list custom modules for.
*
* Its format is:
*
* * `organizations/{organization}/eventThreatDetectionSettings`.
* * `folders/{folder}/eventThreatDetectionSettings`.
* * `projects/{project}/eventThreatDetectionSettings`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Name of the parent to list custom modules for.
*
* Its format is:
*
* * `organizations/{organization}/eventThreatDetectionSettings`.
* * `folders/{folder}/eventThreatDetectionSettings`.
* * `projects/{project}/eventThreatDetectionSettings`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Name of the parent to list custom modules for.
*
* Its format is:
*
* * `organizations/{organization}/eventThreatDetectionSettings`.
* * `folders/{folder}/eventThreatDetectionSettings`.
* * `projects/{project}/eventThreatDetectionSettings`.
* </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 pageToken_ = "";
/**
*
*
* <pre>
* A page token, received from a previous
* `ListEffectiveEventThreatDetectionCustomModules` call. Provide this to
* retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* `ListEffectiveEventThreatDetectionCustomModules` must match the call that
* provided the page token.
* </pre>
*
* <code>string page_token = 2;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A page token, received from a previous
* `ListEffectiveEventThreatDetectionCustomModules` call. Provide this to
* retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* `ListEffectiveEventThreatDetectionCustomModules` must match the call that
* provided the page token.
* </pre>
*
* <code>string page_token = 2;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A page token, received from a previous
* `ListEffectiveEventThreatDetectionCustomModules` call. Provide this to
* retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* `ListEffectiveEventThreatDetectionCustomModules` must match the call that
* provided the page token.
* </pre>
*
* <code>string page_token = 2;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A page token, received from a previous
* `ListEffectiveEventThreatDetectionCustomModules` call. Provide this to
* retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* `ListEffectiveEventThreatDetectionCustomModules` must match the call that
* provided the page token.
* </pre>
*
* <code>string page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A page token, received from a previous
* `ListEffectiveEventThreatDetectionCustomModules` call. Provide this to
* retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* `ListEffectiveEventThreatDetectionCustomModules` must match the call that
* provided the page token.
* </pre>
*
* <code>string page_token = 2;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of modules to return. The service may return fewer than
* this value.
* If unspecified, at most 10 configs will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 3;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* The maximum number of modules to return. The service may return fewer than
* this value.
* If unspecified, at most 10 configs will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 3;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The maximum number of modules to return. The service may return fewer than
* this value.
* If unspecified, at most 10 configs will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000004);
pageSize_ = 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.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest)
private static final com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest();
}
public static com.google.cloud.securitycenter.v1
.ListEffectiveEventThreatDetectionCustomModulesRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<
ListEffectiveEventThreatDetectionCustomModulesRequest>
PARSER =
new com.google.protobuf.AbstractParser<
ListEffectiveEventThreatDetectionCustomModulesRequest>() {
@java.lang.Override
public ListEffectiveEventThreatDetectionCustomModulesRequest 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<ListEffectiveEventThreatDetectionCustomModulesRequest>
parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListEffectiveEventThreatDetectionCustomModulesRequest>
getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.securitycenter.v1.ListEffectiveEventThreatDetectionCustomModulesRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/logging-flume | 35,738 | flume-ng-sources/flume-scribe-source/src/main/java/org/apache/flume/source/scribe/Scribe.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.
*/
/**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.flume.source.scribe;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2017-09-01")
public class Scribe {
public interface Iface {
public ResultCode Log(List<LogEntry> messages) throws org.apache.thrift.TException;
}
public interface AsyncIface {
public void Log(List<LogEntry> messages, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;
}
public static class Client extends org.apache.thrift.TServiceClient implements Iface {
public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
public Factory() {}
public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
return new Client(prot);
}
public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
return new Client(iprot, oprot);
}
}
public Client(org.apache.thrift.protocol.TProtocol prot)
{
super(prot, prot);
}
public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
super(iprot, oprot);
}
public ResultCode Log(List<LogEntry> messages) throws org.apache.thrift.TException
{
send_Log(messages);
return recv_Log();
}
public void send_Log(List<LogEntry> messages) throws org.apache.thrift.TException
{
Log_args args = new Log_args();
args.setMessages(messages);
sendBase("Log", args);
}
public ResultCode recv_Log() throws org.apache.thrift.TException
{
Log_result result = new Log_result();
receiveBase(result, "Log");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "Log failed: unknown result");
}
}
public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
private org.apache.thrift.async.TAsyncClientManager clientManager;
private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
this.clientManager = clientManager;
this.protocolFactory = protocolFactory;
}
public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
return new AsyncClient(protocolFactory, clientManager, transport);
}
}
public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
super(protocolFactory, clientManager, transport);
}
public void Log(List<LogEntry> messages, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
checkReady();
Log_call method_call = new Log_call(messages, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class Log_call extends org.apache.thrift.async.TAsyncMethodCall {
private List<LogEntry> messages;
public Log_call(List<LogEntry> messages, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.messages = messages;
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("Log", org.apache.thrift.protocol.TMessageType.CALL, 0));
Log_args args = new Log_args();
args.setMessages(messages);
args.write(prot);
prot.writeMessageEnd();
}
public ResultCode getResult() throws org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_Log();
}
}
}
public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName());
public Processor(I iface) {
super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
}
protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
processMap.put("Log", new Log());
return processMap;
}
public static class Log<I extends Iface> extends org.apache.thrift.ProcessFunction<I, Log_args> {
public Log() {
super("Log");
}
public Log_args getEmptyArgsInstance() {
return new Log_args();
}
protected boolean isOneway() {
return false;
}
public Log_result getResult(I iface, Log_args args) throws org.apache.thrift.TException {
Log_result result = new Log_result();
result.success = iface.Log(args.messages);
return result;
}
}
}
public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName());
public AsyncProcessor(I iface) {
super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
}
protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
processMap.put("Log", new Log());
return processMap;
}
public static class Log<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, Log_args, ResultCode> {
public Log() {
super("Log");
}
public Log_args getEmptyArgsInstance() {
return new Log_args();
}
public AsyncMethodCallback<ResultCode> getResultHandler(final AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new AsyncMethodCallback<ResultCode>() {
public void onComplete(ResultCode o) {
Log_result result = new Log_result();
result.success = o;
try {
fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
return;
} catch (Exception e) {
LOGGER.error("Exception writing to internal frame buffer", e);
}
fb.close();
}
public void onError(Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TBase msg;
Log_result result = new Log_result();
{
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
return;
} catch (Exception ex) {
LOGGER.error("Exception writing to internal frame buffer", ex);
}
fb.close();
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, Log_args args, org.apache.thrift.async.AsyncMethodCallback<ResultCode> resultHandler) throws TException {
iface.Log(args.messages,resultHandler);
}
}
}
public static class Log_args implements org.apache.thrift.TBase<Log_args, Log_args._Fields>, java.io.Serializable, Cloneable, Comparable<Log_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Log_args");
private static final org.apache.thrift.protocol.TField MESSAGES_FIELD_DESC = new org.apache.thrift.protocol.TField("messages", org.apache.thrift.protocol.TType.LIST, (short)1);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new Log_argsStandardSchemeFactory());
schemes.put(TupleScheme.class, new Log_argsTupleSchemeFactory());
}
public List<LogEntry> messages; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
MESSAGES((short)1, "messages");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // MESSAGES
return MESSAGES;
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 IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.MESSAGES, new org.apache.thrift.meta_data.FieldMetaData("messages", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, LogEntry.class))));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(Log_args.class, metaDataMap);
}
public Log_args() {
}
public Log_args(
List<LogEntry> messages)
{
this();
this.messages = messages;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public Log_args(Log_args other) {
if (other.isSetMessages()) {
List<LogEntry> __this__messages = new ArrayList<LogEntry>(other.messages.size());
for (LogEntry other_element : other.messages) {
__this__messages.add(new LogEntry(other_element));
}
this.messages = __this__messages;
}
}
public Log_args deepCopy() {
return new Log_args(this);
}
@Override
public void clear() {
this.messages = null;
}
public int getMessagesSize() {
return (this.messages == null) ? 0 : this.messages.size();
}
public java.util.Iterator<LogEntry> getMessagesIterator() {
return (this.messages == null) ? null : this.messages.iterator();
}
public void addToMessages(LogEntry elem) {
if (this.messages == null) {
this.messages = new ArrayList<LogEntry>();
}
this.messages.add(elem);
}
public List<LogEntry> getMessages() {
return this.messages;
}
public Log_args setMessages(List<LogEntry> messages) {
this.messages = messages;
return this;
}
public void unsetMessages() {
this.messages = null;
}
/** Returns true if field messages is set (has been assigned a value) and false otherwise */
public boolean isSetMessages() {
return this.messages != null;
}
public void setMessagesIsSet(boolean value) {
if (!value) {
this.messages = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case MESSAGES:
if (value == null) {
unsetMessages();
} else {
setMessages((List<LogEntry>)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case MESSAGES:
return getMessages();
}
throw new 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 IllegalArgumentException();
}
switch (field) {
case MESSAGES:
return isSetMessages();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof Log_args)
return this.equals((Log_args)that);
return false;
}
public boolean equals(Log_args that) {
if (that == null)
return false;
boolean this_present_messages = true && this.isSetMessages();
boolean that_present_messages = true && that.isSetMessages();
if (this_present_messages || that_present_messages) {
if (!(this_present_messages && that_present_messages))
return false;
if (!this.messages.equals(that.messages))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_messages = true && (isSetMessages());
list.add(present_messages);
if (present_messages)
list.add(messages);
return list.hashCode();
}
@Override
public int compareTo(Log_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetMessages()).compareTo(other.isSetMessages());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetMessages()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.messages, other.messages);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Log_args(");
boolean first = true;
sb.append("messages:");
if (this.messages == null) {
sb.append("null");
} else {
sb.append(this.messages);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
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 Log_argsStandardSchemeFactory implements SchemeFactory {
public Log_argsStandardScheme getScheme() {
return new Log_argsStandardScheme();
}
}
private static class Log_argsStandardScheme extends StandardScheme<Log_args> {
public void read(org.apache.thrift.protocol.TProtocol iprot, Log_args 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: // MESSAGES
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list0 = iprot.readListBegin();
struct.messages = new ArrayList<LogEntry>(_list0.size);
LogEntry _elem1;
for (int _i2 = 0; _i2 < _list0.size; ++_i2)
{
_elem1 = new LogEntry();
_elem1.read(iprot);
struct.messages.add(_elem1);
}
iprot.readListEnd();
}
struct.setMessagesIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, Log_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.messages != null) {
oprot.writeFieldBegin(MESSAGES_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.messages.size()));
for (LogEntry _iter3 : struct.messages)
{
_iter3.write(oprot);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class Log_argsTupleSchemeFactory implements SchemeFactory {
public Log_argsTupleScheme getScheme() {
return new Log_argsTupleScheme();
}
}
private static class Log_argsTupleScheme extends TupleScheme<Log_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, Log_args struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetMessages()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetMessages()) {
{
oprot.writeI32(struct.messages.size());
for (LogEntry _iter4 : struct.messages)
{
_iter4.write(oprot);
}
}
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, Log_args struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
{
org.apache.thrift.protocol.TList _list5 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
struct.messages = new ArrayList<LogEntry>(_list5.size);
LogEntry _elem6;
for (int _i7 = 0; _i7 < _list5.size; ++_i7)
{
_elem6 = new LogEntry();
_elem6.read(iprot);
struct.messages.add(_elem6);
}
}
struct.setMessagesIsSet(true);
}
}
}
}
public static class Log_result implements org.apache.thrift.TBase<Log_result, Log_result._Fields>, java.io.Serializable, Cloneable, Comparable<Log_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Log_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I32, (short)0);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new Log_resultStandardSchemeFactory());
schemes.put(TupleScheme.class, new Log_resultTupleSchemeFactory());
}
/**
*
* @see ResultCode
*/
public ResultCode success; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
/**
*
* @see ResultCode
*/
SUCCESS((short)0, "success");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 0: // SUCCESS
return SUCCESS;
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 IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, ResultCode.class)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(Log_result.class, metaDataMap);
}
public Log_result() {
}
public Log_result(
ResultCode success)
{
this();
this.success = success;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public Log_result(Log_result other) {
if (other.isSetSuccess()) {
this.success = other.success;
}
}
public Log_result deepCopy() {
return new Log_result(this);
}
@Override
public void clear() {
this.success = null;
}
/**
*
* @see ResultCode
*/
public ResultCode getSuccess() {
return this.success;
}
/**
*
* @see ResultCode
*/
public Log_result setSuccess(ResultCode success) {
this.success = success;
return this;
}
public void unsetSuccess() {
this.success = null;
}
/** Returns true if field success is set (has been assigned a value) and false otherwise */
public boolean isSetSuccess() {
return this.success != null;
}
public void setSuccessIsSet(boolean value) {
if (!value) {
this.success = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((ResultCode)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return getSuccess();
}
throw new 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 IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof Log_result)
return this.equals((Log_result)that);
return false;
}
public boolean equals(Log_result that) {
if (that == null)
return false;
boolean this_present_success = true && this.isSetSuccess();
boolean that_present_success = true && that.isSetSuccess();
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (!this.success.equals(that.success))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_success = true && (isSetSuccess());
list.add(present_success);
if (present_success)
list.add(success.getValue());
return list.hashCode();
}
@Override
public int compareTo(Log_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Log_result(");
boolean first = true;
sb.append("success:");
if (this.success == null) {
sb.append("null");
} else {
sb.append(this.success);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
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 Log_resultStandardSchemeFactory implements SchemeFactory {
public Log_resultStandardScheme getScheme() {
return new Log_resultStandardScheme();
}
}
private static class Log_resultStandardScheme extends StandardScheme<Log_result> {
public void read(org.apache.thrift.protocol.TProtocol iprot, Log_result 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 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.success = org.apache.flume.source.scribe.ResultCode.findByValue(iprot.readI32());
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, Log_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.success != null) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
oprot.writeI32(struct.success.getValue());
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class Log_resultTupleSchemeFactory implements SchemeFactory {
public Log_resultTupleScheme getScheme() {
return new Log_resultTupleScheme();
}
}
private static class Log_resultTupleScheme extends TupleScheme<Log_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, Log_result struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetSuccess()) {
oprot.writeI32(struct.success.getValue());
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, Log_result struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.success = org.apache.flume.source.scribe.ResultCode.findByValue(iprot.readI32());
struct.setSuccessIsSet(true);
}
}
}
}
}
|
apache/hertzbeat | 35,627 | hertzbeat-ai-agent/src/main/java/org/apache/hertzbeat/ai/agent/tools/impl/AlertDefineToolsImpl.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.ai.agent.tools.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.usthe.sureness.subject.SubjectSum;
import lombok.extern.slf4j.Slf4j;
import org.apache.hertzbeat.ai.agent.adapters.AlertDefineServiceAdapter;
import org.apache.hertzbeat.ai.agent.pojo.dto.Hierarchy;
import org.apache.hertzbeat.ai.agent.config.McpContextHolder;
import org.apache.hertzbeat.ai.agent.tools.AlertDefineTools;
import org.apache.hertzbeat.ai.agent.utils.UtilityClass;
import org.apache.hertzbeat.common.entity.alerter.AlertDefine;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implementation of Alert Define Tools functionality
*/
@Slf4j
@Service
public class AlertDefineToolsImpl implements AlertDefineTools {
@Autowired
private AlertDefineServiceAdapter alertDefineServiceAdapter;
@Override
@Tool(name = "create_alert_rule", description = """
ALERT RULE means when to alert a user
THESE ARE ALERT RULES WITH THRESHOLD VALUES. USERS CAN SPECIFY THE THRESHOLD VALUES FOR EXAMPLE,
IF THE USER SAYS "ALERT ME WHEN MY COST EXCEEDS 700, THE EXPRESSION SHOULD BE 'cost > 700' NOT 'cost < 700'.
APPLY THE SAME LOGIC FOR LESS THAN OPERATOR.
Create a HertzBeat alert rule based on app hierarchy structure and user requirements.
It is important to first understand the hierarchy of apps, metrics, and field conditions
Each app has its own metrics and each metric has its own field conditions.
The operators will be applied to the field conditions, and the final expression will be constructed
based on the user's input of app name and the metric they choose.
CRITICAL WORKFLOW Do all of this iteratively with user interaction at each step
1. ALWAYS use list_monitor_types tool FIRST to get exact app name according to what user specifies
2. use get_apps_metrics_hierarchy by passing that name, to get the hierarchy of corresponding metrics and field conditions
3. Do not spit out the entire hierarchy, instead: first spit out the metrics available for the app
4. Ask the user to choose a metric from the available metrics
5. Based on the metric chosen, present the available field conditions/params
6. You will construct the proper expression with field conditions
7. once this tool successfully executes, ask the user if they want to bind any existing monitors to this alert rule,
get the monitors list for a particular app using the query_monitors tool.
8. based on the user's output, conditionally call the bind_monitors_to_alert_rule tool to bind monitors to the alert rule
VERY VERY IMPORTANT:
- ALWAYS USE the value field from the get_apps_metrics_hierarchy's json response when creating alert expressions on the field parameters
EXAMPLES FOR FIELD CONDITION EXPRESSION( Do not copy these examples, they are just for reference ):
These are all just examples, you can take inspiration from them and create a rule based on hierarchy, always ask the user for all params, do not assume them, even for these examples:
1. Kafka JVM Alert:
- App: "kafka", Metric: "jvm_basic"
- Field condition: equals(VmName, "myVM")
- Field condition expression: equals(VmName, "myVM")
2. LLM Credits Alert:
- App: "openai", Metric: "credit_grants"
- Field condition: total_granted > some_value
- Field condition expression: total_granted > 1000
3. HBase Master Alert:
- App: "hbase_master", Metric: "server"
- Field condition: heap_memory_used > 80 or some_factor<100
- Field condition expression: heap_memory_used > 80 or some_factor<100
4. Complex OpenAI Credits Alert:
- App: "openai", Metric: "credit_grants"
- Field condition: total_used > 123 and total_granted > 333 and (total_granted > 3444 and total_paid_available < 5556)
- Field condition expression: total_used > 123 and total_granted > 333 and (total_granted > 3444 and total_paid_available < 5556)
FIELD CONDITIONS GUIDANCE:
- Field names come from metric's children in hierarchy (leaf nodes)
- Use the "value" field from the metric's children, not the label when creating conditions
- Supported operators: >, <, >=, <=, ==, !=, exists(), !exists() for numeric fields
- equals(), contains(), matches(),exists(), !equals(), !contains(), !matches(), !exists() for string fields
- Supported logical operators: and, or to connect different field parameter rules or rulesets
- ONLY USE THESE OPERATORS, when creating conditions, do not use any other operators
- Support grouping with parentheses: (condition1 and condition2) or condition3
- String values should be quoted: equals(VmName, "my-vm")
- Simple conditions: heap_memory_used > 80, total_granted <= 1000
- Complex conditions: total_used > 123 and total_granted > 333 and (total_granted > 3444 and total_paid_available < 5556)
PRIORITY LEVELS:
- 0: Critical (immediate action required)
- 1: Warning (attention needed, default)
- 2: Info (informational only)
""")
public String createAlertRule(
@ToolParam(description = "Alert rule name (required, must be unique)", required = true) String name,
@ToolParam(description = "App name from hierarchy (must match exact hierarchy app value)", required = true) String app,
@ToolParam(description = "Metrics name from hierarchy (must match exact hierarchy metrics value)", required = true) String metrics,
@ToolParam(description = "Field conditions expression)", required = true) String fieldConditions,
@ToolParam(description = "Alert rule type: 'realtime' (default) or 'periodic'", required = false) String type,
@ToolParam(description = "Execution period in seconds (only for periodic rules, default: 300)", required = false) Integer period,
@ToolParam(description = "Number of consecutive violations before triggering (default: 3)", required = false) Integer times,
@ToolParam(description = "Alert priority as integer: 0=critical, 1=warning, 2=info (default: 1)", required = false) Integer priority,
@ToolParam(description = "Alert rule description (optional)", required = false) String description,
@ToolParam(description = "Alert message template with variables (optional)", required = false) String template,
@ToolParam(description = "Data source type: 'promql' (default)", required = false) String datasource,
@ToolParam(description = "Labels as key:value pairs separated by commas (e.g., 'env:prod,severity:critical')", required = false) String labels,
@ToolParam(description = "Annotations as key:value pairs separated by commas (e.g., 'summary:High CPU')", required = false) String annotations,
@ToolParam(description = "Whether to enable the rule immediately (default: true)", required = false) Boolean enable) {
try {
log.info("Creating HertzBeat alert rule: name={}, app={}, metrics={}, fieldConditions={}", name, app, metrics, fieldConditions);
SubjectSum subjectSum = McpContextHolder.getSubject();
log.debug("Current subject in create_alert_rule tool: {}", subjectSum);
// Validate required parameters
if (name == null || name.trim().isEmpty()) {
return "Error: Alert rule name is required";
}
if (app == null || app.trim().isEmpty()) {
return "Error: App name is required (use get_apps_metrics_hierarchy to find exact names)";
}
if (metrics == null || metrics.trim().isEmpty()) {
return "Error: Metrics name is required (use get_apps_metrics_hierarchy to find exact names)";
}
if (fieldConditions == null || fieldConditions.trim().isEmpty()) {
return "Error: Field conditions are required (e.g., 'equals(VmName, \"arora\")', 'total_granted > 1000')";
}
// Set defaults
if (type == null || type.trim().isEmpty()) {
type = "realtime";
}
if (times == null || times <= 0) {
times = 3;
}
if (priority == null) {
priority = 1; // Default to warning
}
if (enable == null) {
enable = true;
}
if (datasource == null || datasource.trim().isEmpty()) {
datasource = "promql";
}
// Validate alert type
if (!type.equals("realtime") && !type.equals("periodic")) {
return "Error: Alert type must be 'realtime' or 'periodic'";
}
// Validate priority
if (priority < 0 || priority > 2) {
return "Error: Priority must be 0 (critical), 1 (warning), or 2 (info)";
}
// For periodic rules, validate period parameter
if (type.equals("periodic")) {
if (period == null || period <= 0) {
period = 300; // Default 5 minutes
}
}
// CRITICAL VALIDATION: Verify app-metric-field relationships using hierarchy
String validationResult = validateHierarchyRelationships(app.trim(), metrics.trim(), fieldConditions.trim());
if (!validationResult.equals("VALID")) {
return validationResult; // Return validation error message
}
// EXPRESSION VALIDATION: Verify field conditions syntax and operators
String expressionValidation = UtilityClass.validateExpressionSyntax(fieldConditions.trim());
if (!expressionValidation.equals("VALID")) {
return expressionValidation; // Return expression validation error message
}
String expr = String.format("equals(__app__,\"%s\") && equals(__metrics__,\"%s\") && %s",
app.trim(), metrics.trim(), fieldConditions.trim());
// Parse labels if provided
Map<String, String> labelsMap = new HashMap<>();
if (labels != null && !labels.trim().isEmpty()) {
labelsMap.putAll(UtilityClass.parseKeyValuePairs(labels));
}
// Add severity based on priority
String severityLabel = priority == 0 ? "critical" : (priority == 1 ? "warning" : "info");
labelsMap.put("severity", severityLabel);
// Parse annotations if provided
Map<String, String> annotationsMap = new HashMap<>();
if (annotations != null && !annotations.trim().isEmpty()) {
annotationsMap.putAll(UtilityClass.parseKeyValuePairs(annotations));
}
// Add default annotations if not provided
if (!annotationsMap.containsKey("summary")) {
annotationsMap.put("summary", description != null ? description :
String.format("Alert for %s %s when %s", app, metrics, fieldConditions));
}
if (!annotationsMap.containsKey("description")) {
annotationsMap.put("description", String.format("Monitor %s metrics %s with conditions: %s", app, metrics, fieldConditions));
}
// Generate default template if not provided
if (template == null || template.trim().isEmpty()) {
template = String.format("Alert: %s %s - %s", app, metrics, fieldConditions);
}
// Create comprehensive alert definition
AlertDefine alertDefine = AlertDefine.builder()
.name(name.trim())
.type(type)
.expr(expr)
.period(period)
.times(times)
.labels(labelsMap)
.annotations(annotationsMap)
.template(template)
.datasource(datasource)
.enable(enable)
.build();
AlertDefine createdAlertDefine = alertDefineServiceAdapter.addAlertDefine(alertDefine);
// Note: Monitor binding is handled separately via bind_monitors_to_alert_rule tool
String bindingNote = String.format(" (Use bind_monitors_to_alert_rule tool to associate specific monitors)");
log.info("Successfully created alert rule '{}' with ID: {}", name, createdAlertDefine.getId());
StringBuilder response = new StringBuilder();
response.append(String.format("Successfully created %s alert rule '%s' with ID: %d\n",
type, name, createdAlertDefine.getId()));
response.append(String.format("Expression: %s\n", expr));
response.append(String.format("Priority: %d (%s)\n", priority, severityLabel));
response.append(String.format("Trigger after: %d consecutive violations\n", times));
if (type.equals("periodic")) {
response.append(String.format("Execution period: %d seconds\n", period));
}
response.append(String.format("Data source: %s\n", datasource));
response.append(String.format("Enabled: %s\n", enable));
if (!labelsMap.isEmpty()) {
response.append(String.format("Labels: %s\n", labelsMap));
}
response.append(bindingNote);
return response.toString();
} catch (Exception e) {
log.error("Failed to create alert rule '{}': {}", name, e.getMessage(), e);
return "Error creating alert rule '" + name + "': " + e.getMessage();
}
}
// ... other existing methods would go here ...
@Override
@Tool(name = "list_alert_rules", description = """
List existing alert rules with filtering options.
Shows configured thresholds and alert definitions.
""")
public String listAlertRules(
@ToolParam(description = "Search term for rule name or description", required = false) String search,
@ToolParam(description = "Filter by monitor type", required = false) String monitorType,
@ToolParam(description = "Filter by enabled status", required = false) Boolean enabled,
@ToolParam(description = "Page index (default: 0)", required = false) Integer pageIndex,
@ToolParam(description = "Page size (default: 10)", required = false) Integer pageSize) {
try {
log.info("Listing alert rules: search={}, monitorType={}, enabled={}", search, monitorType, enabled);
if (pageIndex == null || pageIndex < 0) {
pageIndex = 0;
}
if (pageSize == null || pageSize <= 0) {
pageSize = 10;
}
Page<AlertDefine> result = alertDefineServiceAdapter.getAlertDefines(
search, monitorType, enabled, "gmtCreate", "desc", pageIndex, pageSize);
StringBuilder response = new StringBuilder();
response.append("Found ").append(result.getContent().size())
.append(" alert rules (Total: ").append(result.getTotalElements()).append("):\n\n");
for (AlertDefine alertDefine : result.getContent()) {
response.append("Rule ID: ").append(alertDefine.getId()).append("\n");
response.append("Name: ").append(alertDefine.getName()).append("\n");
response.append("Expression: ").append(alertDefine.getExpr()).append("\n");
response.append("Type: ").append(alertDefine.getType()).append("\n");
response.append("Trigger Times: ").append(alertDefine.getTimes()).append("\n");
response.append("Enabled: ").append(alertDefine.isEnable()).append("\n");
if (alertDefine.getLabels() != null && !alertDefine.getLabels().isEmpty()) {
response.append("Labels: ").append(alertDefine.getLabels()).append("\n");
}
if (alertDefine.getAnnotations() != null && !alertDefine.getAnnotations().isEmpty()) {
response.append("Summary: ").append(alertDefine.getAnnotations().get("summary")).append("\n");
}
response.append("Created: ").append(alertDefine.getGmtCreate()).append("\n");
response.append("\n");
}
if (result.getContent().isEmpty()) {
response.append("No alert rules found matching the specified criteria.");
}
return response.toString();
} catch (Exception e) {
log.error("Failed to list alert rules: {}", e.getMessage(), e);
return "Error retrieving alert rules: " + e.getMessage();
}
}
@Override
@Tool(name = "toggle_alert_rule", description = """
Enable or disable an alert rule.
Allows activating or deactivating threshold monitoring.
""")
public String toggleAlertRule(
@ToolParam(description = "Alert rule ID", required = true) Long ruleId,
@ToolParam(description = "Whether to enable the rule", required = true) Boolean enabled) {
try {
log.info("Toggling alert rule ID: {} to enabled: {}", ruleId, enabled);
alertDefineServiceAdapter.toggleAlertDefineStatus(ruleId, enabled);
log.info("Successfully toggled alert rule ID: {} to enabled: {}", ruleId, enabled);
return String.format("Successfully %s alert rule ID: %d",
enabled ? "enabled" : "disabled", ruleId);
} catch (Exception e) {
log.error("Failed to toggle alert rule ID {}: {}", ruleId, e.getMessage(), e);
return "Error toggling alert rule: " + e.getMessage();
}
}
@Override
@Tool(name = "get_alert_rule_details", description = """
Get detailed information about a specific alert rule.
Shows complete threshold configuration and rule settings.
""")
public String getAlertRuleDetails(
@ToolParam(description = "Alert rule ID", required = true) Long ruleId) {
try {
log.info("Getting alert rule details for ID: {}", ruleId);
AlertDefine alertDefine = alertDefineServiceAdapter.getAlertDefine(ruleId);
if (alertDefine == null) {
return "Alert rule with ID " + ruleId + " not found";
}
StringBuilder response = new StringBuilder();
response.append("ALERT RULE DETAILS\n");
response.append("==================\n\n");
response.append("Rule ID: ").append(alertDefine.getId()).append("\n");
response.append("Name: ").append(alertDefine.getName()).append("\n");
response.append("Type: ").append(alertDefine.getType()).append("\n");
response.append("Expression: ").append(alertDefine.getExpr()).append("\n");
response.append("Trigger Times: ").append(alertDefine.getTimes()).append("\n");
response.append("Enabled: ").append(alertDefine.isEnable()).append("\n");
if (alertDefine.getPeriod() != null) {
response.append("Period: ").append(alertDefine.getPeriod()).append(" seconds\n");
}
if (alertDefine.getLabels() != null && !alertDefine.getLabels().isEmpty()) {
response.append("Labels: ").append(alertDefine.getLabels()).append("\n");
}
if (alertDefine.getAnnotations() != null && !alertDefine.getAnnotations().isEmpty()) {
response.append("Annotations: ").append(alertDefine.getAnnotations()).append("\n");
}
if (alertDefine.getTemplate() != null) {
response.append("Template: ").append(alertDefine.getTemplate()).append("\n");
}
response.append("Created: ").append(alertDefine.getGmtCreate()).append("\n");
response.append("Modified: ").append(alertDefine.getGmtUpdate()).append("\n");
response.append("Creator: ").append(alertDefine.getCreator()).append("\n");
response.append("Modifier: ").append(alertDefine.getModifier()).append("\n");
return response.toString();
} catch (Exception e) {
log.error("Failed to get alert rule details for ID {}: {}", ruleId, e.getMessage(), e);
return "Error retrieving alert rule details: " + e.getMessage();
}
}
@Override
@Tool(name = "get_apps_metrics_hierarchy", description = """
Get the hierarchical structure of all available apps and their metrics for alert rule creation.
This tool provides the exact app name, metric name and corresponding param names according to each metric.
Returns structured JSON data showing the complete hierarchy with field parameters for alert expressions.
JSON Structure:
- app: The application name
- description: Tool description
- hierarchy: Array of hierarchical data
- Each node has: value, label, type, description
- Leaf nodes have: dataType (numeric/string), unit (if applicable)
- Non-leaf nodes have: children array
VERY IMPORTANT:
- ALWAYS USE the value field from the field parameters when creating alert expressions.
This structured data is needed to create proper alert expressions.
""")
public String getAppsMetricsHierarchy(
@ToolParam(description = "App/Monitor type to get hierarchy for (e.g., 'linux', 'mysql', 'website')", required = true) String app) {
try {
log.info("Getting apps metrics hierarchy for app: {}", app);
SubjectSum subjectSum = McpContextHolder.getSubject();
log.debug("Current subject in get_apps_metrics_hierarchy tool: {}", subjectSum);
List<Hierarchy> hierarchies;
hierarchies = alertDefineServiceAdapter.getAppHierarchy(app.trim().toLowerCase(), "en-US");
ObjectMapper mapper = new ObjectMapper();
ObjectNode result = mapper.createObjectNode();
result.put("app", app.toUpperCase());
if (hierarchies != null && !hierarchies.isEmpty()) {
ArrayNode hierarchyArray = mapper.createArrayNode();
for (Hierarchy hierarchy : hierarchies) {
hierarchyArray.add(UtilityClass.formatHierarchyAsJson(mapper, hierarchy));
}
result.set("hierarchy", hierarchyArray);
} else {
result.put("message", "No hierarchy data available");
}
String jsonResult = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
log.info("Hierarchy JSON: {}", jsonResult);
return jsonResult;
} catch (Exception e) {
log.error("Failed to get apps metrics hierarchy: {}", e.getMessage(), e);
return "Error retrieving apps metrics hierarchy: " + e.getMessage();
}
}
@Override
@Tool(name = "bind_monitors_to_alert_rule", description = """
Bind monitors to an alert rule.
Call this tool if users want to bind specific monitors to their alert rule.
Get the right monitor ids for a particular app using the query_monitors tool.
Get the alert rule ID from the create_alert_rule tool output OR use the list_alert_rules tool with app_name search filter, if the output of create_alert_rule is not applicable.
If monitors are already bound, this will add the new ones to the existing bindings.
""")
public String bindMonitorsToAlertRule(
@ToolParam(description = "Alert rule ID to bind monitors to", required = true) Long ruleId,
@ToolParam(description = "Comma-separated list of monitor IDs to bind", required = true) String monitorIds) {
try {
log.info("Binding monitors to alert rule ID: {}, monitors: {}", ruleId, monitorIds);
SubjectSum subjectSum = McpContextHolder.getSubject();
log.debug("Current subject in bind_monitors_to_alert_rule tool: {}", subjectSum);
if (ruleId == null || ruleId <= 0) {
return "Error: Valid alert rule ID is required";
}
if (monitorIds == null) {
return "Error: Monitor IDs are required";
}
// Get the existing alert rule
AlertDefine existingRule = alertDefineServiceAdapter.getAlertDefine(ruleId);
if (existingRule == null) {
return String.format("Error: Alert rule with ID %d not found", ruleId);
}
// Parse monitor IDs from comma-separated string
String[] monitorIdArray = monitorIds.split(",");
List<String> validMonitorIds = new ArrayList<>();
for (String monitorId : monitorIdArray) {
String trimmedId = monitorId.trim();
if (!trimmedId.isEmpty()) {
try {
Long.parseLong(trimmedId); // Validate it's a number
validMonitorIds.add(trimmedId);
} catch (NumberFormatException e) {
return String.format("Error: Invalid monitor ID '%s'. Monitor IDs must be numeric.", trimmedId);
}
}
}
if (validMonitorIds.isEmpty()) {
return "Error: No valid monitor IDs provided";
}
// Build the monitor instance condition
String monitorCondition;
if (validMonitorIds.size() == 1) {
monitorCondition = String.format("equals(__instance__, \"%s\")", validMonitorIds.get(0));
} else {
StringBuilder conditionBuilder = new StringBuilder("(");
for (int i = 0; i < validMonitorIds.size(); i++) {
if (i > 0) {
conditionBuilder.append(" or ");
}
conditionBuilder.append(String.format("equals(__instance__, \"%s\")", validMonitorIds.get(i)));
}
conditionBuilder.append(")");
monitorCondition = conditionBuilder.toString();
}
// Get the current expression and modify it
String currentExpr = existingRule.getExpr();
String newExpr;
// Check if the expression already has __instance__ conditions
if (currentExpr.contains("__instance__")) {
// Extract existing monitor IDs and merge with new ones
List<String> existingMonitorIds = UtilityClass.extractExistingMonitorIds(currentExpr);
// Add new monitor IDs that aren't already present
for (String newId : validMonitorIds) {
if (!existingMonitorIds.contains(newId)) {
existingMonitorIds.add(newId);
}
}
String updatedMonitorCondition;
if (existingMonitorIds.size() == 1) {
updatedMonitorCondition = String.format("equals(__instance__, \"%s\")", existingMonitorIds.get(0));
} else {
StringBuilder conditionBuilder = new StringBuilder("(");
for (int i = 0; i < existingMonitorIds.size(); i++) {
if (i > 0) {
conditionBuilder.append(" or ");
}
conditionBuilder.append(String.format("equals(__instance__, \"%s\")", existingMonitorIds.get(i)));
}
conditionBuilder.append(")");
updatedMonitorCondition = conditionBuilder.toString();
}
// Replace existing __instance__ conditions with updated ones
newExpr = UtilityClass.replaceInstanceConditions(currentExpr, updatedMonitorCondition);
// Update the alert rule
existingRule.setExpr(newExpr);
alertDefineServiceAdapter.modifyAlertDefine(existingRule);
log.info("Successfully added monitors {} to existing bindings for alert rule ID: {}", validMonitorIds, ruleId);
return String.format("Successfully added %d new monitor(s) to alert rule ID %d.\nTotal bound monitors: %s\nUpdated expression: %s",
validMonitorIds.size(), ruleId, String.join(", ", existingMonitorIds), newExpr);
}
// Insert the monitor condition after the metrics condition
// Pattern: equals(__app__,"app") && equals(__metrics__,"metric") && [existing_conditions]
// Result: equals(__app__,"app") && equals(__metrics__,"metric") && [monitor_condition] && [existing_conditions]
if (currentExpr.matches(".*equals\\(__app__,\"[^\"]+\"\\)\\s*&&\\s*equals\\(__metrics__,\"[^\"]+\"\\)\\s*&&\\s*.*")) {
// Find the position after the metrics condition
String metricsPattern = "equals\\(__metrics__,\"[^\"]+\"\\)";
java.util.regex.Pattern regex = java.util.regex.Pattern.compile(metricsPattern);
java.util.regex.Matcher matcher = regex.matcher(currentExpr);
if (matcher.find()) {
int metricsEnd = matcher.end();
// Find the " && " after the metrics condition
int andPosition = currentExpr.indexOf(" && ", metricsEnd);
if (andPosition != -1) {
String beforeAndPosition = currentExpr.substring(0, andPosition + 4); // Include " && "
String afterAndPosition = currentExpr.substring(andPosition + 4); // Everything after " && "
newExpr = beforeAndPosition + monitorCondition + " && " + afterAndPosition;
} else {
return String.format("Error: Unable to find field conditions after metrics in expression: %s", currentExpr);
}
} else {
return String.format("Error: Unable to parse metrics condition in expression: %s", currentExpr);
}
} else {
return String.format("Error: Expression format not supported for monitor binding: %s", currentExpr);
}
// Update the alert rule
existingRule.setExpr(newExpr);
alertDefineServiceAdapter.modifyAlertDefine(existingRule);
log.info("Successfully bound monitors {} to alert rule ID: {}", validMonitorIds, ruleId);
return String.format("Successfully bound %d monitor(s) to alert rule ID %d.\nMonitor IDs: %s\nUpdated expression: %s",
validMonitorIds.size(), ruleId, String.join(", ", validMonitorIds), newExpr);
} catch (Exception e) {
log.error("Failed to bind monitors to alert rule ID {}: {}", ruleId, e.getMessage(), e);
return String.format("Error binding monitors to alert rule: %s", e.getMessage());
}
}
/**
* Validates that the app, metric, and field conditions are valid according to hierarchy
* @param app App name to validate
* @param metrics Metric name to validate for the app
* @param fieldConditions Field conditions to validate for the metric
* @return "VALID" if all relationships are correct, error message otherwise
*/
private String validateHierarchyRelationships(String app, String metrics, String fieldConditions) {
try {
log.debug("Validating hierarchy relationships: app={}, metrics={}, fieldConditions={}", app, metrics, fieldConditions);
// Get hierarchy for the specified app
List<Hierarchy> hierarchies = alertDefineServiceAdapter.getAppHierarchy(app.toLowerCase(), "en-US");
if (hierarchies == null || hierarchies.isEmpty()) {
return String.format("Error: App '%s' not found in hierarchy. Please use list_monitor_types to get valid app names.", app);
}
// Find the metric in the app's hierarchy
Hierarchy metricHierarchy = UtilityClass.findMetricInHierarchy(hierarchies, metrics);
if (metricHierarchy == null) {
return String.format("Error: Metric '%s' not found for app '%s'. Please use get_apps_metrics_hierarchy to get valid metrics for this app.", metrics, app);
}
// Extract field names from field conditions and validate them
List<String> fieldNames = UtilityClass.extractFieldNamesFromConditions(fieldConditions);
for (String fieldName : fieldNames) {
if (!UtilityClass.isFieldValidForMetric(metricHierarchy, fieldName)) {
return String.format("Error: Field '%s' not found for metric '%s' in app '%s'. Please use get_apps_metrics_hierarchy to get valid field parameters.", fieldName, metrics, app);
}
}
log.debug("Hierarchy validation passed for app={}, metrics={}", app, metrics);
return "VALID";
} catch (Exception e) {
log.error("Error during hierarchy validation: {}", e.getMessage(), e);
return String.format("Error: Unable to validate hierarchy relationships: %s", e.getMessage());
}
}
} |
googleapis/google-api-java-client-services | 35,857 | clients/google-api-services-compute/v1/1.26.0/com/google/api/services/compute/model/Image.java | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.compute.model;
/**
* Represents an Image resource.
*
* You can use images to create boot disks for your VM instances. For more information, read Images.
* (== resource_for beta.images ==) (== resource_for v1.images ==)
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Image extends com.google.api.client.json.GenericJson {
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long archiveSizeBytes;
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String creationTimestamp;
/**
* The deprecation status associated with this image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeprecationStatus deprecated;
/**
* An optional description of this resource. Provide this property when you create the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* Size of the image when restored onto a persistent disk (in GB).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long diskSizeGb;
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String family;
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GuestOsFeature> guestOsFeatures;
static {
// hack to force ProGuard to consider GuestOsFeature used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GuestOsFeature.class);
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.math.BigInteger id;
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey imageEncryptionKey;
/**
* [Output Only] Type of the resource. Always compute#image for images.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String labelFingerprint;
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> labels;
/**
* Integer license codes indicating which licenses are attached to this image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.util.List<java.lang.Long> licenseCodes;
/**
* Any applicable license URI.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> licenses;
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* The parameters of the raw disk image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private RawDisk rawDisk;
/**
* [Output Only] Server-defined URL for the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String selfLink;
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceDisk;
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceDiskEncryptionKey;
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceDiskId;
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceImage;
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceImageEncryptionKey;
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceImageId;
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceSnapshot;
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceSnapshotEncryptionKey;
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceSnapshotId;
/**
* The type of the image used to create this disk. The default and only value is RAW
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceType;
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String status;
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* @return value or {@code null} for none
*/
public java.lang.Long getArchiveSizeBytes() {
return archiveSizeBytes;
}
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* @param archiveSizeBytes archiveSizeBytes or {@code null} for none
*/
public Image setArchiveSizeBytes(java.lang.Long archiveSizeBytes) {
this.archiveSizeBytes = archiveSizeBytes;
return this;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @return value or {@code null} for none
*/
public java.lang.String getCreationTimestamp() {
return creationTimestamp;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @param creationTimestamp creationTimestamp or {@code null} for none
*/
public Image setCreationTimestamp(java.lang.String creationTimestamp) {
this.creationTimestamp = creationTimestamp;
return this;
}
/**
* The deprecation status associated with this image.
* @return value or {@code null} for none
*/
public DeprecationStatus getDeprecated() {
return deprecated;
}
/**
* The deprecation status associated with this image.
* @param deprecated deprecated or {@code null} for none
*/
public Image setDeprecated(DeprecationStatus deprecated) {
this.deprecated = deprecated;
return this;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @param description description or {@code null} for none
*/
public Image setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* Size of the image when restored onto a persistent disk (in GB).
* @return value or {@code null} for none
*/
public java.lang.Long getDiskSizeGb() {
return diskSizeGb;
}
/**
* Size of the image when restored onto a persistent disk (in GB).
* @param diskSizeGb diskSizeGb or {@code null} for none
*/
public Image setDiskSizeGb(java.lang.Long diskSizeGb) {
this.diskSizeGb = diskSizeGb;
return this;
}
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* @return value or {@code null} for none
*/
public java.lang.String getFamily() {
return family;
}
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* @param family family or {@code null} for none
*/
public Image setFamily(java.lang.String family) {
this.family = family;
return this;
}
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* @return value or {@code null} for none
*/
public java.util.List<GuestOsFeature> getGuestOsFeatures() {
return guestOsFeatures;
}
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* @param guestOsFeatures guestOsFeatures or {@code null} for none
*/
public Image setGuestOsFeatures(java.util.List<GuestOsFeature> guestOsFeatures) {
this.guestOsFeatures = guestOsFeatures;
return this;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @return value or {@code null} for none
*/
public java.math.BigInteger getId() {
return id;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @param id id or {@code null} for none
*/
public Image setId(java.math.BigInteger id) {
this.id = id;
return this;
}
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getImageEncryptionKey() {
return imageEncryptionKey;
}
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* @param imageEncryptionKey imageEncryptionKey or {@code null} for none
*/
public Image setImageEncryptionKey(CustomerEncryptionKey imageEncryptionKey) {
this.imageEncryptionKey = imageEncryptionKey;
return this;
}
/**
* [Output Only] Type of the resource. Always compute#image for images.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* [Output Only] Type of the resource. Always compute#image for images.
* @param kind kind or {@code null} for none
*/
public Image setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #decodeLabelFingerprint()
* @return value or {@code null} for none
*/
public java.lang.String getLabelFingerprint() {
return labelFingerprint;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #getLabelFingerprint()
* @return Base64 decoded value or {@code null} for none
*
* @since 1.14
*/
public byte[] decodeLabelFingerprint() {
return com.google.api.client.util.Base64.decodeBase64(labelFingerprint);
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #encodeLabelFingerprint()
* @param labelFingerprint labelFingerprint or {@code null} for none
*/
public Image setLabelFingerprint(java.lang.String labelFingerprint) {
this.labelFingerprint = labelFingerprint;
return this;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #setLabelFingerprint()
*
* <p>
* The value is encoded Base64 or {@code null} for none.
* </p>
*
* @since 1.14
*/
public Image encodeLabelFingerprint(byte[] labelFingerprint) {
this.labelFingerprint = com.google.api.client.util.Base64.encodeBase64URLSafeString(labelFingerprint);
return this;
}
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getLabels() {
return labels;
}
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* @param labels labels or {@code null} for none
*/
public Image setLabels(java.util.Map<String, java.lang.String> labels) {
this.labels = labels;
return this;
}
/**
* Integer license codes indicating which licenses are attached to this image.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.Long> getLicenseCodes() {
return licenseCodes;
}
/**
* Integer license codes indicating which licenses are attached to this image.
* @param licenseCodes licenseCodes or {@code null} for none
*/
public Image setLicenseCodes(java.util.List<java.lang.Long> licenseCodes) {
this.licenseCodes = licenseCodes;
return this;
}
/**
* Any applicable license URI.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getLicenses() {
return licenses;
}
/**
* Any applicable license URI.
* @param licenses licenses or {@code null} for none
*/
public Image setLicenses(java.util.List<java.lang.String> licenses) {
this.licenses = licenses;
return this;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @param name name or {@code null} for none
*/
public Image setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* The parameters of the raw disk image.
* @return value or {@code null} for none
*/
public RawDisk getRawDisk() {
return rawDisk;
}
/**
* The parameters of the raw disk image.
* @param rawDisk rawDisk or {@code null} for none
*/
public Image setRawDisk(RawDisk rawDisk) {
this.rawDisk = rawDisk;
return this;
}
/**
* [Output Only] Server-defined URL for the resource.
* @return value or {@code null} for none
*/
public java.lang.String getSelfLink() {
return selfLink;
}
/**
* [Output Only] Server-defined URL for the resource.
* @param selfLink selfLink or {@code null} for none
*/
public Image setSelfLink(java.lang.String selfLink) {
this.selfLink = selfLink;
return this;
}
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* @return value or {@code null} for none
*/
public java.lang.String getSourceDisk() {
return sourceDisk;
}
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* @param sourceDisk sourceDisk or {@code null} for none
*/
public Image setSourceDisk(java.lang.String sourceDisk) {
this.sourceDisk = sourceDisk;
return this;
}
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceDiskEncryptionKey() {
return sourceDiskEncryptionKey;
}
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* @param sourceDiskEncryptionKey sourceDiskEncryptionKey or {@code null} for none
*/
public Image setSourceDiskEncryptionKey(CustomerEncryptionKey sourceDiskEncryptionKey) {
this.sourceDiskEncryptionKey = sourceDiskEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceDiskId() {
return sourceDiskId;
}
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* @param sourceDiskId sourceDiskId or {@code null} for none
*/
public Image setSourceDiskId(java.lang.String sourceDiskId) {
this.sourceDiskId = sourceDiskId;
return this;
}
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* @return value or {@code null} for none
*/
public java.lang.String getSourceImage() {
return sourceImage;
}
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* @param sourceImage sourceImage or {@code null} for none
*/
public Image setSourceImage(java.lang.String sourceImage) {
this.sourceImage = sourceImage;
return this;
}
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceImageEncryptionKey() {
return sourceImageEncryptionKey;
}
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* @param sourceImageEncryptionKey sourceImageEncryptionKey or {@code null} for none
*/
public Image setSourceImageEncryptionKey(CustomerEncryptionKey sourceImageEncryptionKey) {
this.sourceImageEncryptionKey = sourceImageEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceImageId() {
return sourceImageId;
}
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* @param sourceImageId sourceImageId or {@code null} for none
*/
public Image setSourceImageId(java.lang.String sourceImageId) {
this.sourceImageId = sourceImageId;
return this;
}
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* @return value or {@code null} for none
*/
public java.lang.String getSourceSnapshot() {
return sourceSnapshot;
}
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* @param sourceSnapshot sourceSnapshot or {@code null} for none
*/
public Image setSourceSnapshot(java.lang.String sourceSnapshot) {
this.sourceSnapshot = sourceSnapshot;
return this;
}
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceSnapshotEncryptionKey() {
return sourceSnapshotEncryptionKey;
}
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* @param sourceSnapshotEncryptionKey sourceSnapshotEncryptionKey or {@code null} for none
*/
public Image setSourceSnapshotEncryptionKey(CustomerEncryptionKey sourceSnapshotEncryptionKey) {
this.sourceSnapshotEncryptionKey = sourceSnapshotEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceSnapshotId() {
return sourceSnapshotId;
}
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* @param sourceSnapshotId sourceSnapshotId or {@code null} for none
*/
public Image setSourceSnapshotId(java.lang.String sourceSnapshotId) {
this.sourceSnapshotId = sourceSnapshotId;
return this;
}
/**
* The type of the image used to create this disk. The default and only value is RAW
* @return value or {@code null} for none
*/
public java.lang.String getSourceType() {
return sourceType;
}
/**
* The type of the image used to create this disk. The default and only value is RAW
* @param sourceType sourceType or {@code null} for none
*/
public Image setSourceType(java.lang.String sourceType) {
this.sourceType = sourceType;
return this;
}
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* @return value or {@code null} for none
*/
public java.lang.String getStatus() {
return status;
}
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* @param status status or {@code null} for none
*/
public Image setStatus(java.lang.String status) {
this.status = status;
return this;
}
@Override
public Image set(String fieldName, Object value) {
return (Image) super.set(fieldName, value);
}
@Override
public Image clone() {
return (Image) super.clone();
}
/**
* The parameters of the raw disk image.
*/
public static final class RawDisk extends com.google.api.client.json.GenericJson {
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String containerType;
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sha1Checksum;
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String source;
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* @return value or {@code null} for none
*/
public java.lang.String getContainerType() {
return containerType;
}
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* @param containerType containerType or {@code null} for none
*/
public RawDisk setContainerType(java.lang.String containerType) {
this.containerType = containerType;
return this;
}
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* @return value or {@code null} for none
*/
public java.lang.String getSha1Checksum() {
return sha1Checksum;
}
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* @param sha1Checksum sha1Checksum or {@code null} for none
*/
public RawDisk setSha1Checksum(java.lang.String sha1Checksum) {
this.sha1Checksum = sha1Checksum;
return this;
}
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* @return value or {@code null} for none
*/
public java.lang.String getSource() {
return source;
}
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* @param source source or {@code null} for none
*/
public RawDisk setSource(java.lang.String source) {
this.source = source;
return this;
}
@Override
public RawDisk set(String fieldName, Object value) {
return (RawDisk) super.set(fieldName, value);
}
@Override
public RawDisk clone() {
return (RawDisk) super.clone();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.