Skip to content

Commit 1052216

Browse files
Migrate remaining checkNotNull to checkArgumentNotNull/checkStateNotNull in options package #18719 (#37654)
* Start migrating argument null checks to checkArgumentNotNull (Issue #18719) * Migrate remaining checkNotNull to checkArgumentNotNull/checkStateNotNull in options package Replace Guava checkNotNull (throws NullPointerException) with Beam's checkArgumentNotNull (throws IllegalArgumentException) for argument validation and checkStateNotNull (throws IllegalStateException) for internal state validation. Files modified: - SdkHarnessOptions.java: checkStateNotNull for return value check - PipelineOptionsFactory.java: checkArgumentNotNull for argument check - ValueProvider.java: checkArgumentNotNull + checkStateNotNull - ValueProviders.java: checkStateNotNull for parsed result check - PipelineOptionsValidator.java: checkArgumentNotNull for argument checks - ProxyInvocationHandler.java: checkArgumentNotNull for argument check - MetricNameFilter.java: cleanup commented-out import Fixes #18719
1 parent 87c50c6 commit 1052216

File tree

8 files changed

+95
-68
lines changed

8 files changed

+95
-68
lines changed

sdks/java/core/src/main/java/org/apache/beam/sdk/metrics/MetricNameFilter.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
*/
1818
package org.apache.beam.sdk.metrics;
1919

20-
import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkNotNull;
20+
import static org.apache.beam.sdk.util.Preconditions.checkArgumentNotNull;
2121

2222
import com.google.auto.value.AutoValue;
2323
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -41,13 +41,13 @@ public static MetricNameFilter inNamespace(Class<?> namespace) {
4141
}
4242

4343
public static MetricNameFilter named(String namespace, String name) {
44-
checkNotNull(name, "Must specify a name");
44+
checkArgumentNotNull(name, "Must specify a name");
4545
return new AutoValue_MetricNameFilter(namespace, name);
4646
}
4747

4848
public static MetricNameFilter named(Class<?> namespace, String name) {
49-
checkNotNull(namespace, "Must specify a inNamespace");
50-
checkNotNull(name, "Must specify a name");
49+
checkArgumentNotNull(namespace, "Must specify a namespace");
50+
checkArgumentNotNull(name, "Must specify a name");
5151
return new AutoValue_MetricNameFilter(namespace.getName(), name);
5252
}
5353
}

sdks/java/core/src/main/java/org/apache/beam/sdk/options/PipelineOptionsFactory.java

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@
1818
package org.apache.beam.sdk.options;
1919

2020
import static java.util.Locale.ROOT;
21+
import static org.apache.beam.sdk.util.Preconditions.checkArgumentNotNull;
2122
import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkArgument;
22-
import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkNotNull;
2323

