parentClassNames = newLinkedList();
- Descriptor current = containingMessage;
+ var current = containingMessage;
while (current != null) {
parentClassNames.addFirst(current.getName() + OUTER_CLASS_DELIMITER);
current = current.getContainingType();
}
- String result = String.join("", parentClassNames);
+ var result = String.join("", parentClassNames);
return result;
}
@@ -227,7 +228,7 @@ public ClassName withNested(SimpleClassName className) {
* @see Class#getCanonicalName()
*/
public String canonicalName() {
- String withDots = toDotted(value());
+ var withDots = toDotted(value());
return withDots;
}
@@ -251,7 +252,7 @@ public String canonicalName() {
*/
@Internal
public static String toDotted(String outerDelimited) {
- String result = outerDelimited.replace(OUTER_CLASS_DELIMITER, DOT_SEPARATOR);
+ var result = outerDelimited.replace(OUTER_CLASS_DELIMITER, DOT_SEPARATOR);
return result;
}
@@ -267,6 +268,7 @@ public static String toDotted(String outerDelimited) {
*
* @return {@code MessageOrBuilder} interface FQN
*/
+ @SuppressWarnings("unused") /* Part of the public API. */
public ClassName orBuilder() {
return of(value() + OR_BUILDER_SUFFIX);
}
@@ -274,10 +276,10 @@ public ClassName orBuilder() {
private static ClassName construct(FileDescriptor file,
String typeName,
@Nullable Descriptor enclosing) {
- String packageName = javaPackageName(file);
- String outerClass = outerClassPrefix(file);
- String enclosingTypes = containingClassPrefix(enclosing);
- String result = packageName + outerClass + enclosingTypes + typeName;
+ var packageName = javaPackageName(file);
+ var outerClass = outerClassPrefix(file);
+ var enclosingTypes = containingClassPrefix(enclosing);
+ var result = packageName + outerClass + enclosingTypes + typeName;
return of(result);
}
@@ -286,8 +288,8 @@ private static ClassName construct(FileDescriptor file,
* classes, the most nested name will be returned.
*/
public SimpleClassName toSimple() {
- String fullName = canonicalName();
- String result = afterDot(fullName);
+ var fullName = canonicalName();
+ var result = afterDot(fullName);
return SimpleClassName.create(result);
}
@@ -299,6 +301,7 @@ public SimpleClassName toSimple() {
* @return this name without the package
*/
@Internal
+ @SuppressWarnings("unused") /* Part of the public API. */
public String withoutPackage() {
return toDotted(afterDot(value()));
}
@@ -311,7 +314,7 @@ public String withoutPackage() {
* @return the last part of the name
*/
private static String afterDot(String fullName) {
- int lastDotIndex = fullName.lastIndexOf(DOT_SEPARATOR);
+ var lastDotIndex = fullName.lastIndexOf(DOT_SEPARATOR);
return fullName.substring(lastDotIndex + 1);
}
@@ -319,14 +322,14 @@ private static String afterDot(String fullName) {
* Obtains the name of the package of this class.
*/
public PackageName packageName() {
- int packageEndIndex = packageEndIndex();
- String result = value().substring(0, packageEndIndex);
+ var packageEndIndex = packageEndIndex();
+ var result = value().substring(0, packageEndIndex);
return PackageName.of(result);
}
private int packageEndIndex() {
- String fullName = value();
- int lastDotIndex = fullName.lastIndexOf(DOT_SEPARATOR);
+ var fullName = value();
+ var lastDotIndex = fullName.lastIndexOf(DOT_SEPARATOR);
checkState(lastDotIndex > 0, "%s should be qualified.", fullName);
return lastDotIndex;
}
@@ -337,10 +340,11 @@ private int packageEndIndex() {
* If this class is top level, returns the simple name of this class. If this class is
* nested, returns the name of the declaring top level class.
*/
+ @SuppressWarnings("unused") /* Part of the public API. */
public SimpleClassName topLevelClass() {
- String qualifiedClassName = afterDot(value());
- int delimiterIndex = qualifiedClassName.indexOf(OUTER_CLASS_DELIMITER);
- String topLevelClassName = delimiterIndex >= 0
+ var qualifiedClassName = afterDot(value());
+ var delimiterIndex = qualifiedClassName.indexOf(OUTER_CLASS_DELIMITER);
+ var topLevelClassName = delimiterIndex >= 0
? qualifiedClassName.substring(0, delimiterIndex)
: qualifiedClassName;
return SimpleClassName.create(topLevelClassName);
diff --git a/base/src/main/java/io/spine/code/java/PackageName.java b/base/src/main/java/io/spine/code/java/PackageName.java
index f32c9daaeb..396f6e2dc9 100644
--- a/base/src/main/java/io/spine/code/java/PackageName.java
+++ b/base/src/main/java/io/spine/code/java/PackageName.java
@@ -58,7 +58,7 @@ private PackageName(String value) {
*/
public static PackageName of(String value) {
checkNotNull(value);
- PackageName result = new PackageName(value);
+ var result = new PackageName(value);
return result;
}
@@ -83,7 +83,7 @@ public static PackageName of(Class> cls) {
*/
public PackageName nested(String name) {
checkNotNull(name);
- PackageName result = of(value() + delimiter() + name);
+ var result = of(value() + delimiter() + name);
return result;
}
@@ -97,6 +97,7 @@ public static String delimiter() {
/**
* Obtains Java package delimiter as a single {@code char}.
*/
+ @SuppressWarnings("unused") /* Part of the public API. */
public static char delimiterChar() {
return DELIMITER_CHAR;
}
@@ -105,20 +106,20 @@ public static char delimiterChar() {
* Obtains a Java package name by the passed file descriptor.
*/
public static PackageName resolve(FileDescriptorProto file) {
- String javaPackage = resolveName(file).trim();
+ var javaPackage = resolveName(file).trim();
checkArgument(
!javaPackage.isEmpty(),
"Message classes generated from the file `%s` belong to the default package.%n"
+ "Please use `option java_package` or `package`"
+ " to specify a Java package for these types.", file.getName()
);
- PackageName result = new PackageName(javaPackage);
+ var result = new PackageName(javaPackage);
return result;
}
private static String resolveName(FileDescriptorProto file) {
- String javaPackage = file.getOptions()
- .getJavaPackage();
+ var javaPackage = file.getOptions()
+ .getJavaPackage();
if (isNullOrEmpty(javaPackage)) {
javaPackage = file.getPackage();
}
diff --git a/base/src/main/java/io/spine/code/java/PrimitiveType.java b/base/src/main/java/io/spine/code/java/PrimitiveType.java
index a416357550..ff9a196cbd 100644
--- a/base/src/main/java/io/spine/code/java/PrimitiveType.java
+++ b/base/src/main/java/io/spine/code/java/PrimitiveType.java
@@ -35,6 +35,7 @@
/**
* Enumeration of the Java primitives used for representing Proto scalar types.
*/
+@SuppressWarnings("unused") /* Part of the public API. */
public enum PrimitiveType {
INT(int.class, Integer.class),
LONG(long.class, Long.class),
@@ -59,7 +60,7 @@ public enum PrimitiveType {
*/
public static Optional extends Class>> getWrapperClass(String primitiveType) {
checkNotEmptyOrBlank(primitiveType);
- for (PrimitiveType simpleType : values()) {
+ for (var simpleType : values()) {
if (simpleType.matchesName(primitiveType)) {
return Optional.of(simpleType.getWrapperClass());
}
@@ -69,7 +70,7 @@ public static Optional extends Class>> getWrapperClass(String primitiveType)
}
boolean matchesName(String typeName) {
- boolean result = getName().equals(typeName);
+ var result = getName().equals(typeName);
return result;
}
diff --git a/base/src/main/java/io/spine/code/java/SimpleClassName.java b/base/src/main/java/io/spine/code/java/SimpleClassName.java
index 1644777671..16f7f676f6 100644
--- a/base/src/main/java/io/spine/code/java/SimpleClassName.java
+++ b/base/src/main/java/io/spine/code/java/SimpleClassName.java
@@ -79,8 +79,8 @@ public static SimpleClassName create(@ClassGetSimpleName String value) {
*/
public static SimpleClassName outerOf(FileDescriptorProto file) {
checkNotNull(file);
- String value = outerClassNameOf(file);
- SimpleClassName result = create(value);
+ var value = outerClassNameOf(file);
+ var result = create(value);
return result;
}
@@ -100,17 +100,16 @@ public static SimpleClassName outerOf(FileDescriptor file) {
* {@linkplain Optional#empty() empty Optional} if the option is not set
*/
public static Optional declaredOuterClassName(FileDescriptor file) {
- String className = declaredOuterClassName(file.toProto());
+ var className = declaredOuterClassName(file.toProto());
if (className.isEmpty()) {
return Optional.empty();
}
- SimpleClassName result = outerOf(file);
+ var result = outerOf(file);
return Optional.of(result);
}
private static String declaredOuterClassName(FileDescriptorProto file) {
- String result = file.getOptions()
- .getJavaOuterClassname();
+ var result = file.getOptions().getJavaOuterClassname();
return result;
}
@@ -128,13 +127,12 @@ private static String declaredOuterClassName(FileDescriptorProto file) {
*/
private static String outerClassNameOf(FileDescriptorProto file) {
checkNotNull(file);
- String nameDeclaredInOptions = declaredOuterClassName(file);
+ var nameDeclaredInOptions = declaredOuterClassName(file);
if (!nameDeclaredInOptions.isEmpty()) {
return nameDeclaredInOptions;
}
- String className =
- io.spine.code.proto.FileName.from(file)
- .nameOnlyCamelCase();
+ var className = io.spine.code.proto.FileName.from(file)
+ .nameOnlyCamelCase();
return className;
}
@@ -151,7 +149,7 @@ public static SimpleClassName ofBuilder() {
*/
public static SimpleClassName messageOrBuilder(@ClassGetSimpleName String typeName) {
checkNotEmptyOrBlank(typeName);
- SimpleClassName result = create(typeName + OR_BUILDER_SUFFIX);
+ var result = create(typeName + OR_BUILDER_SUFFIX);
return result;
}
@@ -160,7 +158,7 @@ public static SimpleClassName messageOrBuilder(@ClassGetSimpleName String typeNa
*/
public static SimpleClassName ofMessage(Descriptor descriptor) {
checkNotNull(descriptor);
- SimpleClassName result = create(descriptor.getName());
+ var result = create(descriptor.getName());
return result;
}
diff --git a/base/src/main/java/io/spine/code/proto/AbstractOption.java b/base/src/main/java/io/spine/code/proto/AbstractOption.java
index 9c054951a0..0dc7efed27 100644
--- a/base/src/main/java/io/spine/code/proto/AbstractOption.java
+++ b/base/src/main/java/io/spine/code/proto/AbstractOption.java
@@ -75,7 +75,7 @@ protected GeneratedExtension extension() {
@Override
public Optional valueFrom(K object) {
- E options = optionsFrom(object);
+ var options = optionsFrom(object);
return options.hasExtension(extension)
? Optional.of(options.getExtension(this.extension))
: Optional.empty();
@@ -90,7 +90,7 @@ public boolean equals(Object o) {
if (!(o instanceof AbstractOption)) {
return false;
}
- AbstractOption, ?, ?> option = (AbstractOption, ?, ?>) o;
+ var option = (AbstractOption, ?, ?>) o;
return extension.getNumber() == option.extension.getNumber();
}
diff --git a/base/src/main/java/io/spine/code/proto/CamelCase.java b/base/src/main/java/io/spine/code/proto/CamelCase.java
index 90b365dcba..2293f22cd3 100644
--- a/base/src/main/java/io/spine/code/proto/CamelCase.java
+++ b/base/src/main/java/io/spine/code/proto/CamelCase.java
@@ -26,8 +26,6 @@
package io.spine.code.proto;
-import java.util.Iterator;
-
import static java.lang.Character.toUpperCase;
/**
@@ -46,11 +44,10 @@ private CamelCase() {
* {@code "TestHTTPRequest"}.
*/
static String convert(UnderscoredName name) {
- Iterator iterator = name.words()
- .iterator();
- StringBuilder builder = new StringBuilder(name.value().length());
+ var iterator = name.words().iterator();
+ var builder = new StringBuilder(name.value().length());
while (iterator.hasNext()) {
- String word = iterator.next();
+ var word = iterator.next();
if (!word.isEmpty()) {
builder.append(toUpperCase(word.charAt(0)))
.append(word.substring(1));
diff --git a/base/src/main/java/io/spine/code/proto/ColumnOption.java b/base/src/main/java/io/spine/code/proto/ColumnOption.java
index 99f9576ea7..4ee83e50c1 100644
--- a/base/src/main/java/io/spine/code/proto/ColumnOption.java
+++ b/base/src/main/java/io/spine/code/proto/ColumnOption.java
@@ -27,12 +27,9 @@
package io.spine.code.proto;
import com.google.common.collect.ImmutableList;
-import io.spine.option.EntityOption;
import io.spine.option.OptionsProto;
import io.spine.type.MessageType;
-import java.util.Optional;
-
import static com.google.common.collect.ImmutableList.toImmutableList;
/**
@@ -64,9 +61,8 @@ public static boolean hasColumns(MessageType messageType) {
if (!declaresEntity(messageType)) {
return false;
}
- boolean result = messageType.fields()
- .stream()
- .anyMatch(ColumnOption::isColumn);
+ var result = messageType.fields().stream()
+ .anyMatch(ColumnOption::isColumn);
return result;
}
@@ -80,10 +76,9 @@ public static ImmutableList columnsOf(MessageType messageType)
if (!declaresEntity(messageType)) {
return ImmutableList.of();
}
- ImmutableList result = messageType.fields()
- .stream()
- .filter(ColumnOption::isColumn)
- .collect(toImmutableList());
+ var result = messageType.fields().stream()
+ .filter(ColumnOption::isColumn)
+ .collect(toImmutableList());
return result;
}
@@ -102,8 +97,8 @@ public static boolean isColumn(FieldDeclaration field) {
if (field.isCollection()) {
return false;
}
- ColumnOption option = new ColumnOption();
- Optional value = option.valueFrom(field.descriptor());
+ var option = new ColumnOption();
+ var value = option.valueFrom(field.descriptor());
boolean isColumn = value.orElse(false);
return isColumn;
}
@@ -113,7 +108,7 @@ public static boolean isColumn(FieldDeclaration field) {
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted") // For readability.
private static boolean declaresEntity(MessageType messageType) {
- Optional entityOption = EntityStateOption.valueOf(messageType.descriptor());
+ var entityOption = EntityStateOption.valueOf(messageType.descriptor());
return entityOption.isPresent();
}
}
diff --git a/base/src/main/java/io/spine/code/proto/DescriptorReference.java b/base/src/main/java/io/spine/code/proto/DescriptorReference.java
index 2f665051bf..c866de328c 100644
--- a/base/src/main/java/io/spine/code/proto/DescriptorReference.java
+++ b/base/src/main/java/io/spine/code/proto/DescriptorReference.java
@@ -35,13 +35,11 @@
import java.io.File;
import java.io.IOException;
-import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Iterator;
-import java.util.List;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -111,9 +109,8 @@ static Iterator loadAll() {
*/
@VisibleForTesting
static Iterator loadFromResources(Collection resources) {
- ClassLoader classLoader = DescriptorReference.class.getClassLoader();
- return resources
- .stream()
+ var classLoader = DescriptorReference.class.getClassLoader();
+ return resources.stream()
.map(DescriptorReference::readCatalog)
.flatMap(catalog -> LINE_SPLITTER.splitToList(catalog).stream())
.distinct()
@@ -122,9 +119,9 @@ static Iterator loadFromResources(Collection resources) {
}
private static String readCatalog(URL resource) {
- try (InputStream catalogStream = resource.openStream()) {
- byte[] catalogBytes = toByteArray(catalogStream);
- String catalog = new String(catalogBytes, UTF_8);
+ try (var catalogStream = resource.openStream()) {
+ var catalogBytes = toByteArray(catalogStream);
+ var catalog = new String(catalogBytes, UTF_8);
return catalog;
} catch (IOException e) {
throw illegalStateWithCauseOf(e);
@@ -141,13 +138,13 @@ private static String readCatalog(URL resource) {
*/
public void writeTo(Path directory) {
checkNotNull(directory);
- Path targetFile = directory.resolve(FILE_NAME);
+ var targetFile = directory.resolve(FILE_NAME);
Ensure.ensureFile(targetFile);
try {
- List resources = Files.readAllLines(targetFile);
+ var resources = Files.readAllLines(targetFile);
resources.add(reference);
- String result = String.join(SEPARATOR, resources)
- .trim();
+ var result = String.join(SEPARATOR, resources)
+ .trim();
Files.write(targetFile, ImmutableList.of(result), TRUNCATE_EXISTING);
} catch (IOException e) {
throw illegalStateWithCauseOf(e);
@@ -174,13 +171,13 @@ public void writeTo(Path directory) {
@VisibleForTesting
void writeTo(Path directory, String newline) {
checkNotNull(directory);
- Path targetFile = directory.resolve(FILE_NAME);
+ var targetFile = directory.resolve(FILE_NAME);
Ensure.ensureFile(targetFile);
try {
- List resources = Files.readAllLines(targetFile);
+ var resources = Files.readAllLines(targetFile);
resources.add(reference + newline);
- String result = String.join(SEPARATOR, resources)
- .trim();
+ var result = String.join(SEPARATOR, resources)
+ .trim();
Files.write(targetFile, ImmutableList.of(result), TRUNCATE_EXISTING);
} catch (IOException e) {
throw illegalStateWithCauseOf(e);
diff --git a/base/src/main/java/io/spine/code/proto/EntityIdField.java b/base/src/main/java/io/spine/code/proto/EntityIdField.java
index cca7899c70..912fb6cc3f 100644
--- a/base/src/main/java/io/spine/code/proto/EntityIdField.java
+++ b/base/src/main/java/io/spine/code/proto/EntityIdField.java
@@ -26,7 +26,6 @@
package io.spine.code.proto;
-import com.google.common.collect.ImmutableList;
import io.spine.type.MessageType;
import static com.google.common.base.Preconditions.checkArgument;
@@ -38,6 +37,7 @@
* The first field of the Protobuf message marked with {@code (entity)} option, representing
* its identifier.
*/
+@SuppressWarnings("unused") /* Part of the public API. */
public final class EntityIdField {
private final FieldDeclaration declaration;
@@ -57,11 +57,11 @@ public static EntityIdField of(MessageType messageType) {
checkArgument(messageType.isEntityState(),
"`EntityIdField` expected an `EntityState` descendant, " +
"but got `%s`.", messageType.javaClassName());
- ImmutableList fields = messageType.fields();
+ var fields = messageType.fields();
checkState(fields.size() > 0, "At least one field is expected to be declared " +
"in the `EntityState` message of type `%s`.", messageType.javaClassName());
- FieldDeclaration declaration = fields.get(0);
+ var declaration = fields.get(0);
checkState(!isColumn(declaration), "`EntityIdField` must not be marked as `(column)`." +
" Please check the declaration of `%s` type.", messageType.toProto().getName());
return new EntityIdField(declaration);
diff --git a/base/src/main/java/io/spine/code/proto/EntityStateOption.java b/base/src/main/java/io/spine/code/proto/EntityStateOption.java
index 3a4be0e6f6..ef5aca7090 100644
--- a/base/src/main/java/io/spine/code/proto/EntityStateOption.java
+++ b/base/src/main/java/io/spine/code/proto/EntityStateOption.java
@@ -35,8 +35,9 @@
/**
* An option for a message representing a state of the entity which defines its kind and visibility
- * to queries. There are four kids of options, namely, Aggregate, Projection, Process Manager,
- * and Entity).
+ * to queries.
+ *
+ * There are four kids of options, namely, Aggregate, Projection, Process Manager, and Entity.
*/
@Immutable
public final class EntityStateOption extends MessageOption {
@@ -60,7 +61,7 @@ private EntityStateOption() {
* to avoid instantiating an object.
*/
public static Optional valueOf(Descriptor message) {
- EntityStateOption option = new EntityStateOption();
+ var option = new EntityStateOption();
return option.valueFrom(message);
}
@@ -71,7 +72,7 @@ public static Optional valueOf(Descriptor message) {
* {@code Optional} otherwise
*/
public static Optional entityKindOf(Descriptor message) {
- Optional option = valueOf(message);
+ var option = valueOf(message);
return option.map(EntityOption::getKind);
}
}
diff --git a/base/src/main/java/io/spine/code/proto/FieldContext.java b/base/src/main/java/io/spine/code/proto/FieldContext.java
index 1be3efa0cb..98bf2b1543 100644
--- a/base/src/main/java/io/spine/code/proto/FieldContext.java
+++ b/base/src/main/java/io/spine/code/proto/FieldContext.java
@@ -34,7 +34,7 @@
import java.util.Objects;
import java.util.Optional;
-import static com.google.common.base.Preconditions.checkNotNull;
+import static java.util.Objects.requireNonNull;
/**
* Provides information about a proto field in the nesting hierarchy.
@@ -119,7 +119,7 @@ public FieldContext forChild(FieldDeclaration child) {
* @return the target descriptor
*/
public FieldDescriptor target() {
- return checkNotNull(target, "Empty context cannot have a target.");
+ return requireNonNull(target, "Empty context cannot have a target.");
}
/**
@@ -128,7 +128,7 @@ public FieldDescriptor target() {
* @return the target declaration
*/
public FieldDeclaration targetDeclaration() {
- FieldDescriptor target = target();
+ var target = target();
return new FieldDeclaration(target);
}
@@ -165,19 +165,17 @@ public FieldPath fieldPath() {
* @return {@code true} if this context has the same target and the same parent
*/
public boolean hasSameTargetAndParent(FieldContext other) {
- String thisTargetName = target().getFullName();
- String otherTargetName = other.target()
- .getFullName();
- boolean sameTarget = thisTargetName.equals(otherTargetName);
+ var thisTargetName = target().getFullName();
+ var otherTargetName = other.target().getFullName();
+ var sameTarget = thisTargetName.equals(otherTargetName);
if (!sameTarget) {
return false;
}
- Optional parentFromThis = targetParent()
+ var parentFromThis = targetParent()
.map(FieldDescriptor::getFullName);
- Optional parentFromOther = other
- .targetParent()
+ var parentFromOther = other.targetParent()
.map(FieldDescriptor::getFullName);
- boolean bothHaveParents = parentFromThis.isPresent() && parentFromOther.isPresent();
+ var bothHaveParents = parentFromThis.isPresent() && parentFromOther.isPresent();
return bothHaveParents && parentFromThis.get()
.equals(parentFromOther.get());
}
@@ -190,7 +188,7 @@ public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
- FieldContext context = (FieldContext) o;
+ var context = (FieldContext) o;
return Objects.equals(targetNameOrEmpty(), context.targetNameOrEmpty())
&& Objects.equals(parent, context.parent);
}
diff --git a/base/src/main/java/io/spine/code/proto/FieldDeclaration.java b/base/src/main/java/io/spine/code/proto/FieldDeclaration.java
index 45ba02c822..191a5852fe 100644
--- a/base/src/main/java/io/spine/code/proto/FieldDeclaration.java
+++ b/base/src/main/java/io/spine/code/proto/FieldDeclaration.java
@@ -30,11 +30,8 @@
import com.google.common.primitives.Primitives;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.Any;
-import com.google.protobuf.DescriptorProtos.FieldDescriptorProto;
-import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor.JavaType;
-import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.Message;
import io.spine.annotation.Internal;
import io.spine.base.MessageFile;
@@ -46,7 +43,6 @@
import io.spine.type.KnownTypes;
import io.spine.type.MessageType;
import io.spine.type.TypeName;
-import io.spine.type.TypeUrl;
import io.spine.type.UnknownTypeException;
import java.util.Optional;
@@ -128,7 +124,7 @@ public boolean isDefault(Object fieldValue) {
checkNotNull(fieldValue);
if (isMessage()) {
if (fieldValue instanceof Message) {
- Message message = (Message) fieldValue;
+ var message = (Message) fieldValue;
return Messages.isDefault(message) && sameMessageType(message);
} else {
return false;
@@ -139,9 +135,8 @@ public boolean isDefault(Object fieldValue) {
}
private boolean sameMessageType(Message msg) {
- String messageClassName = msg.getClass()
- .getName();
- String fieldClassName = messageClassName();
+ var messageClassName = msg.getClass().getName();
+ var fieldClassName = messageClassName();
return fieldClassName.equals(messageClassName);
}
@@ -160,16 +155,16 @@ public String javaTypeName() {
}
private static String javaTypeName(FieldDescriptor field) {
- FieldDescriptor.Type fieldType = field.getType();
+ var fieldType = field.getType();
if (fieldType == MESSAGE) {
- MessageType messageType =
+ var messageType =
new MessageType(field.getMessageType());
return messageType.javaClassName()
.canonicalName();
}
if (fieldType == ENUM) {
- EnumType enumType = EnumType.create(field.getEnumType());
+ var enumType = EnumType.create(field.getEnumType());
return enumType.javaClassName()
.canonicalName();
}
@@ -178,14 +173,14 @@ private static String javaTypeName(FieldDescriptor field) {
}
private String messageClassName() {
- TypeName typeName = TypeName.from(field.getMessageType());
- KnownTypes knownTypes = KnownTypes.instance();
+ var typeName = TypeName.from(field.getMessageType());
+ var knownTypes = KnownTypes.instance();
try {
- TypeUrl fieldType = typeName.toUrl();
- ClassName className = knownTypes.classNameOf(fieldType);
+ var fieldType = typeName.toUrl();
+ var className = knownTypes.classNameOf(fieldType);
return className.value();
} catch (UnknownTypeException e) {
- String allTypeUrls = knownTypes.printAllTypes();
+ var allTypeUrls = knownTypes.printAllTypes();
throw newIllegalStateException(
e,
"Cannot find a type %s in the list of known types:%n%s", typeName, allTypeUrls
@@ -207,7 +202,7 @@ private String messageClassName() {
* @return {@code true} if the field is an entity ID, {@code false} otherwise
*/
public boolean isId() {
- boolean fieldMatches = isFirstField() && isNotCollection();
+ var fieldMatches = isFirstField() && isNotCollection();
return fieldMatches && (isCommandsFile() || isEntityField());
}
@@ -307,7 +302,7 @@ public JavaType javaType() {
@Internal
public MessageType messageType() {
checkState(isMessage());
- Descriptor messageType = descriptor().getMessageType();
+ var messageType = descriptor().getMessageType();
return new MessageType(messageType);
}
@@ -318,9 +313,9 @@ public MessageType messageType() {
public ClassName className() {
if (isScalar()) {
@SuppressWarnings("OptionalGetWithoutIsPresent") // checked in `if`
- ScalarType scalarType = ScalarType.of(descriptor().toProto()).get();
- Class> type = scalarType.javaClass();
- Class> wrapped = Primitives.wrap(type);
+ var scalarType = ScalarType.of(descriptor().toProto()).get();
+ var type = scalarType.javaClass();
+ var wrapped = Primitives.wrap(type);
return ClassName.of(wrapped);
}
return ClassName.of(javaTypeName());
@@ -328,16 +323,15 @@ public ClassName className() {
/** Obtains the descriptor of the value of a map. */
public FieldDeclaration valueDeclaration() {
- FieldDescriptor valueDescriptor = FieldTypes.valueDescriptor(field);
+ var valueDescriptor = FieldTypes.valueDescriptor(field);
return new FieldDeclaration(valueDescriptor);
}
private boolean isEntityField() {
- EntityOption entityOption =
- field.getContainingType()
- .getOptions()
- .getExtension(OptionsProto.entity);
- EntityOption.Kind entityKind = entityOption.getKind();
+ var entityOption = field.getContainingType()
+ .getOptions()
+ .getExtension(OptionsProto.entity);
+ var entityKind = entityOption.getKind();
return entityKind.getNumber() > 0;
}
@@ -355,8 +349,8 @@ private boolean isFirstField() {
}
private boolean isCommandsFile() {
- FileDescriptor file = field.getFile();
- boolean result = MessageFile.COMMANDS.test(file.toProto());
+ var file = field.getFile();
+ var result = MessageFile.COMMANDS.test(file.toProto());
return result;
}
@@ -364,8 +358,8 @@ private boolean isCommandsFile() {
* Returns the name of the getter generated by the Protobuf Java plugin for the field.
*/
public String javaGetterName() {
- String camelCasedName = name().toCamelCase();
- String result = format("get%s", camelCasedName);
+ var camelCasedName = name().toCamelCase();
+ var result = format("get%s", camelCasedName);
return result;
}
@@ -374,8 +368,9 @@ public String javaGetterName() {
*
* @return the leading field comments or {@code Optional.empty()} if there are no comments
*/
+ @SuppressWarnings("unused") /* Part of the public API. */
public Optional leadingComments() {
- LocationPath fieldPath = fieldPath();
+ var fieldPath = fieldPath();
return declaringMessage.leadingComments(fieldPath);
}
@@ -387,15 +382,14 @@ public Optional leadingComments() {
* @return the field location path
*/
private LocationPath fieldPath() {
- LocationPath locationPath =
- new LocationPath(declaringMessage.path())
- .append(FIELD_FIELD_NUMBER)
- .append(fieldIndex());
+ var locationPath = new LocationPath(declaringMessage.path())
+ .append(FIELD_FIELD_NUMBER)
+ .append(fieldIndex());
return locationPath;
}
private int fieldIndex() {
- FieldDescriptorProto proto = this.field.toProto();
+ var proto = this.field.toProto();
return declaringMessage.descriptor()
.toProto()
.getFieldList()
@@ -410,7 +404,7 @@ public boolean equals(Object o) {
if (!(o instanceof FieldDeclaration)) {
return false;
}
- FieldDeclaration that = (FieldDeclaration) o;
+ var that = (FieldDeclaration) o;
return Objects.equal(declaringMessage, that.declaringMessage) &&
Objects.equal(field.getFullName(), that.field.getFullName());
}
diff --git a/base/src/main/java/io/spine/code/proto/FieldName.java b/base/src/main/java/io/spine/code/proto/FieldName.java
index 0c47b618bf..90f195d1bb 100644
--- a/base/src/main/java/io/spine/code/proto/FieldName.java
+++ b/base/src/main/java/io/spine/code/proto/FieldName.java
@@ -96,8 +96,8 @@ public static FieldName of(FieldDescriptorProto field) {
*/
@Override
public List words() {
- String[] words = WORD_SEPARATOR_PATTERN.split(value());
- ImmutableList result = ImmutableList.copyOf(words);
+ var words = WORD_SEPARATOR_PATTERN.split(value());
+ var result = ImmutableList.copyOf(words);
return result;
}
@@ -105,8 +105,8 @@ public List words() {
* Obtains the field name in {@code javaCase}.
*/
public String javaCase() {
- String camelCase = toCamelCase();
- String result = Character.toLowerCase(camelCase.charAt(0)) + camelCase.substring(1);
+ var camelCase = toCamelCase();
+ var result = Character.toLowerCase(camelCase.charAt(0)) + camelCase.substring(1);
return result;
}
@@ -114,7 +114,7 @@ public String javaCase() {
* Obtains this field name as a single-entry field path.
*/
public FieldPath asPath() {
- Field field = Field.named(value());
+ var field = Field.named(value());
return field.path();
}
}
diff --git a/base/src/main/java/io/spine/code/proto/FieldTypes.java b/base/src/main/java/io/spine/code/proto/FieldTypes.java
index 319d04bd06..b74f27613a 100644
--- a/base/src/main/java/io/spine/code/proto/FieldTypes.java
+++ b/base/src/main/java/io/spine/code/proto/FieldTypes.java
@@ -26,7 +26,6 @@
package io.spine.code.proto;
-import com.google.protobuf.DescriptorProtos.FieldDescriptorProto;
import com.google.protobuf.Descriptors.FieldDescriptor;
import static com.google.common.base.Preconditions.checkArgument;
@@ -62,7 +61,7 @@ private FieldTypes() {
*/
public static boolean isMessage(FieldDescriptor field) {
checkNotNull(field);
- boolean isMessage = field.getType() == MESSAGE;
+ var isMessage = field.getType() == MESSAGE;
return isMessage;
}
@@ -78,7 +77,7 @@ public static boolean isMessage(FieldDescriptor field) {
*/
public static boolean isRepeated(FieldDescriptor field) {
checkNotNull(field);
- FieldDescriptorProto proto = field.toProto();
+ var proto = field.toProto();
return FieldTypesProto.isRepeated(proto);
}
@@ -91,7 +90,7 @@ public static boolean isRepeated(FieldDescriptor field) {
*/
public static boolean isMap(FieldDescriptor field) {
checkNotNull(field);
- FieldDescriptorProto proto = field.toProto();
+ var proto = field.toProto();
return FieldTypesProto.isMap(proto);
}
@@ -111,8 +110,8 @@ public static FieldDescriptor keyDescriptor(FieldDescriptor field) {
checkArgument(isMap(field),
"Trying to get key descriptor for the non-map field %s.",
field.getName());
- FieldDescriptor descriptor = field.getMessageType()
- .findFieldByName(MAP_ENTRY_KEY);
+ var descriptor = field.getMessageType()
+ .findFieldByName(MAP_ENTRY_KEY);
return descriptor;
}
@@ -132,8 +131,8 @@ public static FieldDescriptor valueDescriptor(FieldDescriptor field) {
checkArgument(isMap(field),
"Trying to get value descriptor for the non-map field %s.",
field.getName());
- FieldDescriptor descriptor = field.getMessageType()
- .findFieldByName(MAP_ENTRY_VALUE);
+ var descriptor = field.getMessageType()
+ .findFieldByName(MAP_ENTRY_VALUE);
return descriptor;
}
}
diff --git a/base/src/main/java/io/spine/code/proto/FieldTypesProto.java b/base/src/main/java/io/spine/code/proto/FieldTypesProto.java
index 1abc021843..a18d0c19d5 100644
--- a/base/src/main/java/io/spine/code/proto/FieldTypesProto.java
+++ b/base/src/main/java/io/spine/code/proto/FieldTypesProto.java
@@ -56,7 +56,7 @@ private FieldTypesProto() {
*/
public static boolean isRepeated(FieldDescriptorProto field) {
checkNotNull(field);
- boolean result = field.getLabel() == LABEL_REPEATED && !isMap(field);
+ var result = field.getLabel() == LABEL_REPEATED && !isMap(field);
return result;
}
@@ -77,8 +77,8 @@ public static boolean isMap(FieldDescriptorProto field) {
if (field.getType() != TYPE_MESSAGE) {
return false;
}
- boolean result = field.getTypeName()
- .endsWith('.' + getEntryNameFor(field));
+ var result = field.getTypeName()
+ .endsWith('.' + getEntryNameFor(field));
return result;
}
@@ -94,7 +94,8 @@ public static boolean isMap(FieldDescriptorProto field) {
* @return the name of the map field
*/
public static String getEntryNameFor(FieldDescriptorProto mapField) {
- FieldName fieldName = FieldName.of(mapField);
+ checkNotNull(mapField);
+ var fieldName = FieldName.of(mapField);
return fieldName.toCamelCase() + ENTRY_SUFFIX;
}
@@ -119,14 +120,16 @@ public static boolean isMessage(FieldDescriptorProto fieldDescriptor) {
* the field descriptor whose type name to modify
* @return the type name without leading dot
*/
+ @SuppressWarnings("unused") /* Part of the public API. */
public static String trimTypeName(FieldDescriptorProto fieldDescriptor) {
- String typeName = fieldDescriptor.getTypeName();
+ checkNotNull(fieldDescriptor);
+ var typeName = fieldDescriptor.getTypeName();
checkNotNull(typeName);
if (typeName.isEmpty()) {
return typeName;
}
- String trimmedName = removeLeadingDot(typeName);
+ var trimmedName = removeLeadingDot(typeName);
return trimmedName;
}
diff --git a/base/src/main/java/io/spine/code/proto/FileDescriptors.java b/base/src/main/java/io/spine/code/proto/FileDescriptors.java
index d1b201eab3..42d11b228d 100644
--- a/base/src/main/java/io/spine/code/proto/FileDescriptors.java
+++ b/base/src/main/java/io/spine/code/proto/FileDescriptors.java
@@ -34,9 +34,7 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
-import java.io.InputStream;
import java.net.URL;
-import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
@@ -112,12 +110,11 @@ private static FluentLogger.Api _debug() {
descriptorSet);
List files;
- try (FileInputStream fis = new FileInputStream(descriptorSet)) {
- FileDescriptorSet fileSet = FileDescriptorSetReader.parse(fis);
- files = fileSet.getFileList()
- .stream()
- .filter(filter)
- .collect(toList());
+ try (var fis = new FileInputStream(descriptorSet)) {
+ var fileSet = FileDescriptorSetReader.parse(fis);
+ files = fileSet.getFileList().stream()
+ .filter(filter)
+ .collect(toList());
} catch (IOException e) {
throw newIllegalStateException(
e, "Cannot get proto file descriptors. Path: `%s`.", descriptorSet
@@ -134,8 +131,8 @@ private static FluentLogger.Api _debug() {
* contained in the loaded files
*/
static Set load() {
- Iterator resources = DescriptorReference.loadAll();
- Set files = stream(resources)
+ var resources = DescriptorReference.loadAll();
+ var files = stream(resources)
.map(FileDescriptors::loadFrom)
.flatMap(set -> set.getFileList().stream())
.filter(distinctBy(FileDescriptorProto::getName))
@@ -162,8 +159,8 @@ static Set load() {
private static Predicate distinctBy(Function selector) {
Set super K> seen = newHashSet();
return element -> {
- K key = selector.apply(element);
- boolean newKey = seen.add(key);
+ var key = selector.apply(element);
+ var newKey = seen.add(key);
return newKey;
};
}
@@ -179,8 +176,8 @@ private static FileDescriptorSet loadFrom(Resource resource) {
}
private static FileDescriptorSet doLoadFrom(Resource resource) {
- try (InputStream stream = resource.open()) {
- FileDescriptorSet parsed = FileDescriptorSetReader.parse(stream);
+ try (var stream = resource.open()) {
+ var parsed = FileDescriptorSetReader.parse(stream);
return parsed;
} catch (IOException e) {
throw newIllegalStateException(
@@ -195,10 +192,10 @@ private static FileDescriptorSet doLoadFrom(Resource resource) {
* Tells if two descriptors represent the same file.
*/
public static boolean sameFiles(FileDescriptor f1, FileDescriptor f2) {
- boolean sameName = f2.getFullName()
- .equals(f1.getFullName());
- boolean samePackage = f2.getPackage()
- .equals(f1.getPackage());
+ var sameName = f2.getFullName()
+ .equals(f1.getFullName());
+ var samePackage = f2.getPackage()
+ .equals(f1.getPackage());
return sameName && samePackage;
}
@@ -206,7 +203,7 @@ public static boolean sameFiles(FileDescriptor f1, FileDescriptor f2) {
* Verifies if the passed file declares types under the "google" package.
*/
public static boolean isGoogle(FileDescriptor file) {
- PackageName packageName = PackageName.of(file.getPackage());
+ var packageName = PackageName.of(file.getPackage());
return packageName.isGoogle();
}
}
diff --git a/base/src/main/java/io/spine/code/proto/FileName.java b/base/src/main/java/io/spine/code/proto/FileName.java
index 9b9d44e737..26a815efe6 100644
--- a/base/src/main/java/io/spine/code/proto/FileName.java
+++ b/base/src/main/java/io/spine/code/proto/FileName.java
@@ -71,7 +71,7 @@ public static FileName of(String value) {
*/
public static FileName from(FileDescriptorProto descriptor) {
checkNotNull(descriptor);
- FileName result = of(descriptor.getName());
+ var result = of(descriptor.getName());
return result;
}
@@ -87,8 +87,8 @@ public static FileName from(FileDescriptor descriptor) {
*/
@Override
public List words() {
- String[] words = nameOnly().split(WORD_SEPARATOR);
- ImmutableList result = ImmutableList.copyOf(words);
+ var words = nameOnly().split(WORD_SEPARATOR);
+ var result = ImmutableList.copyOf(words);
return result;
}
@@ -96,9 +96,9 @@ public List words() {
* Obtains the file name without path and extension.
*/
private String nameOnly() {
- String name = nameWithoutExtension();
- int lastBackslashIndex = name.lastIndexOf(PATH_SEPARATOR);
- String result = name.substring(lastBackslashIndex + 1);
+ var name = nameWithoutExtension();
+ var lastBackslashIndex = name.lastIndexOf(PATH_SEPARATOR);
+ var result = name.substring(lastBackslashIndex + 1);
return result;
}
@@ -106,9 +106,9 @@ private String nameOnly() {
* Returns the file name with extension but without path.
*/
public String nameWithExtension() {
- String fullName = value();
- int lastBackslashIndex = fullName.lastIndexOf(PATH_SEPARATOR);
- String result = fullName.substring(lastBackslashIndex + 1);
+ var fullName = value();
+ var lastBackslashIndex = fullName.lastIndexOf(PATH_SEPARATOR);
+ var result = fullName.substring(lastBackslashIndex + 1);
return result;
}
@@ -123,14 +123,14 @@ public String nameOnlyCamelCase() {
* Returns the file name without extension but including path.
*/
public String nameWithoutExtension() {
- String value = value();
- int extensionIndex = value.lastIndexOf(EXTENSION);
- String result = value.substring(0, extensionIndex);
+ var value = value();
+ var extensionIndex = value.lastIndexOf(EXTENSION);
+ var result = value.substring(0, extensionIndex);
return result;
}
private boolean matches(MessageFile file) {
- boolean result = value().endsWith(file.suffix());
+ var result = value().endsWith(file.suffix());
return result;
}
diff --git a/base/src/main/java/io/spine/code/proto/FileSet.java b/base/src/main/java/io/spine/code/proto/FileSet.java
index b82d7210d0..ea280142e1 100644
--- a/base/src/main/java/io/spine/code/proto/FileSet.java
+++ b/base/src/main/java/io/spine/code/proto/FileSet.java
@@ -46,7 +46,6 @@
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
-import java.util.logging.Level;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Maps.newHashMap;
@@ -113,15 +112,11 @@ public static FileSet parse(File descriptorSet) {
* @return new file set
*/
public static FileSet parseAsKnownFiles(File descriptorSet) {
- Set fileNames = FileDescriptors.parse(descriptorSet)
- .stream()
- .map(FileName::from)
- .collect(toSet());
- Map knownFiles =
- KnownTypes.instance()
- .asTypeSet()
- .allTypes()
- .stream()
+ var fileNames = FileDescriptors.parse(descriptorSet).stream()
+ .map(FileName::from)
+ .collect(toSet());
+ var allTypes = KnownTypes.instance().asTypeSet().allTypes();
+ var knownFiles = allTypes.stream()
.map(Type::file)
.filter(descr -> fileNames.contains(FileName.from(descr.getFile())))
.collect(toMap(FileName::from, // File name as the key.
@@ -131,14 +126,14 @@ public static FileSet parseAsKnownFiles(File descriptorSet) {
if (knownFiles.size() != fileNames.size()) {
onUnknownFiles(knownFiles.keySet(), fileNames, descriptorSet);
}
- FileSet result = new FileSet(knownFiles);
+ var result = new FileSet(knownFiles);
return result;
}
private static void onUnknownFiles(Set knownFiles,
Set requestedFiles,
File descriptorSetFile) {
- Level detailLevel = FINE;
+ var detailLevel = FINE;
logger.atWarning().log(
"Some files are unknown. " +
"%s files are present in classpath but %s files are discovered in `%s`.%n" +
@@ -150,8 +145,7 @@ private static void onUnknownFiles(Set knownFiles,
detailLevel
);
logger.at(detailLevel)
- .log("Could not find files: %s.", lazy(() -> requestedFiles
- .stream()
+ .log("Could not find files: %s.", lazy(() -> requestedFiles.stream()
.filter(fileName -> !knownFiles.contains(fileName))
.map(FileName::toString)
.collect(joining(", "))));
@@ -185,7 +179,7 @@ public static FileSet load() {
*/
public static FileSet of(Iterable protoDescriptors) {
checkNotNull(protoDescriptors);
- ImmutableSet descriptors = ImmutableSet.copyOf(protoDescriptors);
+ var descriptors = ImmutableSet.copyOf(protoDescriptors);
return link(descriptors);
}
@@ -194,9 +188,9 @@ public static FileSet of(Iterable protoDescriptors) {
*/
public List topLevelMessages() {
ImmutableList.Builder result = ImmutableList.builder();
- for (FileDescriptor file : files()) {
- SourceFile sourceFile = SourceFile.from(file);
- List declarations = sourceFile.topLevelMessages();
+ for (var file : files()) {
+ var sourceFile = SourceFile.from(file);
+ var declarations = sourceFile.topLevelMessages();
result.addAll(declarations);
}
return result.build();
@@ -210,8 +204,8 @@ public List topLevelMessages() {
*/
public List findMessageTypes(Predicate predicate) {
ImmutableList.Builder result = ImmutableList.builder();
- for (FileDescriptor file : files()) {
- SourceFile sourceFile = SourceFile.from(file);
+ for (var file : files()) {
+ var sourceFile = SourceFile.from(file);
Collection declarations = sourceFile.allThat(predicate);
result.addAll(declarations);
}
@@ -228,11 +222,11 @@ public FileSet union(FileSet another) {
if (this.isEmpty()) {
return another;
}
- int expectedSize = this.files.size() + another.files.size();
+ var expectedSize = this.files.size() + another.files.size();
Map files = newHashMapWithExpectedSize(expectedSize);
files.putAll(this.files);
files.putAll(another.files);
- FileSet result = new FileSet(files);
+ var result = new FileSet(files);
return result;
}
@@ -248,8 +242,8 @@ public FileSet filter(Predicate predicate) {
.stream()
.filter(predicate)
.collect(toList());
- FileSet newFileSet = newInstance();
- for (FileDescriptor file : filteredFiles) {
+ var newFileSet = newInstance();
+ for (var file : filteredFiles) {
newFileSet.add(file);
}
return newFileSet;
@@ -275,7 +269,7 @@ FileDescriptor[] toArray() {
* {@code false} otherwise.
*/
public boolean contains(FileName fileName) {
- Optional found = tryFind(fileName);
+ var found = tryFind(fileName);
return found.isPresent();
}
@@ -284,8 +278,8 @@ public boolean contains(FileName fileName) {
* {@code false} otherwise.
*/
public boolean containsAll(Collection fileNames) {
- FileSet found = find(fileNames);
- boolean result = found.size() == fileNames.size();
+ var found = find(fileNames);
+ var result = found.size() == fileNames.size();
return result;
}
@@ -294,8 +288,8 @@ public boolean containsAll(Collection fileNames) {
*/
public FileSet find(Collection fileNames) {
Map found = newHashMapWithExpectedSize(fileNames.size());
- for (FileName name : fileNames) {
- Optional file = tryFind(name);
+ for (var name : fileNames) {
+ var file = tryFind(name);
file.ifPresent(fileDescr -> found.put(name, fileDescr));
}
return new FileSet(found);
@@ -317,9 +311,9 @@ public Optional tryFind(FileName fileName) {
*/
@CanIgnoreReturnValue
public boolean add(FileDescriptor file) {
- FileName name = FileName.from(file);
+ var name = FileName.from(file);
Object previous = files.put(name, file);
- boolean isNew = previous == null;
+ var isNew = previous == null;
return isNew;
}
@@ -327,7 +321,7 @@ public boolean add(FileDescriptor file) {
* Obtains the size of the set.
*/
public int size() {
- int result = files.size();
+ var result = files.size();
return result;
}
@@ -335,7 +329,7 @@ public int size() {
* Verifies if the set is empty.
*/
public boolean isEmpty() {
- boolean result = files.isEmpty();
+ var result = files.isEmpty();
return result;
}
@@ -365,7 +359,7 @@ public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
- FileSet other = (FileSet) obj;
+ var other = (FileSet) obj;
return Objects.equals(this.files, other.files);
}
}
diff --git a/base/src/main/java/io/spine/code/proto/Linker.java b/base/src/main/java/io/spine/code/proto/Linker.java
index 2c5eb0f16f..a0a74b2727 100644
--- a/base/src/main/java/io/spine/code/proto/Linker.java
+++ b/base/src/main/java/io/spine/code/proto/Linker.java
@@ -36,7 +36,6 @@
import com.google.protobuf.Descriptors.FileDescriptor;
import java.util.Collection;
-import java.util.Iterator;
import java.util.List;
import static com.google.common.base.Preconditions.checkState;
@@ -71,10 +70,10 @@ final class Linker {
}
static FileSet link(Collection files) {
- Linker linker = new Linker(files);
+ var linker = new Linker(files);
@SuppressWarnings("FloggerSplitLogStatement")
// See: https://github.com/SpineEventEngine/base/issues/612
- FluentLogger.Api debug = logger.atFine();
+ var debug = logger.atFine();
debug.log("Trying to link %d files.", files.size());
try {
linker.resolve();
@@ -82,9 +81,9 @@ static FileSet link(Collection files) {
throw newIllegalStateException(e, "Unable to link descriptor set files.");
}
debug.log("Linking complete. %s", linker);
- FileSet result = linker.resolved()
- .union(linker.partiallyResolved())
- .union(linker.unresolved());
+ var result = linker.resolved()
+ .union(linker.partiallyResolved())
+ .union(linker.unresolved());
return result;
}
@@ -98,11 +97,11 @@ void resolve() throws DescriptorValidationException {
}
private void findNoDependencies() throws DescriptorValidationException {
- Iterator iterator = remaining.iterator();
+ var iterator = remaining.iterator();
while (iterator.hasNext()) {
- FileDescriptorProto next = iterator.next();
+ var next = iterator.next();
if (next.getDependencyCount() == 0) {
- FileDescriptor fd = buildFrom(next, NO_DEPENDENCIES, true);
+ var fd = buildFrom(next, NO_DEPENDENCIES, true);
resolved.add(fd);
iterator.remove();
}
@@ -114,21 +113,21 @@ private void findNoDependencies() throws DescriptorValidationException {
* or no more resolved files found.
*/
private void findResolved() throws DescriptorValidationException {
- boolean resolvedFound = true;
+ var resolvedFound = true;
while (!remaining.isEmpty() && resolvedFound) {
resolvedFound = doFindResolved();
}
}
private boolean doFindResolved() throws DescriptorValidationException {
- boolean result = false;
- Iterator iterator = remaining.iterator();
+ var result = false;
+ var iterator = remaining.iterator();
while (iterator.hasNext()) {
- FileDescriptorProto next = iterator.next();
- Collection dependencyList = dependencies(next);
+ var next = iterator.next();
+ var dependencyList = dependencies(next);
if (resolved.containsAll(dependencyList)) {
- FileSet dependencies = resolved.find(dependencyList);
- FileDescriptor newResolved = buildFrom(next, dependencies.toArray(), true);
+ var dependencies = resolved.find(dependencyList);
+ var newResolved = buildFrom(next, dependencies.toArray(), true);
resolved.add(newResolved);
result = true;
iterator.remove();
@@ -138,22 +137,22 @@ private boolean doFindResolved() throws DescriptorValidationException {
}
private void findPartiallyResolved() throws DescriptorValidationException {
- boolean partiallyResolvedFound = true;
+ var partiallyResolvedFound = true;
while (!remaining.isEmpty() && partiallyResolvedFound) {
partiallyResolvedFound = doFindPartiallyResolved();
}
}
private boolean doFindPartiallyResolved() throws DescriptorValidationException {
- boolean result = false;
- FileSet partialAndResolved = resolved.union(partiallyResolved);
- Iterator iterator = remaining.iterator();
+ var result = false;
+ var partialAndResolved = resolved.union(partiallyResolved);
+ var iterator = remaining.iterator();
while (iterator.hasNext()) {
- FileDescriptorProto next = iterator.next();
- Collection dependencyList = dependencies(next);
- FileSet dependencies = partialAndResolved.find(dependencyList);
+ var next = iterator.next();
+ var dependencyList = dependencies(next);
+ var dependencies = partialAndResolved.find(dependencyList);
if (dependencies.isEmpty()) {
- FileDescriptor newPartial = buildFrom(next, dependencies.toArray(), true);
+ var newPartial = buildFrom(next, dependencies.toArray(), true);
partiallyResolved.add(newPartial);
partialAndResolved.add(newPartial);
result = true;
@@ -173,8 +172,8 @@ private boolean doFindPartiallyResolved() throws DescriptorValidationException {
*/
private void addUnresolved() throws DescriptorValidationException {
while (!remaining.isEmpty()) {
- FileDescriptorProto first = remaining.get(0);
- FileDescriptor fd = buildFrom(first, NO_DEPENDENCIES, true);
+ var first = remaining.get(0);
+ var fd = buildFrom(first, NO_DEPENDENCIES, true);
unresolved.add(fd);
remaining.remove(first);
}
@@ -204,8 +203,8 @@ FileSet unresolved() {
return unresolved;
}
- @SuppressWarnings("DuplicateStringLiteralInspection") // field names
@Override
+ @SuppressWarnings("DuplicateStringLiteralInspection") // field names
public String toString() {
return MoreObjects.toStringHelper(this)
.add("input", namesForDisplay(input))
diff --git a/base/src/main/java/io/spine/code/proto/LocationPath.java b/base/src/main/java/io/spine/code/proto/LocationPath.java
index 1a7ff6672e..114736edcf 100644
--- a/base/src/main/java/io/spine/code/proto/LocationPath.java
+++ b/base/src/main/java/io/spine/code/proto/LocationPath.java
@@ -84,7 +84,7 @@ public static LocationPath fromMessage(Descriptor descriptor) {
path.add(FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER);
if (!MessageType.isTopLevel(descriptor)) {
Deque parentPath = new ArrayDeque<>();
- Descriptor containingType = descriptor.getContainingType();
+ var containingType = descriptor.getContainingType();
while (containingType != null) {
parentPath.addFirst(containingType.getIndex());
containingType = containingType.getContainingType();
@@ -92,7 +92,7 @@ public static LocationPath fromMessage(Descriptor descriptor) {
path.addAll(parentPath);
}
path.add(descriptor.getIndex());
- ImmutableList list = path.build();
+ var list = path.build();
return new LocationPath(list, false);
}
@@ -100,9 +100,9 @@ public static LocationPath fromMessage(Descriptor descriptor) {
* Appends the path item to the end of this path.
*/
LocationPath append(Integer... items) {
- ImmutableList candidates = ImmutableList.copyOf(items);
+ var candidates = ImmutableList.copyOf(items);
checkPath(candidates);
- ImmutableList combined = toBuilder().addAll(candidates).build();
+ var combined = toBuilder().addAll(candidates).build();
return new LocationPath(combined, false);
}
@@ -128,9 +128,9 @@ private static void checkItem(Integer item) {
* Converts the instance to the {@code SourceCodeInfo.Location} instance in the given file.
*/
public SourceCodeInfo.Location toLocationIn(FileDescriptorProto file) {
- List thisPath = toList();
- List locations = file.getSourceCodeInfo().getLocationList();
- for (SourceCodeInfo.Location location : locations) {
+ var thisPath = toList();
+ var locations = file.getSourceCodeInfo().getLocationList();
+ for (var location : locations) {
if (thisPath.equals(location.getPathList())) {
return location;
}
@@ -149,7 +149,7 @@ public boolean equals(Object o) {
if (!(o instanceof LocationPath)) {
return false;
}
- LocationPath that = (LocationPath) o;
+ var that = (LocationPath) o;
return path.equals(that.path);
}
diff --git a/base/src/main/java/io/spine/code/proto/OptionExtensionRegistry.java b/base/src/main/java/io/spine/code/proto/OptionExtensionRegistry.java
index c16a4b82fc..83f725f632 100644
--- a/base/src/main/java/io/spine/code/proto/OptionExtensionRegistry.java
+++ b/base/src/main/java/io/spine/code/proto/OptionExtensionRegistry.java
@@ -26,11 +26,9 @@
package io.spine.code.proto;
-import com.google.common.collect.ImmutableSet;
import com.google.protobuf.Extension;
import com.google.protobuf.ExtensionRegistry;
import io.spine.option.OptionsProto;
-import io.spine.validate.option.ValidatingOptionFactory;
import io.spine.validate.option.ValidatingOptionsLoader;
/**
@@ -63,28 +61,26 @@ public static ExtensionRegistry instance() {
* spine/options.proto} extensions.
*/
private static ExtensionRegistry optionExtensions() {
- ExtensionRegistry registry = ExtensionRegistry.newInstance();
+ var registry = ExtensionRegistry.newInstance();
OptionsProto.registerAllExtensions(registry);
registerCustomOptions(registry);
return registry;
}
private static void registerCustomOptions(ExtensionRegistry target) {
- ImmutableSet implementations =
- ValidatingOptionsLoader.INSTANCE.implementations();
+ var implementations = ValidatingOptionsLoader.INSTANCE.implementations();
implementations.stream()
- .flatMap(factory -> factory.all().stream())
- .map(AbstractOption::extension)
- .filter(extension -> isExtensionRegistered(target, extension))
- .forEach(target::add);
+ .flatMap(factory -> factory.all().stream())
+ .map(AbstractOption::extension)
+ .filter(extension -> isExtensionRegistered(target, extension))
+ .forEach(target::add);
}
private static boolean isExtensionRegistered(ExtensionRegistry registry,
Extension, ?> extension) {
- String name = extension.getDescriptor()
- .getFullName();
- boolean mutableAbsent = registry.findMutableExtensionByName(name) == null;
- boolean immutableAbsent = registry.findImmutableExtensionByName(name) == null;
+ var name = extension.getDescriptor().getFullName();
+ var mutableAbsent = registry.findMutableExtensionByName(name) == null;
+ var immutableAbsent = registry.findImmutableExtensionByName(name) == null;
return mutableAbsent && immutableAbsent;
}
}
diff --git a/base/src/main/java/io/spine/code/proto/PackageName.java b/base/src/main/java/io/spine/code/proto/PackageName.java
index aeb269f2b8..ea84f05268 100644
--- a/base/src/main/java/io/spine/code/proto/PackageName.java
+++ b/base/src/main/java/io/spine/code/proto/PackageName.java
@@ -53,7 +53,7 @@ private PackageName(String value) {
*/
public static PackageName of(String value) {
checkNotNull(value);
- PackageName result = new PackageName(value);
+ var result = new PackageName(value);
return result;
}
@@ -62,8 +62,8 @@ public static PackageName of(String value) {
*/
public static PackageName of(Descriptor message) {
checkNotNull(message);
- PackageName result = of(message.getFile()
- .getPackage());
+ var result = of(message.getFile()
+ .getPackage());
return result;
}
@@ -88,7 +88,7 @@ public static String delimiter() {
*/
public boolean isInnerOf(PackageName parentCandidate) {
checkNotNull(parentCandidate);
- boolean result = value().startsWith(parentCandidate.value());
+ var result = value().startsWith(parentCandidate.value());
return result;
}
diff --git a/base/src/main/java/io/spine/code/proto/ProtoBelongsToModule.java b/base/src/main/java/io/spine/code/proto/ProtoBelongsToModule.java
index 59904c4686..e8b18a946d 100644
--- a/base/src/main/java/io/spine/code/proto/ProtoBelongsToModule.java
+++ b/base/src/main/java/io/spine/code/proto/ProtoBelongsToModule.java
@@ -44,9 +44,8 @@ public abstract class ProtoBelongsToModule implements Predicate {
@Override
public boolean test(SourceFile file) {
- Path filePath = resolve(file);
- boolean exists = filePath.toFile()
- .exists();
+ var filePath = resolve(file);
+ var exists = filePath.toFile().exists();
logger.atFinest()
.log("Checking if the file `%s` exists, result: `%b`.", filePath, exists);
return exists;
@@ -55,6 +54,7 @@ public boolean test(SourceFile file) {
/**
* Obtains this predicate operating with {@link FileDescriptor} instead of {@link SourceFile}.
*/
+ @SuppressWarnings("unused") /* Part of the public API. */
public Predicate forDescriptor() {
Predicate result = descriptor -> test(SourceFile.from(descriptor));
return result;
diff --git a/base/src/main/java/io/spine/code/proto/RejectionsFile.java b/base/src/main/java/io/spine/code/proto/RejectionsFile.java
index 1430593ce7..0d0e52b87b 100644
--- a/base/src/main/java/io/spine/code/proto/RejectionsFile.java
+++ b/base/src/main/java/io/spine/code/proto/RejectionsFile.java
@@ -28,13 +28,11 @@
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
-import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
import io.spine.base.RejectionType;
import io.spine.code.java.SimpleClassName;
import java.util.List;
-import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -67,12 +65,12 @@ public static RejectionsFile from(SourceFile file) {
checkNotNull(file);
checkMatchesConvention(file);
- RejectionsFile result = new RejectionsFile(file.descriptor());
+ var result = new RejectionsFile(file.descriptor());
return result;
}
private static void checkMatchesConvention(SourceFile file) {
- FileDescriptor descriptor = file.descriptor();
+ var descriptor = file.descriptor();
checkArgument(isRejections(descriptor),
"`%s`. A rejection file must have a name ending in `rejections.proto`.",
file);
@@ -80,7 +78,7 @@ private static void checkMatchesConvention(SourceFile file) {
"`%s`. A rejection file should generate Java classes into a single file. " +
"Please set `java_multiple_files` to `false`.",
file);
- Optional outerClass = SimpleClassName.declaredOuterClassName(descriptor);
+ var outerClass = SimpleClassName.declaredOuterClassName(descriptor);
outerClass.ifPresent(name -> checkArgument(
isValidOuterClassName(name),
"%s. A rejection file must have the `java_outer_classname` ending in " +
@@ -92,11 +90,12 @@ private static void checkMatchesConvention(SourceFile file) {
/**
* Obtains rejection messages declared in the file.
*/
+ @SuppressWarnings("unused") /* Part of the public API. */
public List rejectionDeclarations() {
ImmutableList.Builder result = ImmutableList.builder();
- FileDescriptor file = descriptor();
- for (Descriptor type : file.getMessageTypes()) {
- RejectionType declaration = new RejectionType(type);
+ var file = descriptor();
+ for (var type : file.getMessageTypes()) {
+ var declaration = new RejectionType(type);
result.add(declaration);
}
return result.build();
@@ -110,16 +109,16 @@ private static boolean isRejections(FileDescriptor file) {
/**
* Obtains rejection files from the passed set of files.
*/
+ @SuppressWarnings("unused") /* Part of the public API. */
public static ImmutableSet findAll(FileSet fileSet) {
- ImmutableSet result =
- fileSet.files()
- .stream()
- .filter(RejectionsFile::isRejections)
- .map(file -> {
- SourceFile sourceFile = SourceFile.from(file);
- return from(sourceFile);
- })
- .collect(toImmutableSet());
+ checkNotNull(fileSet);
+ var result = fileSet.files().stream()
+ .filter(RejectionsFile::isRejections)
+ .map(file -> {
+ var sourceFile = SourceFile.from(file);
+ return from(sourceFile);
+ })
+ .collect(toImmutableSet());
return result;
}
}
diff --git a/base/src/main/java/io/spine/code/proto/ScalarType.java b/base/src/main/java/io/spine/code/proto/ScalarType.java
index 1baf8dde87..3dd64a28f2 100644
--- a/base/src/main/java/io/spine/code/proto/ScalarType.java
+++ b/base/src/main/java/io/spine/code/proto/ScalarType.java
@@ -88,7 +88,7 @@ public static String javaTypeName(Type protoScalar) {
* @return the corresponding Java type
*/
public static Class> javaType(Type protoScalar) {
- for (ScalarType scalarType : values()) {
+ for (var scalarType : values()) {
if (scalarType.protoScalarType == protoScalar) {
return scalarType.javaClass;
}
@@ -112,8 +112,8 @@ public static boolean isScalarType(FieldDescriptorProto field) {
* @see #isScalarType(com.google.protobuf.DescriptorProtos.FieldDescriptorProto)
*/
public static Optional of(FieldDescriptorProto field) {
- Type type = field.getType();
- for (ScalarType scalarType : values()) {
+ var type = field.getType();
+ for (var scalarType : values()) {
if (scalarType.protoScalarType() == type) {
return Optional.of(scalarType);
}
diff --git a/base/src/main/java/io/spine/code/proto/SourceFile.java b/base/src/main/java/io/spine/code/proto/SourceFile.java
index ccc61f7d4b..2766743dcd 100644
--- a/base/src/main/java/io/spine/code/proto/SourceFile.java
+++ b/base/src/main/java/io/spine/code/proto/SourceFile.java
@@ -28,7 +28,6 @@
import com.google.common.collect.ImmutableList;
import com.google.protobuf.DescriptorProtos.DescriptorProto;
-import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
import io.spine.base.RejectionType;
import io.spine.code.fs.AbstractSourceFile;
@@ -40,7 +39,6 @@
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
-import java.util.Optional;
import java.util.function.Predicate;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -67,7 +65,7 @@ public static SourceFile from(FileDescriptor file) {
private static Path toPath(FileDescriptor file) {
checkNotNull(file);
- Path result = Paths.get(file.getName());
+ var result = Paths.get(file.getName());
return result;
}
@@ -93,15 +91,15 @@ public boolean isRejections() {
.getJavaMultipleFiles()) {
return false;
}
- Optional outerClass = SimpleClassName.declaredOuterClassName(descriptor);
+ var outerClass = SimpleClassName.declaredOuterClassName(descriptor);
- if (!outerClass.isPresent()) {
+ if (outerClass.isEmpty()) {
// There's no outer class name given in options.
// Assuming the file name ends with `rejections.proto`, it's a good rejections file.
return true;
}
- boolean result = RejectionType.isValidOuterClassName(outerClass.get());
+ var result = RejectionType.isValidOuterClassName(outerClass.get());
return result;
}
@@ -129,8 +127,8 @@ public List topLevelMessages() {
*/
public List allThat(Predicate predicate) {
ImmutableList.Builder result = ImmutableList.builder();
- for (Descriptor messageType : descriptor.getMessageTypes()) {
- MessageType declaration = new MessageType(messageType);
+ for (var messageType : descriptor.getMessageTypes()) {
+ var declaration = new MessageType(messageType);
_debug().log("Testing `%s` to match `%s`.", declaration, predicate);
if (predicate.test(messageType.toProto())) {
result.add(declaration);
diff --git a/base/src/main/java/io/spine/code/proto/SourceProtoBelongsToModule.java b/base/src/main/java/io/spine/code/proto/SourceProtoBelongsToModule.java
index 149a6a5d2a..9ced5ca7c0 100644
--- a/base/src/main/java/io/spine/code/proto/SourceProtoBelongsToModule.java
+++ b/base/src/main/java/io/spine/code/proto/SourceProtoBelongsToModule.java
@@ -34,6 +34,7 @@
/**
* A predicate determining if the given {@code .proto} source belongs to the specified module.
*/
+@SuppressWarnings("unused") /* Part of the public API. */
public final class SourceProtoBelongsToModule extends ProtoBelongsToModule {
/** An absolute path to the root folder for the {@code .proto} files in the module. */
@@ -47,7 +48,7 @@ public SourceProtoBelongsToModule(File rootDirectory) {
@Override
protected Path resolve(SourceFile file) {
- Path result = rootPath.resolve(file.path());
+ var result = rootPath.resolve(file.path());
return result;
}
}
diff --git a/base/src/main/java/io/spine/code/proto/TypeSet.java b/base/src/main/java/io/spine/code/proto/TypeSet.java
index 0538262a46..b1117b3469 100644
--- a/base/src/main/java/io/spine/code/proto/TypeSet.java
+++ b/base/src/main/java/io/spine/code/proto/TypeSet.java
@@ -85,9 +85,9 @@ private TypeSet(Builder builder) {
* Obtains message and enum types declared in the passed file.
*/
public static TypeSet from(FileDescriptor file) {
- TypeSet messages = MessageType.allFrom(file);
- TypeSet enums = EnumType.allFrom(file);
- TypeSet services = ServiceType.allFrom(file);
+ var messages = MessageType.allFrom(file);
+ var enums = EnumType.allFrom(file);
+ var services = ServiceType.allFrom(file);
return new TypeSet(messages.messageTypes, enums.enumTypes, services.serviceTypes);
}
@@ -95,8 +95,8 @@ public static TypeSet from(FileDescriptor file) {
* Obtains message and enum types declared in the files represented by the passed set.
*/
public static TypeSet from(FileSet fileSet) {
- TypeSet result = new TypeSet();
- for (FileDescriptor file : fileSet.files()) {
+ var result = new TypeSet();
+ for (var file : fileSet.files()) {
result = result.union(from(file));
}
return result;
@@ -105,10 +105,12 @@ public static TypeSet from(FileSet fileSet) {
/**
* Obtains message types declared in the passed file set.
*/
+ @SuppressWarnings("unused") /* Part of the public API. */
public static ImmutableCollection onlyMessages(FileSet fileSet) {
- TypeSet result = new TypeSet();
- for (FileDescriptor file : fileSet.files()) {
- TypeSet messageTypes = MessageType.allFrom(file);
+ checkNotNull(fileSet);
+ var result = new TypeSet();
+ for (var file : fileSet.files()) {
+ var messageTypes = MessageType.allFrom(file);
result = result.union(messageTypes);
}
return result.messageTypes.values();
@@ -117,8 +119,9 @@ public static ImmutableCollection onlyMessages(FileSet fileSet) {
/**
* Obtains message types declared in the passed file.
*/
+ @SuppressWarnings("unused") /* Part of the public API. */
public static ImmutableCollection onlyMessages(FileDescriptor file) {
- TypeSet typeSet = MessageType.allFrom(file);
+ var typeSet = MessageType.allFrom(file);
return typeSet.messageTypes.values();
}
@@ -126,10 +129,10 @@ public static ImmutableCollection onlyMessages(FileDescriptor file)
* Obtains the size of the set.
*/
public int size() {
- int messagesCount = messageTypes.size();
- int enumsCount = enumTypes.size();
- int servicesCount = serviceTypes.size();
- int result = messagesCount + enumsCount + servicesCount;
+ var messagesCount = messageTypes.size();
+ var enumsCount = enumTypes.size();
+ var servicesCount = serviceTypes.size();
+ var result = messagesCount + enumsCount + servicesCount;
return result;
}
@@ -168,7 +171,7 @@ public int size() {
* @see #find(TypeName)
*/
public boolean contains(TypeName typeName) {
- boolean result = find(typeName).isPresent();
+ var result = find(typeName).isPresent();
return result;
}
@@ -176,7 +179,7 @@ public boolean contains(TypeName typeName) {
* Verifies if the set is empty.
*/
public boolean isEmpty() {
- boolean empty = size() == 0;
+ var empty = size() == 0;
return empty;
}
@@ -184,7 +187,7 @@ public boolean isEmpty() {
* Writes all the types in this set into a {@link TypeRegistry}.
*/
public TypeRegistry toTypeRegistry() {
- TypeRegistry.Builder registry = TypeRegistry.newBuilder();
+ var registry = TypeRegistry.newBuilder();
messageTypes.values()
.stream()
.map(Type::descriptor)
@@ -202,19 +205,16 @@ public TypeSet union(TypeSet another) {
if (this.isEmpty()) {
return another;
}
- ImmutableMap messages =
- unite(this.messageTypes, another.messageTypes);
- ImmutableMap enums =
- unite(this.enumTypes, another.enumTypes);
- ImmutableMap services =
- unite(this.serviceTypes, another.serviceTypes);
- TypeSet result = new TypeSet(messages, enums, services);
+ var messages = unite(this.messageTypes, another.messageTypes);
+ var enums = unite(this.enumTypes, another.enumTypes);
+ var services = unite(this.serviceTypes, another.serviceTypes);
+ var result = new TypeSet(messages, enums, services);
return result;
}
private static > ImmutableMap
unite(Map left, Map right) {
- // Use HashMap instead of ImmutableMap.Builder to deal with duplicates.
+ // Use `HashMap` instead of `ImmutableMap.Builder` to deal with duplicates.
Map union = newHashMapWithExpectedSize(left.size() + right.size());
union.putAll(left);
union.putAll(right);
@@ -225,8 +225,7 @@ public TypeSet union(TypeSet another) {
* Obtains all the types contained in this set.
*/
public ImmutableSet> allTypes() {
- ImmutableSet> types = ImmutableSet
- .>builder()
+ var types = ImmutableSet.>builder()
.addAll(messagesAndEnums())
.addAll(serviceTypes.values())
.build();
@@ -237,8 +236,7 @@ public TypeSet union(TypeSet another) {
* Obtains message and enum types contained in this set.
*/
public Set> messagesAndEnums() {
- ImmutableSet> types = ImmutableSet
- .>builder()
+ var types = ImmutableSet.>builder()
.addAll(messageTypes.values())
.addAll(enumTypes.values())
.build();
@@ -274,7 +272,7 @@ public boolean equals(Object o) {
if (!(o instanceof TypeSet)) {
return false;
}
- TypeSet typeSet = (TypeSet) o;
+ var typeSet = (TypeSet) o;
return Objects.equal(messageTypes, typeSet.messageTypes) &&
Objects.equal(enumTypes, typeSet.enumTypes);
}
@@ -294,11 +292,10 @@ public String toString() {
}
private static String namesForDisplay(Map types) {
- return types.keySet()
- .stream()
- .map(TypeName::value)
- .sorted()
- .collect(joining(lineSeparator()));
+ return types.keySet().stream()
+ .map(TypeName::value)
+ .sorted()
+ .collect(joining(lineSeparator()));
}
/**
@@ -327,21 +324,21 @@ private Builder() {
@CanIgnoreReturnValue
public Builder add(MessageType type) {
- TypeName name = type.name();
+ var name = type.name();
messageTypes.put(name, type);
return this;
}
@CanIgnoreReturnValue
public Builder add(EnumType type) {
- TypeName name = type.name();
+ var name = type.name();
enumTypes.put(name, type);
return this;
}
@CanIgnoreReturnValue
public Builder add(ServiceType type) {
- TypeName name = type.name();
+ var name = type.name();
serviceTypes.put(name, type);
return this;
}
@@ -349,7 +346,7 @@ public Builder add(ServiceType type) {
@CanIgnoreReturnValue
public Builder addAll(Iterable types) {
checkNotNull(types);
- ImmutableMap map = uniqueIndex(types, MessageType::name);
+ var map = uniqueIndex(types, MessageType::name);
messageTypes.putAll(map);
return this;
}
diff --git a/base/src/main/java/io/spine/environment/Environment.java b/base/src/main/java/io/spine/environment/Environment.java
index 383806c492..1aa7652b75 100644
--- a/base/src/main/java/io/spine/environment/Environment.java
+++ b/base/src/main/java/io/spine/environment/Environment.java
@@ -28,7 +28,6 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
-import com.google.common.flogger.FluentLogger;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import io.spine.annotation.SPI;
import io.spine.logging.Logging;
@@ -176,9 +175,8 @@ private Environment(Environment copy) {
@CanIgnoreReturnValue
private Environment register(EnvironmentType type) {
if (!knownTypes.contains(type)) {
- ImmutableList currentlyKnown = knownTypes;
- knownTypes = ImmutableList
- .builder()
+ var currentlyKnown = knownTypes;
+ knownTypes = ImmutableList.builder()
.add(type)
.addAll(currentlyKnown)
.build();
@@ -248,8 +246,8 @@ public Environment createCopy() {
* @return whether the current environment type matches the specified one
*/
public boolean is(Class extends EnvironmentType> type) {
- Class extends EnvironmentType> current = type();
- boolean result = type.isAssignableFrom(current);
+ var current = type();
+ var result = type.isAssignableFrom(current);
return result;
}
@@ -274,13 +272,12 @@ public Class extends EnvironmentType> type() {
}
private Class extends EnvironmentType> firstEnabled() {
- EnvironmentType result =
- knownTypes.stream()
- .filter(EnvironmentType::enabled)
- .findFirst()
- .orElseThrow(() -> newIllegalStateException(
- "`Environment` could not find an active environment type."
- ));
+ var result = knownTypes.stream()
+ .filter(EnvironmentType::enabled)
+ .findFirst()
+ .orElseThrow(() -> newIllegalStateException(
+ "`Environment` could not find an active environment type."
+ ));
return result.getClass();
}
@@ -306,7 +303,7 @@ public void setTo(Class extends EnvironmentType> type) {
checkNotNull(type);
if (CustomEnvironmentType.class.isAssignableFrom(type)) {
@SuppressWarnings("unchecked") // checked one line above
- Class extends CustomEnvironmentType> customType =
+ var customType =
(Class extends CustomEnvironmentType>) type;
register(customType);
}
@@ -318,7 +315,7 @@ private void setCurrentType(@Nullable Class extends EnvironmentType> newCurren
this.currentType = newCurrent;
@SuppressWarnings("FloggerSplitLogStatement")
// See: https://github.com/SpineEventEngine/base/issues/612
- FluentLogger.Api info = _info();
+ var info = _info();
if (previous == null) {
if (newCurrent != null) {
info.log("`Environment` set to `%s`.", newCurrent.getName());
@@ -327,9 +324,9 @@ private void setCurrentType(@Nullable Class extends EnvironmentType> newCurren
if (previous.equals(newCurrent)) {
info.log("`Environment` stays `%s`.", newCurrent.getName());
} else {
- String newType = newCurrent != null
- ? backtick(newCurrent.getName())
- : "undefined";
+ var newType = newCurrent != null
+ ? backtick(newCurrent.getName())
+ : "undefined";
info.log("`Environment` turned from `%s` to %s.", previous.getName(), newType);
}
}
diff --git a/base/src/main/java/io/spine/environment/EnvironmentType.java b/base/src/main/java/io/spine/environment/EnvironmentType.java
index 4c00965ed5..25ee1a8cdc 100644
--- a/base/src/main/java/io/spine/environment/EnvironmentType.java
+++ b/base/src/main/java/io/spine/environment/EnvironmentType.java
@@ -67,7 +67,7 @@ public final boolean equals(Object obj) {
if (obj == null) {
return false;
}
- boolean result = getClass().equals(obj.getClass());
+ var result = getClass().equals(obj.getClass());
return result;
}
}
diff --git a/base/src/main/java/io/spine/environment/Production.java b/base/src/main/java/io/spine/environment/Production.java
index b7c1f2ff03..4684807922 100644
--- a/base/src/main/java/io/spine/environment/Production.java
+++ b/base/src/main/java/io/spine/environment/Production.java
@@ -52,8 +52,7 @@ private Production() {
@Override
protected boolean enabled() {
- boolean tests = Tests.type()
- .enabled();
+ var tests = Tests.type().enabled();
return !tests;
}
}
diff --git a/base/src/main/java/io/spine/environment/Tests.java b/base/src/main/java/io/spine/environment/Tests.java
index 53437e8386..860beea404 100644
--- a/base/src/main/java/io/spine/environment/Tests.java
+++ b/base/src/main/java/io/spine/environment/Tests.java
@@ -91,15 +91,14 @@ private Tests() {
*/
@Override
protected boolean enabled() {
- TestsProperty property = new TestsProperty();
+ var property = new TestsProperty();
if (property.isSet()) {
return property.value();
}
- String stacktrace = Throwables.getStackTraceAsString(new RuntimeException(""));
- boolean result =
- knownTestingFrameworks().stream()
- .anyMatch(stacktrace::contains);
+ var stacktrace = Throwables.getStackTraceAsString(new RuntimeException(""));
+ var result = knownTestingFrameworks().stream()
+ .anyMatch(stacktrace::contains);
return result;
}
}
diff --git a/base/src/main/java/io/spine/environment/TestsProperty.java b/base/src/main/java/io/spine/environment/TestsProperty.java
index 9d169f1e0d..934c4005bf 100644
--- a/base/src/main/java/io/spine/environment/TestsProperty.java
+++ b/base/src/main/java/io/spine/environment/TestsProperty.java
@@ -76,7 +76,7 @@ final class TestsProperty {
private final @Nullable String value;
TestsProperty() {
- String propValue = System.getProperty(KEY);
+ var propValue = System.getProperty(KEY);
if (propValue != null) {
propValue = QUOTES_OR_SPACE.matcher(propValue)
.replaceAll("");
@@ -99,8 +99,8 @@ boolean isSet() {
*/
boolean value() {
checkState(value != null);
- boolean result = TESTS_VALUES.stream()
- .anyMatch(value::equalsIgnoreCase);
+ var result = TESTS_VALUES.stream()
+ .anyMatch(value::equalsIgnoreCase);
return result;
}
diff --git a/base/src/main/java/io/spine/io/Copy.java b/base/src/main/java/io/spine/io/Copy.java
index 75e2bc1331..581aa64a71 100644
--- a/base/src/main/java/io/spine/io/Copy.java
+++ b/base/src/main/java/io/spine/io/Copy.java
@@ -33,7 +33,6 @@
import java.nio.file.attribute.BasicFileAttributes;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
-import java.util.stream.Stream;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.spine.io.IoPreconditions.checkIsDirectory;
@@ -140,19 +139,19 @@ private static void doCopy(Path dir,
Path target,
Predicate matching,
boolean withEnclosingDir) throws IOException {
- Path oldParent = withEnclosingDir
+ var oldParent = withEnclosingDir
? dir.getParent()
: dir;
- ImmutableList paths = contentOf(dir, matching);
- for (Path path : paths) {
- Path relative = oldParent.relativize(path);
- Path newPath = target.resolve(relative);
+ var paths = contentOf(dir, matching);
+ for (var path : paths) {
+ var relative = oldParent.relativize(path);
+ var newPath = target.resolve(relative);
if (isDirectory(path)) {
if (!exists(newPath)) {
createDirectories(newPath);
}
} else if (isRegularFile(path)) {
- Path containingDir = newPath.getParent();
+ var containingDir = newPath.getParent();
if (!exists(containingDir)) {
createDirectories(containingDir);
}
@@ -168,8 +167,8 @@ private static void doCopy(Path dir,
private static ImmutableList contentOf(Path dir, Predicate matching)
throws IOException {
BiPredicate predicate = (path, attrs) -> matching.test(path);
- try (Stream found = find(dir, Integer.MAX_VALUE, predicate)) {
- ImmutableList paths = found.collect(toImmutableList());
+ try (var found = find(dir, Integer.MAX_VALUE, predicate)) {
+ var paths = found.collect(toImmutableList());
return paths;
}
}
diff --git a/base/src/main/java/io/spine/io/Delete.java b/base/src/main/java/io/spine/io/Delete.java
index 20e6c67041..67fb9e2dc1 100644
--- a/base/src/main/java/io/spine/io/Delete.java
+++ b/base/src/main/java/io/spine/io/Delete.java
@@ -56,7 +56,7 @@ private Delete() {
*/
public static void deleteRecursivelyOnShutdownHook(Path directory) {
checkNotNull(directory);
- Runtime runtime = Runtime.getRuntime();
+ var runtime = Runtime.getRuntime();
runtime.addShutdownHook(new Thread(() -> deleteRecursively(directory)));
}
@@ -72,7 +72,7 @@ public static void deleteRecursivelyOnShutdownHook(Path directory) {
*/
@CanIgnoreReturnValue
public static boolean deleteRecursively(Path directory) {
- boolean success = FilesKt.deleteRecursively(directory.toFile());
+ var success = FilesKt.deleteRecursively(directory.toFile());
if (!success) {
logger.atWarning()
.log("Unable to delete the directory `%s`.", directory);
diff --git a/base/src/main/java/io/spine/io/Files2.java b/base/src/main/java/io/spine/io/Files2.java
index 537a58e46d..01c2636cf3 100644
--- a/base/src/main/java/io/spine/io/Files2.java
+++ b/base/src/main/java/io/spine/io/Files2.java
@@ -27,7 +27,6 @@
package io.spine.io;
import java.io.File;
-import java.nio.file.Path;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -48,18 +47,19 @@ public static boolean existsNonEmpty(File file) {
if (!file.exists()) {
return false;
}
- boolean nonEmpty = file.length() > 0;
+ var nonEmpty = file.length() > 0;
return nonEmpty;
}
/**
* Normalizes and transforms the passed path to an absolute file reference.
*/
+ @SuppressWarnings("unused") /* Part of the public API. */
public static File toAbsolute(String path) {
checkNotNull(path);
- File file = new File(path);
- Path normalized = file.toPath().normalize();
- File result = normalized.toAbsolutePath().toFile();
+ var file = new File(path);
+ var normalized = file.toPath().normalize();
+ var result = normalized.toAbsolutePath().toFile();
return result;
}
diff --git a/base/src/main/java/io/spine/io/IoPreconditions.java b/base/src/main/java/io/spine/io/IoPreconditions.java
index 57dde12d72..bceb763bfd 100644
--- a/base/src/main/java/io/spine/io/IoPreconditions.java
+++ b/base/src/main/java/io/spine/io/IoPreconditions.java
@@ -72,7 +72,7 @@ public static File checkExists(File file) throws IllegalStateException {
@CanIgnoreReturnValue
public static Path checkExists(Path path) throws IllegalArgumentException {
checkNotNull(path);
- File file = path.toFile();
+ var file = path.toFile();
checkArgument(file.exists(), DOES_NOT_EXIST, file);
return path;
}
diff --git a/base/src/main/java/io/spine/io/Resource.java b/base/src/main/java/io/spine/io/Resource.java
index 2e1c7304cd..e27c7ef2ed 100644
--- a/base/src/main/java/io/spine/io/Resource.java
+++ b/base/src/main/java/io/spine/io/Resource.java
@@ -28,7 +28,6 @@
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
-import com.google.common.collect.UnmodifiableIterator;
import com.google.common.io.CharStreams;
import java.io.BufferedReader;
@@ -82,9 +81,9 @@ public static Resource file(String path, ClassLoader classLoader) {
* @return the URLs to the resolved resource files
*/
public ImmutableList locateAll() {
- Enumeration resources = resourceEnumeration();
- UnmodifiableIterator iterator = Iterators.forEnumeration(resources);
- ImmutableList result = ImmutableList.copyOf(iterator);
+ var resources = resourceEnumeration();
+ var iterator = Iterators.forEnumeration(resources);
+ var result = ImmutableList.copyOf(iterator);
if (result.isEmpty()) {
throw cannotFind();
}
@@ -93,7 +92,7 @@ public ImmutableList locateAll() {
private Enumeration resourceEnumeration() {
try {
- Enumeration resources = resources();
+ var resources = resources();
return resources;
} catch (IOException e) {
throw illegalStateWithCauseOf(e);
@@ -110,7 +109,7 @@ private Enumeration resourceEnumeration() {
* @return new {@link InputStream}
*/
public InputStream open() {
- URL resource = locate();
+ var resource = locate();
try {
return resource.openStream();
} catch (IOException e) {
diff --git a/base/src/main/java/io/spine/io/ResourceDirectory.java b/base/src/main/java/io/spine/io/ResourceDirectory.java
index b3501cb024..1616837d36 100644
--- a/base/src/main/java/io/spine/io/ResourceDirectory.java
+++ b/base/src/main/java/io/spine/io/ResourceDirectory.java
@@ -78,7 +78,7 @@ public Path toPath() {
@Nullable URL url = locate();
checkState(url != null, "Unable to locate resource directory: `%s`.", path());
try {
- Path result = Paths.get(url.toURI());
+ var result = Paths.get(url.toURI());
return result;
} catch (URISyntaxException e) {
throw illegalStateWithCauseOf(e);
@@ -111,7 +111,7 @@ public void copyContentTo(Path target) throws IOException {
public void copyContentTo(Path target, Predicate matching) throws IOException {
checkTarget(target);
checkNotNull(matching);
- Path from = toPath();
+ var from = toPath();
copyContent(from, target, matching);
}
@@ -139,7 +139,7 @@ public void copyTo(Path target) throws IOException {
public void copyTo(Path target, Predicate matching) throws IOException {
checkTarget(target);
checkNotNull(matching);
- Path from = toPath();
+ var from = toPath();
copyDir(from, target, matching);
}
diff --git a/base/src/main/java/io/spine/io/ResourceObject.java b/base/src/main/java/io/spine/io/ResourceObject.java
index 6ba4b7de72..7c4e22b749 100644
--- a/base/src/main/java/io/spine/io/ResourceObject.java
+++ b/base/src/main/java/io/spine/io/ResourceObject.java
@@ -118,7 +118,7 @@ public boolean equals(Object o) {
if (!(o instanceof ResourceObject)) {
return false;
}
- ResourceObject other = (ResourceObject) o;
+ var other = (ResourceObject) o;
return path.equals(other.path);
}
diff --git a/base/src/main/java/io/spine/json/Json.java b/base/src/main/java/io/spine/json/Json.java
index c5d9401e6b..ffab33465e 100644
--- a/base/src/main/java/io/spine/json/Json.java
+++ b/base/src/main/java/io/spine/json/Json.java
@@ -85,7 +85,7 @@ private Json() {
*/
public static String toJson(Message message) {
checkNotNull(message);
- String result = toJson(message, printer);
+ var result = toJson(message, printer);
return result;
}
@@ -100,7 +100,7 @@ public static String toJson(Message message) {
*/
public static String toCompactJson(Message message) {
checkNotNull(message);
- String result = toJson(message, compactPrinter);
+ var result = toJson(message, compactPrinter);
return result;
}
@@ -109,7 +109,7 @@ private static String toJson(Message message, Printer printer) {
try {
result = printer.print(message);
} catch (InvalidProtocolBufferException e) {
- Throwable rootCause = getRootCause(e);
+ var rootCause = getRootCause(e);
throw new UnknownTypeException(rootCause);
}
checkState(result != null);
@@ -121,9 +121,9 @@ public static T fromJson(String json, Class messageClass)
checkNotNull(json);
checkNotNull(messageClass);
try {
- Message.Builder messageBuilder = builderFor(messageClass);
+ var messageBuilder = builderFor(messageClass);
parser.merge(json, messageBuilder);
- T result = (T) messageBuilder.build();
+ var result = (T) messageBuilder.build();
return result;
} catch (InvalidProtocolBufferException e) {
throw newIllegalArgumentException(
diff --git a/base/src/main/java/io/spine/logging/FloggerClassValue.java b/base/src/main/java/io/spine/logging/FloggerClassValue.java
index 8bed569ef5..35134bd5f4 100644
--- a/base/src/main/java/io/spine/logging/FloggerClassValue.java
+++ b/base/src/main/java/io/spine/logging/FloggerClassValue.java
@@ -60,10 +60,9 @@ private FloggerClassValue() {
}
private static Constructor ctor() {
- Class loggerBackendClass = LoggerBackend.class;
+ var loggerBackendClass = LoggerBackend.class;
try {
- Constructor constructor =
- FluentLogger.class.getDeclaredConstructor(loggerBackendClass);
+ var constructor = FluentLogger.class.getDeclaredConstructor(loggerBackendClass);
constructor.setAccessible(true);
return constructor;
} catch (NoSuchMethodException e) {
@@ -78,9 +77,9 @@ private static Constructor ctor() {
@Override
protected FluentLogger computeValue(Class> type) {
checkNotNull(type);
- LoggerBackend backend = Platform.getBackend(type.getName());
+ var backend = Platform.getBackend(type.getName());
try {
- FluentLogger logger = constructor.newInstance(backend);
+ var logger = constructor.newInstance(backend);
return logger;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
logger.atSevere()
diff --git a/base/src/main/java/io/spine/protobuf/AnyPacker.java b/base/src/main/java/io/spine/protobuf/AnyPacker.java
index 3859ca42a8..e5dd1d3e11 100644
--- a/base/src/main/java/io/spine/protobuf/AnyPacker.java
+++ b/base/src/main/java/io/spine/protobuf/AnyPacker.java
@@ -72,9 +72,9 @@ public static Any pack(Message message) {
if (message instanceof Any) {
return (Any) message;
}
- TypeUrl typeUrl = TypeUrl.from(message.getDescriptorForType());
- String typeUrlPrefix = typeUrl.prefix();
- Any result = Any.pack(message, typeUrlPrefix);
+ var typeUrl = TypeUrl.from(message.getDescriptorForType());
+ var typeUrlPrefix = typeUrl.prefix();
+ var result = Any.pack(message, typeUrlPrefix);
return result;
}
@@ -87,7 +87,7 @@ public static Any pack(Message message) {
*/
public static Message unpack(Any any) {
checkNotNull(any);
- TypeUrl typeUrl = TypeUrl.ofEnclosed(any);
+ var typeUrl = TypeUrl.ofEnclosed(any);
Class extends Message> messageClass = typeUrl.getMessageClass();
return unpack(any, messageClass);
}
@@ -116,14 +116,13 @@ public static T unpack(Any any, Class cls) {
checkNotNull(any);
checkNotNull(cls);
- T defaultInstance = Messages.defaultInstance(cls);
- TypeUrl expectedTypeUrl = TypeUrl.of(defaultInstance);
+ var defaultInstance = Messages.defaultInstance(cls);
+ var expectedTypeUrl = TypeUrl.of(defaultInstance);
checkType(any, expectedTypeUrl);
try {
@SuppressWarnings("unchecked") // Ensured by the check above.
- T result = (T) defaultInstance
- .getParserForType()
- .parseFrom(any.getValue());
+ var result = (T) defaultInstance.getParserForType()
+ .parseFrom(any.getValue());
return result;
} catch (InvalidProtocolBufferException e) {
throw new UnexpectedTypeException(e);
@@ -164,10 +163,10 @@ public static Iterator pack(Iterator iterator) {
public static Function<@Nullable Any, @Nullable T>
unpackFunc(Class type) {
checkNotNull(type);
- T defaultInstance = Messages.defaultInstance(type);
+ var defaultInstance = Messages.defaultInstance(type);
@SuppressWarnings("unchecked")
- Parser parser = (Parser) defaultInstance.getParserForType();
- TypeUrl expectedTypeUrl = TypeUrl.of(defaultInstance);
+ var parser = (Parser) defaultInstance.getParserForType();
+ var expectedTypeUrl = TypeUrl.of(defaultInstance);
return any -> any == null
? null
: parseMessage(parser, expectedTypeUrl, any);
@@ -177,7 +176,7 @@ public static Iterator pack(Iterator iterator) {
parseMessage(Parser parser, TypeUrl expectedTypeUrl, Any any) {
checkType(any, expectedTypeUrl);
try {
- T message = parser.parseFrom(any.getValue());
+ var message = parser.parseFrom(any.getValue());
return message;
} catch (InvalidProtocolBufferException e) {
throw new UnexpectedTypeException(e);
@@ -185,7 +184,7 @@ public static Iterator pack(Iterator iterator) {
}
private static void checkType(Any any, TypeUrl expectedType) {
- TypeUrl actualType = TypeUrl.ofEnclosed(any);
+ var actualType = TypeUrl.ofEnclosed(any);
if (!actualType.equals(expectedType)) {
throw new UnexpectedTypeException(expectedType, actualType);
}
diff --git a/base/src/main/java/io/spine/protobuf/BytesConverter.java b/base/src/main/java/io/spine/protobuf/BytesConverter.java
index aa071fa075..d3ac581dd5 100644
--- a/base/src/main/java/io/spine/protobuf/BytesConverter.java
+++ b/base/src/main/java/io/spine/protobuf/BytesConverter.java
@@ -36,14 +36,13 @@ final class BytesConverter extends ProtoConverter {
@Override
protected ByteString toObject(BytesValue input) {
- ByteString result = input.getValue();
+ var result = input.getValue();
return result;
}
@Override
protected BytesValue toMessage(ByteString input) {
- BytesValue bytes = BytesValue
- .newBuilder()
+ var bytes = BytesValue.newBuilder()
.setValue(input)
.build();
return bytes;
diff --git a/base/src/main/java/io/spine/protobuf/Diff.java b/base/src/main/java/io/spine/protobuf/Diff.java
index fcab76b695..8e1a2885de 100644
--- a/base/src/main/java/io/spine/protobuf/Diff.java
+++ b/base/src/main/java/io/spine/protobuf/Diff.java
@@ -28,12 +28,10 @@
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;
-import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Message;
import io.spine.annotation.Internal;
import io.spine.code.proto.FieldDeclaration;
-import java.util.Map;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
@@ -77,19 +75,16 @@ public static Diff between(M a, M b) {
checkNotNull(a);
checkNotNull(b);
checkArgument(a.getClass().equals(b.getClass()));
- ImmutableSet fields =
- symmetricDifference(decompose(a), decompose(b))
- .stream()
- .map(tuple -> tuple.declaration)
- .collect(toImmutableSet());
+ var fields = symmetricDifference(decompose(a), decompose(b)).stream()
+ .map(tuple -> tuple.declaration)
+ .collect(toImmutableSet());
return new Diff(fields);
}
private static Set decompose(Message message) {
- Map fieldMap = message.getAllFields();
- return fieldMap
- .entrySet()
- .stream()
+ var fieldMap = message.getAllFields();
+ var entries = fieldMap.entrySet();
+ return entries.stream()
.map(entry -> new FieldTuple(
new FieldDeclaration(entry.getKey()), entry.getValue()
))
@@ -129,7 +124,7 @@ public boolean equals(Object o) {
if (!(o instanceof FieldTuple)) {
return false;
}
- FieldTuple tuple = (FieldTuple) o;
+ var tuple = (FieldTuple) o;
return Objects.equal(declaration, tuple.declaration) &&
Objects.equal(value, tuple.value);
}
diff --git a/base/src/main/java/io/spine/protobuf/Durations2.java b/base/src/main/java/io/spine/protobuf/Durations2.java
index 0ef2c0e083..2ba700a993 100644
--- a/base/src/main/java/io/spine/protobuf/Durations2.java
+++ b/base/src/main/java/io/spine/protobuf/Durations2.java
@@ -148,7 +148,7 @@ public static Duration add(@Nullable Duration d1, @Nullable Duration d2) {
if (d2 == null) {
return d1;
}
- Duration result = Durations.add(d1, d2);
+ var result = Durations.add(d1, d2);
return result;
}
@@ -157,7 +157,7 @@ public static Duration add(@Nullable Duration d1, @Nullable Duration d2) {
* {@code Duration} instance with hours and minutes.
*/
public static Duration hoursAndMinutes(long hours, long minutes) {
- Duration result = add(hours(hours), minutes(minutes));
+ var result = add(hours(hours), minutes(minutes));
return result;
}
@@ -167,8 +167,8 @@ public static Duration hoursAndMinutes(long hours, long minutes) {
*/
public static boolean isPositiveOrZero(Duration value) {
checkNotNull(value);
- long millis = toMillis(value);
- boolean result = millis >= 0;
+ var millis = toMillis(value);
+ var result = millis >= 0;
return result;
}
@@ -178,9 +178,9 @@ public static boolean isPositiveOrZero(Duration value) {
*/
public static boolean isPositive(Duration value) {
checkNotNull(value);
- boolean secondsPositive = value.getSeconds() > 0;
- boolean nanosPositive = value.getNanos() > 0;
- boolean result = secondsPositive || nanosPositive;
+ var secondsPositive = value.getSeconds() > 0;
+ var nanosPositive = value.getNanos() > 0;
+ var result = secondsPositive || nanosPositive;
return result;
}
@@ -188,9 +188,9 @@ public static boolean isPositive(Duration value) {
/** Returns {@code true} if the passed value is zero, {@code false} otherwise. */
public static boolean isZero(Duration value) {
checkNotNull(value);
- boolean noSeconds = value.getSeconds() == 0;
- boolean noNanos = value.getNanos() == 0;
- boolean result = noSeconds && noNanos;
+ var noSeconds = value.getSeconds() == 0;
+ var noNanos = value.getNanos() == 0;
+ var result = noSeconds && noNanos;
return result;
}
@@ -199,7 +199,7 @@ public static boolean isZero(Duration value) {
* {@code false} otherwise.
*/
public static boolean isGreaterThan(Duration value, Duration another) {
- boolean result = compare(value, another) > 0;
+ var result = compare(value, another) > 0;
return result;
}
@@ -208,7 +208,7 @@ public static boolean isGreaterThan(Duration value, Duration another) {
* {@code false} otherwise.
*/
public static boolean isLessThan(Duration value, Duration another) {
- boolean result = compare(value, another) < 0;
+ var result = compare(value, another) < 0;
return result;
}
@@ -228,7 +228,7 @@ public static boolean isNegative(Duration value) {
*/
public static Duration of(java.time.Duration value) {
checkNotNull(value);
- Duration result = converter().convert(value);
+ var result = converter().convert(value);
return requireNonNull(result);
}
@@ -238,7 +238,7 @@ public static Duration of(java.time.Duration value) {
@SuppressWarnings("unused")
public static java.time.Duration toJavaTime(Duration value) {
checkNotNull(value);
- java.time.Duration result =
+ var result =
converter().reverse()
.convert(value);
return requireNonNull(result);
@@ -255,10 +255,9 @@ public static java.time.Duration toJavaTime(Duration value) {
*/
public static Duration parse(String str) {
checkNotNull(str);
- Duration result =
- Stringifiers.forDuration()
- .reverse()
- .convert(str);
+ var result = Stringifiers.forDuration()
+ .reverse()
+ .convert(str);
return requireNonNull(result);
}
diff --git a/base/src/main/java/io/spine/protobuf/EnumConverter.java b/base/src/main/java/io/spine/protobuf/EnumConverter.java
index cca4849fa1..aaa7bdb43c 100644
--- a/base/src/main/java/io/spine/protobuf/EnumConverter.java
+++ b/base/src/main/java/io/spine/protobuf/EnumConverter.java
@@ -58,9 +58,9 @@ final class EnumConverter extends ProtoConverter toObject(EnumValue input) {
- String name = input.getName();
+ var name = input.getName();
if (name.isEmpty()) {
- int number = input.getNumber();
+ var number = input.getNumber();
return findByNumber(number);
} else {
return findByName(name);
@@ -74,17 +74,17 @@ protected Enum extends ProtocolMessageEnum> toObject(EnumValue input) {
* if enum constant with such a number is not present
*/
private Enum extends ProtocolMessageEnum> findByNumber(int number) {
- Enum extends ProtocolMessageEnum>[] constants = type.getEnumConstants();
- for (Enum extends ProtocolMessageEnum> constant : constants) {
- boolean isUnrecognized = isUnrecognized(constant);
+ var constants = type.getEnumConstants();
+ for (var constant : constants) {
+ var isUnrecognized = isUnrecognized(constant);
if (isUnrecognized && number == -1) {
return constant;
}
if (isUnrecognized) {
continue;
}
- ProtocolMessageEnum asProtoEnum = (ProtocolMessageEnum) constant;
- int valueNumber = asProtoEnum.getNumber();
+ var asProtoEnum = (ProtocolMessageEnum) constant;
+ var valueNumber = asProtoEnum.getNumber();
if (number == valueNumber) {
return constant;
}
@@ -105,16 +105,15 @@ private static boolean isUnrecognized(Enum extends ProtocolMessageEnum> consta
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // Checked at runtime.
private Enum extends ProtocolMessageEnum> findByName(String name) {
- Enum result = Enum.valueOf((Class extends Enum>) type, name);
+ var result = Enum.valueOf((Class extends Enum>) type, name);
return (Enum extends ProtocolMessageEnum>) result;
}
@Override
protected EnumValue toMessage(Enum extends ProtocolMessageEnum> input) {
- String name = input.name();
- ProtocolMessageEnum asProtoEnum = (ProtocolMessageEnum) input;
- EnumValue value = EnumValue
- .newBuilder()
+ var name = input.name();
+ var asProtoEnum = (ProtocolMessageEnum) input;
+ var value = EnumValue.newBuilder()
.setName(name)
.setNumber(asProtoEnum.getNumber())
.build();
diff --git a/base/src/main/java/io/spine/protobuf/Messages.java b/base/src/main/java/io/spine/protobuf/Messages.java
index d14dce79c4..672eb198c7 100644
--- a/base/src/main/java/io/spine/protobuf/Messages.java
+++ b/base/src/main/java/io/spine/protobuf/Messages.java
@@ -44,6 +44,7 @@
public final class Messages {
/** The name of a message builder factory method. */
+ @SuppressWarnings("unused") /* Part of the public API. */
public static final String METHOD_NEW_BUILDER = "newBuilder";
/**
@@ -68,7 +69,7 @@ private Messages() {
public static M defaultInstance(Class messageClass) {
checkNotNull(messageClass);
@SuppressWarnings("unchecked") // Ensured by the `MessageCacheLoader` implementation.
- M result = (M) defaultInstances.getUnchecked(messageClass);
+ var result = (M) defaultInstances.getUnchecked(messageClass);
return result;
}
@@ -79,12 +80,12 @@ public static M defaultInstance(Class messageClass) {
public static Message.Builder builderFor(Class extends Message> cls) {
checkNotNull(cls);
try {
- Message message = defaultInstance(cls);
- Message.Builder builder = message.toBuilder();
+ var message = defaultInstance(cls);
+ var builder = message.toBuilder();
return builder;
} catch (UncheckedExecutionException e) {
- String errMsg = format("Class `%s` must be a generated proto message.",
- cls.getCanonicalName());
+ var errMsg = format("Class `%s` must be a generated proto message.",
+ cls.getCanonicalName());
throw new IllegalArgumentException(errMsg, e);
}
}
@@ -97,7 +98,7 @@ public static Message ensureMessage(Message msgOrAny) {
checkNotNull(msgOrAny);
Message commandMessage;
if (msgOrAny instanceof Any) {
- Any any = (Any) msgOrAny;
+ var any = (Any) msgOrAny;
commandMessage = AnyPacker.unpack(any);
} else {
commandMessage = msgOrAny;
@@ -120,8 +121,8 @@ private static LoadingCache, Message> loadingCache(int
*/
public static boolean isDefault(Message object) {
checkNotNull(object);
- boolean result = object.getDefaultInstanceForType()
- .equals(object);
+ var result = object.getDefaultInstanceForType()
+ .equals(object);
return result;
}
@@ -134,7 +135,7 @@ public static boolean isDefault(Message object) {
*/
public static boolean isNotDefault(Message object) {
checkNotNull(object);
- boolean result = !isDefault(object);
+ var result = !isDefault(object);
return result;
}
diff --git a/base/src/main/java/io/spine/protobuf/PackingIterator.java b/base/src/main/java/io/spine/protobuf/PackingIterator.java
index 7db2ce52f1..58857c4c2c 100644
--- a/base/src/main/java/io/spine/protobuf/PackingIterator.java
+++ b/base/src/main/java/io/spine/protobuf/PackingIterator.java
@@ -62,8 +62,8 @@ public boolean hasNext() {
*/
@Override
public Any next() {
- Message next = source.next();
- Any result = next != null
+ var next = source.next();
+ var result = next != null
? AnyPacker.pack(next)
: Any.getDefaultInstance();
return result;
diff --git a/base/src/main/java/io/spine/protobuf/PrimitiveConverter.java b/base/src/main/java/io/spine/protobuf/PrimitiveConverter.java
index f8fd5ef658..f8aeee1df4 100644
--- a/base/src/main/java/io/spine/protobuf/PrimitiveConverter.java
+++ b/base/src/main/java/io/spine/protobuf/PrimitiveConverter.java
@@ -39,6 +39,7 @@
import com.google.protobuf.UInt64Value;
import static com.google.common.base.Preconditions.checkArgument;
+import static java.util.Objects.requireNonNull;
/**
* Converts the primitive and built-in types to the corresponding {@link Message}s and back.
@@ -81,22 +82,22 @@ final class PrimitiveConverter extends ProtoConverter boxedType = input.getClass();
- Converter converter = wrapperConverter(boxedType);
- T result = converter.convert(input);
- return result;
+ var converter = wrapperConverter(boxedType);
+ var result = converter.convert(input);
+ return requireNonNull(result);
}
@Override
protected M toMessage(T input) {
- Class> cls = input.getClass();
- Converter converter = primitiveConverter(cls);
- M result = converter.convert(input);
- return result;
+ var cls = input.getClass();
+ var converter = primitiveConverter(cls);
+ var result = converter.convert(input);
+ return requireNonNull(result);
}
private Converter wrapperConverter(Class> boxedType) {
@SuppressWarnings("unchecked")
- Converter converter = (Converter) PROTO_WRAPPER_TO_CONVERTER.get(boxedType);
+ var converter = (Converter) PROTO_WRAPPER_TO_CONVERTER.get(boxedType);
checkArgument(
converter != null,
"Could not find a primitive type for `%s`.",
@@ -107,7 +108,7 @@ private Converter wrapperConverter(Class> boxedType) {
private Converter primitiveConverter(Class> cls) {
@SuppressWarnings("unchecked")
- Converter converter = (Converter) PRIMITIVE_TO_CONVERTER.get(cls);
+ var converter = (Converter) PRIMITIVE_TO_CONVERTER.get(cls);
checkArgument(
converter != null,
"Could not find a wrapper type for `%s`.",
@@ -125,8 +126,7 @@ protected Integer unwrap(Int32Value message) {
@Override
protected Int32Value wrap(Integer value) {
- return Int32Value
- .newBuilder()
+ return Int32Value.newBuilder()
.setValue(value)
.build();
}
@@ -141,8 +141,7 @@ protected Long unwrap(Int64Value message) {
@Override
protected Int64Value wrap(Long value) {
- return Int64Value
- .newBuilder()
+ return Int64Value.newBuilder()
.setValue(value)
.build();
}
@@ -189,8 +188,7 @@ protected Float unwrap(FloatValue message) {
@Override
protected FloatValue wrap(Float value) {
- return FloatValue
- .newBuilder()
+ return FloatValue.newBuilder()
.setValue(value)
.build();
}
@@ -205,8 +203,7 @@ protected Double unwrap(DoubleValue message) {
@Override
protected DoubleValue wrap(Double value) {
- return DoubleValue
- .newBuilder()
+ return DoubleValue.newBuilder()
.setValue(value)
.build();
}
@@ -221,8 +218,7 @@ protected Boolean unwrap(BoolValue message) {
@Override
protected BoolValue wrap(Boolean value) {
- return BoolValue
- .newBuilder()
+ return BoolValue.newBuilder()
.setValue(value)
.build();
}
@@ -237,8 +233,7 @@ protected String unwrap(StringValue message) {
@Override
protected StringValue wrap(String value) {
- return StringValue
- .newBuilder()
+ return StringValue.newBuilder()
.setValue(value)
.build();
}
diff --git a/base/src/main/java/io/spine/protobuf/ProtoConverter.java b/base/src/main/java/io/spine/protobuf/ProtoConverter.java
index a0caedb353..705ab21d31 100644
--- a/base/src/main/java/io/spine/protobuf/ProtoConverter.java
+++ b/base/src/main/java/io/spine/protobuf/ProtoConverter.java
@@ -72,7 +72,7 @@ static Converter forType(Class type) {
converter = new PrimitiveConverter<>();
}
@SuppressWarnings("unchecked") // Logically checked.
- Converter result = (Converter) converter;
+ var result = (Converter) converter;
return result;
}
diff --git a/base/src/main/java/io/spine/protobuf/TypeConverter.java b/base/src/main/java/io/spine/protobuf/TypeConverter.java
index 6425d3af2f..b3f1203369 100644
--- a/base/src/main/java/io/spine/protobuf/TypeConverter.java
+++ b/base/src/main/java/io/spine/protobuf/TypeConverter.java
@@ -37,6 +37,7 @@
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.protobuf.AnyPacker.unpack;
+import static java.util.Objects.requireNonNull;
/**
* A utility for converting the {@linkplain Message Protobuf Messages} (in form of {@link Any}) into
@@ -83,9 +84,9 @@ public static T toObject(Any message, Class target) {
checkNotNull(target);
checkNotRawEnum(message, target);
Converter super Message, T> converter = ProtoConverter.forType(target);
- Message genericMessage = unpack(message);
- T result = converter.convert(genericMessage);
- return result;
+ var genericMessage = unpack(message);
+ var result = converter.convert(genericMessage);
+ return requireNonNull(result);
}
/**
@@ -100,8 +101,8 @@ public static