You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@beam.apache.org by dh...@apache.org on 2016/03/24 03:48:10 UTC
[46/67] [partial] incubator-beam git commit: Directory reorganization
http://git-wip-us.apache.org/repos/asf/incubator-beam/blob/7bef2b7e/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VoidCoder.java
----------------------------------------------------------------------
diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VoidCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VoidCoder.java
deleted file mode 100644
index 0de606b..0000000
--- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/VoidCoder.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2015 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package com.google.cloud.dataflow.sdk.coders;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * A {@link Coder} for {@link Void}. Uses zero bytes per {@link Void}.
- */
-public class VoidCoder extends AtomicCoder<Void> {
-
- @JsonCreator
- public static VoidCoder of() {
- return INSTANCE;
- }
-
- /////////////////////////////////////////////////////////////////////////////
-
- private static final VoidCoder INSTANCE = new VoidCoder();
-
- private VoidCoder() {}
-
- @Override
- public void encode(Void value, OutputStream outStream, Context context) {
- // Nothing to write!
- }
-
- @Override
- public Void decode(InputStream inStream, Context context) {
- // Nothing to read!
- return null;
- }
-
- /**
- * {@inheritDoc}
- *
- * @return {@code true}. {@link VoidCoder} is (vacuously) injective.
- */
- @Override
- public boolean consistentWithEquals() {
- return true;
- }
-
- /**
- * {@inheritDoc}
- *
- * @return {@code true}. {@link VoidCoder#getEncodedElementByteSize} runs in constant time.
- */
- @Override
- public boolean isRegisterByteSizeObserverCheap(Void value, Context context) {
- return true;
- }
-
- @Override
- protected long getEncodedElementByteSize(Void value, Context context)
- throws Exception {
- return 0;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-beam/blob/7bef2b7e/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/package-info.java
----------------------------------------------------------------------
diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/package-info.java
deleted file mode 100644
index fdf931f..0000000
--- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/package-info.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2015 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-/**
- * Defines {@link com.google.cloud.dataflow.sdk.coders.Coder Coders}
- * to specify how data is encoded to and decoded from byte strings.
- *
- * <p>During execution of a Pipeline, elements in a
- * {@link com.google.cloud.dataflow.sdk.values.PCollection}
- * may need to be encoded into byte strings.
- * This happens both at the beginning and end of a pipeline when data is read from and written to
- * persistent storage and also during execution of a pipeline when elements are communicated between
- * machines.
- *
- * <p>Exactly when PCollection elements are encoded during execution depends on which
- * {@link com.google.cloud.dataflow.sdk.runners.PipelineRunner} is being used and how that runner
- * chooses to execute the pipeline. As such, Dataflow requires that all PCollections have an
- * appropriate Coder in case it becomes necessary. In many cases, the Coder can be inferred from
- * the available Java type
- * information and the Pipeline's {@link com.google.cloud.dataflow.sdk.coders.CoderRegistry}. It
- * can be specified per PCollection via
- * {@link com.google.cloud.dataflow.sdk.values.PCollection#setCoder(Coder)} or per type using the
- * {@link com.google.cloud.dataflow.sdk.coders.DefaultCoder} annotation.
- *
- * <p>This package provides a number of coders for common types like {@code Integer},
- * {@code String}, and {@code List}, as well as coders like
- * {@link com.google.cloud.dataflow.sdk.coders.AvroCoder} that can be used to encode many custom
- * types.
- *
- */
-package com.google.cloud.dataflow.sdk.coders;
http://git-wip-us.apache.org/repos/asf/incubator-beam/blob/7bef2b7e/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java
----------------------------------------------------------------------
diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java
deleted file mode 100644
index 111c24d..0000000
--- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtoCoder.java
+++ /dev/null
@@ -1,404 +0,0 @@
-/*
- * Copyright (C) 2015 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.cloud.dataflow.sdk.coders.protobuf;
-
-import static com.google.common.base.Preconditions.checkArgument;
-
-import com.google.cloud.dataflow.sdk.coders.AtomicCoder;
-import com.google.cloud.dataflow.sdk.coders.CannotProvideCoderException;
-import com.google.cloud.dataflow.sdk.coders.Coder;
-import com.google.cloud.dataflow.sdk.coders.CoderException;
-import com.google.cloud.dataflow.sdk.coders.CoderProvider;
-import com.google.cloud.dataflow.sdk.coders.CoderRegistry;
-import com.google.cloud.dataflow.sdk.util.CloudObject;
-import com.google.cloud.dataflow.sdk.util.Structs;
-import com.google.cloud.dataflow.sdk.values.PCollection;
-import com.google.cloud.dataflow.sdk.values.TypeDescriptor;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import com.google.protobuf.ExtensionRegistry;
-import com.google.protobuf.Message;
-import com.google.protobuf.Parser;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Objects;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import javax.annotation.Nullable;
-
-/**
- * A {@link Coder} using Google Protocol Buffers binary format. {@link ProtoCoder} supports both
- * Protocol Buffers syntax versions 2 and 3.
- *
- * <p>To learn more about Protocol Buffers, visit:
- * <a href="https://developers.google.com/protocol-buffers">https://developers.google.com/protocol-buffers</a>
- *
- * <p>{@link ProtoCoder} is registered in the global {@link CoderRegistry} as the default
- * {@link Coder} for any {@link Message} object. Custom message extensions are also supported, but
- * these extensions must be registered for a particular {@link ProtoCoder} instance and that
- * instance must be registered on the {@link PCollection} that needs the extensions:
- *
- * <pre>{@code
- * import MyProtoFile;
- * import MyProtoFile.MyMessage;
- *
- * Coder<MyMessage> coder = ProtoCoder.of(MyMessage.class).withExtensionsFrom(MyProtoFile.class);
- * PCollection<MyMessage> records = input.apply(...).setCoder(coder);
- * }</pre>
- *
- * <h3>Versioning</h3>
- *
- * <p>{@link ProtoCoder} supports both versions 2 and 3 of the Protocol Buffers syntax. However,
- * the Java runtime version of the <code>google.com.protobuf</code> library must match exactly the
- * version of <code>protoc</code> that was used to produce the JAR files containing the compiled
- * <code>.proto</code> messages.
- *
- * <p>For more information, see the
- * <a href="https://developers.google.com/protocol-buffers/docs/proto3#using-proto2-message-types">Protocol Buffers documentation</a>.
- *
- * <h3>{@link ProtoCoder} and Determinism</h3>
- *
- * <p>In general, Protocol Buffers messages can be encoded deterministically within a single
- * pipeline as long as:
- *
- * <ul>
- * <li>The encoded messages (and any transitively linked messages) do not use <code>map</code>
- * fields.</li>
- * <li>Every Java VM that encodes or decodes the messages use the same runtime version of the
- * Protocol Buffers library and the same compiled <code>.proto</code> file JAR.</li>
- * </ul>
- *
- * <h3>{@link ProtoCoder} and Encoding Stability</h3>
- *
- * <p>When changing Protocol Buffers messages, follow the rules in the Protocol Buffers language
- * guides for
- * <a href="https://developers.google.com/protocol-buffers/docs/proto#updating">{@code proto2}</a>
- * and
- * <a href="https://developers.google.com/protocol-buffers/docs/proto3#updating">{@code proto3}</a>
- * syntaxes, depending on your message type. Following these guidelines will ensure that the
- * old encoded data can be read by new versions of the code.
- *
- * <p>Generally, any change to the message type, registered extensions, runtime library, or
- * compiled proto JARs may change the encoding. Thus even if both the original and updated messages
- * can be encoded deterministically within a single job, these deterministic encodings may not be
- * the same across jobs.
- *
- * @param <T> the Protocol Buffers {@link Message} handled by this {@link Coder}.
- */
-public class ProtoCoder<T extends Message> extends AtomicCoder<T> {
-
- /**
- * A {@link CoderProvider} that returns a {@link ProtoCoder} with an empty
- * {@link ExtensionRegistry}.
- */
- public static CoderProvider coderProvider() {
- return PROVIDER;
- }
-
- /**
- * Returns a {@link ProtoCoder} for the given Protocol Buffers {@link Message}.
- */
- public static <T extends Message> ProtoCoder<T> of(Class<T> protoMessageClass) {
- return new ProtoCoder<T>(protoMessageClass, ImmutableSet.<Class<?>>of());
- }
-
- /**
- * Returns a {@link ProtoCoder} for the Protocol Buffers {@link Message} indicated by the given
- * {@link TypeDescriptor}.
- */
- public static <T extends Message> ProtoCoder<T> of(TypeDescriptor<T> protoMessageType) {
- @SuppressWarnings("unchecked")
- Class<T> protoMessageClass = (Class<T>) protoMessageType.getRawType();
- return of(protoMessageClass);
- }
-
- /**
- * Returns a {@link ProtoCoder} like this one, but with the extensions from the given classes
- * registered.
- *
- * <p>Each of the extension host classes must be an class automatically generated by the
- * Protocol Buffers compiler, {@code protoc}, that contains messages.
- *
- * <p>Does not modify this object.
- */
- public ProtoCoder<T> withExtensionsFrom(Iterable<Class<?>> moreExtensionHosts) {
- for (Class<?> extensionHost : moreExtensionHosts) {
- // Attempt to access the required method, to make sure it's present.
- try {
- Method registerAllExtensions =
- extensionHost.getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class);
- checkArgument(
- Modifier.isStatic(registerAllExtensions.getModifiers()),
- "Method registerAllExtensions() must be static");
- } catch (NoSuchMethodException | SecurityException e) {
- throw new IllegalArgumentException(
- String.format("Unable to register extensions for %s", extensionHost.getCanonicalName()),
- e);
- }
- }
-
- return new ProtoCoder<T>(
- protoMessageClass,
- new ImmutableSet.Builder<Class<?>>()
- .addAll(extensionHostClasses)
- .addAll(moreExtensionHosts)
- .build());
- }
-
- /**
- * See {@link #withExtensionsFrom(Iterable)}.
- *
- * <p>Does not modify this object.
- */
- public ProtoCoder<T> withExtensionsFrom(Class<?>... moreExtensionHosts) {
- return withExtensionsFrom(Arrays.asList(moreExtensionHosts));
- }
-
- @Override
- public void encode(T value, OutputStream outStream, Context context) throws IOException {
- if (value == null) {
- throw new CoderException("cannot encode a null " + protoMessageClass.getSimpleName());
- }
- if (context.isWholeStream) {
- value.writeTo(outStream);
- } else {
- value.writeDelimitedTo(outStream);
- }
- }
-
- @Override
- public T decode(InputStream inStream, Context context) throws IOException {
- if (context.isWholeStream) {
- return getParser().parseFrom(inStream, getExtensionRegistry());
- } else {
- return getParser().parseDelimitedFrom(inStream, getExtensionRegistry());
- }
- }
-
- @Override
- public boolean equals(Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof ProtoCoder)) {
- return false;
- }
- ProtoCoder<?> otherCoder = (ProtoCoder<?>) other;
- return protoMessageClass.equals(otherCoder.protoMessageClass)
- && Sets.newHashSet(extensionHostClasses)
- .equals(Sets.newHashSet(otherCoder.extensionHostClasses));
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(protoMessageClass, extensionHostClasses);
- }
-
- /**
- * The encoding identifier is designed to support evolution as per the design of Protocol
- * Buffers. In order to use this class effectively, carefully follow the advice in the Protocol
- * Buffers documentation at
- * <a href="https://developers.google.com/protocol-buffers/docs/proto#updating">Updating
- * A Message Type</a>.
- *
- * <p>In particular, the encoding identifier is guaranteed to be the same for {@link ProtoCoder}
- * instances of the same principal message class, with the same registered extension host classes,
- * and otherwise distinct. Note that the encoding ID does not encode any version of the message
- * or extensions, nor does it include the message schema.
- *
- * <p>When modifying a message class, here are the broadest guidelines; see the above link
- * for greater detail.
- *
- * <ul>
- * <li>Do not change the numeric tags for any fields.
- * <li>Never remove a <code>required</code> field.
- * <li>Only add <code>optional</code> or <code>repeated</code> fields, with sensible defaults.
- * <li>When changing the type of a field, consult the Protocol Buffers documentation to ensure
- * the new and old types are interchangeable.
- * </ul>
- *
- * <p>Code consuming this message class should be prepared to support <i>all</i> versions of
- * the class until it is certain that no remaining serialized instances exist.
- *
- * <p>If backwards incompatible changes must be made, the best recourse is to change the name
- * of your Protocol Buffers message class.
- */
- @Override
- public String getEncodingId() {
- return protoMessageClass.getName() + getSortedExtensionClasses().toString();
- }
-
- @Override
- public void verifyDeterministic() throws NonDeterministicException {
- ProtobufUtil.verifyDeterministic(this);
- }
-
- /**
- * Returns the Protocol Buffers {@link Message} type this {@link ProtoCoder} supports.
- */
- public Class<T> getMessageType() {
- return protoMessageClass;
- }
-
- /**
- * Returns the {@link ExtensionRegistry} listing all known Protocol Buffers extension messages
- * to {@code T} registered with this {@link ProtoCoder}.
- */
- public ExtensionRegistry getExtensionRegistry() {
- if (memoizedExtensionRegistry == null) {
- ExtensionRegistry registry = ExtensionRegistry.newInstance();
- for (Class<?> extensionHost : extensionHostClasses) {
- try {
- extensionHost
- .getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class)
- .invoke(null, registry);
- } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
- throw new IllegalStateException(e);
- }
- }
- memoizedExtensionRegistry = registry.getUnmodifiable();
- }
- return memoizedExtensionRegistry;
- }
-
- ////////////////////////////////////////////////////////////////////////////////////
- // Private implementation details below.
-
- /** The {@link Message} type to be coded. */
- private final Class<T> protoMessageClass;
-
- /**
- * All extension host classes included in this {@link ProtoCoder}. The extensions from these
- * classes will be included in the {@link ExtensionRegistry} used during encoding and decoding.
- */
- private final Set<Class<?>> extensionHostClasses;
-
- // Constants used to serialize and deserialize
- private static final String PROTO_MESSAGE_CLASS = "proto_message_class";
- private static final String PROTO_EXTENSION_HOSTS = "proto_extension_hosts";
-
- // Transient fields that are lazy initialized and then memoized.
- private transient ExtensionRegistry memoizedExtensionRegistry;
- private transient Parser<T> memoizedParser;
-
- /** Private constructor. */
- private ProtoCoder(Class<T> protoMessageClass, Set<Class<?>> extensionHostClasses) {
- this.protoMessageClass = protoMessageClass;
- this.extensionHostClasses = extensionHostClasses;
- }
-
- /**
- * @deprecated For JSON deserialization only.
- */
- @JsonCreator
- @Deprecated
- public static <T extends Message> ProtoCoder<T> of(
- @JsonProperty(PROTO_MESSAGE_CLASS) String protoMessageClassName,
- @Nullable @JsonProperty(PROTO_EXTENSION_HOSTS) List<String> extensionHostClassNames) {
-
- try {
- @SuppressWarnings("unchecked")
- Class<T> protoMessageClass = (Class<T>) Class.forName(protoMessageClassName);
- List<Class<?>> extensionHostClasses = Lists.newArrayList();
- if (extensionHostClassNames != null) {
- for (String extensionHostClassName : extensionHostClassNames) {
- extensionHostClasses.add(Class.forName(extensionHostClassName));
- }
- }
- return of(protoMessageClass).withExtensionsFrom(extensionHostClasses);
- } catch (ClassNotFoundException e) {
- throw new IllegalArgumentException(e);
- }
- }
-
- @Override
- public CloudObject asCloudObject() {
- CloudObject result = super.asCloudObject();
- Structs.addString(result, PROTO_MESSAGE_CLASS, protoMessageClass.getName());
- List<CloudObject> extensionHostClassNames = Lists.newArrayList();
- for (String className : getSortedExtensionClasses()) {
- extensionHostClassNames.add(CloudObject.forString(className));
- }
- Structs.addList(result, PROTO_EXTENSION_HOSTS, extensionHostClassNames);
- return result;
- }
-
- /** Get the memoized {@link Parser}, possibly initializing it lazily. */
- private Parser<T> getParser() {
- if (memoizedParser == null) {
- try {
- @SuppressWarnings("unchecked")
- T protoMessageInstance = (T) protoMessageClass.getMethod("getDefaultInstance").invoke(null);
- @SuppressWarnings("unchecked")
- Parser<T> tParser = (Parser<T>) protoMessageInstance.getParserForType();
- memoizedParser = tParser;
- } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
- throw new IllegalArgumentException(e);
- }
- }
- return memoizedParser;
- }
-
- /**
- * The implementation of the {@link CoderProvider} for this {@link ProtoCoder} returned by
- * {@link #coderProvider()}.
- */
- private static final CoderProvider PROVIDER =
- new CoderProvider() {
- @Override
- public <T> Coder<T> getCoder(TypeDescriptor<T> type) throws CannotProvideCoderException {
- if (!type.isSubtypeOf(new TypeDescriptor<Message>() {})) {
- throw new CannotProvideCoderException(
- String.format(
- "Cannot provide %s because %s is not a subclass of %s",
- ProtoCoder.class.getSimpleName(),
- type,
- Message.class.getName()));
- }
-
- @SuppressWarnings("unchecked")
- TypeDescriptor<? extends Message> messageType = (TypeDescriptor<? extends Message>) type;
- try {
- @SuppressWarnings("unchecked")
- Coder<T> coder = (Coder<T>) ProtoCoder.of(messageType);
- return coder;
- } catch (IllegalArgumentException e) {
- throw new CannotProvideCoderException(e);
- }
- }
- };
-
- private SortedSet<String> getSortedExtensionClasses() {
- SortedSet<String> ret = new TreeSet<>();
- for (Class<?> clazz : extensionHostClasses) {
- ret.add(clazz.getName());
- }
- return ret;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-beam/blob/7bef2b7e/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtil.java
----------------------------------------------------------------------
diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtil.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtil.java
deleted file mode 100644
index 597b1de..0000000
--- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/ProtobufUtil.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (C) 2015 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package com.google.cloud.dataflow.sdk.coders.protobuf;
-
-import static com.google.common.base.Preconditions.checkArgument;
-
-import com.google.cloud.dataflow.sdk.coders.Coder.NonDeterministicException;
-import com.google.protobuf.Descriptors.Descriptor;
-import com.google.protobuf.Descriptors.FieldDescriptor;
-import com.google.protobuf.Descriptors.FileDescriptor.Syntax;
-import com.google.protobuf.Descriptors.GenericDescriptor;
-import com.google.protobuf.ExtensionRegistry;
-import com.google.protobuf.ExtensionRegistry.ExtensionInfo;
-import com.google.protobuf.Message;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Utility functions for reflecting and analyzing Protocol Buffers classes.
- *
- * <p>Used by {@link ProtoCoder}, but in a separate file for testing and isolation.
- */
-class ProtobufUtil {
- /**
- * Returns the {@link Descriptor} for the given Protocol Buffers {@link Message}.
- *
- * @throws IllegalArgumentException if there is an error in Java reflection.
- */
- static Descriptor getDescriptorForClass(Class<? extends Message> clazz) {
- try {
- return (Descriptor) clazz.getMethod("getDescriptor").invoke(null);
- } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
- throw new IllegalArgumentException(e);
- }
- }
-
- /**
- * Returns the {@link Descriptor} for the given Protocol Buffers {@link Message} as well as
- * every class it can include transitively.
- *
- * @throws IllegalArgumentException if there is an error in Java reflection.
- */
- static Set<Descriptor> getRecursiveDescriptorsForClass(
- Class<? extends Message> clazz, ExtensionRegistry registry) {
- Descriptor root = getDescriptorForClass(clazz);
- Set<Descriptor> descriptors = new HashSet<>();
- recursivelyAddDescriptors(root, descriptors, registry);
- return descriptors;
- }
-
- /**
- * Recursively walks the given {@link Message} class and verifies that every field or message
- * linked in uses the Protocol Buffers proto2 syntax.
- */
- static void checkProto2Syntax(Class<? extends Message> clazz, ExtensionRegistry registry) {
- for (GenericDescriptor d : getRecursiveDescriptorsForClass(clazz, registry)) {
- Syntax s = d.getFile().getSyntax();
- checkArgument(
- s == Syntax.PROTO2,
- "Message %s or one of its dependencies does not use proto2 syntax: %s in file %s",
- clazz.getName(),
- d.getFullName(),
- d.getFile().getName());
- }
- }
-
- /**
- * Recursively checks whether the specified class uses any Protocol Buffers fields that cannot
- * be deterministically encoded.
- *
- * @throws NonDeterministicException if the object cannot be encoded deterministically.
- */
- static void verifyDeterministic(ProtoCoder<?> coder) throws NonDeterministicException {
- Class<? extends Message> message = coder.getMessageType();
- ExtensionRegistry registry = coder.getExtensionRegistry();
- Set<Descriptor> descriptors = getRecursiveDescriptorsForClass(message, registry);
- for (Descriptor d : descriptors) {
- for (FieldDescriptor fd : d.getFields()) {
- // If there is a transitively reachable Protocol Buffers map field, then this object cannot
- // be encoded deterministically.
- if (fd.isMapField()) {
- String reason =
- String.format(
- "Protocol Buffers message %s transitively includes Map field %s (from file %s)."
- + " Maps cannot be deterministically encoded.",
- message.getName(),
- fd.getFullName(),
- fd.getFile().getFullName());
- throw new NonDeterministicException(coder, reason);
- }
- }
- }
- }
-
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Disable construction of utility class
- private ProtobufUtil() {}
-
- private static void recursivelyAddDescriptors(
- Descriptor message, Set<Descriptor> descriptors, ExtensionRegistry registry) {
- if (descriptors.contains(message)) {
- return;
- }
- descriptors.add(message);
-
- for (FieldDescriptor f : message.getFields()) {
- recursivelyAddDescriptors(f, descriptors, registry);
- }
- for (FieldDescriptor f : message.getExtensions()) {
- recursivelyAddDescriptors(f, descriptors, registry);
- }
- for (ExtensionInfo info :
- registry.getAllImmutableExtensionsByExtendedType(message.getFullName())) {
- recursivelyAddDescriptors(info.descriptor, descriptors, registry);
- }
- for (ExtensionInfo info :
- registry.getAllMutableExtensionsByExtendedType(message.getFullName())) {
- recursivelyAddDescriptors(info.descriptor, descriptors, registry);
- }
- }
-
- private static void recursivelyAddDescriptors(
- FieldDescriptor field, Set<Descriptor> descriptors, ExtensionRegistry registry) {
- switch (field.getType()) {
- case BOOL:
- case BYTES:
- case DOUBLE:
- case ENUM:
- case FIXED32:
- case FIXED64:
- case FLOAT:
- case INT32:
- case INT64:
- case SFIXED32:
- case SFIXED64:
- case SINT32:
- case SINT64:
- case STRING:
- case UINT32:
- case UINT64:
- // Primitive types do not transitively access anything else.
- break;
-
- case GROUP:
- case MESSAGE:
- // Recursively adds all the fields from this nested Message.
- recursivelyAddDescriptors(field.getMessageType(), descriptors, registry);
- break;
-
- default:
- throw new UnsupportedOperationException(
- "Unexpected Protocol Buffers field type: " + field.getType());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-beam/blob/7bef2b7e/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/package-info.java
----------------------------------------------------------------------
diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/package-info.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/package-info.java
deleted file mode 100644
index b5bcf18..0000000
--- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/coders/protobuf/package-info.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (C) 2015 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-/**
- * Defines a {@link com.google.cloud.dataflow.sdk.coders.Coder}
- * for Protocol Buffers messages, {@code ProtoCoder}.
- *
- * @see com.google.cloud.dataflow.sdk.coders.protobuf.ProtoCoder
- */
-package com.google.cloud.dataflow.sdk.coders.protobuf;
http://git-wip-us.apache.org/repos/asf/incubator-beam/blob/7bef2b7e/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java
----------------------------------------------------------------------
diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java
deleted file mode 100644
index f016b5b..0000000
--- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroIO.java
+++ /dev/null
@@ -1,810 +0,0 @@
-/*
- * Copyright (C) 2015 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package com.google.cloud.dataflow.sdk.io;
-
-import static com.google.common.base.Preconditions.checkState;
-
-import com.google.cloud.dataflow.sdk.coders.AvroCoder;
-import com.google.cloud.dataflow.sdk.coders.Coder;
-import com.google.cloud.dataflow.sdk.coders.VoidCoder;
-import com.google.cloud.dataflow.sdk.io.Read.Bounded;
-import com.google.cloud.dataflow.sdk.options.PipelineOptions;
-import com.google.cloud.dataflow.sdk.runners.PipelineRunner;
-import com.google.cloud.dataflow.sdk.transforms.PTransform;
-import com.google.cloud.dataflow.sdk.util.IOChannelUtils;
-import com.google.cloud.dataflow.sdk.util.MimeTypes;
-import com.google.cloud.dataflow.sdk.values.PCollection;
-import com.google.cloud.dataflow.sdk.values.PDone;
-import com.google.cloud.dataflow.sdk.values.PInput;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
-
-import org.apache.avro.Schema;
-import org.apache.avro.file.DataFileWriter;
-import org.apache.avro.generic.GenericRecord;
-import org.apache.avro.reflect.ReflectData;
-
-import java.io.IOException;
-import java.nio.channels.Channels;
-import java.nio.channels.WritableByteChannel;
-import java.util.regex.Pattern;
-
-import javax.annotation.Nullable;
-
-/**
- * {@link PTransform}s for reading and writing Avro files.
- *
- * <p>To read a {@link PCollection} from one or more Avro files, use
- * {@link AvroIO.Read}, specifying {@link AvroIO.Read#from} to specify
- * the path of the file(s) to read from (e.g., a local filename or
- * filename pattern if running locally, or a Google Cloud Storage
- * filename or filename pattern of the form
- * {@code "gs://<bucket>/<filepath>"}), and optionally
- * {@link AvroIO.Read#named} to specify the name of the pipeline step.
- *
- * <p>It is required to specify {@link AvroIO.Read#withSchema}. To
- * read specific records, such as Avro-generated classes, provide an
- * Avro-generated class type. To read {@link GenericRecord GenericRecords}, provide either
- * a {@link Schema} object or an Avro schema in a JSON-encoded string form.
- * An exception will be thrown if a record doesn't match the specified
- * schema.
- *
- * <p>For example:
- * <pre> {@code
- * Pipeline p = ...;
- *
- * // A simple Read of a local file (only runs locally):
- * PCollection<AvroAutoGenClass> records =
- * p.apply(AvroIO.Read.from("/path/to/file.avro")
- * .withSchema(AvroAutoGenClass.class));
- *
- * // A Read from a GCS file (runs locally and via the Google Cloud
- * // Dataflow service):
- * Schema schema = new Schema.Parser().parse(new File("schema.avsc"));
- * PCollection<GenericRecord> records =
- * p.apply(AvroIO.Read.named("ReadFromAvro")
- * .from("gs://my_bucket/path/to/records-*.avro")
- * .withSchema(schema));
- * } </pre>
- *
- * <p>To write a {@link PCollection} to one or more Avro files, use
- * {@link AvroIO.Write}, specifying {@link AvroIO.Write#to} to specify
- * the path of the file to write to (e.g., a local filename or sharded
- * filename pattern if running locally, or a Google Cloud Storage
- * filename or sharded filename pattern of the form
- * {@code "gs://<bucket>/<filepath>"}), and optionally
- * {@link AvroIO.Write#named} to specify the name of the pipeline step.
- *
- * <p>It is required to specify {@link AvroIO.Write#withSchema}. To
- * write specific records, such as Avro-generated classes, provide an
- * Avro-generated class type. To write {@link GenericRecord GenericRecords}, provide either
- * a {@link Schema} object or a schema in a JSON-encoded string form.
- * An exception will be thrown if a record doesn't match the specified
- * schema.
- *
- * <p>For example:
- * <pre> {@code
- * // A simple Write to a local file (only runs locally):
- * PCollection<AvroAutoGenClass> records = ...;
- * records.apply(AvroIO.Write.to("/path/to/file.avro")
- * .withSchema(AvroAutoGenClass.class));
- *
- * // A Write to a sharded GCS file (runs locally and via the Google Cloud
- * // Dataflow service):
- * Schema schema = new Schema.Parser().parse(new File("schema.avsc"));
- * PCollection<GenericRecord> records = ...;
- * records.apply(AvroIO.Write.named("WriteToAvro")
- * .to("gs://my_bucket/path/to/numbers")
- * .withSchema(schema)
- * .withSuffix(".avro"));
- * } </pre>
- *
- * <p><h3>Permissions</h3>
- * Permission requirements depend on the {@link PipelineRunner} that is used to execute the
- * Dataflow job. Please refer to the documentation of corresponding {@link PipelineRunner}s for
- * more details.
- */
-public class AvroIO {
- /**
- * A root {@link PTransform} that reads from an Avro file (or multiple Avro
- * files matching a pattern) and returns a {@link PCollection} containing
- * the decoding of each record.
- */
- public static class Read {
- /**
- * Returns a {@link PTransform} with the given step name.
- */
- public static Bound<GenericRecord> named(String name) {
- return new Bound<>(GenericRecord.class).named(name);
- }
-
- /**
- * Returns a {@link PTransform} that reads from the file(s)
- * with the given name or pattern. This can be a local filename
- * or filename pattern (if running locally), or a Google Cloud
- * Storage filename or filename pattern of the form
- * {@code "gs://<bucket>/<filepath>"} (if running locally or via
- * the Google Cloud Dataflow service). Standard
- * <a href="http://docs.oracle.com/javase/tutorial/essential/io/find.html">Java
- * Filesystem glob patterns</a> ("*", "?", "[..]") are supported.
- */
- public static Bound<GenericRecord> from(String filepattern) {
- return new Bound<>(GenericRecord.class).from(filepattern);
- }
-
- /**
- * Returns a {@link PTransform} that reads Avro file(s)
- * containing records whose type is the specified Avro-generated class.
- *
- * @param <T> the type of the decoded elements, and the elements
- * of the resulting {@link PCollection}
- */
- public static <T> Bound<T> withSchema(Class<T> type) {
- return new Bound<>(type).withSchema(type);
- }
-
- /**
- * Returns a {@link PTransform} that reads Avro file(s)
- * containing records of the specified schema.
- */
- public static Bound<GenericRecord> withSchema(Schema schema) {
- return new Bound<>(GenericRecord.class).withSchema(schema);
- }
-
- /**
- * Returns a {@link PTransform} that reads Avro file(s)
- * containing records of the specified schema in a JSON-encoded
- * string form.
- */
- public static Bound<GenericRecord> withSchema(String schema) {
- return withSchema((new Schema.Parser()).parse(schema));
- }
-
- /**
- * Returns a {@link PTransform} that reads Avro file(s)
- * that has GCS path validation on pipeline creation disabled.
- *
- * <p>This can be useful in the case where the GCS input location does
- * not exist at the pipeline creation time, but is expected to be available
- * at execution time.
- */
- public static Bound<GenericRecord> withoutValidation() {
- return new Bound<>(GenericRecord.class).withoutValidation();
- }
-
- /**
- * A {@link PTransform} that reads from an Avro file (or multiple Avro
- * files matching a pattern) and returns a bounded {@link PCollection} containing
- * the decoding of each record.
- *
- * @param <T> the type of each of the elements of the resulting
- * PCollection
- */
- public static class Bound<T> extends PTransform<PInput, PCollection<T>> {
- /** The filepattern to read from. */
- @Nullable
- final String filepattern;
- /** The class type of the records. */
- final Class<T> type;
- /** The schema of the input file. */
- @Nullable
- final Schema schema;
- /** An option to indicate if input validation is desired. Default is true. */
- final boolean validate;
-
- Bound(Class<T> type) {
- this(null, null, type, null, true);
- }
-
- Bound(String name, String filepattern, Class<T> type, Schema schema, boolean validate) {
- super(name);
- this.filepattern = filepattern;
- this.type = type;
- this.schema = schema;
- this.validate = validate;
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * with the given step name.
- *
- * <p>Does not modify this object.
- */
- public Bound<T> named(String name) {
- return new Bound<>(name, filepattern, type, schema, validate);
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that reads from the file(s) with the given name or pattern.
- * (See {@link AvroIO.Read#from} for a description of
- * filepatterns.)
- *
- * <p>Does not modify this object.
- */
- public Bound<T> from(String filepattern) {
- return new Bound<>(name, filepattern, type, schema, validate);
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that reads Avro file(s) containing records whose type is the
- * specified Avro-generated class.
- *
- * <p>Does not modify this object.
- *
- * @param <X> the type of the decoded elements and the elements of
- * the resulting PCollection
- */
- public <X> Bound<X> withSchema(Class<X> type) {
- return new Bound<>(name, filepattern, type, ReflectData.get().getSchema(type), validate);
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that reads Avro file(s) containing records of the specified schema.
- *
- * <p>Does not modify this object.
- */
- public Bound<GenericRecord> withSchema(Schema schema) {
- return new Bound<>(name, filepattern, GenericRecord.class, schema, validate);
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that reads Avro file(s) containing records of the specified schema
- * in a JSON-encoded string form.
- *
- * <p>Does not modify this object.
- */
- public Bound<GenericRecord> withSchema(String schema) {
- return withSchema((new Schema.Parser()).parse(schema));
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that has GCS input path validation on pipeline creation disabled.
- *
- * <p>Does not modify this object.
- *
- * <p>This can be useful in the case where the GCS input location does
- * not exist at the pipeline creation time, but is expected to be
- * available at execution time.
- */
- public Bound<T> withoutValidation() {
- return new Bound<>(name, filepattern, type, schema, false);
- }
-
- @Override
- public PCollection<T> apply(PInput input) {
- if (filepattern == null) {
- throw new IllegalStateException(
- "need to set the filepattern of an AvroIO.Read transform");
- }
- if (schema == null) {
- throw new IllegalStateException("need to set the schema of an AvroIO.Read transform");
- }
- if (validate) {
- try {
- checkState(
- !IOChannelUtils.getFactory(filepattern).match(filepattern).isEmpty(),
- "Unable to find any files matching %s",
- filepattern);
- } catch (IOException e) {
- throw new IllegalStateException(
- String.format("Failed to validate %s", filepattern), e);
- }
- }
-
- @SuppressWarnings("unchecked")
- Bounded<T> read =
- type == GenericRecord.class
- ? (Bounded<T>) com.google.cloud.dataflow.sdk.io.Read.from(
- AvroSource.from(filepattern).withSchema(schema))
- : com.google.cloud.dataflow.sdk.io.Read.from(
- AvroSource.from(filepattern).withSchema(type));
-
- PCollection<T> pcol = input.getPipeline().apply("Read", read);
- // Honor the default output coder that would have been used by this PTransform.
- pcol.setCoder(getDefaultOutputCoder());
- return pcol;
- }
-
- @Override
- protected Coder<T> getDefaultOutputCoder() {
- return AvroCoder.of(type, schema);
- }
-
- public String getFilepattern() {
- return filepattern;
- }
-
- public Schema getSchema() {
- return schema;
- }
-
- public boolean needsValidation() {
- return validate;
- }
- }
-
- /** Disallow construction of utility class. */
- private Read() {}
- }
-
- /////////////////////////////////////////////////////////////////////////////
-
- /**
- * A root {@link PTransform} that writes a {@link PCollection} to an Avro file (or
- * multiple Avro files matching a sharding pattern).
- */
- public static class Write {
- /**
- * Returns a {@link PTransform} with the given step name.
- */
- public static Bound<GenericRecord> named(String name) {
- return new Bound<>(GenericRecord.class).named(name);
- }
-
- /**
- * Returns a {@link PTransform} that writes to the file(s)
- * with the given prefix. This can be a local filename
- * (if running locally), or a Google Cloud Storage filename of
- * the form {@code "gs://<bucket>/<filepath>"}
- * (if running locally or via the Google Cloud Dataflow service).
- *
- * <p>The files written will begin with this prefix, followed by
- * a shard identifier (see {@link Bound#withNumShards}, and end
- * in a common extension, if given by {@link Bound#withSuffix}.
- */
- public static Bound<GenericRecord> to(String prefix) {
- return new Bound<>(GenericRecord.class).to(prefix);
- }
-
- /**
- * Returns a {@link PTransform} that writes to the file(s) with the
- * given filename suffix.
- */
- public static Bound<GenericRecord> withSuffix(String filenameSuffix) {
- return new Bound<>(GenericRecord.class).withSuffix(filenameSuffix);
- }
-
- /**
- * Returns a {@link PTransform} that uses the provided shard count.
- *
- * <p>Constraining the number of shards is likely to reduce
- * the performance of a pipeline. Setting this value is not recommended
- * unless you require a specific number of output files.
- *
- * @param numShards the number of shards to use, or 0 to let the system
- * decide.
- */
- public static Bound<GenericRecord> withNumShards(int numShards) {
- return new Bound<>(GenericRecord.class).withNumShards(numShards);
- }
-
- /**
- * Returns a {@link PTransform} that uses the given shard name
- * template.
- *
- * <p>See {@link ShardNameTemplate} for a description of shard templates.
- */
- public static Bound<GenericRecord> withShardNameTemplate(String shardTemplate) {
- return new Bound<>(GenericRecord.class).withShardNameTemplate(shardTemplate);
- }
-
- /**
- * Returns a {@link PTransform} that forces a single file as
- * output.
- *
- * <p>Constraining the number of shards is likely to reduce
- * the performance of a pipeline. Setting this value is not recommended
- * unless you require a specific number of output files.
- */
- public static Bound<GenericRecord> withoutSharding() {
- return new Bound<>(GenericRecord.class).withoutSharding();
- }
-
- /**
- * Returns a {@link PTransform} that writes Avro file(s)
- * containing records whose type is the specified Avro-generated class.
- *
- * @param <T> the type of the elements of the input PCollection
- */
- public static <T> Bound<T> withSchema(Class<T> type) {
- return new Bound<>(type).withSchema(type);
- }
-
- /**
- * Returns a {@link PTransform} that writes Avro file(s)
- * containing records of the specified schema.
- */
- public static Bound<GenericRecord> withSchema(Schema schema) {
- return new Bound<>(GenericRecord.class).withSchema(schema);
- }
-
- /**
- * Returns a {@link PTransform} that writes Avro file(s)
- * containing records of the specified schema in a JSON-encoded
- * string form.
- */
- public static Bound<GenericRecord> withSchema(String schema) {
- return withSchema((new Schema.Parser()).parse(schema));
- }
-
- /**
- * Returns a {@link PTransform} that writes Avro file(s) that has GCS path validation on
- * pipeline creation disabled.
- *
- * <p>This can be useful in the case where the GCS output location does
- * not exist at the pipeline creation time, but is expected to be available
- * at execution time.
- */
- public static Bound<GenericRecord> withoutValidation() {
- return new Bound<>(GenericRecord.class).withoutValidation();
- }
-
- /**
- * A {@link PTransform} that writes a bounded {@link PCollection} to an Avro file (or
- * multiple Avro files matching a sharding pattern).
- *
- * @param <T> the type of each of the elements of the input PCollection
- */
- public static class Bound<T> extends PTransform<PCollection<T>, PDone> {
- /** The filename to write to. */
- @Nullable
- final String filenamePrefix;
- /** Suffix to use for each filename. */
- final String filenameSuffix;
- /** Requested number of shards. 0 for automatic. */
- final int numShards;
- /** Shard template string. */
- final String shardTemplate;
- /** The class type of the records. */
- final Class<T> type;
- /** The schema of the output file. */
- @Nullable
- final Schema schema;
- /** An option to indicate if output validation is desired. Default is true. */
- final boolean validate;
-
- Bound(Class<T> type) {
- this(null, null, "", 0, ShardNameTemplate.INDEX_OF_MAX, type, null, true);
- }
-
- Bound(
- String name,
- String filenamePrefix,
- String filenameSuffix,
- int numShards,
- String shardTemplate,
- Class<T> type,
- Schema schema,
- boolean validate) {
- super(name);
- this.filenamePrefix = filenamePrefix;
- this.filenameSuffix = filenameSuffix;
- this.numShards = numShards;
- this.shardTemplate = shardTemplate;
- this.type = type;
- this.schema = schema;
- this.validate = validate;
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * with the given step name.
- *
- * <p>Does not modify this object.
- */
- public Bound<T> named(String name) {
- return new Bound<>(
- name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate);
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that writes to the file(s) with the given filename prefix.
- *
- * <p>See {@link AvroIO.Write#to(String)} for more information
- * about filenames.
- *
- * <p>Does not modify this object.
- */
- public Bound<T> to(String filenamePrefix) {
- validateOutputComponent(filenamePrefix);
- return new Bound<>(
- name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate);
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that writes to the file(s) with the given filename suffix.
- *
- * <p>See {@link ShardNameTemplate} for a description of shard templates.
- *
- * <p>Does not modify this object.
- */
- public Bound<T> withSuffix(String filenameSuffix) {
- validateOutputComponent(filenameSuffix);
- return new Bound<>(
- name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate);
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that uses the provided shard count.
- *
- * <p>Constraining the number of shards is likely to reduce
- * the performance of a pipeline. Setting this value is not recommended
- * unless you require a specific number of output files.
- *
- * <p>Does not modify this object.
- *
- * @param numShards the number of shards to use, or 0 to let the system
- * decide.
- * @see ShardNameTemplate
- */
- public Bound<T> withNumShards(int numShards) {
- Preconditions.checkArgument(numShards >= 0);
- return new Bound<>(
- name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate);
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that uses the given shard name template.
- *
- * <p>Does not modify this object.
- *
- * @see ShardNameTemplate
- */
- public Bound<T> withShardNameTemplate(String shardTemplate) {
- return new Bound<>(
- name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, validate);
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that forces a single file as output.
- *
- * <p>This is a shortcut for
- * {@code .withNumShards(1).withShardNameTemplate("")}
- *
- * <p>Does not modify this object.
- */
- public Bound<T> withoutSharding() {
- return new Bound<>(name, filenamePrefix, filenameSuffix, 1, "", type, schema, validate);
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that writes to Avro file(s) containing records whose type is the
- * specified Avro-generated class.
- *
- * <p>Does not modify this object.
- *
- * @param <X> the type of the elements of the input PCollection
- */
- public <X> Bound<X> withSchema(Class<X> type) {
- return new Bound<>(
- name,
- filenamePrefix,
- filenameSuffix,
- numShards,
- shardTemplate,
- type,
- ReflectData.get().getSchema(type),
- validate);
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that writes to Avro file(s) containing records of the specified
- * schema.
- *
- * <p>Does not modify this object.
- */
- public Bound<GenericRecord> withSchema(Schema schema) {
- return new Bound<>(
- name,
- filenamePrefix,
- filenameSuffix,
- numShards,
- shardTemplate,
- GenericRecord.class,
- schema,
- validate);
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that writes to Avro file(s) containing records of the specified
- * schema in a JSON-encoded string form.
- *
- * <p>Does not modify this object.
- */
- public Bound<GenericRecord> withSchema(String schema) {
- return withSchema((new Schema.Parser()).parse(schema));
- }
-
- /**
- * Returns a new {@link PTransform} that's like this one but
- * that has GCS output path validation on pipeline creation disabled.
- *
- * <p>Does not modify this object.
- *
- * <p>This can be useful in the case where the GCS output location does
- * not exist at the pipeline creation time, but is expected to be
- * available at execution time.
- */
- public Bound<T> withoutValidation() {
- return new Bound<>(
- name, filenamePrefix, filenameSuffix, numShards, shardTemplate, type, schema, false);
- }
-
- @Override
- public PDone apply(PCollection<T> input) {
- if (filenamePrefix == null) {
- throw new IllegalStateException(
- "need to set the filename prefix of an AvroIO.Write transform");
- }
- if (schema == null) {
- throw new IllegalStateException("need to set the schema of an AvroIO.Write transform");
- }
-
- // Note that custom sinks currently do not expose sharding controls.
- // Thus pipeline runner writers need to individually add support internally to
- // apply user requested sharding limits.
- return input.apply(
- "Write",
- com.google.cloud.dataflow.sdk.io.Write.to(
- new AvroSink<>(
- filenamePrefix, filenameSuffix, shardTemplate, AvroCoder.of(type, schema))));
- }
-
- /**
- * Returns the current shard name template string.
- */
- public String getShardNameTemplate() {
- return shardTemplate;
- }
-
- @Override
- protected Coder<Void> getDefaultOutputCoder() {
- return VoidCoder.of();
- }
-
- public String getFilenamePrefix() {
- return filenamePrefix;
- }
-
- public String getShardTemplate() {
- return shardTemplate;
- }
-
- public int getNumShards() {
- return numShards;
- }
-
- public String getFilenameSuffix() {
- return filenameSuffix;
- }
-
- public Class<T> getType() {
- return type;
- }
-
- public Schema getSchema() {
- return schema;
- }
-
- public boolean needsValidation() {
- return validate;
- }
- }
-
- /** Disallow construction of utility class. */
- private Write() {}
- }
-
- // Pattern which matches old-style shard output patterns, which are now
- // disallowed.
- private static final Pattern SHARD_OUTPUT_PATTERN = Pattern.compile("@([0-9]+|\\*)");
-
- private static void validateOutputComponent(String partialFilePattern) {
- Preconditions.checkArgument(
- !SHARD_OUTPUT_PATTERN.matcher(partialFilePattern).find(),
- "Output name components are not allowed to contain @* or @N patterns: "
- + partialFilePattern);
- }
-
- /////////////////////////////////////////////////////////////////////////////
-
- /** Disallow construction of utility class. */
- private AvroIO() {}
-
- /**
- * A {@link FileBasedSink} for Avro files.
- */
- @VisibleForTesting
- static class AvroSink<T> extends FileBasedSink<T> {
- private final AvroCoder<T> coder;
-
- @VisibleForTesting
- AvroSink(
- String baseOutputFilename, String extension, String fileNameTemplate, AvroCoder<T> coder) {
- super(baseOutputFilename, extension, fileNameTemplate);
- this.coder = coder;
- }
-
- @Override
- public FileBasedSink.FileBasedWriteOperation<T> createWriteOperation(PipelineOptions options) {
- return new AvroWriteOperation<>(this, coder);
- }
-
- /**
- * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriteOperation
- * FileBasedWriteOperation} for Avro files.
- */
- private static class AvroWriteOperation<T> extends FileBasedWriteOperation<T> {
- private final AvroCoder<T> coder;
-
- private AvroWriteOperation(AvroSink<T> sink, AvroCoder<T> coder) {
- super(sink);
- this.coder = coder;
- }
-
- @Override
- public FileBasedWriter<T> createWriter(PipelineOptions options) throws Exception {
- return new AvroWriter<>(this, coder);
- }
- }
-
- /**
- * A {@link com.google.cloud.dataflow.sdk.io.FileBasedSink.FileBasedWriter FileBasedWriter}
- * for Avro files.
- */
- private static class AvroWriter<T> extends FileBasedWriter<T> {
- private final AvroCoder<T> coder;
- private DataFileWriter<T> dataFileWriter;
-
- public AvroWriter(FileBasedWriteOperation<T> writeOperation, AvroCoder<T> coder) {
- super(writeOperation);
- this.mimeType = MimeTypes.BINARY;
- this.coder = coder;
- }
-
- @SuppressWarnings("deprecation") // uses internal test functionality.
- @Override
- protected void prepareWrite(WritableByteChannel channel) throws Exception {
- dataFileWriter = new DataFileWriter<>(coder.createDatumWriter());
- dataFileWriter.create(coder.getSchema(), Channels.newOutputStream(channel));
- }
-
- @Override
- public void write(T value) throws Exception {
- dataFileWriter.append(value);
- }
-
- @Override
- protected void writeFooter() throws Exception {
- dataFileWriter.flush();
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-beam/blob/7bef2b7e/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java
----------------------------------------------------------------------
diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java
deleted file mode 100644
index 297663e..0000000
--- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java
+++ /dev/null
@@ -1,647 +0,0 @@
-/*
- * Copyright (C) 2015 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package com.google.cloud.dataflow.sdk.io;
-
-import com.google.cloud.dataflow.sdk.annotations.Experimental;
-import com.google.cloud.dataflow.sdk.coders.AvroCoder;
-import com.google.cloud.dataflow.sdk.options.PipelineOptions;
-import com.google.cloud.dataflow.sdk.runners.PipelineRunner;
-import com.google.cloud.dataflow.sdk.util.AvroUtils;
-import com.google.cloud.dataflow.sdk.util.AvroUtils.AvroMetadata;
-import com.google.cloud.dataflow.sdk.values.PCollection;
-import com.google.common.base.Preconditions;
-
-import org.apache.avro.Schema;
-import org.apache.avro.file.CodecFactory;
-import org.apache.avro.file.DataFileConstants;
-import org.apache.avro.generic.GenericDatumReader;
-import org.apache.avro.generic.GenericRecord;
-import org.apache.avro.io.BinaryDecoder;
-import org.apache.avro.io.DatumReader;
-import org.apache.avro.io.DecoderFactory;
-import org.apache.avro.reflect.ReflectData;
-import org.apache.avro.reflect.ReflectDatumReader;
-import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
-import org.apache.commons.compress.compressors.snappy.SnappyCompressorInputStream;
-import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PushbackInputStream;
-import java.nio.ByteBuffer;
-import java.nio.channels.Channels;
-import java.nio.channels.ReadableByteChannel;
-import java.util.Collection;
-import java.util.zip.Inflater;
-import java.util.zip.InflaterInputStream;
-
-// CHECKSTYLE.OFF: JavadocStyle
-/**
- * A {@link FileBasedSource} for reading Avro files.
- *
- * <p>To read a {@link PCollection} of objects from one or more Avro files, use
- * {@link AvroSource#from} to specify the path(s) of the files to read. The {@link AvroSource} that
- * is returned will read objects of type {@link GenericRecord} with the schema(s) that were written
- * at file creation. To further configure the {@link AvroSource} to read with a user-defined schema,
- * or to return records of a type other than {@link GenericRecord}, use
- * {@link AvroSource#withSchema(Schema)} (using an Avro {@link Schema}),
- * {@link AvroSource#withSchema(String)} (using a JSON schema), or
- * {@link AvroSource#withSchema(Class)} (to return objects of the Avro-generated class specified).
- *
- * <p>An {@link AvroSource} can be read from using the {@link Read} transform. For example:
- *
- * <pre>
- * {@code
- * AvroSource<MyType> source = AvroSource.from(file.toPath()).withSchema(MyType.class);
- * PCollection<MyType> records = Read.from(mySource);
- * }
- * </pre>
- *
- * <p>The {@link AvroSource#readFromFileWithClass(String, Class)} method is a convenience method
- * that returns a read transform. For example:
- *
- * <pre>
- * {@code
- * PCollection<MyType> records = AvroSource.readFromFileWithClass(file.toPath(), MyType.class));
- * }
- * </pre>
- *
- * <p>This class's implementation is based on the <a
- * href="https://avro.apache.org/docs/1.7.7/spec.html">Avro 1.7.7</a> specification and implements
- * parsing of some parts of Avro Object Container Files. The rationale for doing so is that the Avro
- * API does not provide efficient ways of computing the precise offsets of blocks within a file,
- * which is necessary to support dynamic work rebalancing. However, whenever it is possible to use
- * the Avro API in a way that supports maintaining precise offsets, this class uses the Avro API.
- *
- * <p>Avro Object Container files store records in blocks. Each block contains a collection of
- * records. Blocks may be encoded (e.g., with bzip2, deflate, snappy, etc.). Blocks are delineated
- * from one another by a 16-byte sync marker.
- *
- * <p>An {@link AvroSource} for a subrange of a single file contains records in the blocks such that
- * the start offset of the block is greater than or equal to the start offset of the source and less
- * than the end offset of the source.
- *
- * <p>To use XZ-encoded Avro files, please include an explicit dependency on {@code xz-1.5.jar},
- * which has been marked as optional in the Maven {@code sdk/pom.xml} for Google Cloud Dataflow:
- *
- * <pre>{@code
- * <dependency>
- * <groupId>org.tukaani</groupId>
- * <artifactId>xz</artifactId>
- * <version>1.5</version>
- * </dependency>
- * }</pre>
- *
- * <h3>Permissions</h3>
- * <p>Permission requirements depend on the {@link PipelineRunner} that is used to execute the
- * Dataflow job. Please refer to the documentation of corresponding {@link PipelineRunner}s for
- * more details.
- *
- * @param <T> The type of records to be read from the source.
- */
-// CHECKSTYLE.ON: JavadocStyle
-@Experimental(Experimental.Kind.SOURCE_SINK)
-public class AvroSource<T> extends BlockBasedSource<T> {
- // Default minimum bundle size (chosen as two default-size Avro blocks to attempt to
- // ensure that every source has at least one block of records).
- // The default sync interval is 64k.
- static final long DEFAULT_MIN_BUNDLE_SIZE = 2 * DataFileConstants.DEFAULT_SYNC_INTERVAL;
-
- // The JSON schema used to encode records.
- private final String readSchemaString;
-
- // The JSON schema that was used to write the source Avro file (may differ from the schema we will
- // use to read from it).
- private final String fileSchemaString;
-
- // The type of the records contained in the file.
- private final Class<T> type;
-
- // The following metadata fields are not user-configurable. They are extracted from the object
- // container file header upon subsource creation.
-
- // The codec used to encode the blocks in the Avro file. String value drawn from those in
- // https://avro.apache.org/docs/1.7.7/api/java/org/apache/avro/file/CodecFactory.html
- private final String codec;
-
- // The object container file's 16-byte sync marker.
- private final byte[] syncMarker;
-
- // Default output coder, lazily initialized.
- private transient AvroCoder<T> coder = null;
-
- // Schema of the file, lazily initialized.
- private transient Schema fileSchema;
-
- // Schema used to encode records, lazily initialized.
- private transient Schema readSchema;
-
- /**
- * Creates a {@link Read} transform that will read from an {@link AvroSource} that is configured
- * to read records of the given type from a file pattern.
- */
- public static <T> Read.Bounded<T> readFromFileWithClass(String filePattern, Class<T> clazz) {
- return Read.from(new AvroSource<T>(filePattern, DEFAULT_MIN_BUNDLE_SIZE,
- ReflectData.get().getSchema(clazz).toString(), clazz, null, null));
- }
-
- /**
- * Creates an {@link AvroSource} that reads from the given file name or pattern ("glob"). The
- * returned source can be further configured by calling {@link #withSchema} to return a type other
- * than {@link GenericRecord}.
- */
- public static AvroSource<GenericRecord> from(String fileNameOrPattern) {
- return new AvroSource<>(
- fileNameOrPattern, DEFAULT_MIN_BUNDLE_SIZE, null, GenericRecord.class, null, null);
- }
-
- /**
- * Returns an {@link AvroSource} that's like this one but reads files containing records that
- * conform to the given schema.
- *
- * <p>Does not modify this object.
- */
- public AvroSource<GenericRecord> withSchema(String schema) {
- return new AvroSource<>(
- getFileOrPatternSpec(), getMinBundleSize(), schema, GenericRecord.class, codec, syncMarker);
- }
-
- /**
- * Returns an {@link AvroSource} that's like this one but reads files containing records that
- * conform to the given schema.
- *
- * <p>Does not modify this object.
- */
- public AvroSource<GenericRecord> withSchema(Schema schema) {
- return new AvroSource<>(getFileOrPatternSpec(), getMinBundleSize(), schema.toString(),
- GenericRecord.class, codec, syncMarker);
- }
-
- /**
- * Returns an {@link AvroSource} that's like this one but reads files containing records of the
- * type of the given class.
- *
- * <p>Does not modify this object.
- */
- public <X> AvroSource<X> withSchema(Class<X> clazz) {
- return new AvroSource<X>(getFileOrPatternSpec(), getMinBundleSize(),
- ReflectData.get().getSchema(clazz).toString(), clazz, codec, syncMarker);
- }
-
- /**
- * Returns an {@link AvroSource} that's like this one but uses the supplied minimum bundle size.
- * Refer to {@link OffsetBasedSource} for a description of {@code minBundleSize} and its use.
- *
- * <p>Does not modify this object.
- */
- public AvroSource<T> withMinBundleSize(long minBundleSize) {
- return new AvroSource<T>(
- getFileOrPatternSpec(), minBundleSize, readSchemaString, type, codec, syncMarker);
- }
-
- private AvroSource(String fileNameOrPattern, long minBundleSize, String schema, Class<T> type,
- String codec, byte[] syncMarker) {
- super(fileNameOrPattern, minBundleSize);
- this.readSchemaString = schema;
- this.codec = codec;
- this.syncMarker = syncMarker;
- this.type = type;
- this.fileSchemaString = null;
- }
-
- private AvroSource(String fileName, long minBundleSize, long startOffset, long endOffset,
- String schema, Class<T> type, String codec, byte[] syncMarker, String fileSchema) {
- super(fileName, minBundleSize, startOffset, endOffset);
- this.readSchemaString = schema;
- this.codec = codec;
- this.syncMarker = syncMarker;
- this.type = type;
- this.fileSchemaString = fileSchema;
- }
-
- @Override
- public void validate() {
- // AvroSource objects do not need to be configured with more than a file pattern. Overridden to
- // make this explicit.
- super.validate();
- }
-
- @Override
- public BlockBasedSource<T> createForSubrangeOfFile(String fileName, long start, long end) {
- byte[] syncMarker = this.syncMarker;
- String codec = this.codec;
- String readSchemaString = this.readSchemaString;
- String fileSchemaString = this.fileSchemaString;
- // codec and syncMarker are initially null when the source is created, as they differ
- // across input files and must be read from the file. Here, when we are creating a source
- // for a subrange of a file, we can initialize these values. When the resulting AvroSource
- // is further split, they do not need to be read again.
- if (codec == null || syncMarker == null || fileSchemaString == null) {
- AvroMetadata metadata;
- try {
- Collection<String> files = FileBasedSource.expandFilePattern(fileName);
- Preconditions.checkArgument(files.size() <= 1, "More than 1 file matched %s");
- metadata = AvroUtils.readMetadataFromFile(fileName);
- } catch (IOException e) {
- throw new RuntimeException("Error reading metadata from file " + fileName, e);
- }
- codec = metadata.getCodec();
- syncMarker = metadata.getSyncMarker();
- fileSchemaString = metadata.getSchemaString();
- // If the source was created with a null schema, use the schema that we read from the file's
- // metadata.
- if (readSchemaString == null) {
- readSchemaString = metadata.getSchemaString();
- }
- }
- return new AvroSource<T>(fileName, getMinBundleSize(), start, end, readSchemaString, type,
- codec, syncMarker, fileSchemaString);
- }
-
- @Override
- protected BlockBasedReader<T> createSingleFileReader(PipelineOptions options) {
- return new AvroReader<T>(this);
- }
-
- @Override
- public boolean producesSortedKeys(PipelineOptions options) throws Exception {
- return false;
- }
-
- @Override
- public AvroCoder<T> getDefaultOutputCoder() {
- if (coder == null) {
- Schema.Parser parser = new Schema.Parser();
- coder = AvroCoder.of(type, parser.parse(readSchemaString));
- }
- return coder;
- }
-
- public String getSchema() {
- return readSchemaString;
- }
-
- private Schema getReadSchema() {
- if (readSchemaString == null) {
- return null;
- }
-
- // If the schema has not been parsed, parse it.
- if (readSchema == null) {
- Schema.Parser parser = new Schema.Parser();
- readSchema = parser.parse(readSchemaString);
- }
- return readSchema;
- }
-
- private Schema getFileSchema() {
- if (fileSchemaString == null) {
- return null;
- }
-
- // If the schema has not been parsed, parse it.
- if (fileSchema == null) {
- Schema.Parser parser = new Schema.Parser();
- fileSchema = parser.parse(fileSchemaString);
- }
- return fileSchema;
- }
-
- private byte[] getSyncMarker() {
- return syncMarker;
- }
-
- private String getCodec() {
- return codec;
- }
-
- private DatumReader<T> createDatumReader() {
- Schema readSchema = getReadSchema();
- Schema fileSchema = getFileSchema();
- Preconditions.checkNotNull(
- readSchema, "No read schema has been initialized for source %s", this);
- Preconditions.checkNotNull(
- fileSchema, "No file schema has been initialized for source %s", this);
- if (type == GenericRecord.class) {
- return new GenericDatumReader<>(fileSchema, readSchema);
- } else {
- return new ReflectDatumReader<>(fileSchema, readSchema);
- }
- }
-
- /**
- * A {@link BlockBasedSource.Block} of Avro records.
- *
- * @param <T> The type of records stored in the block.
- */
- @Experimental(Experimental.Kind.SOURCE_SINK)
- static class AvroBlock<T> extends Block<T> {
- // The number of records in the block.
- private final long numRecords;
-
- // The current record in the block.
- private T currentRecord;
-
- // The index of the current record in the block.
- private long currentRecordIndex = 0;
-
- // A DatumReader to read records from the block.
- private final DatumReader<T> reader;
-
- // A BinaryDecoder used by the reader to decode records.
- private final BinaryDecoder decoder;
-
- /**
- * Decodes a byte array as an InputStream. The byte array may be compressed using some
- * codec. Reads from the returned stream will result in decompressed bytes.
- *
- * <p>This supports the same codecs as Avro's {@link CodecFactory}, namely those defined in
- * {@link DataFileConstants}.
- *
- * <ul>
- * <li>"snappy" : Google's Snappy compression
- * <li>"deflate" : deflate compression
- * <li>"bzip2" : Bzip2 compression
- * <li>"xz" : xz compression
- * <li>"null" (the string, not the value): Uncompressed data
- * </ul>
- */
- private static InputStream decodeAsInputStream(byte[] data, String codec) throws IOException {
- ByteArrayInputStream byteStream = new ByteArrayInputStream(data);
- switch (codec) {
- case DataFileConstants.SNAPPY_CODEC:
- return new SnappyCompressorInputStream(byteStream);
- case DataFileConstants.DEFLATE_CODEC:
- // nowrap == true: Do not expect ZLIB header or checksum, as Avro does not write them.
- Inflater inflater = new Inflater(true);
- return new InflaterInputStream(byteStream, inflater);
- case DataFileConstants.XZ_CODEC:
- return new XZCompressorInputStream(byteStream);
- case DataFileConstants.BZIP2_CODEC:
- return new BZip2CompressorInputStream(byteStream);
- case DataFileConstants.NULL_CODEC:
- return byteStream;
- default:
- throw new IllegalArgumentException("Unsupported codec: " + codec);
- }
- }
-
- AvroBlock(byte[] data, long numRecords, AvroSource<T> source) throws IOException {
- this.numRecords = numRecords;
- this.reader = source.createDatumReader();
- this.decoder =
- DecoderFactory.get().binaryDecoder(decodeAsInputStream(data, source.getCodec()), null);
- }
-
- @Override
- public T getCurrentRecord() {
- return currentRecord;
- }
-
- @Override
- public boolean readNextRecord() throws IOException {
- if (currentRecordIndex >= numRecords) {
- return false;
- }
- currentRecord = reader.read(null, decoder);
- currentRecordIndex++;
- return true;
- }
-
- @Override
- public double getFractionOfBlockConsumed() {
- return ((double) currentRecordIndex) / numRecords;
- }
- }
-
- /**
- * A {@link BlockBasedSource.BlockBasedReader} for reading blocks from Avro files.
- *
- * <p>An Avro Object Container File consists of a header followed by a 16-bit sync marker
- * and then a sequence of blocks, where each block begins with two encoded longs representing
- * the total number of records in the block and the block's size in bytes, followed by the
- * block's (optionally-encoded) records. Each block is terminated by a 16-bit sync marker.
- *
- * <p>Here, we consider the sync marker that precedes a block to be its offset, as this allows
- * a reader that begins reading at that offset to detect the sync marker and the beginning of
- * the block.
- *
- * @param <T> The type of records contained in the block.
- */
- @Experimental(Experimental.Kind.SOURCE_SINK)
- public static class AvroReader<T> extends BlockBasedReader<T> {
- // The current block.
- private AvroBlock<T> currentBlock;
-
- // Offset of the block.
- private long currentBlockOffset = 0;
-
- // Size of the current block.
- private long currentBlockSizeBytes = 0;
-
- // Current offset within the stream.
- private long currentOffset = 0;
-
- // Stream used to read from the underlying file.
- // A pushback stream is used to restore bytes buffered during seeking/decoding.
- private PushbackInputStream stream;
-
- // Small buffer for reading encoded values from the stream.
- // The maximum size of an encoded long is 10 bytes, and this buffer will be used to read two.
- private final byte[] readBuffer = new byte[20];
-
- // Decoder to decode binary-encoded values from the buffer.
- private BinaryDecoder decoder;
-
- /**
- * Reads Avro records of type {@code T} from the specified source.
- */
- public AvroReader(AvroSource<T> source) {
- super(source);
- }
-
- @Override
- public synchronized AvroSource<T> getCurrentSource() {
- return (AvroSource<T>) super.getCurrentSource();
- }
-
- @Override
- public boolean readNextBlock() throws IOException {
- // The next block in the file is after the first sync marker that can be read starting from
- // the current offset. First, we seek past the next sync marker, if it exists. After a sync
- // marker is the start of a block. A block begins with the number of records contained in
- // the block, encoded as a long, followed by the size of the block in bytes, encoded as a
- // long. The currentOffset after this method should be last byte after this block, and the
- // currentBlockOffset should be the start of the sync marker before this block.
-
- // Seek to the next sync marker, if one exists.
- currentOffset += advancePastNextSyncMarker(stream, getCurrentSource().getSyncMarker());
-
- // The offset of the current block includes its preceding sync marker.
- currentBlockOffset = currentOffset - getCurrentSource().getSyncMarker().length;
-
- // Read a small buffer to parse the block header.
- // We cannot use a BinaryDecoder to do this directly from the stream because a BinaryDecoder
- // internally buffers data and we only want to read as many bytes from the stream as the size
- // of the header. Though BinaryDecoder#InputStream returns an input stream that is aware of
- // its internal buffering, we would have to re-wrap this input stream to seek for the next
- // block in the file.
- int read = stream.read(readBuffer);
- // We reached the last sync marker in the file.
- if (read <= 0) {
- return false;
- }
- decoder = DecoderFactory.get().binaryDecoder(readBuffer, decoder);
- long numRecords = decoder.readLong();
- long blockSize = decoder.readLong();
-
- // The decoder buffers data internally, but since we know the size of the stream the
- // decoder has constructed from the readBuffer, the number of bytes available in the
- // input stream is equal to the number of unconsumed bytes.
- int headerSize = readBuffer.length - decoder.inputStream().available();
- stream.unread(readBuffer, headerSize, read - headerSize);
-
- // Create the current block by reading blockSize bytes. Block sizes permitted by the Avro
- // specification are [32, 2^30], so this narrowing is ok.
- byte[] data = new byte[(int) blockSize];
- stream.read(data);
- currentBlock = new AvroBlock<>(data, numRecords, getCurrentSource());
- currentBlockSizeBytes = blockSize;
-
- // Update current offset with the number of bytes we read to get the next block.
- currentOffset += headerSize + blockSize;
- return true;
- }
-
- @Override
- public AvroBlock<T> getCurrentBlock() {
- return currentBlock;
- }
-
- @Override
- public long getCurrentBlockOffset() {
- return currentBlockOffset;
- }
-
- @Override
- public long getCurrentBlockSize() {
- return currentBlockSizeBytes;
- }
-
- /**
- * Creates a {@link PushbackInputStream} that has a large enough pushback buffer to be able
- * to push back the syncBuffer and the readBuffer.
- */
- private PushbackInputStream createStream(ReadableByteChannel channel) {
- return new PushbackInputStream(
- Channels.newInputStream(channel),
- getCurrentSource().getSyncMarker().length + readBuffer.length);
- }
-
- /**
- * Starts reading from the provided channel. Assumes that the channel is already seeked to
- * the source's start offset.
- */
- @Override
- protected void startReading(ReadableByteChannel channel) throws IOException {
- stream = createStream(channel);
- currentOffset = getCurrentSource().getStartOffset();
- }
-
- /**
- * Advances to the first byte after the next occurrence of the sync marker in the
- * stream when reading from the current offset. Returns the number of bytes consumed
- * from the stream. Note that this method requires a PushbackInputStream with a buffer
- * at least as big as the marker it is seeking for.
- */
- static long advancePastNextSyncMarker(PushbackInputStream stream, byte[] syncMarker)
- throws IOException {
- Seeker seeker = new Seeker(syncMarker);
- byte[] syncBuffer = new byte[syncMarker.length];
- long totalBytesConsumed = 0;
- // Seek until either a sync marker is found or we reach the end of the file.
- int mark = -1; // Position of the last byte in the sync marker.
- int read; // Number of bytes read.
- do {
- read = stream.read(syncBuffer);
- if (read >= 0) {
- mark = seeker.find(syncBuffer, read);
- // Update the currentOffset with the number of bytes read.
- totalBytesConsumed += read;
- }
- } while (mark < 0 && read > 0);
-
- // If the sync marker was found, unread block data and update the current offsets.
- if (mark >= 0) {
- // The current offset after this call should be just past the sync marker, so we should
- // unread the remaining buffer contents and update the currentOffset accordingly.
- stream.unread(syncBuffer, mark + 1, read - (mark + 1));
- totalBytesConsumed = totalBytesConsumed - (read - (mark + 1));
- }
- return totalBytesConsumed;
- }
-
- /**
- * A {@link Seeker} looks for a given marker within a byte buffer. Uses naive string matching
- * with a sliding window, as sync markers are small and random.
- */
- static class Seeker {
- // The marker to search for.
- private byte[] marker;
-
- // Buffer used for the sliding window.
- private byte[] searchBuffer;
-
- // Number of bytes available to be matched in the buffer.
- private int available = 0;
-
- /**
- * Create a {@link Seeker} that looks for the given marker.
- */
- public Seeker(byte[] marker) {
- this.marker = marker;
- this.searchBuffer = new byte[marker.length];
- }
-
- /**
- * Find the marker in the byte buffer. Returns the index of the end of the marker in the
- * buffer. If the marker is not found, returns -1.
- *
- * <p>State is maintained between calls. If the marker was partially matched, a subsequent
- * call to find will resume matching the marker.
- *
- * @param buffer
- * @return the index of the end of the marker within the buffer, or -1 if the buffer was not
- * found.
- */
- public int find(byte[] buffer, int length) {
- for (int i = 0; i < length; i++) {
- System.arraycopy(searchBuffer, 1, searchBuffer, 0, searchBuffer.length - 1);
- searchBuffer[searchBuffer.length - 1] = buffer[i];
- available = Math.min(available + 1, searchBuffer.length);
- if (ByteBuffer.wrap(searchBuffer, searchBuffer.length - available, available)
- .equals(ByteBuffer.wrap(marker))) {
- available = 0;
- return i;
- }
- }
- return -1;
- }
- }
- }
-}