2424
import com.fasterxml.jackson.annotation.JsonIgnore;
2525
import com.fasterxml.jackson.core.JsonParseException;
@@ -133,8 +133,8 @@
133133
* registered with this factory.
134134
* </ul>
135135
*
136-
* <p>See the <a
137-
* href="http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html">JavaBeans
136+
* <p>See the <a href=
137+
* "http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html">JavaBeans
138138
* specification</a> for more details as to what constitutes a property.
139139
*/
140140
@SuppressWarnings({
@@ -277,7 +277,7 @@ private Builder(String[] args, boolean validation, boolean strictParsing, boolea
277277
* PipelineOptionsFactory#printHelp(PrintStream, Class)}.
278278
*/
279279
public Builder fromArgs(String... args) {
280-
checkNotNull(args, "Arguments should not be null.");
280+
checkArgumentNotNull(args, "Arguments should not be null.");
281281
return new Builder(args, validation, strictParsing, true);
282282
}
283283

@@ -338,7 +338,8 @@ public <T extends PipelineOptions> T as(Class<T> klass) {
338338
appNameOptions.setAppName(defaultAppName);
339339
}
340340

341-
// Ensure the options id has been populated either by the user using the command line
341+
// Ensure the options id has been populated either by the user using the command
342+
// line
342343
// or by the default value factory.
343344
t.getOptionsId();
344345

@@ -433,7 +434,8 @@ private static String findCallersClassName() {
433434
break;
434435
}
435436
}
436-
// Then find the first instance after that is not the PipelineOptionsFactory/Builder class.
437+
// Then find the first instance after that is not the
438+
// PipelineOptionsFactory/Builder class.
437439
while (elements.hasNext()) {
438440
StackTraceElement next = elements.next();
439441
if (!PIPELINE_OPTIONS_FACTORY_CLASSES.contains(next.getClassName())) {
@@ -587,7 +589,7 @@ public static Set<Class<? extends PipelineOptions>> getRegisteredOptions() {
587589
* window.
588590
*/
589591
public static void printHelp(PrintStream out) {
590-
checkNotNull(out);
592+
checkArgumentNotNull(out);
591593
out.println("The set of registered options are:");
592594
Set<Class<? extends PipelineOptions>> sortedOptions =
593595
new TreeSet<>(ClassNameComparator.INSTANCE);
@@ -622,8 +624,8 @@ public static void printHelp(PrintStream out) {
622624
* This method will attempt to format its output to be compatible with a terminal window.
623625
*/
624626
public static void printHelp(PrintStream out, Class<? extends PipelineOptions> iface) {
625-
checkNotNull(out);
626-
checkNotNull(iface);
627+
checkArgumentNotNull(out);
628+
checkArgumentNotNull(iface);
627629
CACHE.get().validateWellFormed(iface);
628630

629631
Set<PipelineOptionSpec> properties = PipelineOptionsReflector.getOptionSpecs(iface, true);
@@ -697,7 +699,7 @@ public static void printHelp(PrintStream out, Class<? extends PipelineOptions> i
697699
*/
698700
public static List<PipelineOptionDescriptor> describe(
699701
Set<Class<? extends PipelineOptions>> ifaces) {
700-
checkNotNull(ifaces);
702+
checkArgumentNotNull(ifaces);
701703
List<PipelineOptionDescriptor> result = new ArrayList<>();
702704
Set<Method> seenMethods = Sets.newHashSet();
703705

@@ -869,7 +871,8 @@ private static List<PropertyDescriptor> getPropertyDescriptors(Set<Method> metho
869871
List<TypeMismatch> mismatches = new ArrayList<>();
870872
Set<String> usedDescriptors = Sets.newHashSet();
871873
/*
872-
* Add all the getter/setter pairs to the list of descriptors removing the getter once
874+
* Add all the getter/setter pairs to the list of descriptors removing the
875+
* getter once
873876
* it has been paired up.
874877
*/
875878
for (Method method : methods) {
@@ -995,7 +998,8 @@ private static List<PropertyDescriptor> validateClass(
995998
+ "PipelineOptions proxy class to implement all of the interfaces.",
996999
iface.getName());
9971000

998-
// Verify that there are no methods with the same name with two different return types.
1001+
// Verify that there are no methods with the same name with two different return
1002+
// types.
9991003
validateReturnType(iface);
10001004

10011005
SortedSet<Method> allInterfaceMethods =
@@ -1098,7 +1102,8 @@ private static void validateMethodAnnotations(
10981102
validateGettersHaveConsistentAnnotation(
10991103
methodNameToAllMethodMap, descriptors, AnnotationPredicates.JSON_SERIALIZE);
11001104

1101-
// Verify that if a method has either @JsonSerialize or @JsonDeserialize then it has both.
1105+
// Verify that if a method has either @JsonSerialize or @JsonDeserialize then it
1106+
// has both.
11021107
validateMethodsHaveBothJsonSerializeAndDeserialize(descriptors);
11031108

11041109
// Verify that no setter has @JsonIgnore.
@@ -1280,7 +1285,8 @@ private static void validateMethodsAreEitherBeanMethodOrKnownMethod(
12801285
knownMethodsNames.add(method.getName());
12811286
}
12821287

1283-
// Verify that no additional methods are on an interface that aren't a bean property.
1288+
// Verify that no additional methods are on an interface that aren't a bean
1289+
// property.
12841290
// Because methods can have multiple declarations, we do a name-based comparison
12851291
// here to prevent false positives.
12861292
SortedSet<Method> unknownMethods = new TreeSet<>(MethodComparator.INSTANCE);
@@ -1823,7 +1829,8 @@ private static Object tryParseObject(String value, Method method) throws IOExcep
18231829
try {
18241830
tree = MAPPER.readTree("\"" + value + "\"");
18251831
} catch (JsonParseException inner) {
1826-
// rethrow the original exception rather the one thrown from the fallback attempt
1832+
// rethrow the original exception rather the one thrown from the fallback
1833+
// attempt
18271834
throw e;
18281835
}
18291836
} else {
@@ -1891,7 +1898,8 @@ private static <T extends PipelineOptions> Map<String, Object> parseObjects(
18911898
}
18921899
}
18931900
Method method = propertyNamesToGetters.get(entry.getKey());
1894-
// Only allow empty argument values for String, String Array, and Collection<String>.
1901+
// Only allow empty argument values for String, String Array, and
1902+
// Collection<String>.
18951903
Class<?> returnType = method.getReturnType();
18961904
JavaType type = MAPPER.getTypeFactory().constructType(method.getGenericReturnType());
18971905

@@ -2089,7 +2097,7 @@ private void initializeRegistry(final ClassLoader loader) {
20892097
}
20902098

20912099
private synchronized void register(Class<? extends PipelineOptions> iface) {
2092-
checkNotNull(iface);
2100+
checkArgumentNotNull(iface);
20932101
checkArgument(iface.isInterface(), "Only interface types are supported.");
20942102

20952103
if (registeredOptions.contains(iface)) {
@@ -2144,15 +2152,17 @@ synchronized <T extends PipelineOptions> Registration<T> validateWellFormed(
21442152
Class<T> iface, Set<Class<? extends PipelineOptions>> validatedPipelineOptionsInterfaces) {
21452153
checkArgument(iface.isInterface(), "Only interface types are supported.");
21462154

2147-
// Validate that every inherited interface must extend PipelineOptions except for
2155+
// Validate that every inherited interface must extend PipelineOptions except
2156+
// for
21482157
// PipelineOptions itself.
21492158
validateInheritedInterfacesExtendPipelineOptions(iface);
21502159

21512160
@SuppressWarnings("unchecked")
21522161
Set<Class<? extends PipelineOptions>> combinedPipelineOptionsInterfaces =
21532162
Stream.concat(validatedPipelineOptionsInterfaces.stream(), Stream.of(iface))
21542163
.collect(Collectors.toSet());
2155-
// Validate that the view of all currently passed in options classes is well formed.
2164+
// Validate that the view of all currently passed in options classes is well
2165+
// formed.
21562166
if (!combinedCache.containsKey(combinedPipelineOptionsInterfaces)) {
21572167
final Class<?>[] interfaces = combinedPipelineOptionsInterfaces.toArray(EMPTY_CLASS_ARRAY);
21582168
@SuppressWarnings("unchecked")

sdks/java/core/src/main/java/org/apache/beam/sdk/options/PipelineOptionsValidator.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717
*/
1818
package org.apache.beam.sdk.options;
1919

20+
import static org.apache.beam.sdk.util.Preconditions.checkArgumentNotNull;
2021
import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkArgument;
21-
import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkNotNull;
2222

2323
import java.lang.reflect.Method;
2424
import java.lang.reflect.Proxy;
@@ -67,8 +67,8 @@ public static <T extends PipelineOptions> T validateCli(Class<T> klass, Pipeline
6767

6868
private static <T extends PipelineOptions> T validate(
6969
Class<T> klass, PipelineOptions options, boolean isCli) {
70-
checkNotNull(klass);
71-
checkNotNull(options);
70+
checkArgumentNotNull(klass);
71+
checkArgumentNotNull(options);
7272
checkArgument(Proxy.isProxyClass(options.getClass()));
7373
checkArgument(Proxy.getInvocationHandler(options) instanceof ProxyInvocationHandler);
7474

sdks/java/core/src/main/java/org/apache/beam/sdk/options/ProxyInvocationHandler.java

Lines changed: 39 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717
*/
1818
package org.apache.beam.sdk.options;
1919

20+
import static org.apache.beam.sdk.util.Preconditions.checkArgumentNotNull;
2021
import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkArgument;
21-
import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkNotNull;
2222

2323
import com.fasterxml.jackson.annotation.JsonIgnore;
2424
import com.fasterxml.jackson.core.JsonGenerator;
@@ -82,9 +82,9 @@
8282
* introspection of the proxy class to store and retrieve values based off of the property name.
8383
*
8484
* <p>Unset properties use the {@code @Default} metadata on the getter to return values. If there is
85-
* no {@code @Default} annotation on the getter, then a <a
86-
* href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">default</a> as
87-
* per the Java Language Specification for the expected return type is returned.
85+
* no {@code @Default} annotation on the getter, then a <a href=
86+
* "https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">default</a> as per the
87+
* Java Language Specification for the expected return type is returned.
8888
*
8989
* <p>In addition to the getter/setter pairs, this proxy invocation handler supports {@link
9090
* Object#equals(Object)}, {@link Object#hashCode()}, {@link Object#toString()} and {@link
@@ -122,7 +122,8 @@ private ComputedProperties(
122122
<T extends PipelineOptions> ComputedProperties updated(
123123
Class<T> iface, T instance, List<PropertyDescriptor> propertyDescriptors) {
124124

125-
// these all use mutable maps and then copyOf, rather than a builder because builders enforce
125+
// these all use mutable maps and then copyOf, rather than a builder because
126+
// builders enforce
126127
// all keys are unique, and its possible they are not here.
127128
Map<String, String> allNewGetters = Maps.newHashMap(gettersToPropertyNames);
128129
Map<String, String> allNewSetters = Maps.newHashMap(settersToPropertyNames);
@@ -147,7 +148,8 @@ <T extends PipelineOptions> ComputedProperties updated(
147148
@SuppressFBWarnings("SE_BAD_FIELD")
148149
private volatile ComputedProperties computedProperties;
149150

150-
// ProxyInvocationHandler implements Serializable only for the sake of throwing an informative
151+
// ProxyInvocationHandler implements Serializable only for the sake of throwing
152+
// an informative
151153
// exception in writeObject()
152154
/**
153155
* Enumerating {@code options} must always be done on a copy made before accessing or deriving
@@ -217,7 +219,8 @@ public Object invoke(Object proxy, Method method, Object[] args) {
217219
ComputedProperties properties = computedProperties;
218220
if (properties.gettersToPropertyNames.containsKey(methodName)) {
219221
String propertyName = properties.gettersToPropertyNames.get(methodName);
220-
// we can't use computeIfAbsent here because evaluating the default may cause more properties
222+
// we can't use computeIfAbsent here because evaluating the default may cause
223+
// more properties
221224
// to be evaluated, and computeIfAbsent is not re-entrant.
222225
if (!options.containsKey(propertyName)) {
223226
// Lazy bind the default to the method.
@@ -286,7 +289,7 @@ static BoundValue fromDefault(@Nullable Object value) {
286289
* @return An object that implements the interface {@code <T>}.
287290
*/
288291
<T extends PipelineOptions> T as(Class<T> iface) {
289-
checkNotNull(iface);
292+
checkArgumentNotNull(iface);
290293
checkArgument(iface.isInterface(), "Not an interface: %s", iface);
291294

292295
T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface);
@@ -376,8 +379,10 @@ class PipelineOptionsDisplayData implements HasDisplayData {
376379
*/
377380
@Override
378381
public void populateDisplayData(DisplayData.Builder builder) {
379-
// We must first make a copy of the current options because a concurrent modification
380-
// may add a new option after we have derived optionSpecs but before we have enumerated
382+
// We must first make a copy of the current options because a concurrent
383+
// modification
384+
// may add a new option after we have derived optionSpecs but before we have
385+
// enumerated
381386
// all the pipeline options.
382387
Map<String, BoundValue> copiedOptions = new HashMap<>(options);
383388
Set<PipelineOptionSpec> optionSpecs =
@@ -396,8 +401,10 @@ public void populateDisplayData(DisplayData.Builder builder) {
396401

397402
for (PipelineOptionSpec optionSpec : specs) {
398403
if (!optionSpec.shouldSerialize()) {
399-
// Options that are excluded for serialization (i.e. those with @JsonIgnore) are also
400-
// excluded from display data. These options are generally not useful for display.
404+
// Options that are excluded for serialization (i.e. those with @JsonIgnore) are
405+
// also
406+
// excluded from display data. These options are generally not useful for
407+
// display.
401408
continue;
402409
}
403410

@@ -481,7 +488,8 @@ private static String displayDataString(@Nullable Object value) {
481488
return Arrays.deepToString((Object[]) value);
482489
}
483490

484-
// At this point, we have some type of primitive array. Arrays.deepToString(..) requires an
491+
// At this point, we have some type of primitive array. Arrays.deepToString(..)
492+
// requires an
485493
// Object array, but will unwrap nested primitive arrays.
486494
String wrapped = Arrays.deepToString(new Object[] {value});
487495
return wrapped.substring(1, wrapped.length() - 1);
@@ -514,12 +522,17 @@ private Multimap<String, PipelineOptionSpec> buildOptionNameToSpecMap(
514522
// Filter out overridden options
515523
for (Map.Entry<String, Collection<PipelineOptionSpec>> entry : optionsMap.asMap().entrySet()) {
516524

517-
/* Compare all interfaces for an option pairwise (iface1, iface2) to look for type
518-
hierarchies. If one is the base-class of the other, remove it from the output and continue
519-
iterating.
520-
521-
This is an N^2 operation per-option, but the number of interfaces defining an option
522-
should always be small (usually 1). */
525+
/*
526+
* Compare all interfaces for an option pairwise (iface1, iface2) to look for
527+
* type
528+
* hierarchies. If one is the base-class of the other, remove it from the output
529+
* and continue
530+
* iterating.
531+
*
532+
* This is an N^2 operation per-option, but the number of interfaces defining an
533+
* option
534+
* should always be small (usually 1).
535+
*/
523536
List<PipelineOptionSpec> specs = Lists.newArrayList(entry.getValue());
524537
if (specs.size() < 2) {
525538
// Only one known implementing interface, no need to check for inheritance
@@ -600,9 +613,9 @@ private static Object getValueFromJson(JsonNode node, Method method) {
600613

601614
/**
602615
* Returns a default value for the method based upon {@code @Default} metadata on the getter to
603-
* return values. If there is no {@code @Default} annotation on the getter, then a <a
604-
* href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">default</a> as
605-
* per the Java Language Specification for the expected return type is returned.
616+
* return values. If there is no {@code @Default} annotation on the getter, then a <a href=
617+
* "https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">default</a> as per
618+
* the Java Language Specification for the expected return type is returned.
606619
*
607620
* @param proxy The proxy object for which we are attempting to get the default.
608621
* @param method The getter method that was invoked.
@@ -651,7 +664,8 @@ private Object getDefault(PipelineOptions proxy, Method method) {
651664
}
652665

653666
/*
654-
* We need to make sure that we return something appropriate for the return type. Thus we return
667+
* We need to make sure that we return something appropriate for the return
668+
* type. Thus we return
655669
* a default value as defined by the JLS.
656670
*/
657671
return Defaults.defaultValue(method.getReturnType());
@@ -750,7 +764,8 @@ public void serialize(PipelineOptions value, JsonGenerator jgen, SerializerProvi
750764
throws IOException {
751765
ProxyInvocationHandler handler = (ProxyInvocationHandler) Proxy.getInvocationHandler(value);
752766
PipelineOptionsFactory.Cache cache = PipelineOptionsFactory.CACHE.get();
753-
// We first copy and then filter out any properties that have been modified since
767+
// We first copy and then filter out any properties that have been modified
768+
// since
754769
// the last serialization of this PipelineOptions and then verify that
755770
// they are all serializable.
756771
Map<String, BoundValue> filteredOptions = Maps.newHashMap(handler.options);

0 commit comments

Comments
 (0)