index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/file/Codec.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.file; import java.io.IOException; import java.nio.ByteBuffer; /** * Interface for Avro-supported compression codecs for data files. * * Note that Codec objects may maintain internal state (e.g. buffers) and are * not thread safe. */ public abstract class Codec { /** Name of the codec; written to the file's metadata. */ public abstract String getName(); /** Compresses the input data */ public abstract ByteBuffer compress(ByteBuffer uncompressedData) throws IOException; /** Decompress the data */ public abstract ByteBuffer decompress(ByteBuffer compressedData) throws IOException; /** * Codecs must implement an equals() method. Two codecs, A and B are equal if: * the result of A and B decompressing content compressed by A is the same AND * the result of A and B decompressing content compressed by B is the same **/ @Override public abstract boolean equals(Object other); /** * Codecs must implement a hashCode() method that is consistent with equals(). */ @Override public abstract int hashCode(); @Override public String toString() { return getName(); } // Codecs often reference the array inside a ByteBuffer. Compute the offset // to the start of data correctly in the case that our ByteBuffer // is a slice() of another. protected static int computeOffset(ByteBuffer data) { return data.arrayOffset() + data.position(); } }
7,300
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/file/CodecFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.file; import java.util.HashMap; import java.util.Map; import java.util.zip.Deflater; import org.apache.avro.AvroRuntimeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Encapsulates the ability to specify and configure a compression codec. * * Currently there are five codecs registered by default: * <ul> * <li>{@code null}</li> * <li>{@code deflate}</li> * <li>{@code snappy}</li> * <li>{@code bzip2}</li> * <li>{@code xz}</li> * <li>{@code zstandard}</li> * </ul> * * New and custom codecs can be registered using * {@link #addCodec(String, CodecFactory)}. */ public abstract class CodecFactory { private static final Logger LOG = LoggerFactory.getLogger(CodecFactory.class); /** Null codec, for no compression. */ public static CodecFactory nullCodec() { return NullCodec.OPTION; } /** * Deflate codec, with specific compression. compressionLevel should be between * 1 and 9, inclusive. */ public static CodecFactory deflateCodec(int compressionLevel) { return new DeflateCodec.Option(compressionLevel); } /** * XZ codec, with specific compression. compressionLevel should be between 1 and * 9, inclusive. */ public static CodecFactory xzCodec(int compressionLevel) { return new XZCodec.Option(compressionLevel); } /** Snappy codec. */ public static CodecFactory snappyCodec() { try { return new SnappyCodec.Option(); } catch (Throwable t) { LOG.debug("Snappy was not available", t); return null; } } /** bzip2 codec. */ public static CodecFactory bzip2Codec() { return new BZip2Codec.Option(); } /** * zstandard codec, with specific compression level. * * @param level The compression level should be between -5 and 22, inclusive. * Negative levels are 'fast' modes akin to lz4 or snappy, levels * above 9 are generally for archival purposes, and levels above 18 * use a lot of memory. */ public static CodecFactory zstandardCodec(int level) { return new ZstandardCodec.Option(level, false, false); } /** * zstandard codec, with specific compression level. * * @param level The compression level should be between -5 and 22, * inclusive. Negative levels are 'fast' modes akin to lz4 or * snappy, levels above 9 are generally for archival * purposes, and levels above 18 use a lot of memory. * @param useChecksum if true, will include a checksum with each data block */ public static CodecFactory zstandardCodec(int level, boolean useChecksum) { return new ZstandardCodec.Option(level, useChecksum, false); } /** * zstandard codec, with specific compression level, checksum, and bufferPool * * @param level The compression level should be between -5 and 22, * inclusive. Negative levels are 'fast' modes akin to lz4 * or snappy, levels above 9 are generally for archival * purposes, and levels above 18 use a lot of memory. * @param useChecksum if true, will include a checksum with each data block * @param useBufferPool if true, will use recycling buffer pool */ public static CodecFactory zstandardCodec(int level, boolean useChecksum, boolean useBufferPool) { return new ZstandardCodec.Option(level, useChecksum, useBufferPool); } /** Creates internal Codec. */ protected abstract Codec createInstance(); /** * Mapping of string names (stored as metas) and codecs. Note that currently * options (like compression level) are not recoverable. */ private static final Map<String, CodecFactory> REGISTERED = new HashMap<>(); public static final int DEFAULT_DEFLATE_LEVEL = Deflater.DEFAULT_COMPRESSION; public static final int DEFAULT_XZ_LEVEL = XZCodec.DEFAULT_COMPRESSION; public static final int DEFAULT_ZSTANDARD_LEVEL = ZstandardCodec.DEFAULT_COMPRESSION; public static final boolean DEFAULT_ZSTANDARD_BUFFERPOOL = ZstandardCodec.DEFAULT_USE_BUFFERPOOL; static { addCodec(DataFileConstants.NULL_CODEC, nullCodec()); addCodec(DataFileConstants.DEFLATE_CODEC, deflateCodec(DEFAULT_DEFLATE_LEVEL)); addCodec(DataFileConstants.BZIP2_CODEC, bzip2Codec()); addCodec(DataFileConstants.XZ_CODEC, xzCodec(DEFAULT_XZ_LEVEL)); addCodec(DataFileConstants.ZSTANDARD_CODEC, zstandardCodec(DEFAULT_ZSTANDARD_LEVEL, DEFAULT_ZSTANDARD_BUFFERPOOL)); addCodec(DataFileConstants.SNAPPY_CODEC, snappyCodec()); } /** * Maps a codec name into a CodecFactory. * * Currently there are six codecs registered by default: * <ul> * <li>{@code null}</li> * <li>{@code deflate}</li> * <li>{@code snappy}</li> * <li>{@code bzip2}</li> * <li>{@code xz}</li> * <li>{@code zstandard}</li> * </ul> */ public static CodecFactory fromString(String s) { CodecFactory o = REGISTERED.get(s); if (o == null) { throw new AvroRuntimeException("Unrecognized codec: " + s); } return o; } /** * Adds a new codec implementation. If name already had a codec associated with * it, returns the previous codec. */ public static CodecFactory addCodec(String name, CodecFactory c) { if (c != null) { return REGISTERED.put(name, c); } return null; } @Override public String toString() { Codec instance = this.createInstance(); return instance.toString(); } }
7,301
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/file/SeekableInput.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.file; import java.io.IOException; import java.io.Closeable; /** An InputStream that supports seek and tell. */ public interface SeekableInput extends Closeable { /** * Set the position for the next {@link java.io.InputStream#read(byte[],int,int) * read()}. */ void seek(long p) throws IOException; /** * Return the position of the next * {@link java.io.InputStream#read(byte[],int,int) read()}. */ long tell() throws IOException; /** Return the length of the file. */ long length() throws IOException; /** Equivalent to {@link java.io.InputStream#read(byte[],int,int)}. */ int read(byte[] b, int off, int len) throws IOException; }
7,302
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/file/XZCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.file; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import org.apache.avro.util.NonCopyingByteArrayOutputStream; import org.apache.commons.compress.compressors.xz.XZCompressorInputStream; import org.apache.commons.compress.compressors.xz.XZCompressorOutputStream; import org.apache.commons.compress.utils.IOUtils; /** * Implements xz compression and decompression. */ public class XZCodec extends Codec { public final static int DEFAULT_COMPRESSION = 6; private static final int DEFAULT_BUFFER_SIZE = 8192; static class Option extends CodecFactory { private int compressionLevel; Option(int compressionLevel) { this.compressionLevel = compressionLevel; } @Override protected Codec createInstance() { return new XZCodec(compressionLevel); } } private int compressionLevel; public XZCodec(int compressionLevel) { this.compressionLevel = compressionLevel; } @Override public String getName() { return DataFileConstants.XZ_CODEC; } @Override public ByteBuffer compress(ByteBuffer data) throws IOException { NonCopyingByteArrayOutputStream baos = new NonCopyingByteArrayOutputStream(DEFAULT_BUFFER_SIZE); try (OutputStream outputStream = new XZCompressorOutputStream(baos, compressionLevel)) { outputStream.write(data.array(), computeOffset(data), data.remaining()); } return baos.asByteBuffer(); } @Override public ByteBuffer decompress(ByteBuffer data) throws IOException { NonCopyingByteArrayOutputStream baos = new NonCopyingByteArrayOutputStream(DEFAULT_BUFFER_SIZE); InputStream bytesIn = new ByteArrayInputStream(data.array(), computeOffset(data), data.remaining()); try (InputStream ios = new XZCompressorInputStream(bytesIn)) { IOUtils.copy(ios, baos); } return baos.asByteBuffer(); } @Override public int hashCode() { return compressionLevel; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || obj.getClass() != getClass()) return false; XZCodec other = (XZCodec) obj; return (this.compressionLevel == other.compressionLevel); } @Override public String toString() { return getName() + "-" + compressionLevel; } }
7,303
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/path/LocationStep.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.path; /** * Selects items based on their "path" (name of a property under which they are * stored) relative to the context. */ public class LocationStep implements PathElement { /** * selector part of location step. either "." or ".." */ private final String selector; /** * name of a property to select */ private final String propertyName; public LocationStep(String selector, String propertyName) { this.selector = selector; this.propertyName = propertyName; } @Override public String toString() { if (propertyName == null || propertyName.isEmpty()) { return selector; } return selector + propertyName; } }
7,304
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/path/PathElement.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.path; /** * root interface for all pieces of an AvroPath expression */ public interface PathElement { }
7,305
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/path/ArrayPositionPredicate.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.path; /** * Returns items by their position (numeric index) in an array */ public class ArrayPositionPredicate implements PositionalPathPredicate { private final long index; public ArrayPositionPredicate(long index) { this.index = index; } @Override public String toString() { return "[" + index + "]"; } }
7,306
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/path/UnionTypePredicate.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.path; /** * Returns items by their position (numeric index of type) in a union schema */ public class UnionTypePredicate implements PositionalPathPredicate { private final String type; public UnionTypePredicate(String type) { this.type = type; } @Override public String toString() { return "[" + type + "]"; } }
7,307
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/path/PathTracingException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.path; import org.apache.avro.Schema; /** * interface for exceptions that can trace the AvroPath of an error * * @param <T> the regular (user-facing) exception that will be * {@link #summarize(Schema)}ed out of this class */ public interface PathTracingException<T extends Throwable> { /** * appends a path element to the trace. expected to be called in reverse-order * as the exception bubbles up the stack * * @param step an AvroPath step tracing back from the location of the original * exception towards the root of the data graph */ void tracePath(PathElement step); /** * produces a user-facing exception to be thrown back out to user code * * @param root the root object for the operation that generated the exception * @return an exception */ T summarize(Schema root); }
7,308
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/path/PathPredicate.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.path; /** * a predicate is a filter that restricts items selected by a * {@link LocationStep} */ public interface PathPredicate extends PathElement { }
7,309
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/path/MapKeyPredicate.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.path; /** * Returns items by their position (string key under which they are stored) in a * map */ public class MapKeyPredicate implements PositionalPathPredicate { private final String key; public MapKeyPredicate(String key) { this.key = key; } public String getKey() { return key; } @Override public String toString() { if (key == null) { return ""; } return "[\"" + key + "\"]"; } }
7,310
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/path/PositionalPathPredicate.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.path; /** * filters items by their context position */ public interface PositionalPathPredicate extends PathPredicate { }
7,311
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/path/TracingNullPointException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.path; import org.apache.avro.Schema; import org.apache.avro.util.SchemaUtil; import java.util.ArrayList; import java.util.List; /** * a {@link NullPointerException} with extra fields used to trace back the path * to a null value through an object graph */ public class TracingNullPointException extends NullPointerException implements PathTracingException<NullPointerException> { private final NullPointerException cause; private final Schema expected; private final boolean customCoderUsed; private final List<PathElement> reversePath; public TracingNullPointException(NullPointerException cause, Schema expected, boolean customCoderUsed) { this.cause = cause; this.expected = expected; this.customCoderUsed = customCoderUsed; this.reversePath = new ArrayList<>(3); // assume short } @Override public void tracePath(PathElement step) { reversePath.add(step); } @Override public synchronized NullPointerException getCause() { return cause; } /** * @return a hopefully helpful error message */ @Override public NullPointerException summarize(Schema root) { StringBuilder sb = new StringBuilder(); sb.append("null value for (non-nullable) "); if (reversePath == null || reversePath.isEmpty()) { // very simple "shallow" NPE, no nesting at all, or custom coders used means we // have no data if (customCoderUsed) { sb.append("field or map key. No further details available as custom coders were used"); } else { sb.append(SchemaUtil.describe(expected)); } } else { PathElement innerMostElement = reversePath.get(0); boolean isNullMapKey = innerMostElement instanceof MapKeyPredicate && ((MapKeyPredicate) innerMostElement).getKey() == null; if (isNullMapKey) { sb.delete(0, sb.length()); // clear sb.append("null key in map"); } else { sb.append(SchemaUtil.describe(expected)); } sb.append(" at "); if (root != null) { sb.append(SchemaUtil.describe(root)); } for (int i = reversePath.size() - 1; i >= 0; i--) { PathElement step = reversePath.get(i); sb.append(step.toString()); } } NullPointerException summary = new NullPointerException(sb.toString()); summary.initCause(cause); return summary; } }
7,312
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/path/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Interfaces and base classes for AvroPath. This functionality is * <b>experimental</b>, meaning these APIs are not expected to be stable any * time soon so use at your own risk. Feedback, however, would be very * appreciated :-) */ package org.apache.avro.path;
7,313
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/path/TracingClassCastException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.path; import org.apache.avro.Schema; import org.apache.avro.util.SchemaUtil; import java.util.ArrayList; import java.util.List; /** * a {@link ClassCastException} with extra fields used to trace back the path to * a bad value through an object graph */ public class TracingClassCastException extends ClassCastException implements PathTracingException<ClassCastException> { private final ClassCastException cause; private final Object datum; private final Schema expected; private final boolean customCoderUsed; private final List<PathElement> reversePath; public TracingClassCastException(ClassCastException cause, Object datum, Schema expected, boolean customCoderUsed) { this.cause = cause; this.datum = datum; this.expected = expected; this.customCoderUsed = customCoderUsed; this.reversePath = new ArrayList<>(3); // assume short } @Override public void tracePath(PathElement step) { reversePath.add(step); } @Override public synchronized ClassCastException getCause() { return cause; } /** * @return a hopefully helpful error message */ @Override public ClassCastException summarize(Schema root) { StringBuilder sb = new StringBuilder(); sb.append("value ").append(SchemaUtil.describe(datum)); sb.append(" cannot be cast to expected type ").append(SchemaUtil.describe(expected)); if (reversePath == null || reversePath.isEmpty()) { // very simple "shallow" NPE, no nesting at all, or custom coders used means we // have no data if (customCoderUsed) { sb.append(". No further details available as custom coders were used"); } } else { sb.append(" at "); if (root != null) { sb.append(SchemaUtil.describe(root)); } for (int i = reversePath.size() - 1; i >= 0; i--) { PathElement step = reversePath.get(i); sb.append(step.toString()); } } ClassCastException summary = new ClassCastException(sb.toString()); summary.initCause(cause); return summary; } }
7,314
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/path/TracingAvroTypeException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.path; import java.util.ArrayList; import java.util.List; import org.apache.avro.AvroTypeException; import org.apache.avro.Schema; import org.apache.avro.util.SchemaUtil; /** * an {@link AvroTypeException} with extra fields used to trace back the path to * a bad value through an object graph */ public class TracingAvroTypeException extends AvroTypeException implements PathTracingException<AvroTypeException> { private final List<PathElement> reversePath; public TracingAvroTypeException(AvroTypeException cause) { super(cause.getMessage(), cause); this.reversePath = new ArrayList<>(3); // expected to be short } @Override public void tracePath(PathElement step) { reversePath.add(step); } @Override public AvroTypeException summarize(Schema root) { AvroTypeException cause = (AvroTypeException) getCause(); StringBuilder sb = new StringBuilder(); sb.append(cause.getMessage()); if (reversePath != null && !reversePath.isEmpty()) { sb.append(" at "); if (root != null) { sb.append(SchemaUtil.describe(root)); } for (int i = reversePath.size() - 1; i >= 0; i--) { PathElement step = reversePath.get(i); sb.append(step.toString()); } } AvroTypeException summary = new AvroTypeException(sb.toString()); summary.initCause(cause); return summary; } }
7,315
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/ReflectDatumReader.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.io.IOException; import java.lang.reflect.Array; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashSet; import java.util.HashMap; import java.util.Collection; import java.util.Map; import java.util.Optional; import org.apache.avro.AvroRuntimeException; import org.apache.avro.Conversion; import org.apache.avro.LogicalType; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.generic.IndexedRecord; import org.apache.avro.io.Decoder; import org.apache.avro.io.ResolvingDecoder; import org.apache.avro.specific.SpecificData; import org.apache.avro.specific.SpecificDatumReader; /** * {@link org.apache.avro.io.DatumReader DatumReader} for existing classes via * Java reflection. */ public class ReflectDatumReader<T> extends SpecificDatumReader<T> { public ReflectDatumReader() { this(null, null, ReflectData.get()); } /** Construct for reading instances of a class. */ public ReflectDatumReader(Class<T> c) { this(new ReflectData(c.getClassLoader())); setSchema(getSpecificData().getSchema(c)); } /** Construct where the writer's and reader's schemas are the same. */ public ReflectDatumReader(Schema root) { this(root, root, ReflectData.get()); } /** Construct given writer's and reader's schema. */ public ReflectDatumReader(Schema writer, Schema reader) { this(writer, reader, ReflectData.get()); } /** Construct given writer's and reader's schema and the data model. */ public ReflectDatumReader(Schema writer, Schema reader, ReflectData data) { super(writer, reader, data); } /** Construct given a {@link ReflectData}. */ public ReflectDatumReader(ReflectData data) { super(data); } @Override protected Object newArray(Object old, int size, Schema schema) { Class<?> collectionClass = ReflectData.getClassProp(schema, SpecificData.CLASS_PROP); Class<?> elementClass = ReflectData.getClassProp(schema, SpecificData.ELEMENT_PROP); if (elementClass == null) { // see if the element class will be converted and use that class // logical types cannot conflict with java-element-class Conversion<?> elementConversion = getData().getConversionFor(schema.getElementType().getLogicalType()); if (elementConversion != null) { elementClass = elementConversion.getConvertedType(); } } if (collectionClass == null && elementClass == null) return super.newArray(old, size, schema); // use specific/generic if (collectionClass != null && !collectionClass.isArray()) { if (old instanceof Collection) { ((Collection<?>) old).clear(); return old; } if (collectionClass.isAssignableFrom(ArrayList.class)) return new ArrayList<>(); if (collectionClass.isAssignableFrom(HashSet.class)) return new HashSet<>(); if (collectionClass.isAssignableFrom(HashMap.class)) return new HashMap<>(); return SpecificData.newInstance(collectionClass, schema); } if (elementClass == null) { elementClass = collectionClass.getComponentType(); } if (elementClass == null) { ReflectData data = (ReflectData) getData(); elementClass = data.getClass(schema.getElementType()); } return Array.newInstance(elementClass, size); } @Override protected Object peekArray(Object array) { return null; } @Override protected void addToArray(Object array, long pos, Object e) { throw new AvroRuntimeException("reflectDatumReader does not use addToArray"); } @Override /** * Called to read an array instance. May be overridden for alternate array * representations. */ protected Object readArray(Object old, Schema expected, ResolvingDecoder in) throws IOException { Schema expectedType = expected.getElementType(); long l = in.readArrayStart(); if (l <= 0) { return newArray(old, 0, expected); } Object array = newArray(old, (int) l, expected); if (array instanceof Collection) { @SuppressWarnings("unchecked") Collection<Object> c = (Collection<Object>) array; return readCollection(c, expectedType, l, in); } else if (array instanceof Map) { // Only for non-string keys, we can use NS_MAP_* fields // So we check the same explicitly here if (ReflectData.isNonStringMapSchema(expected)) { Collection<Object> c = new ArrayList<>(); readCollection(c, expectedType, l, in); Map m = (Map) array; for (Object ele : c) { IndexedRecord rec = ((IndexedRecord) ele); Object key = rec.get(ReflectData.NS_MAP_KEY_INDEX); Object value = rec.get(ReflectData.NS_MAP_VALUE_INDEX); m.put(key, value); } return array; } else { String msg = "Expected a schema of map with non-string keys but got " + expected; throw new AvroRuntimeException(msg); } } else { return readJavaArray(array, expectedType, l, in); } } private Object readJavaArray(Object array, Schema expectedType, long l, ResolvingDecoder in) throws IOException { Class<?> elementType = array.getClass().getComponentType(); if (elementType.isPrimitive()) { return readPrimitiveArray(array, elementType, l, in); } else { return readObjectArray((Object[]) array, expectedType, l, in); } } private Object readPrimitiveArray(Object array, Class<?> c, long l, ResolvingDecoder in) throws IOException { return ArrayAccessor.readArray(array, c, l, in); } private Object readObjectArray(Object[] array, Schema expectedType, long l, ResolvingDecoder in) throws IOException { LogicalType logicalType = expectedType.getLogicalType(); Conversion<?> conversion = getData().getConversionFor(logicalType); int index = 0; if (logicalType != null && conversion != null) { do { int limit = index + (int) l; while (index < limit) { Object element = readWithConversion(null, expectedType, logicalType, conversion, in); array[index] = element; index++; } } while ((l = in.arrayNext()) > 0); } else { do { int limit = index + (int) l; while (index < limit) { Object element = readWithoutConversion(null, expectedType, in); array[index] = element; index++; } } while ((l = in.arrayNext()) > 0); } return array; } private Object readCollection(Collection<Object> c, Schema expectedType, long l, ResolvingDecoder in) throws IOException { LogicalType logicalType = expectedType.getLogicalType(); Conversion<?> conversion = getData().getConversionFor(logicalType); if (logicalType != null && conversion != null) { do { for (int i = 0; i < l; i++) { Object element = readWithConversion(null, expectedType, logicalType, conversion, in); c.add(element); } } while ((l = in.arrayNext()) > 0); } else { do { for (int i = 0; i < l; i++) { Object element = readWithoutConversion(null, expectedType, in); c.add(element); } } while ((l = in.arrayNext()) > 0); } return c; } @Override protected Object readString(Object old, Decoder in) throws IOException { return super.readString(null, in).toString(); } @Override protected Object createString(String value) { return value; } @Override protected Object readBytes(Object old, Schema s, Decoder in) throws IOException { ByteBuffer bytes = in.readBytes(null); Class<?> c = ReflectData.getClassProp(s, SpecificData.CLASS_PROP); if (c != null && c.isArray()) { byte[] result = new byte[bytes.remaining()]; bytes.get(result); return result; } else { return bytes; } } @Override protected Object readInt(Object old, Schema expected, Decoder in) throws IOException { Object value = in.readInt(); String intClass = expected.getProp(SpecificData.CLASS_PROP); if (Byte.class.getName().equals(intClass)) value = ((Integer) value).byteValue(); else if (Short.class.getName().equals(intClass)) value = ((Integer) value).shortValue(); else if (Character.class.getName().equals(intClass)) value = (char) (int) (Integer) value; return value; } @Override protected void readField(Object record, Field field, Object oldDatum, ResolvingDecoder in, Object state) throws IOException { if (state != null) { FieldAccessor accessor = ((FieldAccessor[]) state)[field.pos()]; if (accessor != null) { if (accessor.supportsIO() && (!Schema.Type.UNION.equals(field.schema().getType()) || accessor.isCustomEncoded())) { accessor.read(record, in); return; } if (accessor.isStringable()) { try { String asString = (String) read(null, field.schema(), in); accessor.set(record, asString == null ? null : newInstanceFromString(accessor.getField().getType(), asString)); return; } catch (Exception e) { throw new AvroRuntimeException("Failed to read Stringable", e); } } LogicalType logicalType = field.schema().getLogicalType(); if (logicalType != null) { Conversion<?> conversion = getData().getConversionByClass(accessor.getField().getType(), logicalType); if (conversion != null) { try { accessor.set(record, convert(readWithoutConversion(oldDatum, field.schema(), in), field.schema(), logicalType, conversion)); } catch (IllegalAccessException e) { throw new AvroRuntimeException("Failed to set " + field); } return; } } if (Optional.class.isAssignableFrom(accessor.getField().getType())) { try { Object value = readWithoutConversion(oldDatum, field.schema(), in); accessor.set(record, Optional.ofNullable(value)); return; } catch (IllegalAccessException e) { throw new AvroRuntimeException("Failed to set " + field); } } try { accessor.set(record, readWithoutConversion(oldDatum, field.schema(), in)); return; } catch (IllegalAccessException e) { throw new AvroRuntimeException("Failed to set " + field); } } } super.readField(record, field, oldDatum, in, state); } }
7,316
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/Union.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Declares that a Java type should be represented by an Avro union schema. May * be used for base classes or interfaces whose instantiable subclasses can be * listed in the parameters to the @Union annotation. If applied to method * parameters this determines the reflected message parameter type. If applied * to a method, this determines its return type. A null schema may be specified * with {@link java.lang.Void}. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) @Documented public @interface Union { /** The instantiable classes that compose this union. */ Class[] value(); }
7,317
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/AvroAliases.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.apache.avro.reflect; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.FIELD }) public @interface AvroAliases { AvroAlias[] value(); }
7,318
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/FieldAccessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.io.IOException; import java.lang.reflect.Field; import org.apache.avro.io.Decoder; import org.apache.avro.io.Encoder; abstract class FieldAccessor { FieldAccessor() { } protected abstract Object get(Object object) throws IllegalAccessException; protected abstract void set(Object object, Object value) throws IllegalAccessException, IOException; protected void read(Object object, Decoder in) throws IOException { } protected void write(Object object, Encoder out) throws IOException { } protected boolean supportsIO() { return false; } protected abstract Field getField(); protected boolean isStringable() { return false; } protected boolean isCustomEncoded() { return false; } }
7,319
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/AvroMeta.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Adds the given key:Value pair as metadata into the schema, at the * corresponding node. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.FIELD }) @Repeatable(AvroMeta.AvroMetas.class) public @interface AvroMeta { String key(); String value(); @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.FIELD }) @interface AvroMetas { AvroMeta[] value(); } }
7,320
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/ReflectDatumWriter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import org.apache.avro.AvroRuntimeException; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.io.Encoder; import org.apache.avro.specific.SpecificDatumWriter; import org.apache.avro.util.MapEntry; /** * {@link org.apache.avro.io.DatumWriter DatumWriter} for existing classes via * Java reflection. */ public class ReflectDatumWriter<T> extends SpecificDatumWriter<T> { public ReflectDatumWriter() { this(ReflectData.get()); } public ReflectDatumWriter(Class<T> c) { this(c, ReflectData.get()); } public ReflectDatumWriter(Class<T> c, ReflectData data) { this(data.getSchema(c), data); } public ReflectDatumWriter(Schema root) { this(root, ReflectData.get()); } public ReflectDatumWriter(Schema root, ReflectData reflectData) { super(root, reflectData); } protected ReflectDatumWriter(ReflectData reflectData) { super(reflectData); } /** * Called to write a array. May be overridden for alternate array * representations. */ @Override protected void writeArray(Schema schema, Object datum, Encoder out) throws IOException { if (datum instanceof Collection) { super.writeArray(schema, datum, out); return; } Class<?> elementClass = datum.getClass().getComponentType(); if (null == elementClass) { // not a Collection or an Array throw new AvroRuntimeException("Array data must be a Collection or Array"); } Schema element = schema.getElementType(); if (elementClass.isPrimitive()) { Schema.Type type = element.getType(); out.writeArrayStart(); switch (type) { case BOOLEAN: ArrayAccessor.writeArray((boolean[]) datum, out); break; case DOUBLE: ArrayAccessor.writeArray((double[]) datum, out); break; case FLOAT: ArrayAccessor.writeArray((float[]) datum, out); break; case INT: if (elementClass.equals(int.class)) { ArrayAccessor.writeArray((int[]) datum, out); } else if (elementClass.equals(char.class)) { ArrayAccessor.writeArray((char[]) datum, out); } else if (elementClass.equals(short.class)) { ArrayAccessor.writeArray((short[]) datum, out); } else { arrayError(elementClass, type); } break; case LONG: ArrayAccessor.writeArray((long[]) datum, out); break; default: arrayError(elementClass, type); } out.writeArrayEnd(); } else { out.writeArrayStart(); writeObjectArray(element, (Object[]) datum, out); out.writeArrayEnd(); } } private void writeObjectArray(Schema element, Object[] data, Encoder out) throws IOException { int size = data.length; out.setItemCount(size); for (Object datum : data) { this.write(element, datum, out); } } private void arrayError(Class<?> cl, Schema.Type type) { throw new AvroRuntimeException("Error writing array with inner type " + cl + " and avro type: " + type); } @Override protected void writeBytes(Object datum, Encoder out) throws IOException { if (datum instanceof byte[]) out.writeBytes((byte[]) datum); else super.writeBytes(datum, out); } @Override protected void write(Schema schema, Object datum, Encoder out) throws IOException { if (datum instanceof Byte) datum = ((Byte) datum).intValue(); else if (datum instanceof Short) datum = ((Short) datum).intValue(); else if (datum instanceof Character) datum = (int) (char) (Character) datum; else if (datum instanceof Map && ReflectData.isNonStringMapSchema(schema)) { // Maps with non-string keys are written as arrays. // Schema for such maps is already changed. Here we // just switch the map to a similar form too. Set entries = ((Map) datum).entrySet(); List<Map.Entry> entryList = new ArrayList<>(entries.size()); for (Object obj : ((Map) datum).entrySet()) { Map.Entry e = (Map.Entry) obj; entryList.add(new MapEntry(e.getKey(), e.getValue())); } datum = entryList; } else if (datum instanceof Optional) { datum = ((Optional) datum).orElse(null); } try { super.write(schema, datum, out); } catch (NullPointerException e) { // improve error message throw npe(e, " in " + schema.getFullName()); } } @Override protected void writeField(Object record, Field f, Encoder out, Object state) throws IOException { if (state != null) { FieldAccessor accessor = ((FieldAccessor[]) state)[f.pos()]; if (accessor != null) { if (accessor.supportsIO() && (!Schema.Type.UNION.equals(f.schema().getType()) || accessor.isCustomEncoded())) { accessor.write(record, out); return; } if (accessor.isStringable()) { try { Object object = accessor.get(record); write(f.schema(), (object == null) ? null : object.toString(), out); } catch (IllegalAccessException e) { throw new AvroRuntimeException("Failed to write Stringable", e); } return; } } } super.writeField(record, f, out, state); } }
7,321
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/AvroEncode.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Expert: Fields with this annotation are encoded using the given custom * encoder. This annotation overrides {@link org.apache.avro.reflect.Stringable * Stringable} and {@link org.apache.avro.reflect.Nullable Nullable}. Since no * validation is performed, invalid custom encodings may result in an unreadable * file. Use of {@link org.apache.avro.io.ValidatingEncoder} is recommended. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface AvroEncode { Class<? extends CustomEncoding<?>> using(); }
7,322
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/FieldAccess.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.lang.reflect.Field; abstract class FieldAccess { protected static final int INT_DEFAULT_VALUE = 0; protected static final float FLOAT_DEFAULT_VALUE = 0.0f; protected static final short SHORT_DEFAULT_VALUE = (short) 0; protected static final byte BYTE_DEFAULT_VALUE = (byte) 0; protected static final boolean BOOLEAN_DEFAULT_VALUE = false; protected static final char CHAR_DEFAULT_VALUE = '\u0000'; protected static final long LONG_DEFAULT_VALUE = 0L; protected static final double DOUBLE_DEFAULT_VALUE = 0.0d; protected abstract FieldAccessor getAccessor(Field field); }
7,323
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/AvroAlias.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Adds the given name and space as an alias to the schema. Avro files of this * schema can be read into classes named by the alias. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.FIELD }) @Repeatable(AvroAliases.class) public @interface AvroAlias { String NULL = "NOT A VALID NAMESPACE"; String alias(); String space() default NULL; }
7,324
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/FieldAccessUnsafe.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.io.IOException; import java.lang.reflect.Field; import org.apache.avro.AvroRuntimeException; import org.apache.avro.io.Decoder; import org.apache.avro.io.Encoder; import sun.misc.Unsafe; @SuppressWarnings("restriction") class FieldAccessUnsafe extends FieldAccess { private static final Unsafe UNSAFE; static { try { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); UNSAFE = (Unsafe) theUnsafe.get(null); // It seems not all Unsafe implementations implement the following method. } catch (Exception e) { throw new RuntimeException(e); } } @Override protected FieldAccessor getAccessor(Field field) { AvroEncode enc = field.getAnnotation(AvroEncode.class); if (enc != null) try { return new UnsafeCustomEncodedField(field, enc.using().getDeclaredConstructor().newInstance()); } catch (Exception e) { throw new AvroRuntimeException("Could not instantiate custom Encoding"); } Class<?> c = field.getType(); if (c == int.class) return new UnsafeIntField(field); else if (c == long.class) return new UnsafeLongField(field); else if (c == byte.class) return new UnsafeByteField(field); else if (c == float.class) return new UnsafeFloatField(field); else if (c == double.class) return new UnsafeDoubleField(field); else if (c == char.class) return new UnsafeCharField(field); else if (c == boolean.class) return new UnsafeBooleanField(field); else if (c == short.class) return new UnsafeShortField(field); else return new UnsafeObjectField(field); } abstract static class UnsafeCachedField extends FieldAccessor { protected final long offset; protected Field field; protected final boolean isStringable; UnsafeCachedField(Field f) { this.offset = UNSAFE.objectFieldOffset(f); this.field = f; this.isStringable = f.isAnnotationPresent(Stringable.class); } @Override protected Field getField() { return field; } @Override protected boolean supportsIO() { return true; } @Override protected boolean isStringable() { return isStringable; } } final static class UnsafeIntField extends UnsafeCachedField { UnsafeIntField(Field f) { super(f); } @Override protected void set(Object object, Object value) { UNSAFE.putInt(object, offset, value == null ? INT_DEFAULT_VALUE : (Integer) value); } @Override protected Object get(Object object) { return UNSAFE.getInt(object, offset); } @Override protected void read(Object object, Decoder in) throws IOException { UNSAFE.putInt(object, offset, in.readInt()); } @Override protected void write(Object object, Encoder out) throws IOException { out.writeInt(UNSAFE.getInt(object, offset)); } } final static class UnsafeFloatField extends UnsafeCachedField { protected UnsafeFloatField(Field f) { super(f); } @Override protected void set(Object object, Object value) { UNSAFE.putFloat(object, offset, value == null ? FLOAT_DEFAULT_VALUE : (Float) value); } @Override protected Object get(Object object) { return UNSAFE.getFloat(object, offset); } @Override protected void read(Object object, Decoder in) throws IOException { UNSAFE.putFloat(object, offset, in.readFloat()); } @Override protected void write(Object object, Encoder out) throws IOException { out.writeFloat(UNSAFE.getFloat(object, offset)); } } final static class UnsafeShortField extends UnsafeCachedField { protected UnsafeShortField(Field f) { super(f); } @Override protected void set(Object object, Object value) { UNSAFE.putShort(object, offset, value == null ? SHORT_DEFAULT_VALUE : (Short) value); } @Override protected Object get(Object object) { return UNSAFE.getShort(object, offset); } @Override protected void read(Object object, Decoder in) throws IOException { UNSAFE.putShort(object, offset, (short) in.readInt()); } @Override protected void write(Object object, Encoder out) throws IOException { out.writeInt(UNSAFE.getShort(object, offset)); } } final static class UnsafeByteField extends UnsafeCachedField { protected UnsafeByteField(Field f) { super(f); } @Override protected void set(Object object, Object value) { UNSAFE.putByte(object, offset, value == null ? BYTE_DEFAULT_VALUE : (Byte) value); } @Override protected Object get(Object object) { return UNSAFE.getByte(object, offset); } @Override protected void read(Object object, Decoder in) throws IOException { UNSAFE.putByte(object, offset, (byte) in.readInt()); } @Override protected void write(Object object, Encoder out) throws IOException { out.writeInt(UNSAFE.getByte(object, offset)); } } final static class UnsafeBooleanField extends UnsafeCachedField { protected UnsafeBooleanField(Field f) { super(f); } @Override protected void set(Object object, Object value) { UNSAFE.putBoolean(object, offset, value == null ? BOOLEAN_DEFAULT_VALUE : (Boolean) value); } @Override protected Object get(Object object) { return UNSAFE.getBoolean(object, offset); } @Override protected void read(Object object, Decoder in) throws IOException { UNSAFE.putBoolean(object, offset, in.readBoolean()); } @Override protected void write(Object object, Encoder out) throws IOException { out.writeBoolean(UNSAFE.getBoolean(object, offset)); } } final static class UnsafeCharField extends UnsafeCachedField { protected UnsafeCharField(Field f) { super(f); } @Override protected void set(Object object, Object value) { UNSAFE.putChar(object, offset, value == null ? CHAR_DEFAULT_VALUE : (Character) value); } @Override protected Object get(Object object) { return UNSAFE.getChar(object, offset); } @Override protected void read(Object object, Decoder in) throws IOException { UNSAFE.putChar(object, offset, (char) in.readInt()); } @Override protected void write(Object object, Encoder out) throws IOException { out.writeInt(UNSAFE.getChar(object, offset)); } } final static class UnsafeLongField extends UnsafeCachedField { protected UnsafeLongField(Field f) { super(f); } @Override protected void set(Object object, Object value) { UNSAFE.putLong(object, offset, value == null ? LONG_DEFAULT_VALUE : (Long) value); } @Override protected Object get(Object object) { return UNSAFE.getLong(object, offset); } @Override protected void read(Object object, Decoder in) throws IOException { UNSAFE.putLong(object, offset, in.readLong()); } @Override protected void write(Object object, Encoder out) throws IOException { out.writeLong(UNSAFE.getLong(object, offset)); } } final static class UnsafeDoubleField extends UnsafeCachedField { protected UnsafeDoubleField(Field f) { super(f); } @Override protected void set(Object object, Object value) { UNSAFE.putDouble(object, offset, value == null ? DOUBLE_DEFAULT_VALUE : (Double) value); } @Override protected Object get(Object object) { return UNSAFE.getDouble(object, offset); } @Override protected void read(Object object, Decoder in) throws IOException { UNSAFE.putDouble(object, offset, in.readDouble()); } @Override protected void write(Object object, Encoder out) throws IOException { out.writeDouble(UNSAFE.getDouble(object, offset)); } } final static class UnsafeObjectField extends UnsafeCachedField { protected UnsafeObjectField(Field f) { super(f); } @Override protected void set(Object object, Object value) { UNSAFE.putObject(object, offset, value); } @Override protected Object get(Object object) { return UNSAFE.getObject(object, offset); } @Override protected boolean supportsIO() { return false; } } final static class UnsafeCustomEncodedField extends UnsafeCachedField { private CustomEncoding<?> encoding; UnsafeCustomEncodedField(Field f, CustomEncoding<?> encoding) { super(f); this.encoding = encoding; } @Override protected Object get(Object object) throws IllegalAccessException { return UNSAFE.getObject(object, offset); } @Override protected void set(Object object, Object value) throws IllegalAccessException, IOException { UNSAFE.putObject(object, offset, value); } @Override protected void read(Object object, Decoder in) throws IOException { UNSAFE.putObject(object, offset, encoding.read(in)); } @Override protected void write(Object object, Encoder out) throws IOException { encoding.write(UNSAFE.getObject(object, offset), out); } @Override protected boolean isCustomEncoded() { return true; } } }
7,325
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/Stringable.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Declares that a class or field should be represented by an Avro string. It's * {@link Object#toString()} method will be used to convert it to a string, and * its single String parameter constructor will be used to create instances. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.FIELD }) @Documented public @interface Stringable { }
7,326
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/AvroName.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Sets the avroname for this java field. When reading into this class, a * reflectdatumreader looks for a schema field with the avroname. */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface AvroName { String value(); }
7,327
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/ReflectData.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import org.apache.avro.AvroRuntimeException; import org.apache.avro.AvroTypeException; import org.apache.avro.Conversion; import org.apache.avro.JsonProperties; import org.apache.avro.LogicalType; import org.apache.avro.Protocol; import org.apache.avro.Protocol.Message; import org.apache.avro.Schema; import org.apache.avro.SchemaNormalization; import org.apache.avro.generic.GenericContainer; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericFixed; import org.apache.avro.generic.IndexedRecord; import org.apache.avro.io.BinaryData; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.specific.FixedSize; import org.apache.avro.specific.SpecificData; import org.apache.avro.util.ClassUtils; import org.apache.avro.util.MapUtil; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** Utilities to use existing Java classes and interfaces via reflection. */ public class ReflectData extends SpecificData { private static final String STRING_OUTER_PARENT_REFERENCE = "this$0"; /** * Always false since custom coders are not available for {@link ReflectData}. */ @Override public boolean useCustomCoders() { return false; } /** * {@link ReflectData} implementation that permits null field values. The schema * generated for each field is a union of its declared type and null. */ public static class AllowNull extends ReflectData { private static final AllowNull INSTANCE = new AllowNull(); /** Return the singleton instance. */ public static AllowNull get() { return INSTANCE; } @Override protected Schema createFieldSchema(Field field, Map<String, Schema> names) { Schema schema = super.createFieldSchema(field, names); if (field.getType().isPrimitive()) { // for primitive values, such as int, a null will result in a // NullPointerException at read time return schema; } return makeNullable(schema); } } private static final ReflectData INSTANCE = new ReflectData(); /** For subclasses. Applications normally use {@link ReflectData#get()}. */ public ReflectData() { } /** Construct with a particular classloader. */ public ReflectData(ClassLoader classLoader) { super(classLoader); } /** Return the singleton instance. */ public static ReflectData get() { return INSTANCE; } /** * Cause a class to be treated as though it had an {@link Stringable} * * annotation. */ public ReflectData addStringable(Class c) { stringableClasses.add(c); return this; } /** * If this flag is set to true, default values for fields will be assigned * dynamically using Java reflections. When enabled, defaults are the field * values of an instance created with a no-arg constructor. * * <p> * Let's call this feature `default reflection`. Initially this feature is * disabled. */ private boolean defaultGenerated = false; /** * Enable or disable `default reflection` * * @param enabled set to `true` to enable the feature. This feature is disabled * by default * @return The current instance */ public ReflectData setDefaultsGenerated(boolean enabled) { this.defaultGenerated = enabled; return this; } private final Map<Type, Object> defaultValues = new WeakHashMap<>(); /** * Set the default value for a type. When encountering such type, we'll use this * provided value instead of trying to create a new one. * * <p> * NOTE: This method automatically enable feature `default reflection`. * * @param type The type * @param value Its default value * @return The current instance */ public ReflectData setDefaultGeneratedValue(Type type, Object value) { this.defaultValues.put(type, value); this.setDefaultsGenerated(true); return this; } /** * Get or create new value instance for a field * * @param type The current type * @param field A child field * @return The default field value */ protected Object getOrCreateDefaultValue(Type type, Field field) { Object defaultValue = null; field.setAccessible(true); try { Object typeValue = getOrCreateDefaultValue(type); if (typeValue != null) { defaultValue = field.get(typeValue); } } catch (Exception e) { } return defaultValue; } /** * Get or create new value instance for a type. * * New instances will be instantiated using no-arg constructors. The newly * created one will be cached for later use. * * @param type The type * @return The value */ protected Object getOrCreateDefaultValue(Type type) { return this.defaultValues.computeIfAbsent(type, ignored -> { try { Constructor constructor = ((Class) type).getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (ClassCastException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { // do nothing } return null; }); } @Override public DatumReader createDatumReader(Schema schema) { return new ReflectDatumReader(schema, schema, this); } @Override public DatumReader createDatumReader(Schema writer, Schema reader) { return new ReflectDatumReader(writer, reader, this); } @Override public DatumWriter createDatumWriter(Schema schema) { return new ReflectDatumWriter(schema, this); } @Override public void setField(Object record, String name, int position, Object value) { setField(record, name, position, value, null); } @Override protected void setField(Object record, String name, int position, Object value, Object state) { if (record instanceof IndexedRecord) { super.setField(record, name, position, value); return; } try { getAccessorForField(record, name, position, state).set(record, value); } catch (IllegalAccessException | IOException e) { throw new AvroRuntimeException(e); } } @Override public Object getField(Object record, String name, int position) { return getField(record, name, position, null); } @Override protected Object getField(Object record, String name, int pos, Object state) { if (record instanceof IndexedRecord) { return super.getField(record, name, pos); } try { return getAccessorForField(record, name, pos, state).get(record); } catch (IllegalAccessException e) { throw new AvroRuntimeException(e); } } private FieldAccessor getAccessorForField(Object record, String name, int pos, Object optionalState) { if (optionalState != null) { return ((FieldAccessor[]) optionalState)[pos]; } return getFieldAccessor(record.getClass(), name); } @Override protected boolean isRecord(Object datum) { if (datum == null) return false; if (super.isRecord(datum)) return true; if (datum instanceof Collection) return false; if (datum instanceof Map) return false; if (datum instanceof GenericFixed) return false; return getSchema(datum.getClass()).getType() == Schema.Type.RECORD; } /** * Returns true for arrays and false otherwise, with the following exceptions: * * <ul> * <li> * <p> * Returns true for non-string-keyed maps, which are written as an array of * key/value pair records. * <li> * <p> * Returns false for arrays of bytes, since those should be treated as byte data * type instead. * </ul> */ @Override protected boolean isArray(Object datum) { if (datum == null) return false; Class c = datum.getClass(); return (datum instanceof Collection) || (c.isArray() && c.getComponentType() != Byte.TYPE) || isNonStringMap(datum); } @Override protected Collection getArrayAsCollection(Object datum) { return (datum instanceof Map) ? ((Map) datum).entrySet() : (Collection) datum; } @Override protected boolean isBytes(Object datum) { if (datum == null) return false; if (super.isBytes(datum)) return true; Class c = datum.getClass(); return c.isArray() && c.getComponentType() == Byte.TYPE; } @Override protected Schema getRecordSchema(Object record) { if (record instanceof GenericContainer) return super.getRecordSchema(record); return getSchema(record.getClass()); } @Override public boolean validate(Schema schema, Object datum) { switch (schema.getType()) { case ARRAY: if (!datum.getClass().isArray()) return super.validate(schema, datum); int length = java.lang.reflect.Array.getLength(datum); for (int i = 0; i < length; i++) if (!validate(schema.getElementType(), java.lang.reflect.Array.get(datum, i))) return false; return true; default: return super.validate(schema, datum); } } static final ClassValue<ClassAccessorData> ACCESSOR_CACHE = new ClassValue<ClassAccessorData>() { @Override protected ClassAccessorData computeValue(Class<?> c) { if (!IndexedRecord.class.isAssignableFrom(c)) { return new ClassAccessorData(c); } return null; } }; static class ClassAccessorData { private final Class<?> clazz; private final Map<String, FieldAccessor> byName = new HashMap<>(); // getAccessorsFor is already synchronized, no need to wrap final Map<Schema, FieldAccessor[]> bySchema = new WeakHashMap<>(); private ClassAccessorData(Class<?> c) { clazz = c; for (Field f : getFields(c, false)) { if (f.isAnnotationPresent(AvroIgnore.class)) { continue; } FieldAccessor accessor = ReflectionUtil.getFieldAccess().getAccessor(f); AvroName avroname = f.getAnnotation(AvroName.class); byName.put((avroname != null ? avroname.value() : f.getName()), accessor); } } /** * Return the field accessors as an array, indexed by the field index of the * given schema. */ private synchronized FieldAccessor[] getAccessorsFor(Schema schema) { // if synchronized is removed from this method, adjust bySchema appropriately FieldAccessor[] result = bySchema.get(schema); if (result == null) { result = createAccessorsFor(schema); bySchema.put(schema, result); } return result; } private FieldAccessor[] createAccessorsFor(Schema schema) { List<Schema.Field> avroFields = schema.getFields(); FieldAccessor[] result = new FieldAccessor[avroFields.size()]; for (Schema.Field avroField : schema.getFields()) { result[avroField.pos()] = byName.get(avroField.name()); } return result; } private FieldAccessor getAccessorFor(String fieldName) { FieldAccessor result = byName.get(fieldName); if (result == null) { throw new AvroRuntimeException("No field named " + fieldName + " in: " + clazz); } return result; } } private ClassAccessorData getClassAccessorData(Class<?> c) { return ACCESSOR_CACHE.get(c); } private FieldAccessor[] getFieldAccessors(Class<?> c, Schema s) { ClassAccessorData data = getClassAccessorData(c); if (data != null) { return data.getAccessorsFor(s); } return null; } private FieldAccessor getFieldAccessor(Class<?> c, String fieldName) { ClassAccessorData data = getClassAccessorData(c); if (data != null) { return data.getAccessorFor(fieldName); } return null; } /** @deprecated Replaced by {@link SpecificData#CLASS_PROP} */ @Deprecated static final String CLASS_PROP = "java-class"; /** @deprecated Replaced by {@link SpecificData#KEY_CLASS_PROP} */ @Deprecated static final String KEY_CLASS_PROP = "java-key-class"; /** @deprecated Replaced by {@link SpecificData#ELEMENT_PROP} */ @Deprecated static final String ELEMENT_PROP = "java-element-class"; private static final Map<String, Class> CLASS_CACHE = new ConcurrentHashMap<>(); static Class getClassProp(Schema schema, String prop) { String name = schema.getProp(prop); if (name == null) return null; Class c = CLASS_CACHE.get(name); if (c != null) return c; try { c = ClassUtils.forName(name); CLASS_CACHE.put(name, c); } catch (ClassNotFoundException e) { throw new AvroRuntimeException(e); } return c; } private static final Class BYTES_CLASS = byte[].class; private static final IdentityHashMap<Class, Class> ARRAY_CLASSES; static { ARRAY_CLASSES = new IdentityHashMap<>(); ARRAY_CLASSES.put(byte.class, byte[].class); ARRAY_CLASSES.put(char.class, char[].class); ARRAY_CLASSES.put(short.class, short[].class); ARRAY_CLASSES.put(int.class, int[].class); ARRAY_CLASSES.put(long.class, long[].class); ARRAY_CLASSES.put(float.class, float[].class); ARRAY_CLASSES.put(double.class, double[].class); ARRAY_CLASSES.put(boolean.class, boolean[].class); } /** * It returns false for non-string-maps because Avro writes out such maps as an * array of records. Even their JSON representation is an array. */ @Override protected boolean isMap(Object datum) { return (datum instanceof Map) && !isNonStringMap(datum); } /* * Without the Field or Schema corresponding to the datum, it is not possible to * accurately find out the non-stringable nature of the key. So we check the * class of the keys. If the map is empty, then it doesn't matter whether its * considered a string-key map or a non-string-key map */ private boolean isNonStringMap(Object datum) { if (datum instanceof Map) { Map m = (Map) datum; if (m.size() > 0) { Class keyClass = m.keySet().iterator().next().getClass(); return !isStringable(keyClass) && !isStringType(keyClass); } } return false; } @Override public Class getClass(Schema schema) { // see if the element class will be converted and use that class Conversion<?> conversion = getConversionFor(schema.getLogicalType()); if (conversion != null) { return conversion.getConvertedType(); } switch (schema.getType()) { case ARRAY: Class collectionClass = getClassProp(schema, CLASS_PROP); if (collectionClass != null) return collectionClass; Class elementClass = getClass(schema.getElementType()); if (elementClass.isPrimitive()) { // avoid expensive translation to array type when primitive return ARRAY_CLASSES.get(elementClass); } else { return java.lang.reflect.Array.newInstance(elementClass, 0).getClass(); } case STRING: Class stringClass = getClassProp(schema, CLASS_PROP); if (stringClass != null) return stringClass; return String.class; case BYTES: return BYTES_CLASS; case INT: String intClass = schema.getProp(CLASS_PROP); if (Byte.class.getName().equals(intClass)) return Byte.TYPE; if (Short.class.getName().equals(intClass)) return Short.TYPE; if (Character.class.getName().equals(intClass)) return Character.TYPE; default: return super.getClass(schema); } } static final String NS_MAP_ARRAY_RECORD = // record name prefix "org.apache.avro.reflect.Pair"; static final String NS_MAP_KEY = "key"; // name of key field static final int NS_MAP_KEY_INDEX = 0; // index of key field static final String NS_MAP_VALUE = "value"; // name of value field static final int NS_MAP_VALUE_INDEX = 1; // index of value field /* * Non-string map-keys need special handling and we convert it to an array of * records as: [{"key":{...}, "value":{...}}] */ Schema createNonStringMapSchema(Type keyType, Type valueType, Map<String, Schema> names) { Schema keySchema = createSchema(keyType, names); Schema valueSchema = createSchema(valueType, names); Schema.Field keyField = new Schema.Field(NS_MAP_KEY, keySchema, null, null); Schema.Field valueField = new Schema.Field(NS_MAP_VALUE, valueSchema, null, null); String name = getNameForNonStringMapRecord(keyType, valueType, keySchema, valueSchema); Schema elementSchema = Schema.createRecord(name, null, null, false); elementSchema.setFields(Arrays.asList(keyField, valueField)); Schema arraySchema = Schema.createArray(elementSchema); return arraySchema; } /* * Gets a unique and consistent name per key-value pair. So if the same * key-value are seen in another map, the same name is generated again. */ private String getNameForNonStringMapRecord(Type keyType, Type valueType, Schema keySchema, Schema valueSchema) { // Generate a nice name for classes in java* package if (keyType instanceof Class && valueType instanceof Class) { Class keyClass = (Class) keyType; Class valueClass = (Class) valueType; Package pkg1 = keyClass.getPackage(); Package pkg2 = valueClass.getPackage(); if (pkg1 != null && pkg1.getName().startsWith("java") && pkg2 != null && pkg2.getName().startsWith("java")) { return NS_MAP_ARRAY_RECORD + simpleName(keyClass) + simpleName(valueClass); } } String name = keySchema.getFullName() + valueSchema.getFullName(); long fingerprint = SchemaNormalization.fingerprint64(name.getBytes(StandardCharsets.UTF_8)); if (fingerprint < 0) fingerprint = -fingerprint; // ignore sign String fpString = Long.toString(fingerprint, 16); // hex return NS_MAP_ARRAY_RECORD + fpString; } static boolean isNonStringMapSchema(Schema s) { if (s != null && s.getType() == Schema.Type.ARRAY) { Class c = getClassProp(s, CLASS_PROP); return c != null && Map.class.isAssignableFrom(c); } return false; } /** * Get default value for a schema field. Derived classes can override this * method to provide values based on object instantiation * * @param type Type * @param field Field * @param fieldSchema Schema of the field * @return The default value */ protected Object createSchemaDefaultValue(Type type, Field field, Schema fieldSchema) { Object defaultValue; if (defaultGenerated) { defaultValue = getOrCreateDefaultValue(type, field); if (defaultValue != null) { return deepCopy(fieldSchema, defaultValue); } // if we can't get the default value, try to use previous code below } AvroDefault defaultAnnotation = field.getAnnotation(AvroDefault.class); defaultValue = (defaultAnnotation == null) ? null : Schema.parseJsonToObject(defaultAnnotation.value()); if (defaultValue == null && fieldSchema.isNullable()) { defaultValue = JsonProperties.NULL_VALUE; } return defaultValue; } @Override protected Schema createSchema(Type type, Map<String, Schema> names) { if (type instanceof GenericArrayType) { // generic array Type component = ((GenericArrayType) type).getGenericComponentType(); if (component == Byte.TYPE) // byte array return Schema.create(Schema.Type.BYTES); Schema result = Schema.createArray(createSchema(component, names)); setElement(result, component); return result; } else if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) type; Class raw = (Class) ptype.getRawType(); Type[] params = ptype.getActualTypeArguments(); if (Map.class.isAssignableFrom(raw)) { // Map Class key = (Class) params[0]; if (isStringable(key)) { // Stringable key Schema schema = Schema.createMap(createSchema(params[1], names)); schema.addProp(KEY_CLASS_PROP, key.getName()); return schema; } else if (key != String.class) { Schema schema = createNonStringMapSchema(params[0], params[1], names); schema.addProp(CLASS_PROP, raw.getName()); return schema; } } else if (Collection.class.isAssignableFrom(raw)) { // Collection if (params.length != 1) throw new AvroTypeException("No array type specified."); Schema schema = Schema.createArray(createSchema(params[0], names)); schema.addProp(CLASS_PROP, raw.getName()); return schema; } } else if ((type == Byte.class) || (type == Byte.TYPE)) { Schema result = Schema.create(Schema.Type.INT); result.addProp(CLASS_PROP, Byte.class.getName()); return result; } else if ((type == Short.class) || (type == Short.TYPE)) { Schema result = Schema.create(Schema.Type.INT); result.addProp(CLASS_PROP, Short.class.getName()); return result; } else if ((type == Character.class) || (type == Character.TYPE)) { Schema result = Schema.create(Schema.Type.INT); result.addProp(CLASS_PROP, Character.class.getName()); return result; } else if (type instanceof Class) { // Class Class<?> c = (Class<?>) type; while (c.isAnonymousClass()) { c = c.getSuperclass(); } if (c.isPrimitive() || // primitives c == Void.class || c == Boolean.class || c == Integer.class || c == Long.class || c == Float.class || c == Double.class || c == Byte.class || c == Short.class || c == Character.class) return super.createSchema(type, names); if (c.isArray()) { // array Class component = c.getComponentType(); if (component == Byte.TYPE) { // byte array Schema result = Schema.create(Schema.Type.BYTES); result.addProp(CLASS_PROP, c.getName()); return result; } Schema result = Schema.createArray(createSchema(component, names)); result.addProp(CLASS_PROP, c.getName()); setElement(result, component); return result; } AvroSchema explicit = c.getAnnotation(AvroSchema.class); if (explicit != null) // explicit schema return new Schema.Parser().parse(explicit.value()); if (CharSequence.class.isAssignableFrom(c)) // String return Schema.create(Schema.Type.STRING); if (ByteBuffer.class.isAssignableFrom(c)) // bytes return Schema.create(Schema.Type.BYTES); if (Collection.class.isAssignableFrom(c)) // array throw new AvroRuntimeException("Can't find element type of Collection"); Conversion<?> conversion = getConversionByClass(c); if (conversion != null) { return conversion.getRecommendedSchema(); } String fullName = c.getName(); Schema schema = names.get(fullName); if (schema == null) { AvroDoc annotatedDoc = c.getAnnotation(AvroDoc.class); // Docstring String doc = (annotatedDoc != null) ? annotatedDoc.value() : null; String name = c.getSimpleName(); String space = c.getPackage() == null ? "" : c.getPackage().getName(); if (c.getEnclosingClass() != null) // nested class space = c.getEnclosingClass().getName().replace('$', '.'); Union union = c.getAnnotation(Union.class); if (union != null) { // union annotated return getAnnotatedUnion(union, names); } else if (isStringable(c)) { // Stringable Schema result = Schema.create(Schema.Type.STRING); result.addProp(CLASS_PROP, c.getName()); return result; } else if (c.isEnum()) { // Enum List<String> symbols = new ArrayList<>(); Enum[] constants = (Enum[]) c.getEnumConstants(); for (Enum constant : constants) symbols.add(constant.name()); schema = Schema.createEnum(name, doc, space, symbols); consumeAvroAliasAnnotation(c, schema); } else if (GenericFixed.class.isAssignableFrom(c)) { // fixed int size = c.getAnnotation(FixedSize.class).value(); schema = Schema.createFixed(name, doc, space, size); consumeAvroAliasAnnotation(c, schema); } else if (IndexedRecord.class.isAssignableFrom(c)) { // specific return super.createSchema(type, names); } else { // record List<Schema.Field> fields = new ArrayList<>(); boolean error = Throwable.class.isAssignableFrom(c); schema = Schema.createRecord(name, doc, space, error); consumeAvroAliasAnnotation(c, schema); names.put(c.getName(), schema); for (Field field : getCachedFields(c)) if ((field.getModifiers() & (Modifier.TRANSIENT | Modifier.STATIC)) == 0 && !field.isAnnotationPresent(AvroIgnore.class)) { Schema fieldSchema = createFieldSchema(field, names); annotatedDoc = field.getAnnotation(AvroDoc.class); // Docstring doc = (annotatedDoc != null) ? annotatedDoc.value() : null; Object defaultValue = createSchemaDefaultValue(type, field, fieldSchema); AvroName annotatedName = field.getAnnotation(AvroName.class); // Rename fields String fieldName = (annotatedName != null) ? annotatedName.value() : field.getName(); if (STRING_OUTER_PARENT_REFERENCE.equals(fieldName)) { throw new AvroTypeException("Class " + fullName + " must be a static inner class"); } Schema.Field recordField = new Schema.Field(fieldName, fieldSchema, doc, defaultValue); AvroMeta[] metadata = field.getAnnotationsByType(AvroMeta.class); // add metadata for (AvroMeta meta : metadata) { if (recordField.propsContainsKey(meta.key())) { throw new AvroTypeException("Duplicate field prop key: " + meta.key()); } recordField.addProp(meta.key(), meta.value()); } for (Schema.Field f : fields) { if (f.name().equals(fieldName)) throw new AvroTypeException("double field entry: " + fieldName); } consumeFieldAlias(field, recordField); fields.add(recordField); } if (error) // add Throwable message fields.add(new Schema.Field("detailMessage", THROWABLE_MESSAGE, null, null)); schema.setFields(fields); AvroMeta[] metadata = c.getAnnotationsByType(AvroMeta.class); for (AvroMeta meta : metadata) { if (schema.propsContainsKey(meta.key())) { throw new AvroTypeException("Duplicate type prop key: " + meta.key()); } schema.addProp(meta.key(), meta.value()); } } names.put(fullName, schema); } return schema; } return super.createSchema(type, names); } @Override protected boolean isStringable(Class<?> c) { return c.isAnnotationPresent(Stringable.class) || super.isStringable(c); } private String simpleName(Class<?> c) { String simpleName = null; if (c != null) { while (c.isAnonymousClass()) { c = c.getSuperclass(); } simpleName = c.getSimpleName(); } return simpleName; } private static final Schema THROWABLE_MESSAGE = makeNullable(Schema.create(Schema.Type.STRING)); // if array element type is a class with a union annotation, note it // this is required because we cannot set a property on the union itself private void setElement(Schema schema, Type element) { if (!(element instanceof Class)) return; Class<?> c = (Class<?>) element; Union union = c.getAnnotation(Union.class); if (union != null) // element is annotated union schema.addProp(ELEMENT_PROP, c.getName()); } // construct a schema from a union annotation private Schema getAnnotatedUnion(Union union, Map<String, Schema> names) { List<Schema> branches = new ArrayList<>(); for (Class branch : union.value()) branches.add(createSchema(branch, names)); return Schema.createUnion(branches); } /** Create and return a union of the null schema and the provided schema. */ public static Schema makeNullable(Schema schema) { if (schema.getType() == Schema.Type.UNION) { // check to see if the union already contains NULL for (Schema subType : schema.getTypes()) { if (subType.getType() == Schema.Type.NULL) { return schema; } } // add null as the first type in a new union List<Schema> withNull = new ArrayList<>(); withNull.add(Schema.create(Schema.Type.NULL)); withNull.addAll(schema.getTypes()); return Schema.createUnion(withNull); } else { // create a union with null return Schema.createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), schema)); } } private static final ConcurrentMap<Class<?>, Field[]> FIELDS_CACHE = new ConcurrentHashMap<>(); // Return of this class and its superclasses to serialize. private static Field[] getCachedFields(Class<?> recordClass) { return MapUtil.computeIfAbsent(FIELDS_CACHE, recordClass, rc -> getFields(rc, true)); } private static Field[] getFields(Class<?> recordClass, boolean excludeJava) { Field[] fieldsList; Map<String, Field> fields = new LinkedHashMap<>(); Class<?> c = recordClass; do { if (excludeJava && c.getPackage() != null && c.getPackage().getName().startsWith("java.")) break; // skip java built-in classes Field[] declaredFields = c.getDeclaredFields(); Arrays.sort(declaredFields, Comparator.comparing(Field::getName)); for (Field field : declaredFields) if ((field.getModifiers() & (Modifier.TRANSIENT | Modifier.STATIC)) == 0) if (fields.put(field.getName(), field) != null) throw new AvroTypeException(c + " contains two fields named: " + field); c = c.getSuperclass(); } while (c != null); fieldsList = fields.values().toArray(new Field[0]); return fieldsList; } /** Create a schema for a field. */ protected Schema createFieldSchema(Field field, Map<String, Schema> names) { AvroEncode enc = field.getAnnotation(AvroEncode.class); if (enc != null) try { return enc.using().getDeclaredConstructor().newInstance().getSchema(); } catch (Exception e) { throw new AvroRuntimeException("Could not create schema from custom serializer for " + field.getName()); } AvroSchema explicit = field.getAnnotation(AvroSchema.class); if (explicit != null) // explicit schema return new Schema.Parser().parse(explicit.value()); Union union = field.getAnnotation(Union.class); if (union != null) return getAnnotatedUnion(union, names); Schema schema = createSchema(field.getGenericType(), names); if (field.isAnnotationPresent(Stringable.class)) { // Stringable schema = Schema.create(Schema.Type.STRING); } if (field.isAnnotationPresent(Nullable.class)) // nullable schema = makeNullable(schema); return schema; } /** * Return the protocol for a Java interface. * * <p> * The correct name of the method parameters needs the <code>-parameters</code> * java compiler argument. More info at https://openjdk.java.net/jeps/118 */ @Override public Protocol getProtocol(Class iface) { Protocol protocol = new Protocol(simpleName(iface), iface.getPackage() == null ? "" : iface.getPackage().getName()); Map<String, Schema> names = new LinkedHashMap<>(); Map<String, Message> messages = protocol.getMessages(); Map<TypeVariable<?>, Type> genericTypeVariableMap = ReflectionUtil.resolveTypeVariables(iface); for (Method method : iface.getMethods()) { if ((method.getModifiers() & Modifier.STATIC) == 0) { String name = method.getName(); if (messages.containsKey(name)) throw new AvroTypeException("Two methods with same name: " + name); messages.put(name, getMessage(method, protocol, names, genericTypeVariableMap)); } } // reverse types, since they were defined in reference order List<Schema> types = new ArrayList<>(names.values()); Collections.reverse(types); protocol.setTypes(types); return protocol; } private Message getMessage(Method method, Protocol protocol, Map<String, Schema> names, Map<? extends Type, Type> genericTypeMap) { List<Schema.Field> fields = new ArrayList<>(); for (Parameter parameter : method.getParameters()) { Schema paramSchema = getSchema(genericTypeMap.getOrDefault(parameter.getParameterizedType(), parameter.getType()), names); for (Annotation annotation : parameter.getAnnotations()) { if (annotation instanceof AvroSchema) // explicit schema paramSchema = new Schema.Parser().parse(((AvroSchema) annotation).value()); else if (annotation instanceof Union) // union paramSchema = getAnnotatedUnion(((Union) annotation), names); else if (annotation instanceof Nullable) // nullable paramSchema = makeNullable(paramSchema); } fields.add(new Schema.Field(unmangle(parameter.getName()), paramSchema, null /* doc */, null)); } Schema request = Schema.createRecord(fields); Type genericReturnType = method.getGenericReturnType(); Type returnType = genericTypeMap.getOrDefault(genericReturnType, genericReturnType); Union union = method.getAnnotation(Union.class); Schema response = union == null ? getSchema(returnType, names) : getAnnotatedUnion(union, names); if (method.isAnnotationPresent(Nullable.class)) // nullable response = makeNullable(response); AvroSchema explicit = method.getAnnotation(AvroSchema.class); if (explicit != null) // explicit schema response = new Schema.Parser().parse(explicit.value()); List<Schema> errs = new ArrayList<>(); errs.add(Protocol.SYSTEM_ERROR); // every method can throw for (Type err : method.getGenericExceptionTypes()) errs.add(getSchema(err, names)); Schema errors = Schema.createUnion(errs); return protocol.createMessage(method.getName(), null /* doc */, Collections.emptyMap() /* propMap */, request, response, errors); } private Schema getSchema(Type type, Map<String, Schema> names) { try { return createSchema(type, names); } catch (AvroTypeException e) { // friendly exception throw new AvroTypeException("Error getting schema for " + type + ": " + e.getMessage(), e); } } @Override protected int compare(Object o1, Object o2, Schema s, boolean equals) { switch (s.getType()) { case ARRAY: if (!o1.getClass().isArray()) break; Schema elementType = s.getElementType(); int l1 = java.lang.reflect.Array.getLength(o1); int l2 = java.lang.reflect.Array.getLength(o2); int l = Math.min(l1, l2); for (int i = 0; i < l; i++) { int compare = compare(java.lang.reflect.Array.get(o1, i), java.lang.reflect.Array.get(o2, i), elementType, equals); if (compare != 0) return compare; } return Integer.compare(l1, l2); case BYTES: if (!o1.getClass().isArray()) break; byte[] b1 = (byte[]) o1; byte[] b2 = (byte[]) o2; return BinaryData.compareBytes(b1, 0, b1.length, b2, 0, b2.length); } return super.compare(o1, o2, s, equals); } @Override protected Object getRecordState(Object record, Schema schema) { return getFieldAccessors(record.getClass(), schema); } private void consumeAvroAliasAnnotation(Class<?> c, Schema schema) { AvroAlias[] aliases = c.getAnnotationsByType(AvroAlias.class); for (AvroAlias alias : aliases) { String space = alias.space(); if (AvroAlias.NULL.equals(space)) space = null; schema.addAlias(alias.alias(), space); } } private void consumeFieldAlias(Field field, Schema.Field recordField) { AvroAlias[] aliases = field.getAnnotationsByType(AvroAlias.class); for (AvroAlias alias : aliases) { if (!alias.space().equals(AvroAlias.NULL)) { throw new AvroRuntimeException( "Namespaces are not allowed on field aliases. " + "Offending field: " + recordField.name()); } recordField.addAlias(alias.alias()); } } @Override public Object createFixed(Object old, Schema schema) { // SpecificData will try to instantiate the type returned by getClass, but // that is the converted class and can't be constructed. LogicalType logicalType = schema.getLogicalType(); if (logicalType != null) { Conversion<?> conversion = getConversionFor(schema.getLogicalType()); if (conversion != null) { return new GenericData.Fixed(schema); } } return super.createFixed(old, schema); } @Override public Object newRecord(Object old, Schema schema) { // SpecificData will try to instantiate the type returned by getClass, but // that is the converted class and can't be constructed. LogicalType logicalType = schema.getLogicalType(); if (logicalType != null) { Conversion<?> conversion = getConversionFor(schema.getLogicalType()); if (conversion != null) { return new GenericData.Record(schema); } } return super.newRecord(old, schema); } }
7,328
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/DateAsLongEncoding.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.io.IOException; import java.util.Date; import org.apache.avro.Schema; import org.apache.avro.io.Decoder; import org.apache.avro.io.Encoder; /** * This encoder/decoder writes a java.util.Date object as a long to avro and * reads a Date object from long. The long stores the number of milliseconds * since January 1, 1970, 00:00:00 GMT represented by the Date object. */ public class DateAsLongEncoding extends CustomEncoding<Date> { { schema = Schema.create(Schema.Type.LONG); schema.addProp("CustomEncoding", "DateAsLongEncoding"); } @Override protected final void write(Object datum, Encoder out) throws IOException { out.writeLong(((Date) datum).getTime()); } @Override protected final Date read(Object reuse, Decoder in) throws IOException { if (reuse instanceof Date) { ((Date) reuse).setTime(in.readLong()); return (Date) reuse; } else return new Date(in.readLong()); } }
7,329
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/ArrayAccessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.io.IOException; import java.util.Arrays; import org.apache.avro.io.Encoder; import org.apache.avro.io.ResolvingDecoder; /** * Helper class to provide native array access whenever possible. It is much * faster than using reflection-based operations on arrays. */ class ArrayAccessor { static void writeArray(boolean[] data, Encoder out) throws IOException { int size = data.length; out.setItemCount(size); for (boolean datum : data) { out.startItem(); out.writeBoolean(datum); } } // short, and char arrays are upcast to avro int static void writeArray(short[] data, Encoder out) throws IOException { int size = data.length; out.setItemCount(size); for (short datum : data) { out.startItem(); out.writeInt(datum); } } static void writeArray(char[] data, Encoder out) throws IOException { int size = data.length; out.setItemCount(size); for (char datum : data) { out.startItem(); out.writeInt(datum); } } static void writeArray(int[] data, Encoder out) throws IOException { int size = data.length; out.setItemCount(size); for (int datum : data) { out.startItem(); out.writeInt(datum); } } static void writeArray(long[] data, Encoder out) throws IOException { int size = data.length; out.setItemCount(size); for (long datum : data) { out.startItem(); out.writeLong(datum); } } static void writeArray(float[] data, Encoder out) throws IOException { int size = data.length; out.setItemCount(size); for (float datum : data) { out.startItem(); out.writeFloat(datum); } } static void writeArray(double[] data, Encoder out) throws IOException { int size = data.length; out.setItemCount(size); for (double datum : data) { out.startItem(); out.writeDouble(datum); } } static Object readArray(Object array, Class<?> elementType, long l, ResolvingDecoder in) throws IOException { if (elementType == int.class) return readArray((int[]) array, l, in); if (elementType == long.class) return readArray((long[]) array, l, in); if (elementType == float.class) return readArray((float[]) array, l, in); if (elementType == double.class) return readArray((double[]) array, l, in); if (elementType == boolean.class) return readArray((boolean[]) array, l, in); if (elementType == char.class) return readArray((char[]) array, l, in); if (elementType == short.class) return readArray((short[]) array, l, in); return null; } static boolean[] readArray(boolean[] array, long l, ResolvingDecoder in) throws IOException { int index = 0; do { int limit = index + (int) l; if (array.length < limit) { array = Arrays.copyOf(array, limit); } while (index < limit) { array[index] = in.readBoolean(); index++; } } while ((l = in.arrayNext()) > 0); return array; } static int[] readArray(int[] array, long l, ResolvingDecoder in) throws IOException { int index = 0; do { int limit = index + (int) l; if (array.length < limit) { array = Arrays.copyOf(array, limit); } while (index < limit) { array[index] = in.readInt(); index++; } } while ((l = in.arrayNext()) > 0); return array; } static short[] readArray(short[] array, long l, ResolvingDecoder in) throws IOException { int index = 0; do { int limit = index + (int) l; if (array.length < limit) { array = Arrays.copyOf(array, limit); } while (index < limit) { array[index] = (short) in.readInt(); index++; } } while ((l = in.arrayNext()) > 0); return array; } static char[] readArray(char[] array, long l, ResolvingDecoder in) throws IOException { int index = 0; do { int limit = index + (int) l; if (array.length < limit) { array = Arrays.copyOf(array, limit); } while (index < limit) { array[index] = (char) in.readInt(); index++; } } while ((l = in.arrayNext()) > 0); return array; } static long[] readArray(long[] array, long l, ResolvingDecoder in) throws IOException { int index = 0; do { int limit = index + (int) l; if (array.length < limit) { array = Arrays.copyOf(array, limit); } while (index < limit) { array[index] = in.readLong(); index++; } } while ((l = in.arrayNext()) > 0); return array; } static float[] readArray(float[] array, long l, ResolvingDecoder in) throws IOException { int index = 0; do { int limit = index + (int) l; if (array.length < limit) { array = Arrays.copyOf(array, limit); } while (index < limit) { array[index] = in.readFloat(); index++; } } while ((l = in.arrayNext()) > 0); return array; } static double[] readArray(double[] array, long l, ResolvingDecoder in) throws IOException { int index = 0; do { int limit = index + (int) l; if (array.length < limit) { array = Arrays.copyOf(array, limit); } while (index < limit) { array[index] = in.readDouble(); index++; } } while ((l = in.arrayNext()) > 0); return array; } }
7,330
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/MapEntry.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.util.Map; /** * Class to make Avro immune from the naming variations of key/value fields * among several {@link java.util.Map.Entry} implementations. If objects of this * class are used instead of the regular ones obtained by * {@link Map#entrySet()}, then we need not worry about the actual field-names * or any changes to them in the future.<BR> * Example: {@code ConcurrentHashMap.MapEntry} does not name the fields as key/ * value in Java 1.8 while it used to do so in Java 1.7 * * @param <K> Key of the map-entry * @param <V> Value of the map-entry * @deprecated Use org.apache.avro.util.MapEntry */ @Deprecated public class MapEntry<K, V> implements Map.Entry<K, V> { K key; V value; public MapEntry(K key, V value) { this.key = key; this.value = value; } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } }
7,331
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/AvroSchema.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Declares that a Java type should have a specified Avro schema, overriding the * normally inferred schema. May be used for classes, parameters, fields and * method return types. * <p> * This is useful for slight alterations to the schema that would be * automatically inferred. For example, a <code>List&lt;Integer&gt;</code>whose * elements may be null might use the annotation * * <pre> * &#64;AvroSchema("{\"type\":\"array\",\"items\":[\"null\",\"int\"]}") * </pre> * * since the {@link Nullable} annotation could not be used here. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD }) @Documented public @interface AvroSchema { /** The schema to use for this value. */ String value(); }
7,332
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/FieldAccessReflect.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import org.apache.avro.AvroRuntimeException; import org.apache.avro.io.Decoder; import org.apache.avro.io.Encoder; import java.io.IOException; import java.lang.reflect.Field; class FieldAccessReflect extends FieldAccess { @Override protected FieldAccessor getAccessor(Field field) { AvroEncode enc = field.getAnnotation(AvroEncode.class); if (enc != null) try { return new ReflectionBasesAccessorCustomEncoded(field, enc.using().getDeclaredConstructor().newInstance()); } catch (Exception e) { throw new AvroRuntimeException("Could not instantiate custom Encoding"); } return new ReflectionBasedAccessor(field); } private static class ReflectionBasedAccessor extends FieldAccessor { protected final Field field; private boolean isStringable; private boolean isCustomEncoded; public ReflectionBasedAccessor(Field field) { this.field = field; this.field.setAccessible(true); isStringable = field.isAnnotationPresent(Stringable.class); isCustomEncoded = field.isAnnotationPresent(AvroEncode.class); } @Override public String toString() { return field.getName(); } @Override public Object get(Object object) throws IllegalAccessException { return field.get(object); } @Override public void set(Object object, Object value) throws IllegalAccessException, IOException { if (value == null && field.getType().isPrimitive()) { Object defaultValue = null; if (int.class.equals(field.getType())) { defaultValue = INT_DEFAULT_VALUE; } else if (float.class.equals(field.getType())) { defaultValue = FLOAT_DEFAULT_VALUE; } else if (short.class.equals(field.getType())) { defaultValue = SHORT_DEFAULT_VALUE; } else if (byte.class.equals(field.getType())) { defaultValue = BYTE_DEFAULT_VALUE; } else if (boolean.class.equals(field.getType())) { defaultValue = BOOLEAN_DEFAULT_VALUE; } else if (char.class.equals(field.getType())) { defaultValue = CHAR_DEFAULT_VALUE; } else if (long.class.equals(field.getType())) { defaultValue = LONG_DEFAULT_VALUE; } else if (double.class.equals(field.getType())) { defaultValue = DOUBLE_DEFAULT_VALUE; } field.set(object, defaultValue); } else { field.set(object, value); } } @Override protected Field getField() { return field; } @Override protected boolean isStringable() { return isStringable; } @Override protected boolean isCustomEncoded() { return isCustomEncoded; } } private static final class ReflectionBasesAccessorCustomEncoded extends ReflectionBasedAccessor { private CustomEncoding<?> encoding; public ReflectionBasesAccessorCustomEncoded(Field f, CustomEncoding<?> encoding) { super(f); this.encoding = encoding; } @Override protected void read(Object object, Decoder in) throws IOException { try { field.set(object, encoding.read(in)); } catch (IllegalAccessException e) { throw new AvroRuntimeException(e); } } @Override protected void write(Object object, Encoder out) throws IOException { try { encoding.write(field.get(object), out); } catch (IllegalAccessException e) { throw new AvroRuntimeException(e); } } @Override protected boolean isCustomEncoded() { return true; } @Override protected boolean supportsIO() { return true; } } }
7,333
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/AvroIgnore.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks a field as transient. Such a field will not get written into or read * from a schema, when using reflection. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD }) public @interface AvroIgnore { }
7,334
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/ReflectionUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import org.apache.avro.AvroRuntimeException; import java.lang.invoke.CallSite; import java.lang.invoke.LambdaMetafactory; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.IdentityHashMap; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; /** * A few utility methods for using @link{java.misc.Unsafe}, mostly for private * use. * * Use of Unsafe on Android is forbidden, as Android provides only a very * limited functionality for this class compared to the JDK version. * * InterfaceAudience.Private */ public class ReflectionUtil { private ReflectionUtil() { } private static FieldAccess fieldAccess; static { resetFieldAccess(); } static void resetFieldAccess() { // load only one implementation of FieldAccess // so it is monomorphic and the JIT can inline FieldAccess access = null; try { if (null == System.getProperty("avro.disable.unsafe")) { FieldAccess unsafeAccess = load("org.apache.avro.reflect.FieldAccessUnsafe", FieldAccess.class); if (validate(unsafeAccess)) { access = unsafeAccess; } } } catch (Throwable ignored) { } if (access == null) { try { FieldAccess reflectAccess = load("org.apache.avro.reflect.FieldAccessReflect", FieldAccess.class); if (validate(reflectAccess)) { access = reflectAccess; } } catch (Throwable oops) { throw new AvroRuntimeException("Unable to load a functional FieldAccess class!"); } } fieldAccess = access; } private static <T> T load(String name, Class<T> type) throws Exception { return ReflectionUtil.class.getClassLoader().loadClass(name).asSubclass(type).getDeclaredConstructor() .newInstance(); } public static FieldAccess getFieldAccess() { return fieldAccess; } private static boolean validate(FieldAccess access) throws Exception { return new AccessorTestClass().validate(access); } private static final class AccessorTestClass { private boolean b = true; protected byte by = 0xf; public char c = 'c'; short s = 123; int i = 999; long l = 12345L; float f = 2.2f; double d = 4.4d; Object o = "foo"; Integer i2 = 555; private boolean validate(FieldAccess access) throws Exception { boolean valid = true; valid &= validField(access, "b", b, false); valid &= validField(access, "by", by, (byte) 0xaf); valid &= validField(access, "c", c, 'C'); valid &= validField(access, "s", s, (short) 321); valid &= validField(access, "i", i, 111); valid &= validField(access, "l", l, 54321L); valid &= validField(access, "f", f, 0.2f); valid &= validField(access, "d", d, 0.4d); valid &= validField(access, "o", o, new Object()); valid &= validField(access, "i2", i2, -555); return valid; } private boolean validField(FieldAccess access, String name, Object original, Object toSet) throws Exception { FieldAccessor a = accessor(access, name); boolean valid = original.equals(a.get(this)); a.set(this, toSet); valid &= !original.equals(a.get(this)); return valid; } private FieldAccessor accessor(FieldAccess access, String name) throws Exception { return access.getAccessor(this.getClass().getDeclaredField(name)); } } /** * For an interface, get a map of any {@link TypeVariable}s to their actual * types. * * @param iface interface to resolve types for. * @return a map of {@link TypeVariable}s to actual types. */ protected static Map<TypeVariable<?>, Type> resolveTypeVariables(Class<?> iface) { return resolveTypeVariables(iface, new IdentityHashMap<>()); } private static Map<TypeVariable<?>, Type> resolveTypeVariables(Class<?> iface, Map<TypeVariable<?>, Type> reuse) { for (Type type : iface.getGenericInterfaces()) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type rawType = parameterizedType.getRawType(); if (rawType instanceof Class<?>) { Class<?> classType = (Class<?>) rawType; TypeVariable<? extends Class<?>>[] typeParameters = classType.getTypeParameters(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (int i = 0; i < typeParameters.length; i++) { reuse.putIfAbsent(typeParameters[i], reuse.getOrDefault(actualTypeArguments[i], actualTypeArguments[i])); } resolveTypeVariables(classType, reuse); } } } return reuse; } private static <D> Supplier<D> getConstructorAsSupplier(Class<D> clazz) { try { MethodHandles.Lookup lookup = MethodHandles.lookup(); MethodHandle constructorHandle = lookup.findConstructor(clazz, MethodType.methodType(void.class)); CallSite site = LambdaMetafactory.metafactory(lookup, "get", MethodType.methodType(Supplier.class), constructorHandle.type().generic(), constructorHandle, constructorHandle.type()); return (Supplier<D>) site.getTarget().invokeExact(); } catch (Throwable t) { // if anything goes wrong, don't provide a Supplier return null; } } private static <V, R> Supplier<R> getOneArgConstructorAsSupplier(Class<R> clazz, Class<V> argumentClass, V argument) { Function<V, R> supplierFunction = getConstructorAsFunction(argumentClass, clazz); if (supplierFunction != null) { return () -> supplierFunction.apply(argument); } else { return null; } } public static <V, R> Function<V, R> getConstructorAsFunction(Class<V> parameterClass, Class<R> clazz) { try { MethodHandles.Lookup lookup = MethodHandles.lookup(); MethodHandle constructorHandle = lookup.findConstructor(clazz, MethodType.methodType(void.class, parameterClass)); CallSite site = LambdaMetafactory.metafactory(lookup, "apply", MethodType.methodType(Function.class), constructorHandle.type().generic(), constructorHandle, constructorHandle.type()); return (Function<V, R>) site.getTarget().invokeExact(); } catch (Throwable t) { // if something goes wrong, do not provide a Function instance return null; } } }
7,335
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/AvroDoc.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Sets the avrodoc for this java field. When reading into this class, a * reflectdatumreader looks for a schema field with the avrodoc. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.FIELD }) public @interface AvroDoc { String value(); }
7,336
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/Nullable.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Declares that null is a valid value for a Java type. Causes an Avro union * with null to be used. May be applied to parameters, fields and methods (to * declare the return type). */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD }) @Documented public @interface Nullable { }
7,337
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/CustomEncoding.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.io.IOException; import org.apache.avro.Schema; import org.apache.avro.io.Decoder; import org.apache.avro.io.Encoder; /** * Expert: a custom encoder and decoder that writes an object directly to avro. * No validation is performed to check that the encoding conforms to the schema. * Invalid implementations may result in an unreadable file. The use of * {@link org.apache.avro.io.ValidatingEncoder} is recommended. * * @param <T> The class of objects that can be serialized with this encoder / * decoder. */ public abstract class CustomEncoding<T> { protected Schema schema; protected abstract void write(Object datum, Encoder out) throws IOException; protected abstract T read(Object reuse, Decoder in) throws IOException; T read(Decoder in) throws IOException { return this.read(null, in); } protected Schema getSchema() { return schema; } }
7,338
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/reflect/AvroDefault.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.reflect; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Specifies a default value for a field as a JSON string. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD }) public @interface AvroDefault { String value(); }
7,339
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/ResolvingDecoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Objects; import org.apache.avro.AvroTypeException; import org.apache.avro.Schema; import org.apache.avro.io.parsing.ResolvingGrammarGenerator; import org.apache.avro.io.parsing.Symbol; import org.apache.avro.util.Utf8; /** * {@link Decoder} that performs type-resolution between the reader's and * writer's schemas. * * <p> * When resolving schemas, this class will return the values of fields in * _writer's_ order, not the reader's order. (However, it returns _only_ the * reader's fields, not any extra fields the writer may have written.) To help * clients handle fields that appear to be coming out of order, this class * defines the method {@link #readFieldOrder}. * * <p> * See the <a href="parsing/doc-files/parsing.html">parser documentation</a> for * information on how this works. */ public class ResolvingDecoder extends ValidatingDecoder { private Decoder backup; ResolvingDecoder(Schema writer, Schema reader, Decoder in) throws IOException { this(resolve(writer, reader), in); } /** * Constructs a <tt>ResolvingDecoder</tt> using the given resolver. The resolver * must have been returned by a previous call to * {@link #resolve(Schema, Schema)}. * * @param resolver The resolver to use. * @param in The underlying decoder. * @throws IOException */ private ResolvingDecoder(Object resolver, Decoder in) throws IOException { super((Symbol) resolver, in); } /** * Produces an opaque resolver that can be used to construct a new * {@link ResolvingDecoder#ResolvingDecoder(Object, Decoder)}. The returned * Object is immutable and hence can be simultaneously used in many * ResolvingDecoders. This method is reasonably expensive, the users are * encouraged to cache the result. * * @param writer The writer's schema. Cannot be null. * @param reader The reader's schema. Cannot be null. * @return The opaque resolver. * @throws IOException * @throws NullPointerException if {@code writer} or {@code reader} is * {@code null} */ public static Object resolve(Schema writer, Schema reader) throws IOException { Objects.requireNonNull(writer, "Writer schema cannot be null"); Objects.requireNonNull(reader, "Reader schema cannot be null"); return new ResolvingGrammarGenerator().generate(writer, reader); } /** * Returns the actual order in which the reader's fields will be returned to the * reader. * * This method is useful because {@link ResolvingDecoder} returns values in the * order written by the writer, rather than the order expected by the reader. * This method allows readers to figure out what fields to expect. Let's say the * reader is expecting a three-field record, the first field is a long, the * second a string, and the third an array. In this case, a typical usage might * be as follows: * * <pre> * Schema.Fields[] fieldOrder = in.readFieldOrder(); * for (int i = 0; i &lt; 3; i++) { * switch (fieldOrder[i].pos()) { * case 1: * foo(in.readLong()); * break; * case 2: * someVariable = in.readString(); * break; * case 3: * bar(in); // The code of "bar" will read an array-of-int * break; * } * </pre> * * Note that {@link ResolvingDecoder} will return only the fields expected by * the reader, not other fields that may have been written by the writer. Thus, * the iteration-count of "3" in the above loop will always be correct. * * Throws a runtime exception if we're not just about to read the first field of * a record. (If the client knows the order of incoming fields, then the client * does <em>not</em> need to call this method but rather can just start reading * the field values.) * * @throws AvroTypeException If we're not starting a new record * */ public final Schema.Field[] readFieldOrder() throws IOException { return ((Symbol.FieldOrderAction) parser.advance(Symbol.FIELD_ACTION)).fields; } /** * Same as {@link #readFieldOrder} except that it returns <tt>null</tt> if there * was no reordering of fields, i.e., if the correct thing for the reader to do * is to read (all) of its fields in the order specified by its own schema * (useful for optimizations). */ public final Schema.Field[] readFieldOrderIfDiff() throws IOException { Symbol.FieldOrderAction top = (Symbol.FieldOrderAction) parser.advance(Symbol.FIELD_ACTION); return (top.noReorder ? null : top.fields); } /** * Consume any more data that has been written by the writer but not needed by * the reader so that the the underlying decoder is in proper shape for the next * record. This situation happens when, for example, the writer writes a record * with two fields and the reader needs only the first field. * * This function should be called after completely decoding an object but before * next object can be decoded from the same underlying decoder either directly * or through another resolving decoder. If the same resolving decoder is used * for the next object as well, calling this method is optional; the state of * this resolving decoder ensures that any leftover portions are consumed before * the next object is decoded. * * @throws IOException */ public final void drain() throws IOException { parser.processImplicitActions(); } @Override public long readLong() throws IOException { Symbol actual = parser.advance(Symbol.LONG); if (actual == Symbol.INT) { return in.readInt(); } else if (actual == Symbol.DOUBLE) { return (long) in.readDouble(); } else { assert actual == Symbol.LONG; return in.readLong(); } } @Override public float readFloat() throws IOException { Symbol actual = parser.advance(Symbol.FLOAT); if (actual == Symbol.INT) { return (float) in.readInt(); } else if (actual == Symbol.LONG) { return (float) in.readLong(); } else { assert actual == Symbol.FLOAT; return in.readFloat(); } } @Override public double readDouble() throws IOException { Symbol actual = parser.advance(Symbol.DOUBLE); if (actual == Symbol.INT) { return (double) in.readInt(); } else if (actual == Symbol.LONG) { return (double) in.readLong(); } else if (actual == Symbol.FLOAT) { return (double) in.readFloat(); } else { assert actual == Symbol.DOUBLE; return in.readDouble(); } } @Override public Utf8 readString(Utf8 old) throws IOException { Symbol actual = parser.advance(Symbol.STRING); if (actual == Symbol.BYTES) { return new Utf8(in.readBytes(null).array()); } else { assert actual == Symbol.STRING; return in.readString(old); } } @Override public String readString() throws IOException { Symbol actual = parser.advance(Symbol.STRING); if (actual == Symbol.BYTES) { return new String(in.readBytes(null).array(), StandardCharsets.UTF_8); } else { assert actual == Symbol.STRING; return in.readString(); } } @Override public void skipString() throws IOException { Symbol actual = parser.advance(Symbol.STRING); if (actual == Symbol.BYTES) { in.skipBytes(); } else { assert actual == Symbol.STRING; in.skipString(); } } @Override public ByteBuffer readBytes(ByteBuffer old) throws IOException { Symbol actual = parser.advance(Symbol.BYTES); if (actual == Symbol.STRING) { Utf8 s = in.readString(null); return ByteBuffer.wrap(s.getBytes(), 0, s.getByteLength()); } else { assert actual == Symbol.BYTES; return in.readBytes(old); } } @Override public void skipBytes() throws IOException { Symbol actual = parser.advance(Symbol.BYTES); if (actual == Symbol.STRING) { in.skipString(); } else { assert actual == Symbol.BYTES; in.skipBytes(); } } @Override public int readEnum() throws IOException { parser.advance(Symbol.ENUM); Symbol.EnumAdjustAction top = (Symbol.EnumAdjustAction) parser.popSymbol(); int n = in.readEnum(); if (top.noAdjustments) { return n; } Object o = top.adjustments[n]; if (o instanceof Integer) { return (Integer) o; } else { throw new AvroTypeException((String) o); } } @Override public int readIndex() throws IOException { parser.advance(Symbol.UNION); Symbol top = parser.popSymbol(); final int result; if (top instanceof Symbol.UnionAdjustAction) { result = ((Symbol.UnionAdjustAction) top).rindex; top = ((Symbol.UnionAdjustAction) top).symToParse; } else { result = in.readIndex(); top = ((Symbol.Alternative) top).getSymbol(result); } parser.pushSymbol(top); return result; } @Override public Symbol doAction(Symbol input, Symbol top) throws IOException { if (top instanceof Symbol.FieldOrderAction) { return input == Symbol.FIELD_ACTION ? top : null; } if (top instanceof Symbol.ResolvingAction) { Symbol.ResolvingAction t = (Symbol.ResolvingAction) top; if (t.reader != input) { throw new AvroTypeException("Found " + t.reader + " while looking for " + input); } else { return t.writer; } } else if (top instanceof Symbol.SkipAction) { Symbol symToSkip = ((Symbol.SkipAction) top).symToSkip; parser.skipSymbol(symToSkip); } else if (top instanceof Symbol.WriterUnionAction) { Symbol.Alternative branches = (Symbol.Alternative) parser.popSymbol(); parser.pushSymbol(branches.getSymbol(in.readIndex())); } else if (top instanceof Symbol.ErrorAction) { throw new AvroTypeException(((Symbol.ErrorAction) top).msg); } else if (top instanceof Symbol.DefaultStartAction) { Symbol.DefaultStartAction dsa = (Symbol.DefaultStartAction) top; backup = in; in = DecoderFactory.get().binaryDecoder(dsa.contents, null); } else if (top == Symbol.DEFAULT_END_ACTION) { in = backup; } else { throw new AvroTypeException("Unknown action: " + top); } return null; } @Override public void skipAction() throws IOException { Symbol top = parser.popSymbol(); if (top instanceof Symbol.ResolvingAction) { parser.pushSymbol(((Symbol.ResolvingAction) top).writer); } else if (top instanceof Symbol.SkipAction) { parser.pushSymbol(((Symbol.SkipAction) top).symToSkip); } else if (top instanceof Symbol.WriterUnionAction) { Symbol.Alternative branches = (Symbol.Alternative) parser.popSymbol(); parser.pushSymbol(branches.getSymbol(in.readIndex())); } else if (top instanceof Symbol.ErrorAction) { throw new AvroTypeException(((Symbol.ErrorAction) top).msg); } else if (top instanceof Symbol.DefaultStartAction) { Symbol.DefaultStartAction dsa = (Symbol.DefaultStartAction) top; backup = in; in = DecoderFactory.get().binaryDecoder(dsa.contents, null); } else if (top == Symbol.DEFAULT_END_ACTION) { in = backup; } } }
7,340
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/BinaryDecoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Arrays; import org.apache.avro.AvroRuntimeException; import org.apache.avro.InvalidNumberEncodingException; import org.apache.avro.SystemLimitException; import org.apache.avro.util.Utf8; /** * An {@link Decoder} for binary-format data. * <p/> * Instances are created using {@link DecoderFactory}. * <p/> * This class may read-ahead and buffer bytes from the source beyond what is * required to serve its read methods. The number of unused bytes in the buffer * can be accessed by inputStream().remaining(), if the BinaryDecoder is not * 'direct'. * <p/> * * @see Encoder * @see SystemLimitException */ public class BinaryDecoder extends Decoder { /** * When reading a collection (MAP or ARRAY), this keeps track of the number of * elements to ensure that the * {@link SystemLimitException#checkMaxCollectionLength} constraint is * respected. */ private long collectionCount = 0L; private ByteSource source = null; // we keep the buffer and its state variables in this class and not in a // container class for performance reasons. This improves performance // over a container object by about 5% to 15% // for example, we could have a FastBuffer class with these state variables // and keep a private FastBuffer member here. This simplifies the // "detach source" code and source access to the buffer, but // hurts performance. private byte[] buf = null; private int minPos = 0; private int pos = 0; private int limit = 0; byte[] getBuf() { return buf; } int getPos() { return pos; } int getLimit() { return limit; } void setBuf(byte[] buf, int pos, int len) { this.buf = buf; this.pos = pos; this.limit = pos + len; } void clearBuf() { this.buf = null; } /** protected constructor for child classes */ protected BinaryDecoder() { super(); } BinaryDecoder(InputStream in, int bufferSize) { this(); configure(in, bufferSize); } BinaryDecoder(byte[] data, int offset, int length) { this(); configure(data, offset, length); } BinaryDecoder configure(InputStream in, int bufferSize) { configureSource(bufferSize, new InputStreamByteSource(in)); return this; } BinaryDecoder configure(byte[] data, int offset, int length) { configureSource(DecoderFactory.DEFAULT_BUFFER_SIZE, new ByteArrayByteSource(data, offset, length)); return this; } /** * Initializes this decoder with a new ByteSource. Detaches the old source (if * it exists) from this Decoder. The old source's state no longer depends on * this Decoder and its InputStream interface will continue to drain the * remaining buffer and source data. * <p/> * The decoder will read from the new source. The source will generally replace * the buffer with its own. If the source allocates a new buffer, it will create * it with size bufferSize. */ private void configureSource(int bufferSize, ByteSource source) { if (null != this.source) { this.source.detach(); } source.attach(bufferSize, this); this.source = source; } @Override public void readNull() throws IOException { } @Override public boolean readBoolean() throws IOException { // inlined, shorter version of ensureBounds if (limit == pos) { limit = source.tryReadRaw(buf, 0, buf.length); pos = 0; if (limit == 0) { throw new EOFException(); } } int n = buf[pos++] & 0xff; return n == 1; } @Override public int readInt() throws IOException { ensureBounds(5); // won't throw index out of bounds int len = 1; int b = buf[pos] & 0xff; int n = b & 0x7f; if (b > 0x7f) { b = buf[pos + len++] & 0xff; n ^= (b & 0x7f) << 7; if (b > 0x7f) { b = buf[pos + len++] & 0xff; n ^= (b & 0x7f) << 14; if (b > 0x7f) { b = buf[pos + len++] & 0xff; n ^= (b & 0x7f) << 21; if (b > 0x7f) { b = buf[pos + len++] & 0xff; n ^= (b & 0x7f) << 28; if (b > 0x7f) { throw new InvalidNumberEncodingException("Invalid int encoding"); } } } } } pos += len; if (pos > limit) { throw new EOFException(); } return (n >>> 1) ^ -(n & 1); // back to two's-complement } @Override public long readLong() throws IOException { ensureBounds(10); int b = buf[pos++] & 0xff; int n = b & 0x7f; long l; if (b > 0x7f) { b = buf[pos++] & 0xff; n ^= (b & 0x7f) << 7; if (b > 0x7f) { b = buf[pos++] & 0xff; n ^= (b & 0x7f) << 14; if (b > 0x7f) { b = buf[pos++] & 0xff; n ^= (b & 0x7f) << 21; if (b > 0x7f) { // only the low 28 bits can be set, so this won't carry // the sign bit to the long l = innerLongDecode((long) n); } else { l = n; } } else { l = n; } } else { l = n; } } else { l = n; } if (pos > limit) { throw new EOFException(); } return (l >>> 1) ^ -(l & 1); // back to two's-complement } // splitting readLong up makes it faster because of the JVM does more // optimizations on small methods private long innerLongDecode(long l) throws IOException { int len = 1; int b = buf[pos] & 0xff; l ^= (b & 0x7fL) << 28; if (b > 0x7f) { b = buf[pos + len++] & 0xff; l ^= (b & 0x7fL) << 35; if (b > 0x7f) { b = buf[pos + len++] & 0xff; l ^= (b & 0x7fL) << 42; if (b > 0x7f) { b = buf[pos + len++] & 0xff; l ^= (b & 0x7fL) << 49; if (b > 0x7f) { b = buf[pos + len++] & 0xff; l ^= (b & 0x7fL) << 56; if (b > 0x7f) { b = buf[pos + len++] & 0xff; l ^= (b & 0x7fL) << 63; if (b > 0x7f) { throw new InvalidNumberEncodingException("Invalid long encoding"); } } } } } } pos += len; return l; } @Override public float readFloat() throws IOException { ensureBounds(4); int len = 1; int n = (buf[pos] & 0xff) | ((buf[pos + len++] & 0xff) << 8) | ((buf[pos + len++] & 0xff) << 16) | ((buf[pos + len++] & 0xff) << 24); if ((pos + 4) > limit) { throw new EOFException(); } pos += 4; return Float.intBitsToFloat(n); } @Override public double readDouble() throws IOException { ensureBounds(8); int len = 1; int n1 = (buf[pos] & 0xff) | ((buf[pos + len++] & 0xff) << 8) | ((buf[pos + len++] & 0xff) << 16) | ((buf[pos + len++] & 0xff) << 24); int n2 = (buf[pos + len++] & 0xff) | ((buf[pos + len++] & 0xff) << 8) | ((buf[pos + len++] & 0xff) << 16) | ((buf[pos + len++] & 0xff) << 24); if ((pos + 8) > limit) { throw new EOFException(); } pos += 8; return Double.longBitsToDouble((((long) n1) & 0xffffffffL) | (((long) n2) << 32)); } @Override public Utf8 readString(Utf8 old) throws IOException { int length = SystemLimitException.checkMaxStringLength(readLong()); Utf8 result = (old != null ? old : new Utf8()); result.setByteLength(length); if (0 != length) { doReadBytes(result.getBytes(), 0, length); } return result; } private final Utf8 scratchUtf8 = new Utf8(); @Override public String readString() throws IOException { return readString(scratchUtf8).toString(); } @Override public void skipString() throws IOException { doSkipBytes(readLong()); } @Override public ByteBuffer readBytes(ByteBuffer old) throws IOException { int length = SystemLimitException.checkMaxBytesLength(readLong()); final ByteBuffer result; if (old != null && length <= old.capacity()) { result = old; result.clear(); } else { result = ByteBuffer.allocate(length); } doReadBytes(result.array(), result.position(), length); result.limit(length); return result; } @Override public void skipBytes() throws IOException { doSkipBytes(readLong()); } @Override public void readFixed(byte[] bytes, int start, int length) throws IOException { doReadBytes(bytes, start, length); } @Override public void skipFixed(int length) throws IOException { doSkipBytes(length); } @Override public int readEnum() throws IOException { return readInt(); } protected void doSkipBytes(long length) throws IOException { int remaining = limit - pos; if (length <= remaining) { pos = (int) (pos + length); } else { limit = pos = 0; length -= remaining; source.skipSourceBytes(length); } } /** * Reads <tt>length</tt> bytes into <tt>bytes</tt> starting at <tt>start</tt>. * * @throws EOFException If there are not enough number of bytes in the source. * @throws IOException */ protected void doReadBytes(byte[] bytes, int start, int length) throws IOException { if (length < 0) throw new AvroRuntimeException("Malformed data. Length is negative: " + length); int remaining = limit - pos; if (length <= remaining) { System.arraycopy(buf, pos, bytes, start, length); pos += length; } else { // read the rest of the buffer System.arraycopy(buf, pos, bytes, start, remaining); start += remaining; length -= remaining; pos = limit; // finish from the byte source source.readRaw(bytes, start, length); } } /** * Returns the number of items to follow in the current array or map. Returns 0 * if there are no more items in the current array and the array/map has ended. * Arrays are encoded as a series of blocks. Each block consists of a long count * value, followed by that many array items. A block with count zero indicates * the end of the array. If a block's count is negative, its absolute value is * used, and the count is followed immediately by a long block size indicating * the number of bytes in the block. * * @throws IOException If the first byte cannot be read for any reason other * than the end of the file, if the input stream has been * closed, or if some other I/O error occurs. */ protected long doReadItemCount() throws IOException { long result = readLong(); if (result < 0L) { // Consume byte-count if present readLong(); result = -result; } return result; } /** * Reads the count of items in the current array or map and skip those items, if * possible. If it could skip the items, keep repeating until there are no more * items left in the array or map. Arrays are encoded as a series of blocks. * Each block consists of a long count value, followed by that many array items. * A block with count zero indicates the end of the array. If a block's count is * negative, its absolute value is used, and the count is followed immediately * by a long block size indicating the number of bytes in the block. If block * size is missing, this method return the count of the items found. The client * needs to skip the items individually. * * @return Zero if there are no more items to skip and end of array/map is * reached. Positive number if some items are found that cannot be * skipped and the client needs to skip them individually. * @throws IOException If the first byte cannot be read for any reason other * than the end of the file, if the input stream has been * closed, or if some other I/O error occurs. */ private long doSkipItems() throws IOException { long result = readLong(); while (result < 0L) { final long bytecount = readLong(); doSkipBytes(bytecount); result = readLong(); } return result; } @Override public long readArrayStart() throws IOException { collectionCount = SystemLimitException.checkMaxCollectionLength(0L, doReadItemCount()); return collectionCount; } @Override public long arrayNext() throws IOException { long length = doReadItemCount(); collectionCount = SystemLimitException.checkMaxCollectionLength(collectionCount, length); return length; } @Override public long skipArray() throws IOException { return doSkipItems(); } @Override public long readMapStart() throws IOException { collectionCount = SystemLimitException.checkMaxCollectionLength(0L, doReadItemCount()); return collectionCount; } @Override public long mapNext() throws IOException { long length = doReadItemCount(); collectionCount = SystemLimitException.checkMaxCollectionLength(collectionCount, length); return length; } @Override public long skipMap() throws IOException { return doSkipItems(); } @Override public int readIndex() throws IOException { return readInt(); } /** * Returns true if the current BinaryDecoder is at the end of its source data * and cannot read any further without throwing an EOFException or other * IOException. * <p/> * Not all implementations of BinaryDecoder support isEnd(). Implementations * that do not support isEnd() will throw a * {@link java.lang.UnsupportedOperationException}. * * @throws IOException If the first byte cannot be read for any reason other * than the end of the file, if the input stream has been * closed, or if some other I/O error occurs. */ public boolean isEnd() throws IOException { if (pos < limit) { return false; } if (source.isEof()) { return true; } // read from source. final int read = source.tryReadRaw(buf, 0, buf.length); pos = 0; limit = read; return (0 == read); } /** * Ensures that buf[pos + num - 1] is not out of the buffer array bounds. * However, buf[pos + num -1] may be >= limit if there is not enough data left * in the source to fill the array with num bytes. * <p/> * This method allows readers to read ahead by num bytes safely without checking * for EOF at each byte. However, readers must ensure that their reads are valid * by checking that their read did not advance past the limit before adjusting * pos. * <p/> * num must be less than the buffer size and greater than 0 */ private void ensureBounds(int num) throws IOException { int remaining = limit - pos; if (remaining < num) { // move remaining to front source.compactAndFill(buf, pos, minPos, remaining); if (pos >= limit) throw new EOFException(); } } /** * Returns an {@link java.io.InputStream} that is aware of any buffering that * may occur in this BinaryDecoder. Readers that need to interleave decoding * Avro data with other reads must access this InputStream to do so unless the * implementation is 'direct' and does not read beyond the minimum bytes * necessary from the source. */ public InputStream inputStream() { return source; } /** * BufferAccessor is used by BinaryEncoder to enable {@link ByteSource}s and the * InputStream returned by {@link BinaryDecoder#inputStream} to access the * BinaryEncoder's buffer. When a BufferAccessor is created, it is attached to a * BinaryDecoder and its buffer. Its accessors directly reference the * BinaryDecoder's buffer. When detach() is called, it stores references to the * BinaryDecoder's buffer directly. The BinaryDecoder only detaches a * BufferAccessor when it is initializing to a new ByteSource. Therefore, a * client that is using the InputStream returned by BinaryDecoder.inputStream * can continue to use that stream after a BinaryDecoder has been reinitialized * to read from new data. */ static class BufferAccessor { private final BinaryDecoder decoder; private byte[] buf; private int pos; private int limit; boolean detached = false; private BufferAccessor(BinaryDecoder decoder) { this.decoder = decoder; } void detach() { this.buf = decoder.buf; this.pos = decoder.pos; this.limit = decoder.limit; detached = true; } int getPos() { if (detached) return this.pos; else return decoder.pos; } int getLim() { if (detached) return this.limit; else return decoder.limit; } byte[] getBuf() { if (detached) return this.buf; else return decoder.buf; } void setPos(int pos) { if (detached) this.pos = pos; else decoder.pos = pos; } void setLimit(int limit) { if (detached) this.limit = limit; else decoder.limit = limit; } void setBuf(byte[] buf, int offset, int length) { if (detached) { this.buf = buf; this.limit = offset + length; this.pos = offset; } else { decoder.buf = buf; decoder.limit = offset + length; decoder.pos = offset; decoder.minPos = offset; } } } /** * ByteSource abstracts the source of data from the core workings of * BinaryDecoder. This is very important for performance reasons because * InputStream's API is a barrier to performance due to several quirks: * InputStream does not in general require that as many bytes as possible have * been read when filling a buffer. * <p/> * InputStream's terminating conditions for a read are two-fold: EOFException * and '-1' on the return from read(). Implementations are supposed to return * '-1' on EOF but often do not. The extra terminating conditions cause extra * conditionals on both sides of the API, and slow performance significantly. * <p/> * ByteSource implementations provide read() and skip() variants that have * stronger guarantees than InputStream, freeing client code to be simplified * and faster. * <p/> * {@link #skipSourceBytes} and {@link #readRaw} are guaranteed to have read or * skipped as many bytes as possible, or throw EOFException. * {@link #trySkipBytes} and {@link #tryReadRaw} are guaranteed to attempt to * read or skip as many bytes as possible and never throw EOFException, while * returning the exact number of bytes skipped or read. {@link #isEof} returns * true if all the source bytes have been read or skipped. This condition can * also be detected by a client if an EOFException is thrown from * {@link #skipSourceBytes} or {@link #readRaw}, or if {@link #trySkipBytes} or * {@link #tryReadRaw} return 0; * <p/> * A ByteSource also implements the InputStream contract for use by APIs that * require it. The InputStream interface must take into account buffering in any * decoder that this ByteSource is attached to. The other methods do not account * for buffering. */ abstract static class ByteSource extends InputStream { // maintain a reference to the buffer, so that if this // source is detached from the Decoder, and a client still // has a reference to it via inputStream(), bytes are not // lost protected BufferAccessor ba; protected ByteSource() { } abstract boolean isEof(); protected void attach(int bufferSize, BinaryDecoder decoder) { decoder.buf = new byte[bufferSize]; decoder.pos = 0; decoder.minPos = 0; decoder.limit = 0; this.ba = new BufferAccessor(decoder); } protected void detach() { ba.detach(); } /** * Skips length bytes from the source. If length bytes cannot be skipped due to * end of file/stream/channel/etc an EOFException is thrown * * @param length the number of bytes to attempt to skip * @throws IOException if an error occurs * @throws EOFException if length bytes cannot be skipped */ protected abstract void skipSourceBytes(long length) throws IOException; /** * Attempts to skip <i>skipLength</i> bytes from the source. Returns the actual * number of bytes skipped. This method must attempt to skip as many bytes as * possible up to <i>skipLength</i> bytes. Skipping 0 bytes signals end of * stream/channel/file/etc * * @param skipLength the number of bytes to attempt to skip * @return the count of actual bytes skipped. */ protected abstract long trySkipBytes(long skipLength) throws IOException; /** * Reads raw from the source, into a byte[]. Used for reads that are larger than * the buffer, or otherwise unbuffered. This is a mandatory read -- if there is * not enough bytes in the source, EOFException is thrown. * * @throws IOException if an error occurs * @throws EOFException if len bytes cannot be read */ protected abstract void readRaw(byte[] data, int off, int len) throws IOException; /** * Attempts to copy up to <i>len</i> bytes from the source into data, starting * at index <i>off</i>. Returns the actual number of bytes copied which may be * between 0 and <i>len</i>. * <p/> * This method must attempt to read as much as possible from the source. Returns * 0 when at the end of stream/channel/file/etc. * * @throws IOException if an error occurs reading **/ protected abstract int tryReadRaw(byte[] data, int off, int len) throws IOException; /** * If this source buffers, compacts the buffer by placing the <i>remaining</i> * bytes starting at <i>pos</i> at <i>minPos</i>. This may be done in the * current buffer, or may replace the buffer with a new one. * * The end result must be a buffer with at least 16 bytes of remaining space. * * @param pos * @param minPos * @param remaining * @throws IOException */ protected void compactAndFill(byte[] buf, int pos, int minPos, int remaining) throws IOException { System.arraycopy(buf, pos, buf, minPos, remaining); ba.setPos(minPos); int newLimit = remaining + tryReadRaw(buf, minPos + remaining, buf.length - remaining); ba.setLimit(newLimit); } @Override public int read(byte[] b, int off, int len) throws IOException { int lim = ba.getLim(); int pos = ba.getPos(); byte[] buf = ba.getBuf(); int remaining = (lim - pos); if (remaining >= len) { System.arraycopy(buf, pos, b, off, len); pos = pos + len; ba.setPos(pos); return len; } else { // flush buffer to array System.arraycopy(buf, pos, b, off, remaining); pos = pos + remaining; ba.setPos(pos); // get the rest from the stream (skip array) int inputRead = remaining + tryReadRaw(b, off + remaining, len - remaining); if (inputRead == 0) { return -1; } else { return inputRead; } } } @Override public long skip(long n) throws IOException { int lim = ba.getLim(); int pos = ba.getPos(); int remaining = lim - pos; if (remaining > n) { pos = (int) (pos + n); ba.setPos(pos); return n; } else { pos = lim; ba.setPos(pos); long isSkipCount = trySkipBytes(n - remaining); return isSkipCount + remaining; } } /** * returns the number of bytes remaining that this BinaryDecoder has buffered * from its source */ @Override public int available() throws IOException { return (ba.getLim() - ba.getPos()); } } private static class InputStreamByteSource extends ByteSource { private InputStream in; protected boolean isEof = false; private InputStreamByteSource(InputStream in) { super(); this.in = in; } @Override protected void skipSourceBytes(long length) throws IOException { boolean readZero = false; while (length > 0) { long n = in.skip(length); if (n > 0) { length -= n; continue; } // The inputStream contract is evil. // zero "might" mean EOF. So check for 2 in a row, we will // infinite loop waiting for -1 with some classes others // spuriously will return 0 on occasion without EOF if (n == 0) { if (readZero) { isEof = true; throw new EOFException(); } readZero = true; continue; } // read negative isEof = true; throw new EOFException(); } } @Override protected long trySkipBytes(long length) throws IOException { long leftToSkip = length; try { boolean readZero = false; while (leftToSkip > 0) { long n = in.skip(length); if (n > 0) { leftToSkip -= n; continue; } // The inputStream contract is evil. // zero "might" mean EOF. So check for 2 in a row, we will // infinite loop waiting for -1 with some classes others // spuriously will return 0 on occasion without EOF if (n == 0) { if (readZero) { isEof = true; break; } readZero = true; continue; } // read negative isEof = true; break; } } catch (EOFException eof) { isEof = true; } return length - leftToSkip; } @Override protected void readRaw(byte[] data, int off, int len) throws IOException { while (len > 0) { int read = in.read(data, off, len); if (read < 0) { isEof = true; throw new EOFException(); } len -= read; off += read; } } @Override protected int tryReadRaw(byte[] data, int off, int len) throws IOException { int leftToCopy = len; try { while (leftToCopy > 0) { int read = in.read(data, off, leftToCopy); if (read < 0) { isEof = true; break; } leftToCopy -= read; off += read; } } catch (EOFException eof) { isEof = true; } return len - leftToCopy; } @Override public int read() throws IOException { if (ba.getLim() - ba.getPos() == 0) { return in.read(); } else { int position = ba.getPos(); int result = ba.getBuf()[position] & 0xff; ba.setPos(position + 1); return result; } } @Override public boolean isEof() { return isEof; } @Override public void close() throws IOException { in.close(); } } /** * This byte source is special. It will avoid copying data by using the source's * byte[] as a buffer in the decoder. */ private static class ByteArrayByteSource extends ByteSource { private static final int MIN_SIZE = 16; private byte[] data; private int position; private int max; private boolean compacted = false; private ByteArrayByteSource(byte[] data, int start, int len) { super(); // make sure data is not too small, otherwise getLong may try and // read 10 bytes and get index out of bounds. if (len < MIN_SIZE) { this.data = Arrays.copyOfRange(data, start, start + MIN_SIZE); this.position = 0; this.max = len; } else { // use the array passed in this.data = data; this.position = start; this.max = start + len; } } @Override protected void attach(int bufferSize, BinaryDecoder decoder) { // buffer size is not used here, the byte[] source is the buffer. decoder.buf = this.data; decoder.pos = this.position; decoder.minPos = this.position; decoder.limit = this.max; this.ba = new BufferAccessor(decoder); } @Override protected void skipSourceBytes(long length) throws IOException { long skipped = trySkipBytes(length); if (skipped < length) { throw new EOFException(); } } @Override protected long trySkipBytes(long length) throws IOException { // the buffer is shared, so this should return 0 max = ba.getLim(); position = ba.getPos(); long remaining = (long) max - position; if (remaining >= length) { position = (int) (position + length); ba.setPos(position); return length; } else { position += remaining; ba.setPos(position); return remaining; } } @Override protected void readRaw(byte[] data, int off, int len) throws IOException { int read = tryReadRaw(data, off, len); if (read < len) { throw new EOFException(); } } @Override protected int tryReadRaw(byte[] data, int off, int len) throws IOException { // the buffer is shared, nothing to read return 0; } @Override protected void compactAndFill(byte[] buf, int pos, int minPos, int remaining) throws IOException { // this implementation does not want to mutate the array passed in, // so it makes a new tiny buffer unless it has been compacted once before if (!compacted) { // assumes ensureCapacity is never called with a size more than 16 byte[] tinybuf = new byte[remaining + 16]; System.arraycopy(buf, pos, tinybuf, 0, remaining); ba.setBuf(tinybuf, 0, remaining); compacted = true; } } @Override public int read() throws IOException { max = ba.getLim(); position = ba.getPos(); if (position >= max) { return -1; } else { int result = ba.getBuf()[position++] & 0xff; ba.setPos(position); return result; } } @Override public void close() throws IOException { ba.setPos(ba.getLim()); // effectively set isEof to false } @Override public boolean isEof() { int remaining = ba.getLim() - ba.getPos(); return (remaining == 0); } } }
7,341
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/BlockingDirectBinaryEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; /** * An {@link Encoder} for Avro's binary encoding that does not buffer output. * <p/> * This encoder does not buffer writes in contrast to * {@link BufferedBinaryEncoder}. However, it is lighter-weight and useful when: * The buffering in BufferedBinaryEncoder is not desired because you buffer a * different level or the Encoder is very short-lived. * </p> * The BlockingDirectBinaryEncoder will encode the number of bytes of the Map * and Array blocks. This will allow to postpone the decoding, or skip over it * at all. * <p/> * To construct, use * {@link EncoderFactory#blockingDirectBinaryEncoder(OutputStream, BinaryEncoder)} * <p/> * {@link BlockingDirectBinaryEncoder} instances returned by this method are not * thread-safe * * @see BinaryEncoder * @see EncoderFactory * @see Encoder * @see Decoder */ public class BlockingDirectBinaryEncoder extends DirectBinaryEncoder { private final BufferOutputStream buffer; private OutputStream originalStream; private boolean inBlock = false; private long blockItemCount; /** * Create a writer that sends its output to the underlying stream * <code>out</code>. * * @param out The Outputstream to write to */ public BlockingDirectBinaryEncoder(OutputStream out) { super(out); this.buffer = new BufferOutputStream(); } private void startBlock() { if (inBlock) { throw new RuntimeException("Nested Maps/Arrays are not supported by the BlockingDirectBinaryEncoder"); } originalStream = out; buffer.reset(); out = buffer; inBlock = true; } private void endBlock() { if (!inBlock) { throw new RuntimeException("Called endBlock, while not buffering a block"); } out = originalStream; if (blockItemCount > 0) { try { // Make it negative, so the reader knows that the number of bytes is coming writeLong(-blockItemCount); writeLong(buffer.size()); writeFixed(buffer.toBufferWithoutCopy()); } catch (IOException e) { throw new RuntimeException(e); } } inBlock = false; buffer.reset(); } @Override public void setItemCount(long itemCount) throws IOException { blockItemCount = itemCount; } @Override public void writeArrayStart() throws IOException { startBlock(); } @Override public void writeArrayEnd() throws IOException { endBlock(); // Writes another zero to indicate that this is the last block super.writeArrayEnd(); } @Override public void writeMapStart() throws IOException { startBlock(); } @Override public void writeMapEnd() throws IOException { endBlock(); // Writes another zero to indicate that this is the last block super.writeMapEnd(); } private static class BufferOutputStream extends ByteArrayOutputStream { BufferOutputStream() { } ByteBuffer toBufferWithoutCopy() { return ByteBuffer.wrap(buf, 0, count); } } }
7,342
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/BinaryData.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.AvroRuntimeException; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.util.internal.ThreadLocalWithInitial; /** Utilities for binary-encoded data. */ public class BinaryData { private BinaryData() { } // no public ctor private static class Decoders { private final BinaryDecoder d1, d2; public Decoders() { this.d1 = new BinaryDecoder(new byte[0], 0, 0); this.d2 = new BinaryDecoder(new byte[0], 0, 0); } public void set(byte[] data1, int off1, int len1, byte[] data2, int off2, int len2) { d1.setBuf(data1, off1, len1); d2.setBuf(data2, off2, len2); } public void clear() { d1.clearBuf(); d2.clearBuf(); } } // no public ctor private static final ThreadLocal<Decoders> DECODERS = ThreadLocalWithInitial.of(Decoders::new); /** * Compare binary encoded data. If equal, return zero. If greater-than, return * 1, if less than return -1. Order is consistent with that of * {@link org.apache.avro.generic.GenericData#compare(Object, Object, Schema)}. */ public static int compare(byte[] b1, int s1, byte[] b2, int s2, Schema schema) { return compare(b1, s1, b1.length - s1, b2, s2, b2.length - s2, schema); } /** * Compare binary encoded data. If equal, return zero. If greater-than, return * 1, if less than return -1. Order is consistent with that of * {@link org.apache.avro.generic.GenericData#compare(Object, Object, Schema)}. */ public static int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2, Schema schema) { Decoders decoders = DECODERS.get(); decoders.set(b1, s1, l1, b2, s2, l2); try { return compare(decoders, schema); } catch (IOException e) { throw new AvroRuntimeException(e); } finally { decoders.clear(); } } /** * If equal, return the number of bytes consumed. If greater than, return GT, if * less than, return LT. */ private static int compare(Decoders d, Schema schema) throws IOException { Decoder d1 = d.d1; Decoder d2 = d.d2; switch (schema.getType()) { case RECORD: { for (Field field : schema.getFields()) { if (field.order() == Field.Order.IGNORE) { GenericDatumReader.skip(field.schema(), d1); GenericDatumReader.skip(field.schema(), d2); continue; } int c = compare(d, field.schema()); if (c != 0) { return (field.order() != Field.Order.DESCENDING) ? c : -c; } } return 0; } case ENUM: case INT: return Integer.compare(d1.readInt(), d2.readInt()); case LONG: return Long.compare(d1.readLong(), d2.readLong()); case FLOAT: return Float.compare(d1.readFloat(), d2.readFloat()); case DOUBLE: return Double.compare(d1.readDouble(), d2.readDouble()); case BOOLEAN: return Boolean.compare(d1.readBoolean(), d2.readBoolean()); case ARRAY: { long i = 0; // position in array long r1 = 0, r2 = 0; // remaining in current block long l1 = 0, l2 = 0; // total array length while (true) { if (r1 == 0) { // refill blocks(s) r1 = d1.readLong(); if (r1 < 0) { r1 = -r1; d1.readLong(); } l1 += r1; } if (r2 == 0) { r2 = d2.readLong(); if (r2 < 0) { r2 = -r2; d2.readLong(); } l2 += r2; } if (r1 == 0 || r2 == 0) // empty block: done return Long.compare(l1, l2); long l = Math.min(l1, l2); while (i < l) { // compare to end of block int c = compare(d, schema.getElementType()); if (c != 0) return c; i++; r1--; r2--; } } } case MAP: throw new AvroRuntimeException("Can't compare maps!"); case UNION: { int i1 = d1.readInt(); int i2 = d2.readInt(); int c = Integer.compare(i1, i2); return c == 0 ? compare(d, schema.getTypes().get(i1)) : c; } case FIXED: { int size = schema.getFixedSize(); int c = compareBytes(d.d1.getBuf(), d.d1.getPos(), size, d.d2.getBuf(), d.d2.getPos(), size); d.d1.skipFixed(size); d.d2.skipFixed(size); return c; } case STRING: case BYTES: { int l1 = d1.readInt(); int l2 = d2.readInt(); int c = compareBytes(d.d1.getBuf(), d.d1.getPos(), l1, d.d2.getBuf(), d.d2.getPos(), l2); d.d1.skipFixed(l1); d.d2.skipFixed(l2); return c; } case NULL: return 0; default: throw new AvroRuntimeException("Unexpected schema to compare!"); } } /** * Lexicographically compare bytes. If equal, return zero. If greater-than, * return a positive value, if less than return a negative value. */ public static int compareBytes(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { int end1 = s1 + l1; int end2 = s2 + l2; for (int i = s1, j = s2; i < end1 && j < end2; i++, j++) { int a = (b1[i] & 0xff); int b = (b2[j] & 0xff); if (a != b) { return a - b; } } return l1 - l2; } private static class HashData { private final BinaryDecoder decoder; public HashData() { this.decoder = new BinaryDecoder(new byte[0], 0, 0); } public void set(byte[] bytes, int start, int len) { this.decoder.setBuf(bytes, start, len); } } private static final ThreadLocal<HashData> HASH_DATA = ThreadLocalWithInitial.of(HashData::new); /** * Hash binary encoded data. Consistent with * {@link org.apache.avro.generic.GenericData#hashCode(Object, Schema)}. */ public static int hashCode(byte[] bytes, int start, int length, Schema schema) { HashData data = HASH_DATA.get(); data.set(bytes, start, length); try { return hashCode(data, schema); } catch (IOException e) { throw new AvroRuntimeException(e); } } private static int hashCode(HashData data, Schema schema) throws IOException { Decoder decoder = data.decoder; switch (schema.getType()) { case RECORD: { int hashCode = 1; for (Field field : schema.getFields()) { if (field.order() == Field.Order.IGNORE) { GenericDatumReader.skip(field.schema(), decoder); continue; } hashCode = hashCode * 31 + hashCode(data, field.schema()); } return hashCode; } case ENUM: case INT: return decoder.readInt(); case BOOLEAN: return Boolean.hashCode(decoder.readBoolean()); case FLOAT: return Float.hashCode(decoder.readFloat()); case LONG: return Long.hashCode(decoder.readLong()); case DOUBLE: return Double.hashCode(decoder.readDouble()); case ARRAY: { Schema elementType = schema.getElementType(); int hashCode = 1; for (long l = decoder.readArrayStart(); l != 0; l = decoder.arrayNext()) { for (long i = 0; i < l; i++) { hashCode = hashCode * 31 + hashCode(data, elementType); } } return hashCode; } case MAP: throw new AvroRuntimeException("Can't hashCode maps!"); case UNION: return hashCode(data, schema.getTypes().get(decoder.readInt())); case FIXED: return hashBytes(1, data, schema.getFixedSize(), false); case STRING: return hashBytes(0, data, decoder.readInt(), false); case BYTES: return hashBytes(1, data, decoder.readInt(), true); case NULL: return 0; default: throw new AvroRuntimeException("Unexpected schema to hashCode!"); } } private static int hashBytes(int init, HashData data, int len, boolean rev) throws IOException { int hashCode = init; byte[] bytes = data.decoder.getBuf(); int start = data.decoder.getPos(); int end = start + len; if (rev) for (int i = end - 1; i >= start; i--) hashCode = hashCode * 31 + bytes[i]; else for (int i = start; i < end; i++) hashCode = hashCode * 31 + bytes[i]; data.decoder.skipFixed(len); return hashCode; } /** Skip a binary-encoded long, returning the position after it. */ public static int skipLong(final byte[] bytes, int start) { while ((bytes[start++] & 0x80) != 0) { } return start; } /** * Encode a boolean to the byte array at the given position. Will throw * IndexOutOfBounds if the position is not valid. * * @return The number of bytes written to the buffer, 1. */ public static int encodeBoolean(boolean b, byte[] buf, int pos) { buf[pos] = b ? (byte) 1 : (byte) 0; return 1; } /** * Encode an integer to the byte array at the given position. Will throw * IndexOutOfBounds if it overflows. Users should ensure that there are at least * 5 bytes left in the buffer before calling this method. * * @return The number of bytes written to the buffer, between 1 and 5. */ public static int encodeInt(int n, byte[] buf, int pos) { // move sign to low-order bit, and flip others if negative n = (n << 1) ^ (n >> 31); int start = pos; if ((n & ~0x7F) != 0) { buf[pos++] = (byte) ((n | 0x80) & 0xFF); n >>>= 7; if (n > 0x7F) { buf[pos++] = (byte) ((n | 0x80) & 0xFF); n >>>= 7; if (n > 0x7F) { buf[pos++] = (byte) ((n | 0x80) & 0xFF); n >>>= 7; if (n > 0x7F) { buf[pos++] = (byte) ((n | 0x80) & 0xFF); n >>>= 7; } } } } buf[pos++] = (byte) n; return pos - start; } /** * Encode a long to the byte array at the given position. Will throw * IndexOutOfBounds if it overflows. Users should ensure that there are at least * 10 bytes left in the buffer before calling this method. * * @return The number of bytes written to the buffer, between 1 and 10. */ public static int encodeLong(long n, byte[] buf, int pos) { // move sign to low-order bit, and flip others if negative n = (n << 1) ^ (n >> 63); int start = pos; if ((n & ~0x7FL) != 0) { buf[pos++] = (byte) ((n | 0x80) & 0xFF); n >>>= 7; if (n > 0x7F) { buf[pos++] = (byte) ((n | 0x80) & 0xFF); n >>>= 7; if (n > 0x7F) { buf[pos++] = (byte) ((n | 0x80) & 0xFF); n >>>= 7; if (n > 0x7F) { buf[pos++] = (byte) ((n | 0x80) & 0xFF); n >>>= 7; if (n > 0x7F) { buf[pos++] = (byte) ((n | 0x80) & 0xFF); n >>>= 7; if (n > 0x7F) { buf[pos++] = (byte) ((n | 0x80) & 0xFF); n >>>= 7; if (n > 0x7F) { buf[pos++] = (byte) ((n | 0x80) & 0xFF); n >>>= 7; if (n > 0x7F) { buf[pos++] = (byte) ((n | 0x80) & 0xFF); n >>>= 7; if (n > 0x7F) { buf[pos++] = (byte) ((n | 0x80) & 0xFF); n >>>= 7; } } } } } } } } } buf[pos++] = (byte) n; return pos - start; } /** * Encode a float to the byte array at the given position. Will throw * IndexOutOfBounds if it overflows. Users should ensure that there are at least * 4 bytes left in the buffer before calling this method. * * @return Returns the number of bytes written to the buffer, 4. */ public static int encodeFloat(float f, byte[] buf, int pos) { final int bits = Float.floatToRawIntBits(f); buf[pos + 3] = (byte) (bits >>> 24); buf[pos + 2] = (byte) (bits >>> 16); buf[pos + 1] = (byte) (bits >>> 8); buf[pos] = (byte) (bits); return 4; } /** * Encode a double to the byte array at the given position. Will throw * IndexOutOfBounds if it overflows. Users should ensure that there are at least * 8 bytes left in the buffer before calling this method. * * @return Returns the number of bytes written to the buffer, 8. */ public static int encodeDouble(double d, byte[] buf, int pos) { final long bits = Double.doubleToRawLongBits(d); int first = (int) (bits & 0xFFFFFFFF); int second = (int) ((bits >>> 32) & 0xFFFFFFFF); // the compiler seems to execute this order the best, likely due to // register allocation -- the lifetime of constants is minimized. buf[pos] = (byte) (first); buf[pos + 4] = (byte) (second); buf[pos + 5] = (byte) (second >>> 8); buf[pos + 1] = (byte) (first >>> 8); buf[pos + 2] = (byte) (first >>> 16); buf[pos + 6] = (byte) (second >>> 16); buf[pos + 7] = (byte) (second >>> 24); buf[pos + 3] = (byte) (first >>> 24); return 8; } }
7,343
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/BufferedBinaryEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.util.Objects; import org.apache.avro.AvroRuntimeException; /** * An {@link Encoder} for Avro's binary encoding. * <p/> * This implementation buffers output to enhance performance. Output may not * appear on the underlying output until flush() is called. * <p/> * {@link DirectBinaryEncoder} can be used in place of this implementation if * the buffering semantics are not desired, and the performance difference is * acceptable. * <p/> * To construct or reconfigure, use * {@link EncoderFactory#binaryEncoder(OutputStream, BinaryEncoder)}. * <p/> * To change the buffer size, configure the factory instance used to create * instances with {@link EncoderFactory#configureBufferSize(int)} * * @see Encoder * @see EncoderFactory * @see BlockingBinaryEncoder * @see DirectBinaryEncoder */ public class BufferedBinaryEncoder extends BinaryEncoder { private byte[] buf; private int pos; private ByteSink sink; private int bulkLimit; BufferedBinaryEncoder(OutputStream out, int bufferSize) { configure(out, bufferSize); } BufferedBinaryEncoder configure(OutputStream out, int bufferSize) { Objects.requireNonNull(out, "OutputStream cannot be null"); if (null != this.sink) { if (pos > 0) { try { flushBuffer(); } catch (IOException e) { throw new AvroRuntimeException("Failure flushing old output", e); } } } this.sink = new OutputStreamSink(out); pos = 0; if (null == buf || buf.length != bufferSize) { buf = new byte[bufferSize]; } bulkLimit = buf.length >>> 1; if (bulkLimit > 512) { bulkLimit = 512; } return this; } @Override public void flush() throws IOException { flushBuffer(); sink.innerFlush(); } /** * Flushes the internal buffer to the underlying output. Does not flush the * underlying output. */ private void flushBuffer() throws IOException { if (pos > 0) { try { sink.innerWrite(buf, 0, pos); } finally { pos = 0; } } } /** * Ensures that the buffer has at least num bytes free to write to between its * current position and the end. This will not expand the buffer larger than its * current size, for writes larger than or near to the size of the buffer, we * flush the buffer and write directly to the output, bypassing the buffer. * * @param num * @throws IOException */ private void ensureBounds(int num) throws IOException { int remaining = buf.length - pos; if (remaining < num) { flushBuffer(); } } @Override public void writeBoolean(boolean b) throws IOException { // inlined, shorter version of ensureBounds if (buf.length == pos) { flushBuffer(); } pos += BinaryData.encodeBoolean(b, buf, pos); } @Override public void writeInt(int n) throws IOException { ensureBounds(5); pos += BinaryData.encodeInt(n, buf, pos); } @Override public void writeLong(long n) throws IOException { ensureBounds(10); pos += BinaryData.encodeLong(n, buf, pos); } @Override public void writeFloat(float f) throws IOException { ensureBounds(4); pos += BinaryData.encodeFloat(f, buf, pos); } @Override public void writeDouble(double d) throws IOException { ensureBounds(8); pos += BinaryData.encodeDouble(d, buf, pos); } @Override public void writeFixed(byte[] bytes, int start, int len) throws IOException { if (len > bulkLimit) { // too big, write direct flushBuffer(); sink.innerWrite(bytes, start, len); return; } ensureBounds(len); System.arraycopy(bytes, start, buf, pos, len); pos += len; } @Override public void writeFixed(ByteBuffer bytes) throws IOException { ByteBuffer readOnlyBytes = bytes.asReadOnlyBuffer(); if (!bytes.hasArray() && bytes.remaining() > bulkLimit) { flushBuffer(); sink.innerWrite(readOnlyBytes); // bypass the readOnlyBytes } else { super.writeFixed(readOnlyBytes); } } @Override protected void writeZero() throws IOException { writeByte(0); } private void writeByte(int b) throws IOException { if (pos == buf.length) { flushBuffer(); } buf[pos++] = (byte) (b & 0xFF); } @Override public int bytesBuffered() { return pos; } /** * ByteSink abstracts the destination of written data from the core workings of * BinaryEncoder. * <p/> * Currently the only destination option is an OutputStream, but we may later * want to handle other constructs or specialize for certain OutputStream * Implementations such as ByteBufferOutputStream. * <p/> */ private abstract static class ByteSink { protected ByteSink() { } /** Write data from bytes, starting at off, for len bytes **/ protected abstract void innerWrite(byte[] bytes, int off, int len) throws IOException; protected abstract void innerWrite(ByteBuffer buff) throws IOException; /** Flush the underlying output, if supported **/ protected abstract void innerFlush() throws IOException; } static class OutputStreamSink extends ByteSink { private final OutputStream out; private final WritableByteChannel channel; private OutputStreamSink(OutputStream out) { super(); this.out = out; channel = Channels.newChannel(out); } @Override protected void innerWrite(byte[] bytes, int off, int len) throws IOException { out.write(bytes, off, len); } @Override protected void innerFlush() throws IOException { out.flush(); } @Override protected void innerWrite(ByteBuffer buff) throws IOException { channel.write(buff); } } }
7,344
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/FastReaderBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.avro.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.function.IntFunction; import org.apache.avro.AvroTypeException; import org.apache.avro.Conversion; import org.apache.avro.Conversions; import org.apache.avro.Resolver; import org.apache.avro.Resolver.Action; import org.apache.avro.Resolver.Container; import org.apache.avro.Resolver.EnumAdjust; import org.apache.avro.Resolver.Promote; import org.apache.avro.Resolver.ReaderUnion; import org.apache.avro.Resolver.RecordAdjust; import org.apache.avro.Resolver.Skip; import org.apache.avro.Resolver.WriterUnion; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.generic.GenericArray; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericData.InstanceSupplier; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericEnumSymbol; import org.apache.avro.generic.GenericFixed; import org.apache.avro.generic.IndexedRecord; import org.apache.avro.io.FastReaderBuilder.RecordReader.Stage; import org.apache.avro.io.parsing.ResolvingGrammarGenerator; import org.apache.avro.reflect.ReflectionUtil; import org.apache.avro.specific.SpecificData; import org.apache.avro.specific.SpecificRecordBase; import org.apache.avro.util.Utf8; import org.apache.avro.util.WeakIdentityHashMap; import org.apache.avro.util.internal.Accessor; public class FastReaderBuilder { /** * Generic/SpecificData instance that contains basic functionalities like * instantiation of objects */ private final GenericData data; /** first schema is reader schema, second is writer schema */ private final Map<Schema, Map<Schema, RecordReader>> readerCache = Collections .synchronizedMap(new WeakIdentityHashMap<>()); private boolean keyClassEnabled = true; private boolean classPropEnabled = true; public static FastReaderBuilder get() { return new FastReaderBuilder(GenericData.get()); } public static FastReaderBuilder getSpecific() { return new FastReaderBuilder(SpecificData.get()); } public static boolean isSupportedData(GenericData data) { return data.getClass() == GenericData.class || data.getClass() == SpecificData.class; } public FastReaderBuilder(GenericData parentData) { this.data = parentData; } public FastReaderBuilder withKeyClassEnabled(boolean enabled) { this.keyClassEnabled = enabled; return this; } public boolean isKeyClassEnabled() { return this.keyClassEnabled; } public FastReaderBuilder withClassPropEnabled(boolean enabled) { this.classPropEnabled = enabled; return this; } public boolean isClassPropEnabled() { return this.classPropEnabled; } public <D> DatumReader<D> createDatumReader(Schema schema) throws IOException { return createDatumReader(schema, schema); } @SuppressWarnings("unchecked") public <D> DatumReader<D> createDatumReader(Schema writerSchema, Schema readerSchema) throws IOException { Schema resolvedWriterSchema = Schema.applyAliases(writerSchema, readerSchema); return (DatumReader<D>) getReaderFor(readerSchema, resolvedWriterSchema); } private FieldReader getReaderFor(Schema readerSchema, Schema writerSchema) throws IOException { Action resolvedAction = Resolver.resolve(writerSchema, readerSchema, data); return getReaderFor(resolvedAction, null); } private FieldReader getReaderFor(Action action, Conversion<?> explicitConversion) throws IOException { final FieldReader baseReader = getNonConvertedReader(action); return applyConversions(action.reader, baseReader, explicitConversion); } private RecordReader createRecordReader(RecordAdjust action) throws IOException { // record readers are created in a two-step process, first registering it, then // initializing it, // to prevent endless loops on recursive types RecordReader recordReader = getRecordReaderFromCache(action.reader, action.writer); synchronized (recordReader) { // only need to initialize once if (recordReader.getInitializationStage() == Stage.NEW) { initializeRecordReader(recordReader, action); } } return recordReader; } private RecordReader initializeRecordReader(RecordReader recordReader, RecordAdjust action) throws IOException { recordReader.startInitialization(); // generate supplier for the new object instances Object testInstance = action.instanceSupplier.newInstance(null, action.reader); IntFunction<Conversion<?>> conversionSupplier = getConversionSupplier(testInstance); ExecutionStep[] readSteps = new ExecutionStep[action.fieldActions.length + action.readerOrder.length - action.firstDefault]; int i = 0; int fieldCounter = 0; // compute what to do with writer's fields for (; i < action.fieldActions.length; i++) { Action fieldAction = action.fieldActions[i]; if (fieldAction instanceof Skip) { readSteps[i] = (r, decoder) -> GenericDatumReader.skip(fieldAction.writer, decoder); } else { Field readerField = action.readerOrder[fieldCounter++]; Conversion<?> conversion = conversionSupplier.apply(readerField.pos()); FieldReader reader = getReaderFor(fieldAction, conversion); readSteps[i] = createFieldSetter(readerField, reader); } } // add defaulting if required for (; i < readSteps.length; i++) { readSteps[i] = getDefaultingStep(action.readerOrder[fieldCounter++]); } recordReader.finishInitialization(readSteps, action.reader, action.instanceSupplier); return recordReader; } private ExecutionStep createFieldSetter(Field field, FieldReader reader) { int pos = field.pos(); if (reader.canReuse()) { return (object, decoder) -> { IndexedRecord record = (IndexedRecord) object; record.put(pos, reader.read(record.get(pos), decoder)); }; } else { return (object, decoder) -> { IndexedRecord record = (IndexedRecord) object; record.put(pos, reader.read(null, decoder)); }; } } private ExecutionStep getDefaultingStep(Schema.Field field) throws IOException { Object defaultValue = data.getDefaultValue(field); if (isObjectImmutable(defaultValue)) { return createFieldSetter(field, (old, d) -> defaultValue); } else if (defaultValue instanceof Utf8) { return createFieldSetter(field, reusingReader((old, d) -> readUtf8(old, (Utf8) defaultValue))); } else if (defaultValue instanceof List && ((List<?>) defaultValue).isEmpty()) { return createFieldSetter(field, reusingReader((old, d) -> data.newArray(old, 0, field.schema()))); } else if (defaultValue instanceof Map && ((Map<?, ?>) defaultValue).isEmpty()) { return createFieldSetter(field, reusingReader((old, d) -> data.newMap(old, 0))); } else { DatumReader<Object> datumReader = createDatumReader(field.schema()); byte[] encoded = getEncodedValue(field); FieldReader fieldReader = reusingReader( (old, decoder) -> datumReader.read(old, DecoderFactory.get().binaryDecoder(encoded, null))); return createFieldSetter(field, fieldReader); } } private boolean isObjectImmutable(Object object) { return object == null || object instanceof Number || object instanceof String || object instanceof GenericEnumSymbol || object.getClass().isEnum(); } private Utf8 readUtf8(Object reuse, Utf8 newValue) { if (reuse instanceof Utf8) { Utf8 oldUtf8 = (Utf8) reuse; oldUtf8.set(newValue); return oldUtf8; } else { return new Utf8(newValue); } } private byte[] getEncodedValue(Field field) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); Encoder encoder = EncoderFactory.get().binaryEncoder(out, null); ResolvingGrammarGenerator.encode(encoder, field.schema(), Accessor.defaultValue(field)); encoder.flush(); return out.toByteArray(); } private IntFunction<Conversion<?>> getConversionSupplier(Object record) { if (record instanceof SpecificRecordBase) { return ((SpecificRecordBase) record)::getConversion; } else { return index -> null; } } private RecordReader getRecordReaderFromCache(Schema readerSchema, Schema writerSchema) { return readerCache.computeIfAbsent(readerSchema, k -> new WeakIdentityHashMap<>()).computeIfAbsent(writerSchema, k -> new RecordReader()); } private FieldReader applyConversions(Schema readerSchema, FieldReader reader, Conversion<?> explicitConversion) { Conversion<?> conversion = explicitConversion; if (conversion == null) { if (readerSchema.getLogicalType() == null) { return reader; } conversion = data.getConversionFor(readerSchema.getLogicalType()); if (conversion == null) { return reader; } } Conversion<?> finalConversion = conversion; return (old, decoder) -> Conversions.convertToLogicalType(reader.read(old, decoder), readerSchema, readerSchema.getLogicalType(), finalConversion); } private FieldReader getNonConvertedReader(Action action) throws IOException { switch (action.type) { case CONTAINER: switch (action.reader.getType()) { case MAP: return createMapReader(action.reader, (Container) action); case ARRAY: return createArrayReader(action.reader, (Container) action); default: throw new IllegalStateException("Error getting reader for action type " + action.getClass()); } case DO_NOTHING: return getReaderForBaseType(action.reader, action.writer); case RECORD: return createRecordReader((RecordAdjust) action); case ENUM: return createEnumReader((EnumAdjust) action); case PROMOTE: return createPromotingReader((Promote) action); case WRITER_UNION: return createUnionReader((WriterUnion) action); case READER_UNION: return getReaderFor(((ReaderUnion) action).actualAction, null); case ERROR: return (old, decoder) -> { throw new AvroTypeException(action.toString()); }; default: throw new IllegalStateException("Error getting reader for action type " + action.getClass()); } } private FieldReader getReaderForBaseType(Schema readerSchema, Schema writerSchema) throws IOException { switch (readerSchema.getType()) { case NULL: return (old, decoder) -> { decoder.readNull(); return null; }; case BOOLEAN: return (old, decoder) -> decoder.readBoolean(); case STRING: return createStringReader(readerSchema, writerSchema); case INT: return (old, decoder) -> decoder.readInt(); case LONG: return (old, decoder) -> decoder.readLong(); case FLOAT: return (old, decoder) -> decoder.readFloat(); case DOUBLE: return (old, decoder) -> decoder.readDouble(); case BYTES: return createBytesReader(); case FIXED: return createFixedReader(readerSchema, writerSchema); case RECORD: // covered by action type case UNION: // covered by action type case ENUM: // covered by action type case MAP: // covered by action type case ARRAY: // covered by action type default: throw new IllegalStateException("Error getting reader for type " + readerSchema.getFullName()); } } private FieldReader createPromotingReader(Promote promote) throws IOException { switch (promote.reader.getType()) { case BYTES: return (reuse, decoder) -> ByteBuffer.wrap(decoder.readString(null).getBytes()); case STRING: return createBytesPromotingToStringReader(promote.reader); case LONG: return (reuse, decoder) -> (long) decoder.readInt(); case FLOAT: switch (promote.writer.getType()) { case INT: return (reuse, decoder) -> (float) decoder.readInt(); case LONG: return (reuse, decoder) -> (float) decoder.readLong(); default: } break; case DOUBLE: switch (promote.writer.getType()) { case INT: return (reuse, decoder) -> (double) decoder.readInt(); case LONG: return (reuse, decoder) -> (double) decoder.readLong(); case FLOAT: return (reuse, decoder) -> (double) decoder.readFloat(); default: } break; default: } throw new IllegalStateException( "No promotion possible for type " + promote.writer.getType() + " to " + promote.reader.getType()); } private FieldReader createStringReader(Schema readerSchema, Schema writerSchema) { FieldReader stringReader = createSimpleStringReader(readerSchema); if (isClassPropEnabled()) { return getTransformingStringReader(readerSchema.getProp(SpecificData.CLASS_PROP), stringReader); } else { return stringReader; } } private FieldReader createSimpleStringReader(Schema readerSchema) { String stringProperty = readerSchema.getProp(GenericData.STRING_PROP); if (GenericData.StringType.String.name().equals(stringProperty)) { return (old, decoder) -> decoder.readString(); } else { return (old, decoder) -> decoder.readString(old instanceof Utf8 ? (Utf8) old : null); } } private FieldReader createBytesPromotingToStringReader(Schema readerSchema) { String stringProperty = readerSchema.getProp(GenericData.STRING_PROP); if (GenericData.StringType.String.name().equals(stringProperty)) { return (old, decoder) -> getStringFromByteBuffer(decoder.readBytes(null)); } else { return (old, decoder) -> getUtf8FromByteBuffer(old, decoder.readBytes(null)); } } private String getStringFromByteBuffer(ByteBuffer buffer) { return new String(buffer.array(), buffer.position(), buffer.remaining(), StandardCharsets.UTF_8); } private Utf8 getUtf8FromByteBuffer(Object old, ByteBuffer buffer) { return (old instanceof Utf8) ? ((Utf8) old).set(new Utf8(buffer.array())) : new Utf8(buffer.array()); } private FieldReader createUnionReader(WriterUnion action) throws IOException { FieldReader[] unionReaders = new FieldReader[action.actions.length]; for (int i = 0; i < action.actions.length; i++) { unionReaders[i] = getReaderFor(action.actions[i], null); } return createUnionReader(unionReaders); } private FieldReader createUnionReader(FieldReader[] unionReaders) { return reusingReader((reuse, decoder) -> { final int selection = decoder.readIndex(); return unionReaders[selection].read(null, decoder); }); } private FieldReader createMapReader(Schema readerSchema, Container action) throws IOException { FieldReader keyReader = createMapKeyReader(readerSchema); FieldReader valueReader = getReaderFor(action.elementAction, null); return new MapReader(keyReader, valueReader); } private FieldReader createMapKeyReader(Schema readerSchema) { FieldReader stringReader = createSimpleStringReader(readerSchema); if (isKeyClassEnabled()) { return getTransformingStringReader(readerSchema.getProp(SpecificData.KEY_CLASS_PROP), createSimpleStringReader(readerSchema)); } else { return stringReader; } } private FieldReader getTransformingStringReader(String valueClass, FieldReader stringReader) { if (valueClass == null) { return stringReader; } else { Function<String, ?> transformer = findClass(valueClass) .map(clazz -> ReflectionUtil.getConstructorAsFunction(String.class, clazz)).orElse(null); if (transformer != null) { return (old, decoder) -> transformer.apply((String) stringReader.read(null, decoder)); } } return stringReader; } private Optional<Class<?>> findClass(String clazz) { try { return Optional.of(data.getClassLoader().loadClass(clazz)); } catch (ReflectiveOperationException e) { return Optional.empty(); } } @SuppressWarnings("unchecked") private FieldReader createArrayReader(Schema readerSchema, Container action) throws IOException { FieldReader elementReader = getReaderFor(action.elementAction, null); return reusingReader((reuse, decoder) -> { if (reuse instanceof GenericArray) { GenericArray<Object> reuseArray = (GenericArray<Object>) reuse; long l = decoder.readArrayStart(); reuseArray.clear(); while (l > 0) { for (long i = 0; i < l; i++) { reuseArray.add(elementReader.read(reuseArray.peek(), decoder)); } l = decoder.arrayNext(); } return reuseArray; } else { long l = decoder.readArrayStart(); List<Object> array = (reuse instanceof List) ? (List<Object>) reuse : new GenericData.Array<>((int) l, readerSchema); array.clear(); while (l > 0) { for (long i = 0; i < l; i++) { array.add(elementReader.read(null, decoder)); } l = decoder.arrayNext(); } return array; } }); } private FieldReader createEnumReader(EnumAdjust action) { return reusingReader((reuse, decoder) -> { int index = decoder.readEnum(); Object resultObject = action.values[index]; if (resultObject == null) { throw new AvroTypeException("No match for " + action.writer.getEnumSymbols().get(index)); } return resultObject; }); } private FieldReader createFixedReader(Schema readerSchema, Schema writerSchema) { return reusingReader((reuse, decoder) -> { GenericFixed fixed = (GenericFixed) data.createFixed(reuse, readerSchema); decoder.readFixed(fixed.bytes(), 0, readerSchema.getFixedSize()); return fixed; }); } private FieldReader createBytesReader() { return reusingReader( (reuse, decoder) -> decoder.readBytes(reuse instanceof ByteBuffer ? (ByteBuffer) reuse : null)); } public static FieldReader reusingReader(ReusingFieldReader reader) { return reader; } public interface FieldReader extends DatumReader<Object> { @Override public Object read(Object reuse, Decoder decoder) throws IOException; public default boolean canReuse() { return false; } @Override default void setSchema(Schema schema) { throw new UnsupportedOperationException(); } } public interface ReusingFieldReader extends FieldReader { @Override public default boolean canReuse() { return true; } } public static class RecordReader implements FieldReader { public enum Stage { NEW, INITIALIZING, INITIALIZED } private ExecutionStep[] readSteps; private InstanceSupplier supplier; private Schema schema; private Stage stage = Stage.NEW; public Stage getInitializationStage() { return this.stage; } public void reset() { this.stage = Stage.NEW; } public void startInitialization() { this.stage = Stage.INITIALIZING; } public void finishInitialization(ExecutionStep[] readSteps, Schema schema, InstanceSupplier supp) { this.readSteps = readSteps; this.schema = schema; this.supplier = supp; this.stage = Stage.INITIALIZED; } @Override public boolean canReuse() { return true; } @Override public Object read(Object reuse, Decoder decoder) throws IOException { Object object = supplier.newInstance(reuse, schema); for (ExecutionStep thisStep : readSteps) { thisStep.execute(object, decoder); } return object; } } public static class MapReader implements FieldReader { private final FieldReader keyReader; private final FieldReader valueReader; public MapReader(FieldReader keyReader, FieldReader valueReader) { this.keyReader = keyReader; this.valueReader = valueReader; } @Override public Object read(Object reuse, Decoder decoder) throws IOException { long l = decoder.readMapStart(); Map<Object, Object> targetMap = new HashMap<>(); while (l > 0) { for (int i = 0; i < l; i++) { Object key = keyReader.read(null, decoder); Object value = valueReader.read(null, decoder); targetMap.put(key, value); } l = decoder.mapNext(); } return targetMap; } } public interface ExecutionStep { public void execute(Object record, Decoder decoder) throws IOException; } }
7,345
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/Decoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.avro.util.Utf8; /** * Low-level support for de-serializing Avro values. * <p/> * This class has two types of methods. One type of methods support the reading * of leaf values (for example, {@link #readLong} and {@link #readString}). * <p/> * The other type of methods support the reading of maps and arrays. These * methods are {@link #readArrayStart}, {@link #arrayNext}, and similar methods * for maps). See {@link #readArrayStart} for details on these methods.) * <p/> * {@link DecoderFactory} contains Decoder construction and configuration * facilities. * * @see DecoderFactory * @see Encoder */ public abstract class Decoder { /** * "Reads" a null value. (Doesn't actually read anything, but advances the state * of the parser if the implementation is stateful.) * * @throws AvroTypeException If this is a stateful reader and null is not the * type of the next value to be read */ public abstract void readNull() throws IOException; /** * Reads a boolean value written by {@link Encoder#writeBoolean}. * * @throws AvroTypeException If this is a stateful reader and boolean is not the * type of the next value to be read */ public abstract boolean readBoolean() throws IOException; /** * Reads an integer written by {@link Encoder#writeInt}. * * @throws AvroTypeException If encoded value is larger than 32-bits * @throws AvroTypeException If this is a stateful reader and int is not the * type of the next value to be read */ public abstract int readInt() throws IOException; /** * Reads a long written by {@link Encoder#writeLong}. * * @throws AvroTypeException If this is a stateful reader and long is not the * type of the next value to be read */ public abstract long readLong() throws IOException; /** * Reads a float written by {@link Encoder#writeFloat}. * * @throws AvroTypeException If this is a stateful reader and is not the type of * the next value to be read */ public abstract float readFloat() throws IOException; /** * Reads a double written by {@link Encoder#writeDouble}. * * @throws AvroTypeException If this is a stateful reader and is not the type of * the next value to be read */ public abstract double readDouble() throws IOException; /** * Reads a char-string written by {@link Encoder#writeString}. * * @throws AvroTypeException If this is a stateful reader and char-string is not * the type of the next value to be read */ public abstract Utf8 readString(Utf8 old) throws IOException; /** * Reads a char-string written by {@link Encoder#writeString}. * * @throws AvroTypeException If this is a stateful reader and char-string is not * the type of the next value to be read */ public abstract String readString() throws IOException; /** * Discards a char-string written by {@link Encoder#writeString}. * * @throws AvroTypeException If this is a stateful reader and char-string is not * the type of the next value to be read */ public abstract void skipString() throws IOException; /** * Reads a byte-string written by {@link Encoder#writeBytes}. if <tt>old</tt> is * not null and has sufficient capacity to take in the bytes being read, the * bytes are returned in <tt>old</tt>. * * @throws AvroTypeException If this is a stateful reader and byte-string is not * the type of the next value to be read */ public abstract ByteBuffer readBytes(ByteBuffer old) throws IOException; /** * Discards a byte-string written by {@link Encoder#writeBytes}. * * @throws AvroTypeException If this is a stateful reader and byte-string is not * the type of the next value to be read */ public abstract void skipBytes() throws IOException; /** * Reads fixed sized binary object. * * @param bytes The buffer to store the contents being read. * @param start The position where the data needs to be written. * @param length The size of the binary object. * @throws AvroTypeException If this is a stateful reader and fixed sized binary * object is not the type of the next value to be read * or the length is incorrect. * @throws IOException */ public abstract void readFixed(byte[] bytes, int start, int length) throws IOException; /** * A shorthand for <tt>readFixed(bytes, 0, bytes.length)</tt>. * * @throws AvroTypeException If this is a stateful reader and fixed sized binary * object is not the type of the next value to be read * or the length is incorrect. * @throws IOException */ public void readFixed(byte[] bytes) throws IOException { readFixed(bytes, 0, bytes.length); } /** * Discards fixed sized binary object. * * @param length The size of the binary object to be skipped. * @throws AvroTypeException If this is a stateful reader and fixed sized binary * object is not the type of the next value to be read * or the length is incorrect. * @throws IOException */ public abstract void skipFixed(int length) throws IOException; /** * Reads an enumeration. * * @return The enumeration's value. * @throws AvroTypeException If this is a stateful reader and enumeration is not * the type of the next value to be read. * @throws IOException */ public abstract int readEnum() throws IOException; /** * Reads and returns the size of the first block of an array. If this method * returns non-zero, then the caller should read the indicated number of items, * and then call {@link #arrayNext} to find out the number of items in the next * block. The typical pattern for consuming an array looks like: * * <pre> * for(long i = in.readArrayStart(); i != 0; i = in.arrayNext()) { * for (long j = 0; j < i; j++) { * read next element of the array; * } * } * </pre> * * @throws AvroTypeException If this is a stateful reader and array is not the * type of the next value to be read */ public abstract long readArrayStart() throws IOException; /** * Processes the next block of an array and returns the number of items in the * block and let's the caller read those items. * * @throws AvroTypeException When called outside of an array context */ public abstract long arrayNext() throws IOException; /** * Used for quickly skipping through an array. Note you can either skip the * entire array, or read the entire array (with {@link #readArrayStart}), but * you can't mix the two on the same array. * * This method will skip through as many items as it can, all of them if * possible. It will return zero if there are no more items to skip through, or * an item count if it needs the client's help in skipping. The typical usage * pattern is: * * <pre> * for(long i = in.skipArray(); i != 0; i = i.skipArray()) { * for (long j = 0; j < i; j++) { * read and discard the next element of the array; * } * } * </pre> * * Note that this method can automatically skip through items if a byte-count is * found in the underlying data, or if a schema has been provided to the * implementation, but otherwise the client will have to skip through items * itself. * * @throws AvroTypeException If this is a stateful reader and array is not the * type of the next value to be read */ public abstract long skipArray() throws IOException; /** * Reads and returns the size of the next block of map-entries. Similar to * {@link #readArrayStart}. * * As an example, let's say you want to read a map of records, the record * consisting of an Long field and a Boolean field. Your code would look * something like this: * * <pre> * Map<String, Record> m = new HashMap<String, Record>(); * Record reuse = new Record(); * for (long i = in.readMapStart(); i != 0; i = in.readMapNext()) { * for (long j = 0; j < i; j++) { * String key = in.readString(); * reuse.intField = in.readInt(); * reuse.boolField = in.readBoolean(); * m.put(key, reuse); * } * } * </pre> * * @throws AvroTypeException If this is a stateful reader and map is not the * type of the next value to be read */ public abstract long readMapStart() throws IOException; /** * Processes the next block of map entries and returns the count of them. * Similar to {@link #arrayNext}. See {@link #readMapStart} for details. * * @throws AvroTypeException When called outside of a map context */ public abstract long mapNext() throws IOException; /** * Support for quickly skipping through a map similar to {@link #skipArray}. * * As an example, let's say you want to skip a map of records, the record * consisting of an Long field and a Boolean field. Your code would look * something like this: * * <pre> * for (long i = in.skipMap(); i != 0; i = in.skipMap()) { * for (long j = 0; j < i; j++) { * in.skipString(); // Discard key * in.readInt(); // Discard int-field of value * in.readBoolean(); // Discard boolean-field of value * } * } * </pre> * * @throws AvroTypeException If this is a stateful reader and array is not the * type of the next value to be read */ public abstract long skipMap() throws IOException; /** * Reads the tag of a union written by {@link Encoder#writeIndex}. * * @throws AvroTypeException If this is a stateful reader and union is not the * type of the next value to be read */ public abstract int readIndex() throws IOException; }
7,346
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/ValidatingEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.avro.AvroTypeException; import org.apache.avro.Schema; import org.apache.avro.io.parsing.ValidatingGrammarGenerator; import org.apache.avro.io.parsing.Parser; import org.apache.avro.io.parsing.Symbol; import org.apache.avro.util.Utf8; /** * An implementation of {@link Encoder} that wraps another Encoder and ensures * that the sequence of operations conforms to the provided schema. * <p/> * Use {@link EncoderFactory#validatingEncoder(Schema, Encoder)} to construct * and configure. * <p/> * ValidatingEncoder is not thread-safe. * * @see Encoder * @see EncoderFactory */ public class ValidatingEncoder extends ParsingEncoder implements Parser.ActionHandler { protected Encoder out; protected final Parser parser; ValidatingEncoder(Symbol root, Encoder out) throws IOException { this.out = out; this.parser = new Parser(root, this); } ValidatingEncoder(Schema schema, Encoder in) throws IOException { this(new ValidatingGrammarGenerator().generate(schema), in); } @Override public void flush() throws IOException { out.flush(); } /** * Reconfigures this ValidatingEncoder to wrap the encoder provided. * * @param encoder The Encoder to wrap for validation. * @return This ValidatingEncoder. */ public ValidatingEncoder configure(Encoder encoder) { this.parser.reset(); this.out = encoder; return this; } @Override public void writeNull() throws IOException { parser.advance(Symbol.NULL); out.writeNull(); } @Override public void writeBoolean(boolean b) throws IOException { parser.advance(Symbol.BOOLEAN); out.writeBoolean(b); } @Override public void writeInt(int n) throws IOException { parser.advance(Symbol.INT); out.writeInt(n); } @Override public void writeLong(long n) throws IOException { parser.advance(Symbol.LONG); out.writeLong(n); } @Override public void writeFloat(float f) throws IOException { parser.advance(Symbol.FLOAT); out.writeFloat(f); } @Override public void writeDouble(double d) throws IOException { parser.advance(Symbol.DOUBLE); out.writeDouble(d); } @Override public void writeString(Utf8 utf8) throws IOException { parser.advance(Symbol.STRING); out.writeString(utf8); } @Override public void writeString(String str) throws IOException { parser.advance(Symbol.STRING); out.writeString(str); } @Override public void writeString(CharSequence charSequence) throws IOException { parser.advance(Symbol.STRING); out.writeString(charSequence); } @Override public void writeBytes(ByteBuffer bytes) throws IOException { parser.advance(Symbol.BYTES); out.writeBytes(bytes); } @Override public void writeBytes(byte[] bytes, int start, int len) throws IOException { parser.advance(Symbol.BYTES); out.writeBytes(bytes, start, len); } @Override public void writeFixed(byte[] bytes, int start, int len) throws IOException { parser.advance(Symbol.FIXED); Symbol.IntCheckAction top = (Symbol.IntCheckAction) parser.popSymbol(); if (len != top.size) { throw new AvroTypeException( "Incorrect length for fixed binary: expected " + top.size + " but received " + len + " bytes."); } out.writeFixed(bytes, start, len); } @Override public void writeEnum(int e) throws IOException { parser.advance(Symbol.ENUM); Symbol.IntCheckAction top = (Symbol.IntCheckAction) parser.popSymbol(); if (e < 0 || e >= top.size) { throw new AvroTypeException("Enumeration out of range: max is " + top.size + " but received " + e); } out.writeEnum(e); } @Override public void writeArrayStart() throws IOException { push(); parser.advance(Symbol.ARRAY_START); out.writeArrayStart(); } @Override public void writeArrayEnd() throws IOException { parser.advance(Symbol.ARRAY_END); out.writeArrayEnd(); pop(); } @Override public void writeMapStart() throws IOException { push(); parser.advance(Symbol.MAP_START); out.writeMapStart(); } @Override public void writeMapEnd() throws IOException { parser.advance(Symbol.MAP_END); out.writeMapEnd(); pop(); } @Override public void setItemCount(long itemCount) throws IOException { super.setItemCount(itemCount); out.setItemCount(itemCount); } @Override public void startItem() throws IOException { super.startItem(); out.startItem(); } @Override public void writeIndex(int unionIndex) throws IOException { parser.advance(Symbol.UNION); Symbol.Alternative top = (Symbol.Alternative) parser.popSymbol(); parser.pushSymbol(top.getSymbol(unionIndex)); out.writeIndex(unionIndex); } @Override public Symbol doAction(Symbol input, Symbol top) throws IOException { return null; } }
7,347
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/DecoderFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import java.io.InputStream; import org.apache.avro.Schema; /** * A factory for creating and configuring {@link Decoder}s. * <p/> * Factories are thread-safe, and are generally cached by applications for * performance reasons. Multiple instances are only required if multiple * concurrent configurations are needed. * * @see Decoder */ public class DecoderFactory { private static final DecoderFactory DEFAULT_FACTORY = new DefaultDecoderFactory(); static final int DEFAULT_BUFFER_SIZE = 8192; int binaryDecoderBufferSize = DEFAULT_BUFFER_SIZE; /** Constructor for factory instances */ public DecoderFactory() { super(); } /** * @deprecated use the equivalent {@link #get()} instead */ @Deprecated public static DecoderFactory defaultFactory() { return get(); } /** * Returns an immutable static DecoderFactory configured with default settings * All mutating methods throw IllegalArgumentExceptions. All creator methods * create objects with default settings. */ public static DecoderFactory get() { return DEFAULT_FACTORY; } /** * Configures this factory to use the specified buffer size when creating * Decoder instances that buffer their input. The default buffer size is 8192 * bytes. * * @param size The preferred buffer size. Valid values are in the range [32, * 16*1024*1024]. Values outside this range are rounded to the * nearest value in the range. Values less than 512 or greater than * 1024*1024 are not recommended. * @return This factory, to enable method chaining: * * <pre> * DecoderFactory myFactory = new DecoderFactory().useBinaryDecoderBufferSize(4096); * </pre> */ public DecoderFactory configureDecoderBufferSize(int size) { if (size < 32) size = 32; if (size > 16 * 1024 * 1024) size = 16 * 1024 * 1024; this.binaryDecoderBufferSize = size; return this; } /** * Returns this factory's configured preferred buffer size. Used when creating * Decoder instances that buffer. See {@link #configureDecoderBufferSize} * * @return The preferred buffer size, in bytes. */ public int getConfiguredBufferSize() { return this.binaryDecoderBufferSize; } /** * @deprecated use the equivalent * {@link #binaryDecoder(InputStream, BinaryDecoder)} instead */ @Deprecated public BinaryDecoder createBinaryDecoder(InputStream in, BinaryDecoder reuse) { return binaryDecoder(in, reuse); } /** * Creates or reinitializes a {@link BinaryDecoder} with the input stream * provided as the source of data. If <i>reuse</i> is provided, it will be * reinitialized to the given input stream. * <p/> * {@link BinaryDecoder} instances returned by this method buffer their input, * reading up to {@link #getConfiguredBufferSize()} bytes past the minimum * required to satisfy read requests in order to achieve better performance. If * the buffering is not desired, use * {@link #directBinaryDecoder(InputStream, BinaryDecoder)}. * <p/> * {@link BinaryDecoder#inputStream()} provides a view on the data that is * buffer-aware, for users that need to interleave access to data with the * Decoder API. * * @param in The InputStream to initialize to * @param reuse The BinaryDecoder to <i>attempt</i> to reuse given the factory * configuration. A BinaryDecoder implementation may not be * compatible with reuse, causing a new instance to be returned. If * null, a new instance is returned. * @return A BinaryDecoder that uses <i>in</i> as its source of data. If * <i>reuse</i> is null, this will be a new instance. If <i>reuse</i> is * not null, then it may be reinitialized if compatible, otherwise a new * instance will be returned. * @see BinaryDecoder * @see Decoder */ public BinaryDecoder binaryDecoder(InputStream in, BinaryDecoder reuse) { if (null == reuse || !reuse.getClass().equals(BinaryDecoder.class)) { return new BinaryDecoder(in, binaryDecoderBufferSize); } else { return reuse.configure(in, binaryDecoderBufferSize); } } /** * Creates or reinitializes a {@link BinaryDecoder} with the input stream * provided as the source of data. If <i>reuse</i> is provided, it will be * reinitialized to the given input stream. * <p/> * {@link BinaryDecoder} instances returned by this method do not buffer their * input. In most cases a buffering BinaryDecoder is sufficient in combination * with {@link BinaryDecoder#inputStream()} which provides a buffer-aware view * on the data. * <p/> * A "direct" BinaryDecoder does not read ahead from an InputStream or other * data source that cannot be rewound. From the perspective of a client, a * "direct" decoder must never read beyond the minimum necessary bytes to * service a {@link BinaryDecoder} API read request. * <p/> * In the case that the improved performance of a buffering implementation does * not outweigh the inconvenience of its buffering semantics, a "direct" decoder * can be used. * * @param in The InputStream to initialize to * @param reuse The BinaryDecoder to <i>attempt</i> to reuse given the factory * configuration. A BinaryDecoder implementation may not be * compatible with reuse, causing a new instance to be returned. If * null, a new instance is returned. * @return A BinaryDecoder that uses <i>in</i> as its source of data. If * <i>reuse</i> is null, this will be a new instance. If <i>reuse</i> is * not null, then it may be reinitialized if compatible, otherwise a new * instance will be returned. * @see DirectBinaryDecoder * @see Decoder */ public BinaryDecoder directBinaryDecoder(InputStream in, BinaryDecoder reuse) { if (null == reuse || !reuse.getClass().equals(DirectBinaryDecoder.class)) { return new DirectBinaryDecoder(in); } else { return ((DirectBinaryDecoder) reuse).configure(in); } } /** * @deprecated use {@link #binaryDecoder(byte[], int, int, BinaryDecoder)} * instead */ @Deprecated public BinaryDecoder createBinaryDecoder(byte[] bytes, int offset, int length, BinaryDecoder reuse) { if (null == reuse || !reuse.getClass().equals(BinaryDecoder.class)) { return new BinaryDecoder(bytes, offset, length); } else { return reuse.configure(bytes, offset, length); } } /** * Creates or reinitializes a {@link BinaryDecoder} with the byte array provided * as the source of data. If <i>reuse</i> is provided, it will attempt to * reinitialize <i>reuse</i> to the new byte array. This instance will use the * provided byte array as its buffer. * <p/> * {@link BinaryDecoder#inputStream()} provides a view on the data that is * buffer-aware and can provide a view of the data not yet read by Decoder API * methods. * * @param bytes The byte array to initialize to * @param offset The offset to start reading from * @param length The maximum number of bytes to read from the byte array * @param reuse The BinaryDecoder to attempt to reinitialize. if null a new * BinaryDecoder is created. * @return A BinaryDecoder that uses <i>bytes</i> as its source of data. If * <i>reuse</i> is null, this will be a new instance. <i>reuse</i> may * be reinitialized if appropriate, otherwise a new instance is * returned. Clients must not assume that <i>reuse</i> is reinitialized * and returned. */ public BinaryDecoder binaryDecoder(byte[] bytes, int offset, int length, BinaryDecoder reuse) { if (null == reuse || !reuse.getClass().equals(BinaryDecoder.class)) { return new BinaryDecoder(bytes, offset, length); } else { return reuse.configure(bytes, offset, length); } } /** @deprecated use {@link #binaryDecoder(byte[], BinaryDecoder)} instead */ @Deprecated public BinaryDecoder createBinaryDecoder(byte[] bytes, BinaryDecoder reuse) { return binaryDecoder(bytes, 0, bytes.length, reuse); } /** * This method is shorthand for * * <pre> * createBinaryDecoder(bytes, 0, bytes.length, reuse); * </pre> * * {@link #binaryDecoder(byte[], int, int, BinaryDecoder)} */ public BinaryDecoder binaryDecoder(byte[] bytes, BinaryDecoder reuse) { return binaryDecoder(bytes, 0, bytes.length, reuse); } /** * Creates a {@link JsonDecoder} using the InputStream provided for reading data * that conforms to the Schema provided. * <p/> * * @param schema The Schema for data read from this JsonEncoder. Cannot be null. * @param input The InputStream to read from. Cannot be null. * @return A JsonEncoder configured with <i>input</i> and <i>schema</i> * @throws IOException */ public JsonDecoder jsonDecoder(Schema schema, InputStream input) throws IOException { return new JsonDecoder(schema, input); } /** * Creates a {@link JsonDecoder} using the String provided for reading data that * conforms to the Schema provided. * <p/> * * @param schema The Schema for data read from this JsonEncoder. Cannot be null. * @param input The String to read from. Cannot be null. * @return A JsonEncoder configured with <i>input</i> and <i>schema</i> * @throws IOException */ public JsonDecoder jsonDecoder(Schema schema, String input) throws IOException { return new JsonDecoder(schema, input); } /** * Creates a {@link ValidatingDecoder} wrapping the Decoder provided. This * ValidatingDecoder will ensure that operations against it conform to the * schema provided. * * @param schema The Schema to validate against. Cannot be null. * @param wrapped The Decoder to wrap. * @return A ValidatingDecoder configured with <i>wrapped</i> and <i>schema</i> * @throws IOException */ public ValidatingDecoder validatingDecoder(Schema schema, Decoder wrapped) throws IOException { return new ValidatingDecoder(schema, wrapped); } /** * Creates a {@link ResolvingDecoder} wrapping the Decoder provided. This * ResolvingDecoder will resolve input conforming to the <i>writer</i> schema * from the wrapped Decoder, and present it as the <i>reader</i> schema. * * @param writer The Schema that the source data is in. Cannot be null. * @param reader The Schema that the reader wishes to read the data as. Cannot * be null. * @param wrapped The Decoder to wrap. * @return A ResolvingDecoder configured to resolve <i>writer</i> to * <i>reader</i> from <i>in</i> * @throws IOException */ public ResolvingDecoder resolvingDecoder(Schema writer, Schema reader, Decoder wrapped) throws IOException { return new ResolvingDecoder(writer, reader, wrapped); } private static class DefaultDecoderFactory extends DecoderFactory { @Override public DecoderFactory configureDecoderBufferSize(int bufferSize) { throw new IllegalArgumentException("This Factory instance is Immutable"); } } }
7,348
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/ParsingEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import java.util.Arrays; import org.apache.avro.AvroTypeException; /** * Base class for <a href="parsing/package-summary.html">parser</a>-based * {@link Encoder}s. */ public abstract class ParsingEncoder extends Encoder { /** * Tracks the number of items that remain to be written in the collections * (array or map). */ private long[] counts = new long[10]; protected int pos = -1; @Override public void setItemCount(long itemCount) throws IOException { if (counts[pos] != 0) { throw new AvroTypeException("Incorrect number of items written. " + counts[pos] + " more required."); } counts[pos] = itemCount; } @Override public void startItem() throws IOException { counts[pos]--; } /** Push a new collection on to the stack. */ protected final void push() { if (++pos == counts.length) { counts = Arrays.copyOf(counts, pos + 10); } counts[pos] = 0; } protected final void pop() { if (counts[pos] != 0) { throw new AvroTypeException("Incorrect number of items written. " + counts[pos] + " more required."); } pos--; } protected final int depth() { return pos; } }
7,349
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/EncoderFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import java.io.OutputStream; import java.util.EnumSet; import org.apache.avro.AvroRuntimeException; import org.apache.avro.Schema; import com.fasterxml.jackson.core.JsonGenerator; /** * A factory for creating and configuring {@link Encoder} instances. * <p/> * Factory methods that create Encoder instances are thread-safe. Multiple * instances with different configurations can be cached by an application. * * @see Encoder * @see BinaryEncoder * @see JsonEncoder * @see ValidatingEncoder * @see BufferedBinaryEncoder * @see BlockingBinaryEncoder * @see DirectBinaryEncoder */ public class EncoderFactory { private static final int DEFAULT_BUFFER_SIZE = 2048; private static final int DEFAULT_BLOCK_BUFFER_SIZE = 64 * 1024; private static final int MIN_BLOCK_BUFFER_SIZE = 64; private static final int MAX_BLOCK_BUFFER_SIZE = 1024 * 1024 * 1024; private static final EncoderFactory DEFAULT_FACTORY = new DefaultEncoderFactory(); protected int binaryBufferSize = DEFAULT_BUFFER_SIZE; protected int binaryBlockSize = DEFAULT_BLOCK_BUFFER_SIZE; /** * Returns an immutable static DecoderFactory with default configuration. All * configuration methods throw AvroRuntimeExceptions if called. */ public static EncoderFactory get() { return DEFAULT_FACTORY; } /** * Configures this factory to use the specified buffer size when creating * Encoder instances that buffer their output. The default buffer size is 2048 * bytes. * * @param size The buffer size to configure new instances with. Valid values are * in the range [32, 16*1024*1024]. Values outside this range are * set to the nearest value in the range. Values less than 256 will * limit performance but will consume less memory if the * BinaryEncoder is short-lived, values greater than 8*1024 are not * likely to improve performance but may be useful for the * downstream OutputStream. * @return This factory, to enable method chaining: * * <pre> * EncoderFactory factory = new EncoderFactory().configureBufferSize(4096); * </pre> * * @see #binaryEncoder(OutputStream, BinaryEncoder) */ public EncoderFactory configureBufferSize(int size) { if (size < 32) size = 32; if (size > 16 * 1024 * 1024) size = 16 * 1024 * 1024; this.binaryBufferSize = size; return this; } /** * Returns this factory's configured default buffer size. Used when creating * Encoder instances that buffer writes. * * @see #configureBufferSize(int) * @see #binaryEncoder(OutputStream, BinaryEncoder) * @return The preferred buffer size, in bytes. */ public int getBufferSize() { return this.binaryBufferSize; } /** * Configures this factory to construct blocking BinaryEncoders with the * specified block buffer size. The default buffer size is 64 * 1024 bytes. * * @param size The preferred block size for array blocking. Arrays larger than * this size will be segmented into blocks according to the Avro * spec. Valid values are in the range [64, 1024*1024*1024] Values * outside this range are set to the nearest value in the range. The * encoder will require at least this amount of memory. * @return This factory, to enable method chaining: * * <pre> * EncoderFactory factory = new EncoderFactory().configureBlockSize(8000); * </pre> * * @see #blockingBinaryEncoder(OutputStream, BinaryEncoder) */ public EncoderFactory configureBlockSize(int size) { if (size < MIN_BLOCK_BUFFER_SIZE) size = MIN_BLOCK_BUFFER_SIZE; if (size > MAX_BLOCK_BUFFER_SIZE) size = MAX_BLOCK_BUFFER_SIZE; this.binaryBlockSize = size; return this; } /** * Returns this factory's configured default block buffer size. * {@link BinaryEncoder} instances created with * #blockingBinaryEncoder(OutputStream, BinaryEncoder) will have block buffers * of this size. * <p/> * * @see #configureBlockSize(int) * @see #blockingBinaryEncoder(OutputStream, BinaryEncoder) * @return The preferred block size, in bytes. */ public int getBlockSize() { return this.binaryBlockSize; } /** * Creates or reinitializes a {@link BinaryEncoder} with the OutputStream * provided as the destination for written data. If <i>reuse</i> is provided, an * attempt will be made to reconfigure <i>reuse</i> rather than construct a new * instance, but this is not guaranteed, a new instance may be returned. * <p/> * The {@link BinaryEncoder} implementation returned may buffer its output. Data * may not appear on the underlying OutputStream until {@link Encoder#flush()} * is called. The buffer size is configured with * {@link #configureBufferSize(int)}. * </p> * If buffering is not desired, and lower performance is acceptable, use * {@link #directBinaryEncoder(OutputStream, BinaryEncoder)} * <p/> * {@link BinaryEncoder} instances returned by this method are not thread-safe * * @param out The OutputStream to write to. Cannot be null. * @param reuse The BinaryEncoder to <i>attempt</i> to reuse given the factory * configuration. A BinaryEncoder implementation may not be * compatible with reuse, causing a new instance to be returned. If * null, a new instance is returned. * @return A BinaryEncoder that uses <i>out</i> as its data output. If * <i>reuse</i> is null, this will be a new instance. If <i>reuse</i> is * not null, then the returned instance may be a new instance or * <i>reuse</i> reconfigured to use <i>out</i>. * @throws IOException * @see BufferedBinaryEncoder * @see Encoder */ public BinaryEncoder binaryEncoder(OutputStream out, BinaryEncoder reuse) { if (null == reuse || !reuse.getClass().equals(BufferedBinaryEncoder.class)) { return new BufferedBinaryEncoder(out, this.binaryBufferSize); } else { return ((BufferedBinaryEncoder) reuse).configure(out, this.binaryBufferSize); } } /** * Creates or reinitializes a {@link BinaryEncoder} with the OutputStream * provided as the destination for written data. If <i>reuse</i> is provided, an * attempt will be made to reconfigure <i>reuse</i> rather than construct a new * instance, but this is not guaranteed, a new instance may be returned. * <p/> * The {@link BinaryEncoder} implementation returned does not buffer its output, * calling {@link Encoder#flush()} will simply cause the wrapped OutputStream to * be flushed. * <p/> * Performance of unbuffered writes can be significantly slower than buffered * writes. {@link #binaryEncoder(OutputStream, BinaryEncoder)} returns * BinaryEncoder instances that are tuned for performance but may buffer output. * The unbuffered, 'direct' encoder may be desired when buffering semantics are * problematic, or if the lifetime of the encoder is so short that the buffer * would not be useful. * <p/> * {@link BinaryEncoder} instances returned by this method are not thread-safe. * * @param out The OutputStream to initialize to. Cannot be null. * @param reuse The BinaryEncoder to <i>attempt</i> to reuse given the factory * configuration. A BinaryEncoder implementation may not be * compatible with reuse, causing a new instance to be returned. If * null, a new instance is returned. * @return A BinaryEncoder that uses <i>out</i> as its data output. If * <i>reuse</i> is null, this will be a new instance. If <i>reuse</i> is * not null, then the returned instance may be a new instance or * <i>reuse</i> reconfigured to use <i>out</i>. * @see DirectBinaryEncoder * @see Encoder */ public BinaryEncoder directBinaryEncoder(OutputStream out, BinaryEncoder reuse) { if (null == reuse || !reuse.getClass().equals(DirectBinaryEncoder.class)) { return new DirectBinaryEncoder(out); } else { return ((DirectBinaryEncoder) reuse).configure(out); } } /** * Creates or reinitializes a {@link BlockingDirectBinaryEncoder} with the * OutputStream provided as the destination for written data. If <i>reuse</i> is * provided, an attempt will be made to reconfigure <i>reuse</i> rather than * construct a new instance, but this is not guaranteed, a new instance may be * returned. * <p/> * The {@link BinaryEncoder} implementation returned does not buffer its output, * calling {@link Encoder#flush()} will simply cause the wrapped OutputStream to * be flushed. * <p/> * The {@link BlockingDirectBinaryEncoder} will write the block sizes for the * arrays and maps so efficient skipping can be done. * <p/> * Performance of unbuffered writes can be significantly slower than buffered * writes. {@link #binaryEncoder(OutputStream, BinaryEncoder)} returns * BinaryEncoder instances that are tuned for performance but may buffer output. * The unbuffered, 'direct' encoder may be desired when buffering semantics are * problematic, or if the lifetime of the encoder is so short that the buffer * would not be useful. * <p/> * {@link BinaryEncoder} instances returned by this method are not thread-safe. * * @param out The OutputStream to initialize to. Cannot be null. * @param reuse The BinaryEncoder to <i>attempt</i> to reuse given the factory * configuration. A BinaryEncoder implementation may not be * compatible with reuse, causing a new instance to be returned. If * null, a new instance is returned. * @return A BinaryEncoder that uses <i>out</i> as its data output. If * <i>reuse</i> is null, this will be a new instance. If <i>reuse</i> is * not null, then the returned instance may be a new instance or * <i>reuse</i> reconfigured to use <i>out</i>. * @see DirectBinaryEncoder * @see Encoder */ public BinaryEncoder blockingDirectBinaryEncoder(OutputStream out, BinaryEncoder reuse) { if (null == reuse || !reuse.getClass().equals(BlockingDirectBinaryEncoder.class)) { return new BlockingDirectBinaryEncoder(out); } else { return ((DirectBinaryEncoder) reuse).configure(out); } } /** * Creates or reinitializes a {@link BinaryEncoder} with the OutputStream * provided as the destination for written data. If <i>reuse</i> is provided, an * attempt will be made to reconfigure <i>reuse</i> rather than construct a new * instance, but this is not guaranteed, a new instance may be returned. * <p/> * The {@link BinaryEncoder} implementation returned buffers its output, calling * {@link Encoder#flush()} is required for output to appear on the underlying * OutputStream. * <p/> * The returned BinaryEncoder implements the Avro binary encoding using blocks * delimited with byte sizes for Arrays and Maps. This allows for some decoders * to skip over large Arrays or Maps without decoding the contents, but adds * some overhead. The default block size is configured with * {@link #configureBlockSize(int)} * <p/> * {@link BinaryEncoder} instances returned by this method are not thread-safe. * * @param out The OutputStream to initialize to. Cannot be null. * @param reuse The BinaryEncoder to <i>attempt</i> to reuse given the factory * configuration. A BinaryEncoder implementation may not be * compatible with reuse, causing a new instance to be returned. If * null, a new instance is returned. * @return A BinaryEncoder that uses <i>out</i> as its data output. If * <i>reuse</i> is null, this will be a new instance. If <i>reuse</i> is * not null, then the returned instance may be a new instance or * <i>reuse</i> reconfigured to use <i>out</i>. * @throws IOException * @see BlockingBinaryEncoder * @see Encoder */ public BinaryEncoder blockingBinaryEncoder(OutputStream out, BinaryEncoder reuse) { int blockSize = this.binaryBlockSize; int bufferSize = (blockSize * 2 >= this.binaryBufferSize) ? 32 : this.binaryBufferSize; if (null == reuse || !reuse.getClass().equals(BlockingBinaryEncoder.class)) { return new BlockingBinaryEncoder(out, blockSize, bufferSize); } else { return ((BlockingBinaryEncoder) reuse).configure(out, blockSize, bufferSize); } } /** * Creates a {@link JsonEncoder} using the OutputStream provided for writing * data conforming to the Schema provided. * <p/> * {@link JsonEncoder} buffers its output. Data may not appear on the underlying * OutputStream until {@link Encoder#flush()} is called. * <p/> * {@link JsonEncoder} is not thread-safe. * * @param schema The Schema for data written to this JsonEncoder. Cannot be * null. * @param out The OutputStream to write to. Cannot be null. * @return A JsonEncoder configured with <i>out</i> and <i>schema</i> * @throws IOException */ public JsonEncoder jsonEncoder(Schema schema, OutputStream out) throws IOException { return new JsonEncoder(schema, out); } /** * Creates a {@link JsonEncoder} using the OutputStream provided for writing * data conforming to the Schema provided with optional pretty printing. * <p/> * {@link JsonEncoder} buffers its output. Data may not appear on the underlying * OutputStream until {@link Encoder#flush()} is called. * <p/> * {@link JsonEncoder} is not thread-safe. * * @param schema The Schema for data written to this JsonEncoder. Cannot be * null. * @param out The OutputStream to write to. Cannot be null. * @param pretty Pretty print encoding. * @return A JsonEncoder configured with <i>out</i>, <i>schema</i> and * <i>pretty</i> * @throws IOException */ public JsonEncoder jsonEncoder(Schema schema, OutputStream out, boolean pretty) throws IOException { return new JsonEncoder(schema, out, pretty); } /** * Creates a {@link JsonEncoder} using the OutputStream provided for writing * data conforming to the Schema provided with optional pretty printing. * <p/> * {@link JsonEncoder} buffers its output. Data may not appear on the underlying * OutputStream until {@link Encoder#flush()} is called. * <p/> * {@link JsonEncoder} is not thread-safe. * * @param schema The Schema for data written to this JsonEncoder. Cannot be * null. * @param out The OutputStream to write to. Cannot be null. * @param pretty Pretty print encoding. * @param autoflush Whether to Automatically flush the data to storage, default * is true controls the underlying FLUSH_PASSED_TO_STREAM * feature of JsonGenerator * @return A JsonEncoder configured with <i>out</i>, <i>schema</i> and * <i>pretty</i> * @throws IOException */ public JsonEncoder jsonEncoder(Schema schema, OutputStream out, boolean pretty, boolean autoflush) throws IOException { EnumSet<JsonEncoder.JsonOptions> options = EnumSet.noneOf(JsonEncoder.JsonOptions.class); if (pretty) { options.add(JsonEncoder.JsonOptions.Pretty); } if (!autoflush) { options.add(JsonEncoder.JsonOptions.NoFlushStream); } return new JsonEncoder(schema, out, options); } /** * Creates a {@link JsonEncoder} using the {@link JsonGenerator} provided for * output of data conforming to the Schema provided. * <p/> * {@link JsonEncoder} buffers its output. Data may not appear on the underlying * output until {@link Encoder#flush()} is called. * <p/> * {@link JsonEncoder} is not thread-safe. * * @param schema The Schema for data written to this JsonEncoder. Cannot be * null. * @param gen The JsonGenerator to write with. Cannot be null. * @return A JsonEncoder configured with <i>gen</i> and <i>schema</i> * @throws IOException */ JsonEncoder jsonEncoder(Schema schema, JsonGenerator gen) throws IOException { return new JsonEncoder(schema, gen); } /** * Creates a {@link ValidatingEncoder} that wraps the Encoder provided. This * ValidatingEncoder will ensure that operations against it conform to the * schema provided. * <p/> * Many {@link Encoder}s buffer their output. Data may not appear on the * underlying output until {@link Encoder#flush()} is called. * <p/> * {@link ValidatingEncoder} is not thread-safe. * * @param schema The Schema to validate operations against. Cannot be null. * @param encoder The Encoder to wrap. Cannot be be null. * @return A ValidatingEncoder configured to wrap <i>encoder</i> and validate * against <i>schema</i> * @throws IOException */ public ValidatingEncoder validatingEncoder(Schema schema, Encoder encoder) throws IOException { return new ValidatingEncoder(schema, encoder); } // default encoder is not mutable private static class DefaultEncoderFactory extends EncoderFactory { @Override public EncoderFactory configureBlockSize(int size) { throw new AvroRuntimeException("Default EncoderFactory cannot be configured"); } @Override public EncoderFactory configureBufferSize(int size) { throw new AvroRuntimeException("Default EncoderFactory cannot be configured"); } } }
7,350
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/JsonDecoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Stack; import org.apache.avro.AvroTypeException; import org.apache.avro.Schema; import org.apache.avro.io.parsing.JsonGrammarGenerator; import org.apache.avro.io.parsing.Parser; import org.apache.avro.io.parsing.Symbol; import org.apache.avro.util.Utf8; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.util.TokenBuffer; /** * A {@link Decoder} for Avro's JSON data encoding. * </p> * Construct using {@link DecoderFactory}. * </p> * JsonDecoder is not thread-safe. */ public class JsonDecoder extends ParsingDecoder implements Parser.ActionHandler { private JsonParser in; private static JsonFactory jsonFactory = new JsonFactory(); Stack<ReorderBuffer> reorderBuffers = new Stack<>(); ReorderBuffer currentReorderBuffer; private static class ReorderBuffer { public Map<String, TokenBuffer> savedFields = new HashMap<>(); public JsonParser origParser = null; } private JsonDecoder(Symbol root, InputStream in) throws IOException { super(root); configure(in); } private JsonDecoder(Symbol root, String in) throws IOException { super(root); configure(in); } JsonDecoder(Schema schema, InputStream in) throws IOException { this(getSymbol(schema), in); } JsonDecoder(Schema schema, String in) throws IOException { this(getSymbol(schema), in); } private static Symbol getSymbol(Schema schema) { Objects.requireNonNull(schema, "Schema cannot be null"); return new JsonGrammarGenerator().generate(schema); } /** * Reconfigures this JsonDecoder to use the InputStream provided. * <p/> * If the InputStream provided is null, a NullPointerException is thrown. * <p/> * Otherwise, this JsonDecoder will reset its state and then reconfigure its * input. * * @param in The InputStream to read from. Cannot be null. * @throws IOException * @throws NullPointerException if {@code in} is {@code null} * @return this JsonDecoder */ public JsonDecoder configure(InputStream in) throws IOException { Objects.requireNonNull(in, "InputStream cannot be null"); parser.reset(); reorderBuffers.clear(); currentReorderBuffer = null; this.in = jsonFactory.createParser(in); this.in.nextToken(); return this; } /** * Reconfigures this JsonDecoder to use the String provided for input. * <p/> * If the String provided is null, a NullPointerException is thrown. * <p/> * Otherwise, this JsonDecoder will reset its state and then reconfigure its * input. * * @param in The String to read from. Cannot be null. * @throws IOException * @throws NullPointerException if {@code in} is {@code null} * @return this JsonDecoder */ public JsonDecoder configure(String in) throws IOException { Objects.requireNonNull(in, "String to read from cannot be null"); parser.reset(); reorderBuffers.clear(); currentReorderBuffer = null; this.in = new JsonFactory().createParser(in); this.in.nextToken(); return this; } private void advance(Symbol symbol) throws IOException { this.parser.processTrailingImplicitActions(); if (in.getCurrentToken() == null && this.parser.depth() == 1) throw new EOFException(); parser.advance(symbol); } @Override public void readNull() throws IOException { advance(Symbol.NULL); if (in.getCurrentToken() == JsonToken.VALUE_NULL) { in.nextToken(); } else { throw error("null"); } } @Override public boolean readBoolean() throws IOException { advance(Symbol.BOOLEAN); JsonToken t = in.getCurrentToken(); if (t == JsonToken.VALUE_TRUE || t == JsonToken.VALUE_FALSE) { in.nextToken(); return t == JsonToken.VALUE_TRUE; } else { throw error("boolean"); } } @Override public int readInt() throws IOException { advance(Symbol.INT); if (in.getCurrentToken() == JsonToken.VALUE_NUMBER_INT) { int result = in.getIntValue(); in.nextToken(); return result; } if (in.getCurrentToken() == JsonToken.VALUE_NUMBER_FLOAT) { float value = in.getFloatValue(); if (Math.abs(value - Math.round(value)) <= Float.MIN_VALUE) { int result = Math.round(value); in.nextToken(); return result; } } throw error("int"); } @Override public long readLong() throws IOException { advance(Symbol.LONG); if (in.getCurrentToken() == JsonToken.VALUE_NUMBER_INT) { long result = in.getLongValue(); in.nextToken(); return result; } if (in.getCurrentToken() == JsonToken.VALUE_NUMBER_FLOAT) { double value = in.getDoubleValue(); if (Math.abs(value - Math.round(value)) <= Double.MIN_VALUE) { long result = Math.round(value); in.nextToken(); return result; } } throw error("long"); } @Override public float readFloat() throws IOException { advance(Symbol.FLOAT); if (in.getCurrentToken().isNumeric()) { float result = in.getFloatValue(); in.nextToken(); return result; } else { throw error("float"); } } @Override public double readDouble() throws IOException { advance(Symbol.DOUBLE); if (in.getCurrentToken().isNumeric()) { double result = in.getDoubleValue(); in.nextToken(); return result; } else { throw error("double"); } } @Override public Utf8 readString(Utf8 old) throws IOException { return new Utf8(readString()); } @Override public String readString() throws IOException { advance(Symbol.STRING); if (parser.topSymbol() == Symbol.MAP_KEY_MARKER) { parser.advance(Symbol.MAP_KEY_MARKER); if (in.getCurrentToken() != JsonToken.FIELD_NAME) { throw error("map-key"); } } else { if (in.getCurrentToken() != JsonToken.VALUE_STRING) { throw error("string"); } } String result = in.getText(); in.nextToken(); return result; } @Override public void skipString() throws IOException { advance(Symbol.STRING); if (parser.topSymbol() == Symbol.MAP_KEY_MARKER) { parser.advance(Symbol.MAP_KEY_MARKER); if (in.getCurrentToken() != JsonToken.FIELD_NAME) { throw error("map-key"); } } else { if (in.getCurrentToken() != JsonToken.VALUE_STRING) { throw error("string"); } } in.nextToken(); } @Override public ByteBuffer readBytes(ByteBuffer old) throws IOException { advance(Symbol.BYTES); if (in.getCurrentToken() == JsonToken.VALUE_STRING) { byte[] result = readByteArray(); in.nextToken(); return ByteBuffer.wrap(result); } else { throw error("bytes"); } } private byte[] readByteArray() throws IOException { byte[] result = in.getText().getBytes(StandardCharsets.ISO_8859_1); return result; } @Override public void skipBytes() throws IOException { advance(Symbol.BYTES); if (in.getCurrentToken() == JsonToken.VALUE_STRING) { in.nextToken(); } else { throw error("bytes"); } } private void checkFixed(int size) throws IOException { advance(Symbol.FIXED); Symbol.IntCheckAction top = (Symbol.IntCheckAction) parser.popSymbol(); if (size != top.size) { throw new AvroTypeException( "Incorrect length for fixed binary: expected " + top.size + " but received " + size + " bytes."); } } @Override public void readFixed(byte[] bytes, int start, int len) throws IOException { checkFixed(len); if (in.getCurrentToken() == JsonToken.VALUE_STRING) { byte[] result = readByteArray(); in.nextToken(); if (result.length != len) { throw new AvroTypeException("Expected fixed length " + len + ", but got" + result.length); } System.arraycopy(result, 0, bytes, start, len); } else { throw error("fixed"); } } @Override public void skipFixed(int length) throws IOException { checkFixed(length); doSkipFixed(length); } private void doSkipFixed(int length) throws IOException { if (in.getCurrentToken() == JsonToken.VALUE_STRING) { byte[] result = readByteArray(); in.nextToken(); if (result.length != length) { throw new AvroTypeException("Expected fixed length " + length + ", but got" + result.length); } } else { throw error("fixed"); } } @Override protected void skipFixed() throws IOException { advance(Symbol.FIXED); Symbol.IntCheckAction top = (Symbol.IntCheckAction) parser.popSymbol(); doSkipFixed(top.size); } @Override public int readEnum() throws IOException { advance(Symbol.ENUM); Symbol.EnumLabelsAction top = (Symbol.EnumLabelsAction) parser.popSymbol(); if (in.getCurrentToken() == JsonToken.VALUE_STRING) { in.getText(); int n = top.findLabel(in.getText()); if (n >= 0) { in.nextToken(); return n; } throw new AvroTypeException("Unknown symbol in enum " + in.getText()); } else { throw error("fixed"); } } @Override public long readArrayStart() throws IOException { advance(Symbol.ARRAY_START); if (in.getCurrentToken() == JsonToken.START_ARRAY) { in.nextToken(); return doArrayNext(); } else { throw error("array-start"); } } @Override public long arrayNext() throws IOException { advance(Symbol.ITEM_END); return doArrayNext(); } private long doArrayNext() throws IOException { if (in.getCurrentToken() == JsonToken.END_ARRAY) { parser.advance(Symbol.ARRAY_END); in.nextToken(); return 0; } else { return 1; } } @Override public long skipArray() throws IOException { advance(Symbol.ARRAY_START); if (in.getCurrentToken() == JsonToken.START_ARRAY) { in.skipChildren(); in.nextToken(); advance(Symbol.ARRAY_END); } else { throw error("array-start"); } return 0; } @Override public long readMapStart() throws IOException { advance(Symbol.MAP_START); if (in.getCurrentToken() == JsonToken.START_OBJECT) { in.nextToken(); return doMapNext(); } else { throw error("map-start"); } } @Override public long mapNext() throws IOException { advance(Symbol.ITEM_END); return doMapNext(); } private long doMapNext() throws IOException { if (in.getCurrentToken() == JsonToken.END_OBJECT) { in.nextToken(); advance(Symbol.MAP_END); return 0; } else { return 1; } } @Override public long skipMap() throws IOException { advance(Symbol.MAP_START); if (in.getCurrentToken() == JsonToken.START_OBJECT) { in.skipChildren(); in.nextToken(); advance(Symbol.MAP_END); } else { throw error("map-start"); } return 0; } @Override public int readIndex() throws IOException { advance(Symbol.UNION); Symbol.Alternative a = (Symbol.Alternative) parser.popSymbol(); String label; if (in.getCurrentToken() == JsonToken.VALUE_NULL) { label = "null"; } else if (in.getCurrentToken() == JsonToken.START_OBJECT && in.nextToken() == JsonToken.FIELD_NAME) { label = in.getText(); in.nextToken(); parser.pushSymbol(Symbol.UNION_END); } else { throw error("start-union"); } int n = a.findLabel(label); if (n < 0) throw new AvroTypeException("Unknown union branch " + label); parser.pushSymbol(a.getSymbol(n)); return n; } @Override public Symbol doAction(Symbol input, Symbol top) throws IOException { if (top instanceof Symbol.FieldAdjustAction) { Symbol.FieldAdjustAction fa = (Symbol.FieldAdjustAction) top; String name = fa.fname; if (currentReorderBuffer != null) { try (TokenBuffer tokenBuffer = currentReorderBuffer.savedFields.get(name)) { if (tokenBuffer != null) { currentReorderBuffer.savedFields.remove(name); currentReorderBuffer.origParser = in; in = tokenBuffer.asParser(); in.nextToken(); return null; } } } if (in.getCurrentToken() == JsonToken.FIELD_NAME) { do { String fn = in.getText(); in.nextToken(); if (name.equals(fn) || fa.aliases.contains(fn)) { return null; } else { if (currentReorderBuffer == null) { currentReorderBuffer = new ReorderBuffer(); } try (TokenBuffer tokenBuffer = new TokenBuffer(in)) { // Moves the parser to the end of the current event e.g. END_OBJECT tokenBuffer.copyCurrentStructure(in); currentReorderBuffer.savedFields.put(fn, tokenBuffer); } in.nextToken(); } } while (in.getCurrentToken() == JsonToken.FIELD_NAME); throw new AvroTypeException("Expected field name not found: " + fa.fname); } } else if (top == Symbol.FIELD_END) { if (currentReorderBuffer != null && currentReorderBuffer.origParser != null) { in = currentReorderBuffer.origParser; currentReorderBuffer.origParser = null; } } else if (top == Symbol.RECORD_START) { if (in.getCurrentToken() == JsonToken.START_OBJECT) { in.nextToken(); reorderBuffers.push(currentReorderBuffer); currentReorderBuffer = null; } else { throw error("record-start"); } } else if (top == Symbol.RECORD_END || top == Symbol.UNION_END) { // AVRO-2034 advance to the end of our object while (in.getCurrentToken() != JsonToken.END_OBJECT) { in.nextToken(); } if (top == Symbol.RECORD_END) { if (currentReorderBuffer != null && !currentReorderBuffer.savedFields.isEmpty()) { throw error("Unknown fields: " + currentReorderBuffer.savedFields.keySet()); } currentReorderBuffer = reorderBuffers.pop(); } // AVRO-2034 advance beyond the end object for the next record. in.nextToken(); } else { throw new AvroTypeException("Unknown action symbol " + top); } return null; } private AvroTypeException error(String type) { return new AvroTypeException("Expected " + type + ". Got " + in.getCurrentToken()); } }
7,351
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/DirectBinaryEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import java.io.OutputStream; import java.util.Objects; /** * An {@link Encoder} for Avro's binary encoding that does not buffer output. * <p/> * This encoder does not buffer writes, and as a result is slower than * {@link BufferedBinaryEncoder}. However, it is lighter-weight and useful when * the buffering in BufferedBinaryEncoder is not desired and/or the Encoder is * very short-lived. * <p/> * To construct, use * {@link EncoderFactory#directBinaryEncoder(OutputStream, BinaryEncoder)} * <p/> * DirectBinaryEncoder is not thread-safe * * @see BinaryEncoder * @see EncoderFactory * @see Encoder * @see Decoder */ public class DirectBinaryEncoder extends BinaryEncoder { protected OutputStream out; // the buffer is used for writing floats, doubles, and large longs. private final byte[] buf = new byte[12]; /** * Create a writer that sends its output to the underlying stream * <code>out</code>. **/ public DirectBinaryEncoder(OutputStream out) { configure(out); } DirectBinaryEncoder configure(OutputStream out) { Objects.requireNonNull(out, "OutputStream cannot be null"); this.out = out; return this; } @Override public void flush() throws IOException { out.flush(); } @Override public void writeBoolean(boolean b) throws IOException { out.write(b ? 1 : 0); } /* * buffering is slower for ints that encode to just 1 or two bytes, and faster * for large ones. (Sun JRE 1.6u22, x64 -server) */ @Override public void writeInt(int n) throws IOException { int val = (n << 1) ^ (n >> 31); if ((val & ~0x7F) == 0) { out.write(val); return; } else if ((val & ~0x3FFF) == 0) { out.write(0x80 | val); out.write(val >>> 7); return; } int len = BinaryData.encodeInt(n, buf, 0); out.write(buf, 0, len); } /* * buffering is slower for writeLong when the number is small enough to fit in * an int. (Sun JRE 1.6u22, x64 -server) */ @Override public void writeLong(long n) throws IOException { long val = (n << 1) ^ (n >> 63); // move sign to low-order bit if ((val & ~0x7FFFFFFFL) == 0) { int i = (int) val; while ((i & ~0x7F) != 0) { out.write((byte) ((0x80 | i) & 0xFF)); i >>>= 7; } out.write((byte) i); return; } int len = BinaryData.encodeLong(n, buf, 0); out.write(buf, 0, len); } @Override public void writeFloat(float f) throws IOException { int len = BinaryData.encodeFloat(f, buf, 0); out.write(buf, 0, len); } @Override public void writeDouble(double d) throws IOException { int len = BinaryData.encodeDouble(d, buf, 0); out.write(buf, 0, len); } @Override public void writeFixed(byte[] bytes, int start, int len) throws IOException { out.write(bytes, start, len); } @Override protected void writeZero() throws IOException { out.write(0); } @Override public int bytesBuffered() { return 0; } }
7,352
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/BinaryEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import org.apache.avro.util.Utf8; /** * An abstract {@link Encoder} for Avro's binary encoding. * <p/> * To construct and configure instances, use {@link EncoderFactory} * * @see EncoderFactory * @see BufferedBinaryEncoder * @see DirectBinaryEncoder * @see BlockingBinaryEncoder * @see Encoder * @see Decoder */ public abstract class BinaryEncoder extends Encoder { @Override public void writeNull() throws IOException { } @Override public void writeString(Utf8 utf8) throws IOException { this.writeBytes(utf8.getBytes(), 0, utf8.getByteLength()); } @Override public void writeString(String string) throws IOException { if (0 == string.length()) { writeZero(); return; } byte[] bytes = string.getBytes(StandardCharsets.UTF_8); writeInt(bytes.length); writeFixed(bytes, 0, bytes.length); } @Override public void writeBytes(ByteBuffer bytes) throws IOException { int len = bytes.limit() - bytes.position(); if (0 == len) { writeZero(); } else { writeInt(len); writeFixed(bytes); } } @Override public void writeBytes(byte[] bytes, int start, int len) throws IOException { if (0 == len) { writeZero(); return; } this.writeInt(len); this.writeFixed(bytes, start, len); } @Override public void writeEnum(int e) throws IOException { this.writeInt(e); } @Override public void writeArrayStart() throws IOException { } @Override public void setItemCount(long itemCount) throws IOException { if (itemCount > 0) { this.writeLong(itemCount); } } @Override public void startItem() throws IOException { } @Override public void writeArrayEnd() throws IOException { writeZero(); } @Override public void writeMapStart() throws IOException { } @Override public void writeMapEnd() throws IOException { writeZero(); } @Override public void writeIndex(int unionIndex) throws IOException { writeInt(unionIndex); } /** Write a zero byte to the underlying output. **/ protected abstract void writeZero() throws IOException; /** * Returns the number of bytes currently buffered by this encoder. If this * Encoder does not buffer, this will always return zero. * <p/> * Call {@link #flush()} to empty the buffer to the underlying output. */ public abstract int bytesBuffered(); }
7,353
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/BlockingBinaryEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.Arrays; import org.apache.avro.AvroTypeException; import org.apache.avro.Schema; /** * A {@link BinaryEncoder} implementation that writes large arrays and maps as a * sequence of blocks. So long as individual primitive values fit in memory, * arbitrarily long arrays and maps may be written and subsequently read without * exhausting memory. Values are buffered until the specified block size would * be exceeded, minimizing block overhead. * <p/> * Use {@link EncoderFactory#blockingBinaryEncoder(OutputStream, BinaryEncoder)} * to construct and configure. * <p/> * BlockingBinaryEncoder buffers writes, data may not appear on the output until * {@link #flush()} is called. * <p/> * BlockingBinaryEncoder is not thread-safe * * @see BinaryEncoder * @see EncoderFactory * @see Encoder */ public class BlockingBinaryEncoder extends BufferedBinaryEncoder { /* * Implementation note: * * Blocking is complicated because of nesting. If a large, nested value * overflows your buffer, you've got to do a lot of dancing around to output the * blocks correctly. * * To handle this complexity, this class keeps a stack of blocked values: each * time a new block is started (e.g., by a call to {@link #writeArrayStart}), an * entry is pushed onto this stack. * * In this stack, we keep track of the state of a block. Blocks can be in two * states. "Regular" blocks have a non-zero byte count. "Overflow" blocks help * us deal with the case where a block contains a value that's too big to * buffer. In this case, the block contains only one item, and we give it an * unknown byte-count. Because these values (1,unknown) are fixed, we're able to * write the header for these overflow blocks to the underlying stream without * seeing the entire block. After writing this header, we've freed our buffer * space to be fully devoted to blocking the large, inner value. */ private static class BlockedValue { public enum State { /** * The bottom element of our stack represents being _outside_ of a blocked * value. */ ROOT, /** * Represents the "regular" case, i.e., a blocked-value whose current block is * fully contained in the buffer. In this case, {@link BlockedValue#start} * points to the start of the blocks _data_ -- but no room has been left for a * header! When this block is terminated, it's data will have to be moved over a * bit to make room for the header. */ REGULAR, /** * Represents a blocked-value whose current block is in the overflow state. In * this case, {@link BlockedValue#start} is zero. The header for such a block * has _already been written_ (we've written out a header indicating that the * block has a single item, and we put a "zero" down for the byte-count to * indicate that we don't know the physical length of the buffer. Any blocks * _containing_ this block must be in the {@link #OVERFLOW} state. */ OVERFLOW } /** The type of this blocked value (ARRAY or MAP). */ public Schema.Type type; /** The state of this BlockedValue */ public State state; /** The location in the buffer where this blocked value starts */ public int start; /** * The index one past the last byte for the previous item. If this is the first * item, this is same as {@link #start}. */ public int lastFullItem; /** * Number of items in this blocked value that are stored in the buffer. */ public int items; /** Number of items left to write */ public long itemsLeftToWrite; /** Create a ROOT instance. */ public BlockedValue() { this.type = null; this.state = BlockedValue.State.ROOT; this.start = this.lastFullItem = 0; this.items = 1; // Makes various assertions work out } /** * Check invariants of <code>this</code> and also the <code>BlockedValue</code> * containing <code>this</code>. */ public boolean check(BlockedValue prev, int pos) { assert state != State.ROOT || type == null; assert (state == State.ROOT || type == Schema.Type.ARRAY || type == Schema.Type.MAP); assert 0 <= items; assert 0 != items || start == pos; // 0==items ==> start==pos assert 1 < items || start == lastFullItem; // 1<=items ==> start==lFI assert items <= 1 || start <= lastFullItem; // 1<items ==> start<=lFI assert lastFullItem <= pos; switch (state) { case ROOT: assert start == 0; assert prev == null; break; case REGULAR: assert start >= 0; assert prev.lastFullItem <= start; assert 1 <= prev.items; break; case OVERFLOW: assert start == 0; assert items == 1; assert prev.state == State.ROOT || prev.state == State.OVERFLOW; break; } return false; } } /** * The buffer to hold the bytes before being written into the underlying stream. */ private byte[] buf; /** * Index into the location in {@link #buf}, where next byte can be written. */ private int pos; /** * The state stack. */ private BlockedValue[] blockStack; private int stackTop = -1; private static final int STACK_STEP = 10; // buffer large enough for up to two ints for a block header // rounded up to a multiple of 4 bytes. private byte[] headerBuffer = new byte[12]; private boolean check() { assert buf != null; assert 0 <= pos; assert pos <= buf.length : pos + " " + buf.length; assert blockStack != null; BlockedValue prev = null; for (int i = 0; i <= stackTop; i++) { BlockedValue v = blockStack[i]; v.check(prev, pos); prev = v; } return true; } BlockingBinaryEncoder(OutputStream out, int blockBufferSize, int binaryEncoderBufferSize) { super(out, binaryEncoderBufferSize); this.buf = new byte[blockBufferSize]; this.pos = 0; blockStack = new BlockedValue[0]; expandStack(); BlockedValue bv = blockStack[++stackTop]; bv.type = null; bv.state = BlockedValue.State.ROOT; bv.start = bv.lastFullItem = 0; bv.items = 1; assert check(); } private void expandStack() { int oldLength = blockStack.length; blockStack = Arrays.copyOf(blockStack, blockStack.length + STACK_STEP); for (int i = oldLength; i < blockStack.length; i++) { blockStack[i] = new BlockedValue(); } } BlockingBinaryEncoder configure(OutputStream out, int blockBufferSize, int binaryEncoderBufferSize) { super.configure(out, binaryEncoderBufferSize); pos = 0; stackTop = 0; if (null == buf || buf.length != blockBufferSize) { buf = new byte[blockBufferSize]; } assert check(); return this; } @Override public void flush() throws IOException { BlockedValue bv = blockStack[stackTop]; if (bv.state == BlockedValue.State.ROOT) { super.writeFixed(buf, 0, pos); pos = 0; } else { while (bv.state != BlockedValue.State.OVERFLOW) { compact(); } } super.flush(); assert check(); } @Override public void writeBoolean(boolean b) throws IOException { ensureBounds(1); pos += BinaryData.encodeBoolean(b, buf, pos); } @Override public void writeInt(int n) throws IOException { ensureBounds(5); pos += BinaryData.encodeInt(n, buf, pos); } @Override public void writeLong(long n) throws IOException { ensureBounds(10); pos += BinaryData.encodeLong(n, buf, pos); } @Override public void writeFloat(float f) throws IOException { ensureBounds(4); pos += BinaryData.encodeFloat(f, buf, pos); } @Override public void writeDouble(double d) throws IOException { ensureBounds(8); pos += BinaryData.encodeDouble(d, buf, pos); } @Override public void writeFixed(byte[] bytes, int start, int len) throws IOException { doWriteBytes(bytes, start, len); } @Override public void writeFixed(ByteBuffer bytes) throws IOException { int pos = bytes.position(); int len = bytes.remaining(); if (bytes.hasArray()) { doWriteBytes(bytes.array(), bytes.arrayOffset() + pos, len); } else { byte[] b = new byte[len]; bytes.duplicate().get(b, 0, len); doWriteBytes(b, 0, len); } } @Override protected void writeZero() throws IOException { ensureBounds(1); buf[pos++] = (byte) 0; } @Override public void writeArrayStart() throws IOException { if (stackTop + 1 == blockStack.length) { expandStack(); } BlockedValue bv = blockStack[++stackTop]; bv.type = Schema.Type.ARRAY; bv.state = BlockedValue.State.REGULAR; bv.start = bv.lastFullItem = pos; bv.items = 0; assert check(); } @Override public void setItemCount(long itemCount) throws IOException { BlockedValue v = blockStack[stackTop]; assert v.type == Schema.Type.ARRAY || v.type == Schema.Type.MAP; assert v.itemsLeftToWrite == 0; v.itemsLeftToWrite = itemCount; assert check(); } @Override public void startItem() throws IOException { if (blockStack[stackTop].state == BlockedValue.State.OVERFLOW) { finishOverflow(); } BlockedValue t = blockStack[stackTop]; t.items++; t.lastFullItem = pos; t.itemsLeftToWrite--; assert check(); } @Override public void writeArrayEnd() throws IOException { BlockedValue top = blockStack[stackTop]; if (top.type != Schema.Type.ARRAY) { throw new AvroTypeException("Called writeArrayEnd outside of an array."); } if (top.itemsLeftToWrite != 0) { throw new AvroTypeException("Failed to write expected number of array elements."); } endBlockedValue(); assert check(); } @Override public void writeMapStart() throws IOException { if (stackTop + 1 == blockStack.length) { expandStack(); } BlockedValue bv = blockStack[++stackTop]; bv.type = Schema.Type.MAP; bv.state = BlockedValue.State.REGULAR; bv.start = bv.lastFullItem = pos; bv.items = 0; assert check(); } @Override public void writeMapEnd() throws IOException { BlockedValue top = blockStack[stackTop]; if (top.type != Schema.Type.MAP) { throw new AvroTypeException("Called writeMapEnd outside of a map."); } if (top.itemsLeftToWrite != 0) { throw new AvroTypeException("Failed to read write expected number of array elements."); } endBlockedValue(); assert check(); } @Override public void writeIndex(int unionIndex) throws IOException { ensureBounds(5); pos += BinaryData.encodeInt(unionIndex, buf, pos); } @Override public int bytesBuffered() { return pos + super.bytesBuffered(); } private void endBlockedValue() throws IOException { for (;;) { assert check(); BlockedValue t = blockStack[stackTop]; assert t.state != BlockedValue.State.ROOT; if (t.state == BlockedValue.State.OVERFLOW) { finishOverflow(); } assert t.state == BlockedValue.State.REGULAR; if (0 < t.items) { int byteCount = pos - t.start; if (t.start == 0 && blockStack[stackTop - 1].state != BlockedValue.State.REGULAR) { // Lucky us -- don't have to // move super.writeInt(-t.items); super.writeInt(byteCount); } else { int headerSize = 0; headerSize += BinaryData.encodeInt(-t.items, headerBuffer, headerSize); headerSize += BinaryData.encodeInt(byteCount, headerBuffer, headerSize); if (buf.length >= pos + headerSize) { pos += headerSize; final int m = t.start; System.arraycopy(buf, m, buf, m + headerSize, byteCount); System.arraycopy(headerBuffer, 0, buf, m, headerSize); } else { compact(); continue; } } } stackTop--; ensureBounds(1); buf[pos++] = 0; // Sentinel for last block in a blocked value assert check(); if (blockStack[stackTop].state == BlockedValue.State.ROOT) { flush(); } return; } } /** * Called when we've finished writing the last item in an overflow buffer. When * this is finished, the top of the stack will be an empty block in the * "regular" state. * * @throws IOException */ private void finishOverflow() throws IOException { BlockedValue s = blockStack[stackTop]; if (s.state != BlockedValue.State.OVERFLOW) { throw new IllegalStateException("Not an overflow block"); } assert check(); // Flush any remaining data for this block super.writeFixed(buf, 0, pos); pos = 0; // Reset top of stack to be in REGULAR mode s.state = BlockedValue.State.REGULAR; s.start = s.lastFullItem = 0; s.items = 0; assert check(); } private void ensureBounds(int l) throws IOException { while (buf.length < (pos + l)) { if (blockStack[stackTop].state == BlockedValue.State.REGULAR) { compact(); } else { super.writeFixed(buf, 0, pos); pos = 0; } } } private void doWriteBytes(byte[] bytes, int start, int len) throws IOException { if (len < buf.length) { ensureBounds(len); System.arraycopy(bytes, start, buf, pos, len); pos += len; } else { ensureBounds(buf.length); assert blockStack[stackTop].state == BlockedValue.State.ROOT || blockStack[stackTop].state == BlockedValue.State.OVERFLOW; write(bytes, start, len); } } private void write(byte[] b, int off, int len) throws IOException { if (blockStack[stackTop].state == BlockedValue.State.ROOT) { super.writeFixed(b, off, len); } else { assert check(); while (buf.length < (pos + len)) { if (blockStack[stackTop].state == BlockedValue.State.REGULAR) { compact(); } else { super.writeFixed(buf, 0, pos); pos = 0; if (buf.length <= len) { super.writeFixed(b, off, len); len = 0; } } } System.arraycopy(b, off, buf, pos, len); pos += len; } assert check(); } /** Only call if you're there are REGULAR-state values on the stack. */ private void compact() throws IOException { assert check(); // Find first REGULAR-state value BlockedValue s = null; int i; for (i = 1; i <= stackTop; i++) { s = blockStack[i]; if (s.state == BlockedValue.State.REGULAR) break; } assert s != null; // We're going to transition "s" into the overflow state. To do // this, We're going to flush any bytes prior to "s", then write // any full items of "s" into a block, start an overflow // block, write any remaining bytes of "s" up to the start of the // next more deeply-nested blocked-value, and finally move over // any remaining bytes (which will be from more deeply-nested // blocked values). // Flush any bytes prios to "s" super.writeFixed(buf, 0, s.start); // Write any full items of "s" if (1 < s.items) { super.writeInt(-(s.items - 1)); super.writeInt(s.lastFullItem - s.start); super.writeFixed(buf, s.start, s.lastFullItem - s.start); s.start = s.lastFullItem; s.items = 1; } // Start an overflow block for s super.writeInt(1); // Write any remaining bytes for "s", up to the next-most // deeply-nested value BlockedValue n = ((i + 1) <= stackTop ? blockStack[i + 1] : null); int end = (n == null ? pos : n.start); super.writeFixed(buf, s.lastFullItem, end - s.lastFullItem); // Move over any bytes that remain (and adjust indices) System.arraycopy(buf, end, buf, 0, pos - end); for (int j = i + 1; j <= stackTop; j++) { n = blockStack[j]; n.start -= end; n.lastFullItem -= end; } pos -= end; assert s.items == 1; s.start = s.lastFullItem = 0; s.state = BlockedValue.State.OVERFLOW; assert check(); } }
7,354
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/DatumReader.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import org.apache.avro.Schema; /** * Read data of a schema. * <p> * Determines the in-memory data representation. */ public interface DatumReader<D> { /** Set the writer's schema. */ void setSchema(Schema schema); /** * Read a datum. Traverse the schema, depth-first, reading all leaf values in * the schema into a datum that is returned. If the provided datum is non-null * it may be reused and returned. */ D read(D reuse, Decoder in) throws IOException; }
7,355
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/ParsingDecoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import org.apache.avro.io.parsing.SkipParser; import org.apache.avro.io.parsing.Symbol; import org.apache.avro.io.parsing.Parser.ActionHandler; import org.apache.avro.io.parsing.SkipParser.SkipHandler; /** * Base class for <a href="parsing/package-summary.html">parser</a>-based * {@link Decoder}s. */ public abstract class ParsingDecoder extends Decoder implements ActionHandler, SkipHandler { protected final SkipParser parser; protected ParsingDecoder(Symbol root) throws IOException { this.parser = new SkipParser(root, this, this); } protected abstract void skipFixed() throws IOException; @Override public void skipAction() throws IOException { parser.popSymbol(); } @Override public void skipTopSymbol() throws IOException { Symbol top = parser.topSymbol(); if (top == Symbol.NULL) { readNull(); } else if (top == Symbol.BOOLEAN) { readBoolean(); } else if (top == Symbol.INT) { readInt(); } else if (top == Symbol.LONG) { readLong(); } else if (top == Symbol.FLOAT) { readFloat(); } else if (top == Symbol.DOUBLE) { readDouble(); } else if (top == Symbol.STRING) { skipString(); } else if (top == Symbol.BYTES) { skipBytes(); } else if (top == Symbol.ENUM) { readEnum(); } else if (top == Symbol.FIXED) { skipFixed(); } else if (top == Symbol.UNION) { readIndex(); } else if (top == Symbol.ARRAY_START) { skipArray(); } else if (top == Symbol.MAP_START) { skipMap(); } } }
7,356
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/ValidatingDecoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Objects; import org.apache.avro.AvroTypeException; import org.apache.avro.Schema; import org.apache.avro.io.parsing.Parser; import org.apache.avro.io.parsing.Symbol; import org.apache.avro.io.parsing.ValidatingGrammarGenerator; import org.apache.avro.util.Utf8; /** * An implementation of {@link Decoder} that ensures that the sequence of * operations conforms to a schema. * <p/> * Use {@link DecoderFactory#validatingDecoder(Schema, Decoder)} to construct * and configure. * <p/> * ValidatingDecoder is not thread-safe. * * @see Decoder * @see DecoderFactory */ public class ValidatingDecoder extends ParsingDecoder implements Parser.ActionHandler { protected Decoder in; ValidatingDecoder(Symbol root, Decoder in) throws IOException { super(root); this.configure(in); } ValidatingDecoder(Schema schema, Decoder in) throws IOException { this(getSymbol(schema), in); } private static Symbol getSymbol(Schema schema) { Objects.requireNonNull(schema, "Schema cannot be null"); return new ValidatingGrammarGenerator().generate(schema); } /** Re-initialize, reading from a new underlying Decoder. */ public ValidatingDecoder configure(Decoder in) throws IOException { this.parser.reset(); this.in = in; return this; } @Override public void readNull() throws IOException { parser.advance(Symbol.NULL); in.readNull(); } @Override public boolean readBoolean() throws IOException { parser.advance(Symbol.BOOLEAN); return in.readBoolean(); } @Override public int readInt() throws IOException { parser.advance(Symbol.INT); return in.readInt(); } @Override public long readLong() throws IOException { parser.advance(Symbol.LONG); return in.readLong(); } @Override public float readFloat() throws IOException { parser.advance(Symbol.FLOAT); return in.readFloat(); } @Override public double readDouble() throws IOException { parser.advance(Symbol.DOUBLE); return in.readDouble(); } @Override public Utf8 readString(Utf8 old) throws IOException { parser.advance(Symbol.STRING); return in.readString(old); } @Override public String readString() throws IOException { parser.advance(Symbol.STRING); return in.readString(); } @Override public void skipString() throws IOException { parser.advance(Symbol.STRING); in.skipString(); } @Override public ByteBuffer readBytes(ByteBuffer old) throws IOException { parser.advance(Symbol.BYTES); return in.readBytes(old); } @Override public void skipBytes() throws IOException { parser.advance(Symbol.BYTES); in.skipBytes(); } private void checkFixed(int size) throws IOException { parser.advance(Symbol.FIXED); Symbol.IntCheckAction top = (Symbol.IntCheckAction) parser.popSymbol(); if (size != top.size) { throw new AvroTypeException( "Incorrect length for fixed binary: expected " + top.size + " but received " + size + " bytes."); } } @Override public void readFixed(byte[] bytes, int start, int len) throws IOException { checkFixed(len); in.readFixed(bytes, start, len); } @Override public void skipFixed(int length) throws IOException { checkFixed(length); in.skipFixed(length); } @Override protected void skipFixed() throws IOException { parser.advance(Symbol.FIXED); Symbol.IntCheckAction top = (Symbol.IntCheckAction) parser.popSymbol(); in.skipFixed(top.size); } @Override public int readEnum() throws IOException { parser.advance(Symbol.ENUM); Symbol.IntCheckAction top = (Symbol.IntCheckAction) parser.popSymbol(); int result = in.readEnum(); if (result < 0 || result >= top.size) { throw new AvroTypeException("Enumeration out of range: max is " + top.size + " but received " + result); } return result; } @Override public long readArrayStart() throws IOException { parser.advance(Symbol.ARRAY_START); long result = in.readArrayStart(); if (result == 0) { parser.advance(Symbol.ARRAY_END); } return result; } @Override public long arrayNext() throws IOException { parser.processTrailingImplicitActions(); long result = in.arrayNext(); if (result == 0) { parser.advance(Symbol.ARRAY_END); } return result; } @Override public long skipArray() throws IOException { parser.advance(Symbol.ARRAY_START); for (long c = in.skipArray(); c != 0; c = in.skipArray()) { while (c-- > 0) { parser.skipRepeater(); } } parser.advance(Symbol.ARRAY_END); return 0; } @Override public long readMapStart() throws IOException { parser.advance(Symbol.MAP_START); long result = in.readMapStart(); if (result == 0) { parser.advance(Symbol.MAP_END); } return result; } @Override public long mapNext() throws IOException { parser.processTrailingImplicitActions(); long result = in.mapNext(); if (result == 0) { parser.advance(Symbol.MAP_END); } return result; } @Override public long skipMap() throws IOException { parser.advance(Symbol.MAP_START); for (long c = in.skipMap(); c != 0; c = in.skipMap()) { while (c-- > 0) { parser.skipRepeater(); } } parser.advance(Symbol.MAP_END); return 0; } @Override public int readIndex() throws IOException { parser.advance(Symbol.UNION); Symbol.Alternative top = (Symbol.Alternative) parser.popSymbol(); int result = in.readIndex(); parser.pushSymbol(top.getSymbol(result)); return result; } @Override public Symbol doAction(Symbol input, Symbol top) throws IOException { return null; } }
7,357
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/Encoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.Flushable; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.avro.util.Utf8; /** * Low-level support for serializing Avro values. * <p/> * This class has two types of methods. One type of methods support the writing * of leaf values (for example, {@link #writeLong} and {@link #writeString}). * These methods have analogs in {@link Decoder}. * <p/> * The other type of methods support the writing of maps and arrays. These * methods are {@link #writeArrayStart}, {@link #startItem}, and * {@link #writeArrayEnd} (and similar methods for maps). Some implementations * of {@link Encoder} handle the buffering required to break large maps and * arrays into blocks, which is necessary for applications that want to do * streaming. (See {@link #writeArrayStart} for details on these methods.) * <p/> * {@link EncoderFactory} contains Encoder construction and configuration * facilities. * * @see EncoderFactory * @see Decoder */ public abstract class Encoder implements Flushable { /** * "Writes" a null value. (Doesn't actually write anything, but advances the * state of the parser if this class is stateful.) * * @throws AvroTypeException If this is a stateful writer and a null is not * expected */ public abstract void writeNull() throws IOException; /** * Write a boolean value. * * @throws AvroTypeException If this is a stateful writer and a boolean is not * expected */ public abstract void writeBoolean(boolean b) throws IOException; /** * Writes a 32-bit integer. * * @throws AvroTypeException If this is a stateful writer and an integer is not * expected */ public abstract void writeInt(int n) throws IOException; /** * Write a 64-bit integer. * * @throws AvroTypeException If this is a stateful writer and a long is not * expected */ public abstract void writeLong(long n) throws IOException; /** * Write a float. * * @throws IOException * @throws AvroTypeException If this is a stateful writer and a float is not * expected */ public abstract void writeFloat(float f) throws IOException; /** * Write a double. * * @throws AvroTypeException If this is a stateful writer and a double is not * expected */ public abstract void writeDouble(double d) throws IOException; /** * Write a Unicode character string. * * @throws AvroTypeException If this is a stateful writer and a char-string is * not expected */ public abstract void writeString(Utf8 utf8) throws IOException; /** * Write a Unicode character string. The default implementation converts the * String to a {@link org.apache.avro.util.Utf8}. Some Encoder implementations * may want to do something different as a performance optimization. * * @throws AvroTypeException If this is a stateful writer and a char-string is * not expected */ public void writeString(String str) throws IOException { writeString(new Utf8(str)); } /** * Write a Unicode character string. If the CharSequence is an * {@link org.apache.avro.util.Utf8} it writes this directly, otherwise the * CharSequence is converted to a String via toString() and written. * * @throws AvroTypeException If this is a stateful writer and a char-string is * not expected */ public void writeString(CharSequence charSequence) throws IOException { if (charSequence instanceof Utf8) writeString((Utf8) charSequence); else writeString(charSequence.toString()); } /** * Write a byte string. * * @throws AvroTypeException If this is a stateful writer and a byte-string is * not expected */ public abstract void writeBytes(ByteBuffer bytes) throws IOException; /** * Write a byte string. * * @throws AvroTypeException If this is a stateful writer and a byte-string is * not expected */ public abstract void writeBytes(byte[] bytes, int start, int len) throws IOException; /** * Writes a byte string. Equivalent to * <tt>writeBytes(bytes, 0, bytes.length)</tt> * * @throws IOException * @throws AvroTypeException If this is a stateful writer and a byte-string is * not expected */ public void writeBytes(byte[] bytes) throws IOException { writeBytes(bytes, 0, bytes.length); } /** * Writes a fixed size binary object. * * @param bytes The contents to write * @param start The position within <tt>bytes</tt> where the contents start. * @param len The number of bytes to write. * @throws AvroTypeException If this is a stateful writer and a byte-string is * not expected * @throws IOException */ public abstract void writeFixed(byte[] bytes, int start, int len) throws IOException; /** * A shorthand for <tt>writeFixed(bytes, 0, bytes.length)</tt> * * @param bytes */ public void writeFixed(byte[] bytes) throws IOException { writeFixed(bytes, 0, bytes.length); } /** Writes a fixed from a ByteBuffer. */ public void writeFixed(ByteBuffer bytes) throws IOException { int pos = bytes.position(); int len = bytes.limit() - pos; if (bytes.hasArray()) { writeFixed(bytes.array(), bytes.arrayOffset() + pos, len); } else { byte[] b = new byte[len]; bytes.duplicate().get(b, 0, len); writeFixed(b, 0, len); } } /** * Writes an enumeration. * * @param e * @throws AvroTypeException If this is a stateful writer and an enumeration is * not expected or the <tt>e</tt> is out of range. * @throws IOException */ public abstract void writeEnum(int e) throws IOException; /** * Call this method to start writing an array. * * When starting to serialize an array, call {@link #writeArrayStart}. Then, * before writing any data for any item call {@link #setItemCount} followed by a * sequence of {@link #startItem()} and the item itself. The number of * {@link #startItem()} should match the number specified in * {@link #setItemCount}. When actually writing the data of the item, you can * call any {@link Encoder} method (e.g., {@link #writeLong}). When all items of * the array have been written, call {@link #writeArrayEnd}. * * As an example, let's say you want to write an array of records, the record * consisting of an Long field and a Boolean field. Your code would look * something like this: * * <pre> * out.writeArrayStart(); * out.setItemCount(list.size()); * for (Record r : list) { * out.startItem(); * out.writeLong(r.longField); * out.writeBoolean(r.boolField); * } * out.writeArrayEnd(); * </pre> * * @throws AvroTypeException If this is a stateful writer and an array is not * expected */ public abstract void writeArrayStart() throws IOException; /** * Call this method before writing a batch of items in an array or a map. Then * for each item, call {@link #startItem()} followed by any of the other write * methods of {@link Encoder}. The number of calls to {@link #startItem()} must * be equal to the count specified in {@link #setItemCount}. Once a batch is * completed you can start another batch with {@link #setItemCount}. * * @param itemCount The number of {@link #startItem()} calls to follow. * @throws IOException */ public abstract void setItemCount(long itemCount) throws IOException; /** * Start a new item of an array or map. See {@link #writeArrayStart} for usage * information. * * @throws AvroTypeException If called outside of an array or map context */ public abstract void startItem() throws IOException; /** * Call this method to finish writing an array. See {@link #writeArrayStart} for * usage information. * * @throws AvroTypeException If items written does not match count provided to * {@link #writeArrayStart} * @throws AvroTypeException If not currently inside an array */ public abstract void writeArrayEnd() throws IOException; /** * Call this to start a new map. See {@link #writeArrayStart} for details on * usage. * * As an example of usage, let's say you want to write a map of records, the * record consisting of an Long field and a Boolean field. Your code would look * something like this: * * <pre> * out.writeMapStart(); * out.setItemCount(list.size()); * for (Map.Entry<String, Record> entry : map.entrySet()) { * out.startItem(); * out.writeString(entry.getKey()); * out.writeLong(entry.getValue().longField); * out.writeBoolean(entry.getValue().boolField); * } * out.writeMapEnd(); * </pre> * * @throws AvroTypeException If this is a stateful writer and a map is not * expected */ public abstract void writeMapStart() throws IOException; /** * Call this method to terminate the inner-most, currently-opened map. See * {@link #writeArrayStart} for more details. * * @throws AvroTypeException If items written does not match count provided to * {@link #writeMapStart} * @throws AvroTypeException If not currently inside a map */ public abstract void writeMapEnd() throws IOException; /** * Call this method to write the tag of a union. * * As an example of usage, let's say you want to write a union, whose second * branch is a record consisting of an Long field and a Boolean field. Your code * would look something like this: * * <pre> * out.writeIndex(1); * out.writeLong(record.longField); * out.writeBoolean(record.boolField); * </pre> * * @throws AvroTypeException If this is a stateful writer and a map is not * expected */ public abstract void writeIndex(int unionIndex) throws IOException; }
7,358
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/DirectBinaryDecoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import org.apache.avro.InvalidNumberEncodingException; import org.apache.avro.SystemLimitException; import org.apache.avro.util.ByteBufferInputStream; /** * A non-buffering version of {@link BinaryDecoder}. * <p/> * This implementation will not read-ahead from the provided InputStream beyond * the minimum required to service the API requests. * * @see Encoder */ class DirectBinaryDecoder extends BinaryDecoder { private InputStream in; private class ByteReader { public ByteBuffer read(ByteBuffer old, int length) throws IOException { final ByteBuffer result; if (old != null && length <= old.capacity()) { result = old; result.clear(); } else { result = ByteBuffer.allocate(length); } doReadBytes(result.array(), result.position(), length); result.limit(length); return result; } } private class ReuseByteReader extends ByteReader { private final ByteBufferInputStream bbi; public ReuseByteReader(ByteBufferInputStream bbi) { this.bbi = bbi; } @Override public ByteBuffer read(ByteBuffer old, int length) throws IOException { if (old != null) { return super.read(old, length); } else { return bbi.readBuffer(length); } } } private ByteReader byteReader; DirectBinaryDecoder(InputStream in) { super(); configure(in); } DirectBinaryDecoder configure(InputStream in) { this.in = in; byteReader = (in instanceof ByteBufferInputStream) ? new ReuseByteReader((ByteBufferInputStream) in) : new ByteReader(); return this; } @Override public boolean readBoolean() throws IOException { int n = in.read(); if (n < 0) { throw new EOFException(); } return n == 1; } @Override public int readInt() throws IOException { int n = 0; int b; int shift = 0; do { b = in.read(); if (b >= 0) { n |= (b & 0x7F) << shift; if ((b & 0x80) == 0) { return (n >>> 1) ^ -(n & 1); // back to two's-complement } } else { throw new EOFException(); } shift += 7; } while (shift < 32); throw new InvalidNumberEncodingException("Invalid int encoding"); } @Override public long readLong() throws IOException { long n = 0; int b; int shift = 0; do { b = in.read(); if (b >= 0) { n |= (b & 0x7FL) << shift; if ((b & 0x80) == 0) { return (n >>> 1) ^ -(n & 1); // back to two's-complement } } else { throw new EOFException(); } shift += 7; } while (shift < 64); throw new InvalidNumberEncodingException("Invalid long encoding"); } private final byte[] buf = new byte[8]; @Override public float readFloat() throws IOException { doReadBytes(buf, 0, 4); int n = (((int) buf[0]) & 0xff) | ((((int) buf[1]) & 0xff) << 8) | ((((int) buf[2]) & 0xff) << 16) | ((((int) buf[3]) & 0xff) << 24); return Float.intBitsToFloat(n); } @Override public double readDouble() throws IOException { doReadBytes(buf, 0, 8); long n = (((long) buf[0]) & 0xff) | ((((long) buf[1]) & 0xff) << 8) | ((((long) buf[2]) & 0xff) << 16) | ((((long) buf[3]) & 0xff) << 24) | ((((long) buf[4]) & 0xff) << 32) | ((((long) buf[5]) & 0xff) << 40) | ((((long) buf[6]) & 0xff) << 48) | ((((long) buf[7]) & 0xff) << 56); return Double.longBitsToDouble(n); } @Override public ByteBuffer readBytes(ByteBuffer old) throws IOException { long length = readLong(); return byteReader.read(old, SystemLimitException.checkMaxBytesLength(length)); } @Override protected void doSkipBytes(long length) throws IOException { while (length > 0) { long n = in.skip(length); if (n <= 0) { throw new EOFException(); } length -= n; } } @Override protected void doReadBytes(byte[] bytes, int start, int length) throws IOException { for (;;) { int n = in.read(bytes, start, length); if (n == length || length == 0) { return; } else if (n < 0) { throw new EOFException(); } start += n; length -= n; } } @Override public InputStream inputStream() { return in; } @Override public boolean isEnd() throws IOException { throw new UnsupportedOperationException(); } }
7,359
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/JsonEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.BitSet; import java.util.EnumSet; import java.util.Objects; import java.util.Set; import org.apache.avro.AvroTypeException; import org.apache.avro.Schema; import org.apache.avro.io.parsing.JsonGrammarGenerator; import org.apache.avro.io.parsing.Parser; import org.apache.avro.io.parsing.Symbol; import org.apache.avro.util.Utf8; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.PrettyPrinter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.core.util.MinimalPrettyPrinter; /** * An {@link Encoder} for Avro's JSON data encoding. * </p> * Construct using {@link EncoderFactory}. * </p> * JsonEncoder buffers output, and data may not appear on the output until * {@link Encoder#flush()} is called. * </p> * JsonEncoder is not thread-safe. */ public class JsonEncoder extends ParsingEncoder implements Parser.ActionHandler { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); final Parser parser; private JsonGenerator out; private boolean includeNamespace = true; /** * Has anything been written into the collections? */ protected BitSet isEmpty = new BitSet(); JsonEncoder(Schema sc, OutputStream out) throws IOException { this(sc, getJsonGenerator(out, EnumSet.noneOf(JsonOptions.class))); } JsonEncoder(Schema sc, OutputStream out, boolean pretty) throws IOException { this(sc, getJsonGenerator(out, pretty ? EnumSet.of(JsonOptions.Pretty) : EnumSet.noneOf(JsonOptions.class))); } JsonEncoder(Schema sc, OutputStream out, Set<JsonOptions> options) throws IOException { this(sc, getJsonGenerator(out, options)); } JsonEncoder(Schema sc, JsonGenerator out) throws IOException { configure(out); this.parser = new Parser(new JsonGrammarGenerator().generate(sc), this); } @Override public void flush() throws IOException { parser.processImplicitActions(); if (out != null) { out.flush(); } } enum JsonOptions { Pretty, // Prevent underlying outputstream to be flush for optimisation purpose. NoFlushStream } // by default, one object per line. // with pretty option use default pretty printer with root line separator. private static JsonGenerator getJsonGenerator(OutputStream out, Set<JsonOptions> options) throws IOException { Objects.requireNonNull(out, "OutputStream cannot be null"); JsonGenerator g = new JsonFactory().createGenerator(out, JsonEncoding.UTF8); if (options.contains(JsonOptions.NoFlushStream)) { g = g.configure(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM, false); } final PrettyPrinter pp; if (options.contains(JsonOptions.Pretty)) { pp = new DefaultPrettyPrinter(LINE_SEPARATOR); } else { pp = new MinimalPrettyPrinter(LINE_SEPARATOR); } g.setPrettyPrinter(pp); return g; } public boolean isIncludeNamespace() { return includeNamespace; } public void setIncludeNamespace(final boolean includeNamespace) { this.includeNamespace = includeNamespace; } /** * Reconfigures this JsonEncoder to use the output stream provided. * <p/> * If the OutputStream provided is null, a NullPointerException is thrown. * <p/> * Otherwise, this JsonEncoder will flush its current output and then * reconfigure its output to use a default UTF8 JsonGenerator that writes to the * provided OutputStream. * * @param out The OutputStream to direct output to. Cannot be null. * @throws IOException * @throws NullPointerException if {@code out} is {@code null} * @return this JsonEncoder */ public JsonEncoder configure(OutputStream out) throws IOException { return this.configure(out, true); } /** * Reconfigures this JsonEncoder to use the output stream provided. * <p/> * If the OutputStream provided is null, a NullPointerException is thrown. * <p/> * Otherwise, this JsonEncoder will flush its current output and then * reconfigure its output to use a default UTF8 JsonGenerator that writes to the * provided OutputStream. * * @param out The OutputStream to direct output to. Cannot be null. * @throws IOException * @throws NullPointerException if {@code out} is {@code null} * @return this JsonEncoder */ public JsonEncoder configure(OutputStream out, boolean autoflush) throws IOException { EnumSet<JsonOptions> jsonOptions = EnumSet.noneOf(JsonOptions.class); if (!autoflush) { jsonOptions.add(JsonOptions.NoFlushStream); } this.configure(getJsonGenerator(out, jsonOptions)); return this; } /** * Reconfigures this JsonEncoder to output to the JsonGenerator provided. * <p/> * If the JsonGenerator provided is null, a NullPointerException is thrown. * <p/> * Otherwise, this JsonEncoder will flush its current output and then * reconfigure its output to use the provided JsonGenerator. * * @param generator The JsonGenerator to direct output to. Cannot be null. * @throws IOException * @throws NullPointerException if {@code generator} is {@code null} * @return this JsonEncoder */ private JsonEncoder configure(JsonGenerator generator) throws IOException { Objects.requireNonNull(generator, "JsonGenerator cannot be null"); if (null != parser) { flush(); } this.out = generator; return this; } @Override public void writeNull() throws IOException { parser.advance(Symbol.NULL); out.writeNull(); } @Override public void writeBoolean(boolean b) throws IOException { parser.advance(Symbol.BOOLEAN); out.writeBoolean(b); } @Override public void writeInt(int n) throws IOException { parser.advance(Symbol.INT); out.writeNumber(n); } @Override public void writeLong(long n) throws IOException { parser.advance(Symbol.LONG); out.writeNumber(n); } @Override public void writeFloat(float f) throws IOException { parser.advance(Symbol.FLOAT); out.writeNumber(f + 0d); } @Override public void writeDouble(double d) throws IOException { parser.advance(Symbol.DOUBLE); out.writeNumber(d); } @Override public void writeString(Utf8 utf8) throws IOException { writeString(utf8.toString()); } @Override public void writeString(String str) throws IOException { parser.advance(Symbol.STRING); if (parser.topSymbol() == Symbol.MAP_KEY_MARKER) { parser.advance(Symbol.MAP_KEY_MARKER); out.writeFieldName(str); } else { out.writeString(str); } } @Override public void writeBytes(ByteBuffer bytes) throws IOException { if (bytes.hasArray()) { writeBytes(bytes.array(), bytes.position(), bytes.remaining()); } else { byte[] b = new byte[bytes.remaining()]; bytes.duplicate().get(b); writeBytes(b); } } @Override public void writeBytes(byte[] bytes, int start, int len) throws IOException { parser.advance(Symbol.BYTES); writeByteArray(bytes, start, len); } private void writeByteArray(byte[] bytes, int start, int len) throws IOException { out.writeString(new String(bytes, start, len, StandardCharsets.ISO_8859_1)); } @Override public void writeFixed(byte[] bytes, int start, int len) throws IOException { parser.advance(Symbol.FIXED); Symbol.IntCheckAction top = (Symbol.IntCheckAction) parser.popSymbol(); if (len != top.size) { throw new AvroTypeException( "Incorrect length for fixed binary: expected " + top.size + " but received " + len + " bytes."); } writeByteArray(bytes, start, len); } @Override public void writeEnum(int e) throws IOException { parser.advance(Symbol.ENUM); Symbol.EnumLabelsAction top = (Symbol.EnumLabelsAction) parser.popSymbol(); if (e < 0 || e >= top.size) { throw new AvroTypeException("Enumeration out of range: max is " + top.size + " but received " + e); } out.writeString(top.getLabel(e)); } @Override public void writeArrayStart() throws IOException { parser.advance(Symbol.ARRAY_START); out.writeStartArray(); push(); isEmpty.set(depth()); } @Override public void writeArrayEnd() throws IOException { if (!isEmpty.get(pos)) { parser.advance(Symbol.ITEM_END); } pop(); parser.advance(Symbol.ARRAY_END); out.writeEndArray(); } @Override public void writeMapStart() throws IOException { push(); isEmpty.set(depth()); parser.advance(Symbol.MAP_START); out.writeStartObject(); } @Override public void writeMapEnd() throws IOException { if (!isEmpty.get(pos)) { parser.advance(Symbol.ITEM_END); } pop(); parser.advance(Symbol.MAP_END); out.writeEndObject(); } @Override public void startItem() throws IOException { if (!isEmpty.get(pos)) { parser.advance(Symbol.ITEM_END); } super.startItem(); isEmpty.clear(depth()); } @Override public void writeIndex(int unionIndex) throws IOException { parser.advance(Symbol.UNION); Symbol.Alternative top = (Symbol.Alternative) parser.popSymbol(); Symbol symbol = top.getSymbol(unionIndex); if (symbol != Symbol.NULL && includeNamespace) { out.writeStartObject(); out.writeFieldName(top.getLabel(unionIndex)); parser.pushSymbol(Symbol.UNION_END); } parser.pushSymbol(symbol); } @Override public Symbol doAction(Symbol input, Symbol top) throws IOException { if (top instanceof Symbol.FieldAdjustAction) { Symbol.FieldAdjustAction fa = (Symbol.FieldAdjustAction) top; out.writeFieldName(fa.fname); } else if (top == Symbol.RECORD_START) { out.writeStartObject(); } else if (top == Symbol.RECORD_END || top == Symbol.UNION_END) { out.writeEndObject(); } else if (top != Symbol.FIELD_END) { throw new AvroTypeException("Unknown action symbol " + top); } return null; } }
7,360
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/DatumWriter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io; import java.io.IOException; import org.apache.avro.Schema; /** * Write data of a schema. * <p> * Implemented for different in-memory data representations. */ public interface DatumWriter<D> { /** Set the schema. */ void setSchema(Schema schema); /** * Write a datum. Traverse the schema, depth first, writing each leaf value in * the schema from the datum to the output. */ void write(D datum, Encoder out) throws IOException; }
7,361
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/parsing/Parser.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io.parsing; import java.io.IOException; import java.util.Arrays; import org.apache.avro.AvroTypeException; /** * Parser is the class that maintains the stack for parsing. This class is used * by encoders, which are not required to skip. */ public class Parser { /** * The parser knows how to handle the terminal and non-terminal symbols. But it * needs help from outside to handle implicit and explicit actions. The clients * implement this interface to provide this help. */ public interface ActionHandler { /** * Handle the action symbol <tt>top</tt> when the <tt>input</tt> is sought to be * taken off the stack. * * @param input The input symbol from the caller of advance * @param top The symbol at the top the stack. * @return <tt>null</tt> if advance() is to continue processing the stack. If * not <tt>null</tt> the return value will be returned by advance(). * @throws IOException */ Symbol doAction(Symbol input, Symbol top) throws IOException; } protected final ActionHandler symbolHandler; protected Symbol[] stack; protected int pos; public Parser(Symbol root, ActionHandler symbolHandler) { this.symbolHandler = symbolHandler; this.stack = new Symbol[5]; // Start small to make sure expansion code works this.stack[0] = root; this.pos = 1; } /** * If there is no sufficient room in the stack, use this expand it. */ private void expandStack() { stack = Arrays.copyOf(stack, stack.length + Math.max(stack.length, 1024)); } /** * Recursively replaces the symbol at the top of the stack with its production, * until the top is a terminal. Then checks if the top symbol matches the * terminal symbol suppled <tt>terminal</tt>. * * @param input The symbol to match against the terminal at the top of the * stack. * @return The terminal symbol at the top of the stack unless an implicit action * resulted in another symbol, in which case that symbol is returned. */ public final Symbol advance(Symbol input) throws IOException { for (;;) { Symbol top = stack[--pos]; if (top == input) { return top; // A common case } Symbol.Kind k = top.kind; if (k == Symbol.Kind.IMPLICIT_ACTION) { Symbol result = symbolHandler.doAction(input, top); if (result != null) { return result; } } else if (k == Symbol.Kind.TERMINAL) { throw new AvroTypeException("Attempt to process a " + input + " when a " + top + " was expected."); } else if (k == Symbol.Kind.REPEATER && input == ((Symbol.Repeater) top).end) { return input; } else { pushProduction(top); } } } /** * Performs any implicit actions at the top the stack, expanding any production * (other than the root) that may be encountered. This method will fail if there * are any repeaters on the stack. * * @throws IOException */ public final void processImplicitActions() throws IOException { while (pos > 1) { Symbol top = stack[pos - 1]; if (top.kind == Symbol.Kind.IMPLICIT_ACTION) { pos--; symbolHandler.doAction(null, top); } else if (top.kind != Symbol.Kind.TERMINAL) { pos--; pushProduction(top); } else { break; } } } /** * Performs any "trailing" implicit actions at the top the stack. */ public final void processTrailingImplicitActions() throws IOException { while (pos >= 1) { Symbol top = stack[pos - 1]; if (top.kind == Symbol.Kind.IMPLICIT_ACTION && ((Symbol.ImplicitAction) top).isTrailing) { pos--; symbolHandler.doAction(null, top); } else { break; } } } /** * Pushes the production for the given symbol <tt>sym</tt>. If <tt>sym</tt> is a * repeater and <tt>input</tt> is either {@link Symbol#ARRAY_END} or * {@link Symbol#MAP_END} pushes nothing. * * @param sym */ public final void pushProduction(Symbol sym) { Symbol[] p = sym.production; while (pos + p.length > stack.length) { expandStack(); } System.arraycopy(p, 0, stack, pos, p.length); pos += p.length; } /** * Pops and returns the top symbol from the stack. */ public Symbol popSymbol() { return stack[--pos]; } /** * Returns the top symbol from the stack. */ public Symbol topSymbol() { return stack[pos - 1]; } /** * Pushes <tt>sym</tt> on to the stack. */ public void pushSymbol(Symbol sym) { if (pos == stack.length) { expandStack(); } stack[pos++] = sym; } /** * Returns the depth of the stack. */ public int depth() { return pos; } public void reset() { pos = 1; } }
7,362
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/parsing/SkipParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io.parsing; import java.io.IOException; /** * A parser that capable of skipping as well read and write. This class is used * by decoders who (unlink encoders) are required to implement methods to skip. */ public class SkipParser extends Parser { /** * The clients implement this interface to skip symbols and actions. */ public interface SkipHandler { /** * Skips the action at the top of the stack. */ void skipAction() throws IOException; /** * Skips the symbol at the top of the stack. */ void skipTopSymbol() throws IOException; } private final SkipHandler skipHandler; public SkipParser(Symbol root, ActionHandler symbolHandler, SkipHandler skipHandler) throws IOException { super(root, symbolHandler); this.skipHandler = skipHandler; } /** * Skips data by calling <code>skipXyz</code> or <code>readXyz</code> methods on * <code>this</code>, until the parser stack reaches the target level. */ public final void skipTo(int target) throws IOException { outer: while (target < pos) { Symbol top = stack[pos - 1]; while (top.kind != Symbol.Kind.TERMINAL) { if (top.kind == Symbol.Kind.IMPLICIT_ACTION || top.kind == Symbol.Kind.EXPLICIT_ACTION) { skipHandler.skipAction(); } else { --pos; pushProduction(top); } continue outer; } skipHandler.skipTopSymbol(); } } /** * Skips the repeater at the top the stack. */ public final void skipRepeater() throws IOException { int target = pos; Symbol repeater = stack[--pos]; assert repeater.kind == Symbol.Kind.REPEATER; pushProduction(repeater); skipTo(target); } /** * Pushes the given symbol on to the skip and skips it. * * @param symToSkip The symbol that should be skipped. */ public final void skipSymbol(Symbol symToSkip) throws IOException { int target = pos; pushSymbol(symToSkip); skipTo(target); } }
7,363
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/parsing/ValidatingGrammarGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io.parsing; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; /** * The class that generates validating grammar. */ public class ValidatingGrammarGenerator { /** * Returns the non-terminal that is the start symbol for the grammar for the * given schema <tt>sc</tt>. */ public Symbol generate(Schema schema) { return Symbol.root(generate(schema, new HashMap<>())); } /** * Returns the non-terminal that is the start symbol for the grammar for the * given schema <tt>sc</tt>. If there is already an entry for the given schema * in the given map <tt>seen</tt> then that entry is returned. Otherwise a new * symbol is generated and an entry is inserted into the map. * * @param sc The schema for which the start symbol is required * @param seen A map of schema to symbol mapping done so far. * @return The start symbol for the schema */ public Symbol generate(Schema sc, Map<LitS, Symbol> seen) { switch (sc.getType()) { case NULL: return Symbol.NULL; case BOOLEAN: return Symbol.BOOLEAN; case INT: return Symbol.INT; case LONG: return Symbol.LONG; case FLOAT: return Symbol.FLOAT; case DOUBLE: return Symbol.DOUBLE; case STRING: return Symbol.STRING; case BYTES: return Symbol.BYTES; case FIXED: return Symbol.seq(Symbol.intCheckAction(sc.getFixedSize()), Symbol.FIXED); case ENUM: return Symbol.seq(Symbol.intCheckAction(sc.getEnumSymbols().size()), Symbol.ENUM); case ARRAY: return Symbol.seq(Symbol.repeat(Symbol.ARRAY_END, generate(sc.getElementType(), seen)), Symbol.ARRAY_START); case MAP: return Symbol.seq(Symbol.repeat(Symbol.MAP_END, generate(sc.getValueType(), seen), Symbol.STRING), Symbol.MAP_START); case RECORD: { LitS wsc = new LitS(sc); Symbol rresult = seen.get(wsc); if (rresult == null) { Symbol[] production = new Symbol[sc.getFields().size()]; /** * We construct a symbol without filling the array. Please see * {@link Symbol#production} for the reason. */ rresult = Symbol.seq(production); seen.put(wsc, rresult); int i = production.length; for (Field f : sc.getFields()) { production[--i] = generate(f.schema(), seen); } } return rresult; } case UNION: List<Schema> subs = sc.getTypes(); Symbol[] symbols = new Symbol[subs.size()]; String[] labels = new String[subs.size()]; int i = 0; for (Schema b : sc.getTypes()) { symbols[i] = generate(b, seen); labels[i] = b.getFullName(); i++; } return Symbol.seq(Symbol.alt(symbols, labels), Symbol.UNION); default: throw new RuntimeException("Unexpected schema type"); } } /** A wrapper around Schema that does "==" equality. */ static class LitS { public final Schema actual; public LitS(Schema actual) { this.actual = actual; } /** * Two LitS are equal if and only if their underlying schema is the same (not * merely equal). */ @Override public boolean equals(Object o) { if (!(o instanceof LitS)) return false; return actual.equals(((LitS) o).actual); } @Override public int hashCode() { return actual.hashCode(); } } }
7,364
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/parsing/Symbol.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io.parsing; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.avro.Schema; /** * Symbol is the base of all symbols (terminals and non-terminals) of the * grammar. */ public abstract class Symbol { /* * The type of symbol. */ public enum Kind { /** terminal symbols which have no productions */ TERMINAL, /** Start symbol for some grammar */ ROOT, /** non-terminal symbol which is a sequence of one or more other symbols */ SEQUENCE, /** non-terminal to represent the contents of an array or map */ REPEATER, /** non-terminal to represent the union */ ALTERNATIVE, /** non-terminal action symbol which are automatically consumed */ IMPLICIT_ACTION, /** non-terminal action symbol which is explicitly consumed */ EXPLICIT_ACTION }; /// The kind of this symbol. public final Kind kind; /** * The production for this symbol. If this symbol is a terminal this is * <tt>null</tt>. Otherwise this holds the the sequence of the symbols that * forms the production for this symbol. The sequence is in the reverse order of * production. This is useful for easy copying onto parsing stack. * * Please note that this is a final. So the production for a symbol should be * known before that symbol is constructed. This requirement cannot be met for * those symbols which are recursive (e.g. a record that holds union a branch of * which is the record itself). To resolve this problem, we initialize the * symbol with an array of nulls. Later we fill the symbols. Not clean, but * works. The other option is to not have this field a final. But keeping it * final and thus keeping symbol immutable gives some comfort. See various * generators how we generate records. */ public final Symbol[] production; /** * Constructs a new symbol of the given kind <tt>kind</tt>. */ protected Symbol(Kind kind) { this(kind, null); } protected Symbol(Kind kind, Symbol[] production) { this.production = production; this.kind = kind; } /** * A convenience method to construct a root symbol. */ static Symbol root(Symbol... symbols) { return new Root(symbols); } /** * A convenience method to construct a sequence. * * @param production The constituent symbols of the sequence. */ static Symbol seq(Symbol... production) { return new Sequence(production); } /** * A convenience method to construct a repeater. * * @param symsToRepeat The symbols to repeat in the repeater. */ static Symbol repeat(Symbol endSymbol, Symbol... symsToRepeat) { return new Repeater(endSymbol, symsToRepeat); } /** * A convenience method to construct a union. */ static Symbol alt(Symbol[] symbols, String[] labels) { return new Alternative(symbols, labels); } /** * A convenience method to construct an ErrorAction. * * @param e */ static Symbol error(String e) { return new ErrorAction(e); } /** * A convenience method to construct a ResolvingAction. * * @param w The writer symbol * @param r The reader symbol */ static Symbol resolve(Symbol w, Symbol r) { return new ResolvingAction(w, r); } private static class Fixup { public final Symbol[] symbols; public final int pos; public Fixup(Symbol[] symbols, int pos) { this.symbols = symbols; this.pos = pos; } } public Symbol flatten(Map<Sequence, Sequence> map, Map<Sequence, List<Fixup>> map2) { return this; } public int flattenedSize() { return 1; } /** * Flattens the given sub-array of symbols into an sub-array of symbols. Every * <tt>Sequence</tt> in the input are replaced by its production recursively. * Non-<tt>Sequence</tt> symbols, they internally have other symbols those * internal symbols also get flattened. When flattening is done, the only place * there might be Sequence symbols is in the productions of a Repeater, * Alternative, or the symToParse and symToSkip in a UnionAdjustAction or * SkipAction. * * Why is this done? We want our parsers to be fast. If we left the grammars * unflattened, then the parser would be constantly copying the contents of * nested Sequence productions onto the parsing stack. Instead, because of * flattening, we have a long top-level production with no Sequences unless the * Sequence is absolutely needed, e.g., in the case of a Repeater or an * Alterantive. * * Well, this is not exactly true when recursion is involved. Where there is a * recursive record, that record will be "inlined" once, but any internal (ie, * recursive) references to that record will be a Sequence for the record. That * Sequence will not further inline itself -- it will refer to itself as a * Sequence. The same is true for any records nested in this outer recursive * record. Recursion is rare, and we want things to be fast in the typical case, * which is why we do the flattening optimization. * * * The algorithm does a few tricks to handle recursive symbol definitions. In * order to avoid infinite recursion with recursive symbols, we have a map of * Symbol->Symbol. Before fully constructing a flattened symbol for a * <tt>Sequence</tt> we insert an empty output symbol into the map and then * start filling the production for the <tt>Sequence</tt>. If the same * <tt>Sequence</tt> is encountered due to recursion, we simply return the * (empty) output <tt>Sequence<tt> from the map. Then we actually fill out * the production for the <tt>Sequence</tt>. As part of the flattening process * we copy the production of <tt>Sequence</tt>s into larger arrays. If the * original <tt>Sequence</tt> has not not be fully constructed yet, we copy a * bunch of <tt>null</tt>s. Fix-up remembers all those <tt>null</tt> patches. * The fix-ups gets finally filled when we know the symbols to occupy those * patches. * * @param in The array of input symbols to flatten * @param start The position where the input sub-array starts. * @param out The output that receives the flattened list of symbols. The * output array should have sufficient space to receive the * expanded sub-array of symbols. * @param skip The position where the output input sub-array starts. * @param map A map of symbols which have already been expanded. Useful for * handling recursive definitions and for caching. * @param map2 A map to to store the list of fix-ups. */ static void flatten(Symbol[] in, int start, Symbol[] out, int skip, Map<Sequence, Sequence> map, Map<Sequence, List<Fixup>> map2) { for (int i = start, j = skip; i < in.length; i++) { Symbol s = in[i].flatten(map, map2); if (s instanceof Sequence) { Symbol[] p = s.production; List<Fixup> l = map2.get(s); if (l == null) { System.arraycopy(p, 0, out, j, p.length); // Copy any fixups that will be applied to p to add missing symbols for (List<Fixup> fixups : map2.values()) { copyFixups(fixups, out, j, p); } } else { l.add(new Fixup(out, j)); } j += p.length; } else { out[j++] = s; } } } private static void copyFixups(List<Fixup> fixups, Symbol[] out, int outPos, Symbol[] toCopy) { for (int i = 0, n = fixups.size(); i < n; i += 1) { Fixup fixup = fixups.get(i); if (fixup.symbols == toCopy) { fixups.add(new Fixup(out, fixup.pos + outPos)); } } } /** * Returns the amount of space required to flatten the given sub-array of * symbols. * * @param symbols The array of input symbols. * @param start The index where the subarray starts. * @return The number of symbols that will be produced if one expands the given * input. */ protected static int flattenedSize(Symbol[] symbols, int start) { int result = 0; for (int i = start; i < symbols.length; i++) { if (symbols[i] instanceof Sequence) { Sequence s = (Sequence) symbols[i]; result += s.flattenedSize(); } else { result += 1; } } return result; } private static class Terminal extends Symbol { private final String printName; public Terminal(String printName) { super(Kind.TERMINAL); this.printName = printName; } @Override public String toString() { return printName; } } public static class ImplicitAction extends Symbol { /** * Set to <tt>true</tt> if and only if this implicit action is a trailing * action. That is, it is an action that follows real symbol. E.g * {@link Symbol#DEFAULT_END_ACTION}. */ public final boolean isTrailing; private ImplicitAction() { this(false); } private ImplicitAction(boolean isTrailing) { super(Kind.IMPLICIT_ACTION); this.isTrailing = isTrailing; } } protected static class Root extends Symbol { private Root(Symbol... symbols) { super(Kind.ROOT, makeProduction(symbols)); production[0] = this; } private static Symbol[] makeProduction(Symbol[] symbols) { Symbol[] result = new Symbol[flattenedSize(symbols, 0) + 1]; flatten(symbols, 0, result, 1, new HashMap<>(), new HashMap<>()); return result; } } protected static class Sequence extends Symbol implements Iterable<Symbol> { private Sequence(Symbol[] productions) { super(Kind.SEQUENCE, productions); } public Symbol get(int index) { return production[index]; } public int size() { return production.length; } @Override public Iterator<Symbol> iterator() { return new Iterator<Symbol>() { private int pos = production.length; @Override public boolean hasNext() { return 0 < pos; } @Override public Symbol next() { if (0 < pos) { return production[--pos]; } else { throw new NoSuchElementException(); } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public Sequence flatten(Map<Sequence, Sequence> map, Map<Sequence, List<Fixup>> map2) { Sequence result = map.get(this); if (result == null) { result = new Sequence(new Symbol[flattenedSize()]); map.put(this, result); List<Fixup> l = new ArrayList<>(); map2.put(result, l); flatten(production, 0, result.production, 0, map, map2); for (Fixup f : l) { System.arraycopy(result.production, 0, f.symbols, f.pos, result.production.length); } map2.remove(result); } return result; } @Override public final int flattenedSize() { return flattenedSize(production, 0); } } public static class Repeater extends Symbol { public final Symbol end; private Repeater(Symbol end, Symbol... sequenceToRepeat) { super(Kind.REPEATER, makeProduction(sequenceToRepeat)); this.end = end; production[0] = this; } private static Symbol[] makeProduction(Symbol[] p) { Symbol[] result = new Symbol[p.length + 1]; System.arraycopy(p, 0, result, 1, p.length); return result; } @Override public Repeater flatten(Map<Sequence, Sequence> map, Map<Sequence, List<Fixup>> map2) { Repeater result = new Repeater(end, new Symbol[flattenedSize(production, 1)]); flatten(production, 1, result.production, 1, map, map2); return result; } } /** * Returns true if the Parser contains any Error symbol, indicating that it may * fail for some inputs. */ public static boolean hasErrors(Symbol symbol) { return hasErrors(symbol, new HashSet<>()); } private static boolean hasErrors(Symbol symbol, Set<Symbol> visited) { // avoid infinite recursion if (visited.contains(symbol)) { return false; } visited.add(symbol); switch (symbol.kind) { case ALTERNATIVE: return hasErrors(symbol, ((Alternative) symbol).symbols, visited); case EXPLICIT_ACTION: return false; case IMPLICIT_ACTION: if (symbol instanceof ErrorAction) { return true; } if (symbol instanceof UnionAdjustAction) { return hasErrors(((UnionAdjustAction) symbol).symToParse, visited); } return false; case REPEATER: Repeater r = (Repeater) symbol; return hasErrors(r.end, visited) || hasErrors(symbol, r.production, visited); case ROOT: case SEQUENCE: return hasErrors(symbol, symbol.production, visited); case TERMINAL: return false; default: throw new RuntimeException("unknown symbol kind: " + symbol.kind); } } private static boolean hasErrors(Symbol root, Symbol[] symbols, Set<Symbol> visited) { if (null != symbols) { for (Symbol s : symbols) { if (s == root) { continue; } if (hasErrors(s, visited)) { return true; } } } return false; } public static class Alternative extends Symbol { public final Symbol[] symbols; public final String[] labels; private Alternative(Symbol[] symbols, String[] labels) { super(Kind.ALTERNATIVE); this.symbols = symbols; this.labels = labels; } public Symbol getSymbol(int index) { return symbols[index]; } public String getLabel(int index) { return labels[index]; } public int size() { return symbols.length; } public int findLabel(String label) { if (label != null) { for (int i = 0; i < labels.length; i++) { if (label.equals(labels[i])) { return i; } } } return -1; } @Override public Alternative flatten(Map<Sequence, Sequence> map, Map<Sequence, List<Fixup>> map2) { Symbol[] ss = new Symbol[symbols.length]; for (int i = 0; i < ss.length; i++) { ss[i] = symbols[i].flatten(map, map2); } return new Alternative(ss, labels); } } public static class ErrorAction extends ImplicitAction { public final String msg; private ErrorAction(String msg) { this.msg = msg; } } public static IntCheckAction intCheckAction(int size) { return new IntCheckAction(size); } public static class IntCheckAction extends Symbol { public final int size; @Deprecated public IntCheckAction(int size) { super(Kind.EXPLICIT_ACTION); this.size = size; } } public static EnumAdjustAction enumAdjustAction(int rsymCount, Object[] adj) { return new EnumAdjustAction(rsymCount, adj); } public static class EnumAdjustAction extends IntCheckAction { public final boolean noAdjustments; public final Object[] adjustments; @Deprecated public EnumAdjustAction(int rsymCount, Object[] adjustments) { super(rsymCount); this.adjustments = adjustments; boolean noAdj = true; if (adjustments != null) { int count = Math.min(rsymCount, adjustments.length); noAdj = (adjustments.length <= rsymCount); for (int i = 0; noAdj && i < count; i++) noAdj &= ((adjustments[i] instanceof Integer) && i == (Integer) adjustments[i]); } this.noAdjustments = noAdj; } } public static WriterUnionAction writerUnionAction() { return new WriterUnionAction(); } public static class WriterUnionAction extends ImplicitAction { private WriterUnionAction() { } } public static class ResolvingAction extends ImplicitAction { public final Symbol writer; public final Symbol reader; private ResolvingAction(Symbol writer, Symbol reader) { this.writer = writer; this.reader = reader; } @Override public ResolvingAction flatten(Map<Sequence, Sequence> map, Map<Sequence, List<Fixup>> map2) { return new ResolvingAction(writer.flatten(map, map2), reader.flatten(map, map2)); } } public static SkipAction skipAction(Symbol symToSkip) { return new SkipAction(symToSkip); } public static class SkipAction extends ImplicitAction { public final Symbol symToSkip; @Deprecated public SkipAction(Symbol symToSkip) { super(true); this.symToSkip = symToSkip; } @Override public SkipAction flatten(Map<Sequence, Sequence> map, Map<Sequence, List<Fixup>> map2) { return new SkipAction(symToSkip.flatten(map, map2)); } } public static FieldAdjustAction fieldAdjustAction(int rindex, String fname, Set<String> aliases) { return new FieldAdjustAction(rindex, fname, aliases); } public static class FieldAdjustAction extends ImplicitAction { public final int rindex; public final String fname; public final Set<String> aliases; @Deprecated public FieldAdjustAction(int rindex, String fname, Set<String> aliases) { this.rindex = rindex; this.fname = fname; this.aliases = aliases; } } public static FieldOrderAction fieldOrderAction(Schema.Field[] fields) { return new FieldOrderAction(fields); } public static final class FieldOrderAction extends ImplicitAction { public final boolean noReorder; public final Schema.Field[] fields; @Deprecated public FieldOrderAction(Schema.Field[] fields) { this.fields = fields; boolean noReorder = true; for (int i = 0; noReorder && i < fields.length; i++) noReorder &= (i == fields[i].pos()); this.noReorder = noReorder; } } public static DefaultStartAction defaultStartAction(byte[] contents) { return new DefaultStartAction(contents); } public static class DefaultStartAction extends ImplicitAction { public final byte[] contents; @Deprecated public DefaultStartAction(byte[] contents) { this.contents = contents; } } public static UnionAdjustAction unionAdjustAction(int rindex, Symbol sym) { return new UnionAdjustAction(rindex, sym); } public static class UnionAdjustAction extends ImplicitAction { public final int rindex; public final Symbol symToParse; @Deprecated public UnionAdjustAction(int rindex, Symbol symToParse) { this.rindex = rindex; this.symToParse = symToParse; } @Override public UnionAdjustAction flatten(Map<Sequence, Sequence> map, Map<Sequence, List<Fixup>> map2) { return new UnionAdjustAction(rindex, symToParse.flatten(map, map2)); } } /** For JSON. */ public static EnumLabelsAction enumLabelsAction(List<String> symbols) { return new EnumLabelsAction(symbols); } public static class EnumLabelsAction extends IntCheckAction { public final List<String> symbols; @Deprecated public EnumLabelsAction(List<String> symbols) { super(symbols.size()); this.symbols = symbols; } public String getLabel(int n) { return symbols.get(n); } public int findLabel(String l) { if (l != null) { for (int i = 0; i < symbols.size(); i++) { if (l.equals(symbols.get(i))) { return i; } } } return -1; } } /** * The terminal symbols for the grammar. */ public static final Symbol NULL = new Symbol.Terminal("null"); public static final Symbol BOOLEAN = new Symbol.Terminal("boolean"); public static final Symbol INT = new Symbol.Terminal("int"); public static final Symbol LONG = new Symbol.Terminal("long"); public static final Symbol FLOAT = new Symbol.Terminal("float"); public static final Symbol DOUBLE = new Symbol.Terminal("double"); public static final Symbol STRING = new Symbol.Terminal("string"); public static final Symbol BYTES = new Symbol.Terminal("bytes"); public static final Symbol FIXED = new Symbol.Terminal("fixed"); public static final Symbol ENUM = new Symbol.Terminal("enum"); public static final Symbol UNION = new Symbol.Terminal("union"); public static final Symbol ARRAY_START = new Symbol.Terminal("array-start"); public static final Symbol ARRAY_END = new Symbol.Terminal("array-end"); public static final Symbol MAP_START = new Symbol.Terminal("map-start"); public static final Symbol MAP_END = new Symbol.Terminal("map-end"); public static final Symbol ITEM_END = new Symbol.Terminal("item-end"); public static final Symbol WRITER_UNION_ACTION = writerUnionAction(); /* a pseudo terminal used by parsers */ public static final Symbol FIELD_ACTION = new Symbol.Terminal("field-action"); public static final Symbol RECORD_START = new ImplicitAction(false); public static final Symbol RECORD_END = new ImplicitAction(true); public static final Symbol UNION_END = new ImplicitAction(true); public static final Symbol FIELD_END = new ImplicitAction(true); public static final Symbol DEFAULT_END_ACTION = new ImplicitAction(true); public static final Symbol MAP_KEY_MARKER = new Symbol.Terminal("map-key-marker"); }
7,365
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/parsing/JsonGrammarGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io.parsing; import java.util.HashMap; import java.util.Map; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; /** * The class that generates a grammar suitable to parse Avro data in JSON * format. */ public class JsonGrammarGenerator extends ValidatingGrammarGenerator { /** * Returns the non-terminal that is the start symbol for the grammar for the * grammar for the given schema <tt>sc</tt>. */ @Override public Symbol generate(Schema schema) { return Symbol.root(generate(schema, new HashMap<>())); } /** * Returns the non-terminal that is the start symbol for grammar of the given * schema <tt>sc</tt>. If there is already an entry for the given schema in the * given map <tt>seen</tt> then that entry is returned. Otherwise a new symbol * is generated and an entry is inserted into the map. * * @param sc The schema for which the start symbol is required * @param seen A map of schema to symbol mapping done so far. * @return The start symbol for the schema */ @Override public Symbol generate(Schema sc, Map<LitS, Symbol> seen) { switch (sc.getType()) { case NULL: case BOOLEAN: case INT: case LONG: case FLOAT: case DOUBLE: case STRING: case BYTES: case FIXED: case UNION: return super.generate(sc, seen); case ENUM: return Symbol.seq(Symbol.enumLabelsAction(sc.getEnumSymbols()), Symbol.ENUM); case ARRAY: return Symbol.seq(Symbol.repeat(Symbol.ARRAY_END, Symbol.ITEM_END, generate(sc.getElementType(), seen)), Symbol.ARRAY_START); case MAP: return Symbol.seq(Symbol.repeat(Symbol.MAP_END, Symbol.ITEM_END, generate(sc.getValueType(), seen), Symbol.MAP_KEY_MARKER, Symbol.STRING), Symbol.MAP_START); case RECORD: { LitS wsc = new LitS(sc); Symbol rresult = seen.get(wsc); if (rresult == null) { Symbol[] production = new Symbol[sc.getFields().size() * 3 + 2]; rresult = Symbol.seq(production); seen.put(wsc, rresult); int i = production.length; int n = 0; production[--i] = Symbol.RECORD_START; for (Field f : sc.getFields()) { production[--i] = Symbol.fieldAdjustAction(n, f.name(), f.aliases()); production[--i] = generate(f.schema(), seen); production[--i] = Symbol.FIELD_END; n++; } production[--i] = Symbol.RECORD_END; } return rresult; } default: throw new RuntimeException("Unexpected schema type"); } } }
7,366
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/io/parsing/ResolvingGrammarGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.io.parsing; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.avro.AvroTypeException; import org.apache.avro.Resolver; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.io.Encoder; import org.apache.avro.io.EncoderFactory; import org.apache.avro.util.internal.Accessor; import org.apache.avro.util.internal.Accessor.ResolvingGrammarGeneratorAccessor; import com.fasterxml.jackson.databind.JsonNode; /** * The class that generates a resolving grammar to resolve between two schemas. */ public class ResolvingGrammarGenerator extends ValidatingGrammarGenerator { static { Accessor.setAccessor(new ResolvingGrammarGeneratorAccessor() { @Override protected void encode(Encoder e, Schema s, JsonNode n) throws IOException { ResolvingGrammarGenerator.encode(e, s, n); } }); } /** * Resolves the writer schema <tt>writer</tt> and the reader schema * <tt>reader</tt> and returns the start symbol for the grammar generated. * * @param writer The schema used by the writer * @param reader The schema used by the reader * @return The start symbol for the resolving grammar * @throws IOException */ public final Symbol generate(Schema writer, Schema reader) throws IOException { Resolver.Action r = Resolver.resolve(writer, reader); return Symbol.root(generate(r, new HashMap<>())); } /** * Takes a {@link Resolver.Action} for resolving two schemas and returns the * start symbol for a grammar that implements that resolution. If the action is * for a record and there's already a symbol for that record in <tt>seen</tt>, * then that symbol is returned. Otherwise a new symbol is generated and * returned. * * @param action The resolver to be implemented * @param seen The &lt;Action&gt; to symbol map of start symbols of resolving * grammars so far. * @return The start symbol for the resolving grammar * @throws IOException */ private Symbol generate(Resolver.Action action, Map<Object, Symbol> seen) throws IOException { if (action instanceof Resolver.DoNothing) { return simpleGen(action.writer, seen); } else if (action instanceof Resolver.ErrorAction) { return Symbol.error(action.toString()); } else if (action instanceof Resolver.Skip) { return Symbol.skipAction(simpleGen(action.writer, seen)); } else if (action instanceof Resolver.Promote) { return Symbol.resolve(simpleGen(action.writer, seen), simpleGen(action.reader, seen)); } else if (action instanceof Resolver.ReaderUnion) { Resolver.ReaderUnion ru = (Resolver.ReaderUnion) action; Symbol s = generate(ru.actualAction, seen); return Symbol.seq(Symbol.unionAdjustAction(ru.firstMatch, s), Symbol.UNION); } else if (action.writer.getType() == Schema.Type.ARRAY) { Symbol es = generate(((Resolver.Container) action).elementAction, seen); return Symbol.seq(Symbol.repeat(Symbol.ARRAY_END, es), Symbol.ARRAY_START); } else if (action.writer.getType() == Schema.Type.MAP) { Symbol es = generate(((Resolver.Container) action).elementAction, seen); return Symbol.seq(Symbol.repeat(Symbol.MAP_END, es, Symbol.STRING), Symbol.MAP_START); } else if (action.writer.getType() == Schema.Type.UNION) { if (((Resolver.WriterUnion) action).unionEquiv) { return simpleGen(action.reader, seen); } Resolver.Action[] branches = ((Resolver.WriterUnion) action).actions; Symbol[] symbols = new Symbol[branches.length]; String[] labels = new String[branches.length]; int i = 0; for (Resolver.Action branch : branches) { symbols[i] = generate(branch, seen); labels[i] = action.writer.getTypes().get(i).getFullName(); i++; } return Symbol.seq(Symbol.alt(symbols, labels), Symbol.WRITER_UNION_ACTION); } else if (action instanceof Resolver.EnumAdjust) { Resolver.EnumAdjust e = (Resolver.EnumAdjust) action; Object[] adjs = new Object[e.adjustments.length]; for (int i = 0; i < adjs.length; i++) { adjs[i] = (0 <= e.adjustments[i] ? Integer.valueOf(e.adjustments[i]) : "No match for " + e.writer.getEnumSymbols().get(i)); } return Symbol.seq(Symbol.enumAdjustAction(e.reader.getEnumSymbols().size(), adjs), Symbol.ENUM); } else if (action instanceof Resolver.RecordAdjust) { Symbol result = seen.get(action); if (result == null) { final Resolver.RecordAdjust ra = (Resolver.RecordAdjust) action; int defaultCount = ra.readerOrder.length - ra.firstDefault; int count = 1 + ra.fieldActions.length + 3 * defaultCount; final Symbol[] production = new Symbol[count]; result = Symbol.seq(production); seen.put(action, result); production[--count] = Symbol.fieldOrderAction(ra.readerOrder); final Resolver.Action[] actions = ra.fieldActions; for (Resolver.Action wfa : actions) { production[--count] = generate(wfa, seen); } for (int i = ra.firstDefault; i < ra.readerOrder.length; i++) { final Schema.Field rf = ra.readerOrder[i]; byte[] bb = getBinary(rf.schema(), Accessor.defaultValue(rf)); production[--count] = Symbol.defaultStartAction(bb); production[--count] = simpleGen(rf.schema(), seen); production[--count] = Symbol.DEFAULT_END_ACTION; } } return result; } throw new IllegalArgumentException("Unrecognized Resolver.Action: " + action); } private Symbol simpleGen(Schema s, Map<Object, Symbol> seen) { switch (s.getType()) { case NULL: return Symbol.NULL; case BOOLEAN: return Symbol.BOOLEAN; case INT: return Symbol.INT; case LONG: return Symbol.LONG; case FLOAT: return Symbol.FLOAT; case DOUBLE: return Symbol.DOUBLE; case BYTES: return Symbol.BYTES; case STRING: return Symbol.STRING; case FIXED: return Symbol.seq(Symbol.intCheckAction(s.getFixedSize()), Symbol.FIXED); case ENUM: return Symbol.seq(Symbol.enumAdjustAction(s.getEnumSymbols().size(), null), Symbol.ENUM); case ARRAY: return Symbol.seq(Symbol.repeat(Symbol.ARRAY_END, simpleGen(s.getElementType(), seen)), Symbol.ARRAY_START); case MAP: return Symbol.seq(Symbol.repeat(Symbol.MAP_END, simpleGen(s.getValueType(), seen), Symbol.STRING), Symbol.MAP_START); case UNION: { final List<Schema> subs = s.getTypes(); final Symbol[] symbols = new Symbol[subs.size()]; final String[] labels = new String[subs.size()]; int i = 0; for (Schema b : s.getTypes()) { symbols[i] = simpleGen(b, seen); labels[i++] = b.getFullName(); } return Symbol.seq(Symbol.alt(symbols, labels), Symbol.UNION); } case RECORD: { Symbol result = seen.get(s); if (result == null) { final Symbol[] production = new Symbol[s.getFields().size() + 1]; result = Symbol.seq(production); seen.put(s, result); int i = production.length; production[--i] = Symbol.fieldOrderAction(s.getFields().toArray(new Schema.Field[0])); for (Field f : s.getFields()) { production[--i] = simpleGen(f.schema(), seen); } // FieldOrderAction is needed even though the field-order hasn't changed, // because the _reader_ doesn't know the field order hasn't changed, and // thus it will probably call {@ ResolvingDecoder.fieldOrder} to find out. } return result; } default: throw new IllegalArgumentException("Unexpected schema: " + s); } } private static EncoderFactory factory = new EncoderFactory().configureBufferSize(32); /** * Returns the Avro binary encoded version of <tt>n</tt> according to the schema * <tt>s</tt>. * * @param s The schema for encoding * @param n The Json node that has the value to be encoded. * @return The binary encoded version of <tt>n</tt>. * @throws IOException */ private static byte[] getBinary(Schema s, JsonNode n) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); Encoder e = factory.binaryEncoder(out, null); encode(e, s, n); e.flush(); return out.toByteArray(); } /** * Encodes the given Json node <tt>n</tt> on to the encoder <tt>e</tt> according * to the schema <tt>s</tt>. * * @param e The encoder to encode into. * @param s The schema for the object being encoded. * @param n The Json node to encode. * @throws IOException */ public static void encode(Encoder e, Schema s, JsonNode n) throws IOException { switch (s.getType()) { case RECORD: for (Field f : s.getFields()) { String name = f.name(); JsonNode v = n.get(name); if (v == null) { v = Accessor.defaultValue(f); } if (v == null) { throw new AvroTypeException("No default value for: " + name); } encode(e, f.schema(), v); } break; case ENUM: e.writeEnum(s.getEnumOrdinal(n.textValue())); break; case ARRAY: e.writeArrayStart(); e.setItemCount(n.size()); Schema i = s.getElementType(); for (JsonNode node : n) { e.startItem(); encode(e, i, node); } e.writeArrayEnd(); break; case MAP: e.writeMapStart(); e.setItemCount(n.size()); Schema v = s.getValueType(); for (Iterator<String> it = n.fieldNames(); it.hasNext();) { e.startItem(); String key = it.next(); e.writeString(key); encode(e, v, n.get(key)); } e.writeMapEnd(); break; case UNION: int correctIndex = 0; List<Schema> innerTypes = s.getTypes(); while (correctIndex < innerTypes.size() && !isCompatible(innerTypes.get(correctIndex).getType(), n)) { correctIndex++; } if (correctIndex >= innerTypes.size()) { throw new AvroTypeException("Not compatible default value for union: " + n); } e.writeIndex(correctIndex); encode(e, innerTypes.get(correctIndex), n); break; case FIXED: if (!n.isTextual()) throw new AvroTypeException("Non-string default value for fixed: " + n); byte[] bb = n.textValue().getBytes(StandardCharsets.ISO_8859_1); if (bb.length != s.getFixedSize()) { bb = Arrays.copyOf(bb, s.getFixedSize()); } e.writeFixed(bb); break; case STRING: if (!n.isTextual()) throw new AvroTypeException("Non-string default value for string: " + n); e.writeString(n.textValue()); break; case BYTES: if (!n.isTextual()) throw new AvroTypeException("Non-string default value for bytes: " + n); e.writeBytes(n.textValue().getBytes(StandardCharsets.ISO_8859_1)); break; case INT: if (!n.isNumber()) throw new AvroTypeException("Non-numeric default value for int: " + n); e.writeInt(n.intValue()); break; case LONG: if (!n.isNumber()) throw new AvroTypeException("Non-numeric default value for long: " + n); e.writeLong(n.longValue()); break; case FLOAT: if (!n.isNumber()) throw new AvroTypeException("Non-numeric default value for float: " + n); e.writeFloat((float) n.doubleValue()); break; case DOUBLE: if (!n.isNumber()) throw new AvroTypeException("Non-numeric default value for double: " + n); e.writeDouble(n.doubleValue()); break; case BOOLEAN: if (!n.isBoolean()) throw new AvroTypeException("Non-boolean default for boolean: " + n); e.writeBoolean(n.booleanValue()); break; case NULL: if (!n.isNull()) throw new AvroTypeException("Non-null default value for null type: " + n); e.writeNull(); break; } } private static boolean isCompatible(Schema.Type stype, JsonNode value) { switch (stype) { case RECORD: case ENUM: case ARRAY: case MAP: case UNION: return true; case FIXED: case STRING: case BYTES: return value.isTextual(); case INT: case LONG: case FLOAT: case DOUBLE: return value.isNumber(); case BOOLEAN: return value.isBoolean(); case NULL: return value.isNull(); } return true; } }
7,367
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/message/MessageDecoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.avro.message; import org.apache.avro.util.ReusableByteArrayInputStream; import org.apache.avro.util.ReusableByteBufferInputStream; import org.apache.avro.util.internal.ThreadLocalWithInitial; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; /** * Deserializes a single datum from a ByteBuffer, byte array, or InputStream. * * @param <D> a datum class */ public interface MessageDecoder<D> { /** * Deserialize a single datum from an InputStream. * * @param stream stream to read from * @return a datum read from the stream * @throws BadHeaderException If the payload's header is not recognized. * @throws MissingSchemaException If the payload's schema cannot be found. * @throws IOException */ D decode(InputStream stream) throws IOException; /** * Deserialize a single datum from an InputStream. * * @param stream stream to read from * @param reuse a datum instance to reuse, avoiding instantiation if possible * @return a datum read from the stream * @throws BadHeaderException If the payload's header is not recognized. * @throws MissingSchemaException If the payload's schema cannot be found. * @throws IOException */ D decode(InputStream stream, D reuse) throws IOException; /** * Deserialize a single datum from a ByteBuffer. * * @param encoded a ByteBuffer containing an encoded datum * @return a datum read from the stream * @throws BadHeaderException If the payload's header is not recognized. * @throws MissingSchemaException If the payload's schema cannot be found. * @throws IOException */ D decode(ByteBuffer encoded) throws IOException; /** * Deserialize a single datum from a ByteBuffer. * * @param encoded a ByteBuffer containing an encoded datum * @param reuse a datum instance to reuse, avoiding instantiation if possible * @return a datum read from the stream * @throws BadHeaderException If the payload's header is not recognized. * @throws MissingSchemaException If the payload's schema cannot be found. * @throws IOException */ D decode(ByteBuffer encoded, D reuse) throws IOException; /** * Deserialize a single datum from a byte array. * * @param encoded a byte array containing an encoded datum * @return a datum read from the stream * @throws BadHeaderException If the payload's header is not recognized. * @throws MissingSchemaException If the payload's schema cannot be found. * @throws IOException */ D decode(byte[] encoded) throws IOException; /** * Deserialize a single datum from a byte array. * * @param encoded a byte array containing an encoded datum * @param reuse a datum instance to reuse, avoiding instantiation if possible * @return a datum read from the stream * @throws BadHeaderException If the payload's header is not recognized. * @throws MissingSchemaException If the payload's schema cannot be found. * @throws IOException */ D decode(byte[] encoded, D reuse) throws IOException; /** * Base class for {@link MessageEncoder} implementations that provides default * implementations for most of the {@code DatumEncoder} API. * <p> * Implementations provided by this base class are thread-safe. * * @param <D> a datum class */ abstract class BaseDecoder<D> implements MessageDecoder<D> { private static final ThreadLocal<ReusableByteArrayInputStream> BYTE_ARRAY_IN = ThreadLocalWithInitial .of(ReusableByteArrayInputStream::new); private static final ThreadLocal<ReusableByteBufferInputStream> BYTE_BUFFER_IN = ThreadLocalWithInitial .of(ReusableByteBufferInputStream::new); @Override public D decode(InputStream stream) throws IOException { return decode(stream, null); } @Override public D decode(ByteBuffer encoded) throws IOException { return decode(encoded, null); } @Override public D decode(byte[] encoded) throws IOException { return decode(encoded, null); } @Override public D decode(ByteBuffer encoded, D reuse) throws IOException { ReusableByteBufferInputStream in = BYTE_BUFFER_IN.get(); in.setByteBuffer(encoded); return decode(in, reuse); } @Override public D decode(byte[] encoded, D reuse) throws IOException { ReusableByteArrayInputStream in = BYTE_ARRAY_IN.get(); in.setByteArray(encoded, 0, encoded.length); return decode(in, reuse); } } }
7,368
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/message/BinaryMessageEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.avro.message; import org.apache.avro.AvroRuntimeException; import org.apache.avro.Schema; import org.apache.avro.SchemaNormalization; import org.apache.avro.generic.GenericData; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.security.NoSuchAlgorithmException; /** * A {@link MessageEncoder} that adds a header and 8-byte schema fingerprint to * each datum encoded as binary. * <p> * This class is thread-safe. */ public class BinaryMessageEncoder<D> implements MessageEncoder<D> { static final byte[] V1_HEADER = new byte[] { (byte) 0xC3, (byte) 0x01 }; private final RawMessageEncoder<D> writeCodec; /** * Creates a new {@link BinaryMessageEncoder} that uses the given * {@link GenericData data model} to deconstruct datum instances described by * the {@link Schema schema}. * <p> * Buffers returned by {@link BinaryMessageEncoder#encode} are copied and will * not be modified by future calls to {@code encode}. * * @param model the {@link GenericData data model} for datum instances * @param schema the {@link Schema} for datum instances */ public BinaryMessageEncoder(GenericData model, Schema schema) { this(model, schema, true); } /** * Creates a new {@link BinaryMessageEncoder} that uses the given * {@link GenericData data model} to deconstruct datum instances described by * the {@link Schema schema}. * <p> * If {@code shouldCopy} is true, then buffers returned by * {@link BinaryMessageEncoder#encode} are copied and will not be modified by * future calls to {@code encode}. * <p> * If {@code shouldCopy} is false, then buffers returned by {@code encode} wrap * a thread-local buffer that can be reused by future calls to {@code encode}, * but may not be. Callers should only set {@code shouldCopy} to false if the * buffer will be copied before the current thread's next call to * {@code encode}. * * @param model the {@link GenericData data model} for datum instances * @param schema the {@link Schema} for datum instances * @param shouldCopy whether to copy buffers before returning encoded results */ public BinaryMessageEncoder(GenericData model, Schema schema, boolean shouldCopy) { this.writeCodec = new V1MessageEncoder<>(model, schema, shouldCopy); } @Override public ByteBuffer encode(D datum) throws IOException { return writeCodec.encode(datum); } @Override public void encode(D datum, OutputStream stream) throws IOException { writeCodec.encode(datum, stream); } /** * This is a RawDatumEncoder that adds the V1 header to the outgoing buffer. * BinaryDatumEncoder wraps this class to avoid confusion over what it does. It * should not have an "is a" relationship with RawDatumEncoder because it adds * the extra bytes. */ private static class V1MessageEncoder<D> extends RawMessageEncoder<D> { private final byte[] headerBytes; V1MessageEncoder(GenericData model, Schema schema, boolean shouldCopy) { super(model, schema, shouldCopy); this.headerBytes = getWriteHeader(schema); } @Override public void encode(D datum, OutputStream stream) throws IOException { stream.write(headerBytes); super.encode(datum, stream); } private static byte[] getWriteHeader(Schema schema) { try { byte[] fp = SchemaNormalization.parsingFingerprint("CRC-64-AVRO", schema); byte[] ret = new byte[V1_HEADER.length + fp.length]; System.arraycopy(V1_HEADER, 0, ret, 0, V1_HEADER.length); System.arraycopy(fp, 0, ret, V1_HEADER.length, fp.length); return ret; } catch (NoSuchAlgorithmException e) { throw new AvroRuntimeException(e); } } } }
7,369
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/message/MissingSchemaException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.avro.message; import org.apache.avro.AvroRuntimeException; /** * Exception thrown by a {@link MessageDecoder} when the message is encoded * using an unknown {@link org.apache.avro.Schema}. * <p> * Using a {@link SchemaStore} to provide schemas to the decoder can avoid this * problem. */ public class MissingSchemaException extends AvroRuntimeException { public MissingSchemaException(String message) { super(message); } }
7,370
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/message/SchemaStore.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.avro.message; import org.apache.avro.Schema; import org.apache.avro.SchemaNormalization; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Interface for classes that can provide avro schemas by fingerprint. */ public interface SchemaStore { /** * Retrieves a fingerprint by its AVRO-CRC-64 fingerprint. * * @param fingerprint an AVRO-CRC-64 fingerprint long * @return a Schema with the given fingerprint, or null */ Schema findByFingerprint(long fingerprint); /** * A map-based cache of schemas by AVRO-CRC-64 fingerprint. * <p> * This class is thread-safe. */ class Cache implements SchemaStore { private final Map<Long, Schema> schemas = new ConcurrentHashMap<>(); /** * Adds a schema to this cache that can be retrieved using its AVRO-CRC-64 * fingerprint. * * @param schema a {@link Schema} */ public void addSchema(Schema schema) { long fp = SchemaNormalization.parsingFingerprint64(schema); schemas.put(fp, schema); } @Override public Schema findByFingerprint(long fingerprint) { return schemas.get(fingerprint); } } }
7,371
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/message/RawMessageEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.avro.message; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.io.BinaryEncoder; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.EncoderFactory; import org.apache.avro.util.internal.ThreadLocalWithInitial; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; /** * A {@link MessageEncoder} that encodes only a datum's bytes, without * additional information (such as a schema fingerprint). * <p> * This class is thread-safe. */ public class RawMessageEncoder<D> implements MessageEncoder<D> { private static final ThreadLocal<BufferOutputStream> TEMP = ThreadLocalWithInitial.of(BufferOutputStream::new); private static final ThreadLocal<BinaryEncoder> ENCODER = new ThreadLocal<>(); private final boolean copyOutputBytes; private final DatumWriter<D> writer; /** * Creates a new {@link RawMessageEncoder} that uses the given * {@link GenericData data model} to deconstruct datum instances described by * the {@link Schema schema}. * <p> * Buffers returned by {@link RawMessageEncoder#encode} are copied and will not * be modified by future calls to {@code encode}. * * @param model the {@link GenericData data model} for datum instances * @param schema the {@link Schema} for datum instances */ public RawMessageEncoder(GenericData model, Schema schema) { this(model, schema, true); } /** * Creates a new {@link RawMessageEncoder} that uses the given * {@link GenericData data model} to deconstruct datum instances described by * the {@link Schema schema}. * <p> * If {@code shouldCopy} is true, then buffers returned by * {@link RawMessageEncoder#encode} are copied and will not be modified by * future calls to {@code encode}. * <p> * If {@code shouldCopy} is false, then buffers returned by {@code encode} wrap * a thread-local buffer that can be reused by future calls to {@code encode}, * but may not be. Callers should only set {@code shouldCopy} to false if the * buffer will be copied before the current thread's next call to * {@code encode}. * * @param model the {@link GenericData data model} for datum instances * @param schema the {@link Schema} for datum instances * @param shouldCopy whether to copy buffers before returning encoded results */ public RawMessageEncoder(GenericData model, Schema schema, boolean shouldCopy) { Schema writeSchema = schema; this.copyOutputBytes = shouldCopy; this.writer = model.createDatumWriter(writeSchema); } @Override public ByteBuffer encode(D datum) throws IOException { BufferOutputStream temp = TEMP.get(); temp.reset(); encode(datum, temp); if (copyOutputBytes) { return temp.toBufferWithCopy(); } else { return temp.toBufferWithoutCopy(); } } @Override public void encode(D datum, OutputStream stream) throws IOException { BinaryEncoder encoder = EncoderFactory.get().directBinaryEncoder(stream, ENCODER.get()); ENCODER.set(encoder); writer.write(datum, encoder); encoder.flush(); } private static class BufferOutputStream extends ByteArrayOutputStream { BufferOutputStream() { } ByteBuffer toBufferWithoutCopy() { return ByteBuffer.wrap(buf, 0, count); } ByteBuffer toBufferWithCopy() { return ByteBuffer.wrap(toByteArray()); } } }
7,372
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/message/BadHeaderException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.avro.message; import org.apache.avro.AvroRuntimeException; /** * Exception thrown by a {@link MessageDecoder} when a message header is not * recognized. * <p> * This usually indicates that the encoded bytes were not an Avro message. */ public class BadHeaderException extends AvroRuntimeException { public BadHeaderException(String message) { super(message); } }
7,373
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/message/MessageEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.avro.message; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; /** * Serializes an individual datum as a ByteBuffer or to an OutputStream. * * @param <D> a datum class */ public interface MessageEncoder<D> { /** * Serialize a single datum to a ByteBuffer. * * @param datum a datum * @return a ByteBuffer containing the serialized datum * @throws IOException */ ByteBuffer encode(D datum) throws IOException; /** * Serialize a single datum to an OutputStream. * * @param datum a datum * @param stream an OutputStream to serialize the datum to * @throws IOException */ void encode(D datum, OutputStream stream) throws IOException; }
7,374
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/message/BinaryMessageDecoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.avro.message; import org.apache.avro.Schema; import org.apache.avro.SchemaNormalization; import org.apache.avro.generic.GenericData; import org.apache.avro.util.internal.ThreadLocalWithInitial; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * A {@link MessageDecoder} that reads a binary-encoded datum. This checks for * the datum header and decodes the payload with the schema that corresponds to * the 8-byte schema fingerprint. * <p> * Instances can decode message payloads for known {@link Schema schemas}, which * are schemas added using {@link #addSchema(Schema)}, schemas resolved by the * {@link SchemaStore} passed to the constructor, or the expected schema passed * to the constructor. Messages encoded using an unknown schema will cause * instances to throw a {@link MissingSchemaException}. * <p> * It is safe to continue using instances of this class after {@link #decode} * throws {@link BadHeaderException} or {@link MissingSchemaException}. * <p> * This class is thread-safe. */ public class BinaryMessageDecoder<D> extends MessageDecoder.BaseDecoder<D> { private static final ThreadLocal<byte[]> HEADER_BUFFER = ThreadLocalWithInitial.of(() -> new byte[10]); private static final ThreadLocal<ByteBuffer> FP_BUFFER = ThreadLocalWithInitial.of(() -> { byte[] header = HEADER_BUFFER.get(); return ByteBuffer.wrap(header).order(ByteOrder.LITTLE_ENDIAN); }); private final GenericData model; private final Schema readSchema; private final SchemaStore resolver; private final Map<Long, RawMessageDecoder<D>> codecByFingerprint = new ConcurrentHashMap<>(); /** * Creates a new {@link BinaryMessageEncoder} that uses the given * {@link GenericData data model} to construct datum instances described by the * {@link Schema schema}. * <p> * The {@code readSchema} is as used the expected schema (read schema). Datum * instances created by this class will be described by the expected schema. * <p> * If {@code readSchema} is {@code null}, the write schema of an incoming buffer * is used as read schema for that datum instance. * <p> * The schema used to decode incoming buffers is determined by the schema * fingerprint encoded in the message header. This class can decode messages * that were encoded using the {@code readSchema} (if any) and other schemas * that are added using {@link #addSchema(Schema)}. * * @param model the {@link GenericData data model} for datum instances * @param readSchema the {@link Schema} used to construct datum instances */ public BinaryMessageDecoder(GenericData model, Schema readSchema) { this(model, readSchema, null); } /** * Creates a new {@link BinaryMessageEncoder} that uses the given * {@link GenericData data model} to construct datum instances described by the * {@link Schema schema}. * <p> * The {@code readSchema} is used as the expected schema (read schema). Datum * instances created by this class will be described by the expected schema. * <p> * If {@code readSchema} is {@code null}, the write schema of an incoming buffer * is used as read schema for that datum instance. * <p> * The schema used to decode incoming buffers is determined by the schema * fingerprint encoded in the message header. This class can decode messages * that were encoded using the {@code readSchema} (if any), other schemas that * are added using {@link #addSchema(Schema)}, or schemas returned by the * {@code resolver}. * * @param model the {@link GenericData data model} for datum instances * @param readSchema the {@link Schema} used to construct datum instances * @param resolver a {@link SchemaStore} used to find schemas by fingerprint */ public BinaryMessageDecoder(GenericData model, Schema readSchema, SchemaStore resolver) { this.model = model; this.readSchema = readSchema; this.resolver = resolver; if (readSchema != null) { addSchema(readSchema); } } /** * Adds a {@link Schema} that can be used to decode buffers. * * @param writeSchema a {@link Schema} to use when decoding buffers */ public void addSchema(Schema writeSchema) { long fp = SchemaNormalization.parsingFingerprint64(writeSchema); final Schema actualReadSchema = this.readSchema != null ? this.readSchema : writeSchema; codecByFingerprint.put(fp, new RawMessageDecoder<D>(model, writeSchema, actualReadSchema)); } private RawMessageDecoder<D> getDecoder(long fp) { RawMessageDecoder<D> decoder = codecByFingerprint.get(fp); if (decoder != null) { return decoder; } if (resolver != null) { Schema writeSchema = resolver.findByFingerprint(fp); if (writeSchema != null) { addSchema(writeSchema); return codecByFingerprint.get(fp); } } throw new MissingSchemaException("Cannot resolve schema for fingerprint: " + fp); } @Override public D decode(InputStream stream, D reuse) throws IOException { byte[] header = HEADER_BUFFER.get(); try { if (!readFully(stream, header)) { throw new BadHeaderException("Not enough header bytes"); } } catch (IOException e) { throw new IOException("Failed to read header and fingerprint bytes", e); } if (BinaryMessageEncoder.V1_HEADER[0] != header[0] || BinaryMessageEncoder.V1_HEADER[1] != header[1]) { throw new BadHeaderException(String.format("Unrecognized header bytes: 0x%02X 0x%02X", header[0], header[1])); } RawMessageDecoder<D> decoder = getDecoder(FP_BUFFER.get().getLong(2)); return decoder.decode(stream, reuse); } /** * Reads a buffer from a stream, making multiple read calls if necessary. * * @param stream an InputStream to read from * @param bytes a buffer * @return true if the buffer is complete, false otherwise (stream ended) * @throws IOException */ private boolean readFully(InputStream stream, byte[] bytes) throws IOException { int pos = 0; int bytesRead; while ((bytes.length - pos) > 0 && (bytesRead = stream.read(bytes, pos, bytes.length - pos)) > 0) { pos += bytesRead; } return (pos == bytes.length); } }
7,375
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/message/RawMessageDecoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.avro.message; import org.apache.avro.AvroRuntimeException; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.io.BinaryDecoder; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DecoderFactory; import java.io.IOException; import java.io.InputStream; /** * A {@link MessageDecoder} that deserializes from raw datum bytes. * <p> * This class uses the schema passed to its constructor when decoding buffers. * To decode buffers that have different schemas, use * {@link BinaryMessageEncoder} and {@link BinaryMessageDecoder}. * <p> * This will not throw {@link BadHeaderException} because it expects no header, * and will not throw {@link MissingSchemaException} because it always uses the * read schema from its constructor. * <p> * This class is thread-safe. */ public class RawMessageDecoder<D> extends MessageDecoder.BaseDecoder<D> { private static final ThreadLocal<BinaryDecoder> DECODER = new ThreadLocal<>(); private final DatumReader<D> reader; /** * Creates a new {@link RawMessageDecoder} that uses the given * {@link GenericData data model} to construct datum instances described by the * {@link Schema schema}. * <p> * The {@code schema} is used as both the expected schema (read schema) and for * the schema of payloads that are decoded (written schema). * * @param model the {@link GenericData data model} for datum instances * @param schema the {@link Schema} used to construct datum instances and to * decode buffers. */ public RawMessageDecoder(GenericData model, Schema schema) { this(model, schema, schema); } /** * Creates a new {@link RawMessageDecoder} that uses the given * {@link GenericData data model} to construct datum instances described by the * {@link Schema readSchema}. * <p> * The {@code readSchema} is used for the expected schema and the * {@code writeSchema} is the schema used to decode buffers. The * {@code writeSchema} must be the schema that was used to encode all buffers * decoded by this class. * * @param model the {@link GenericData data model} for datum instances * @param readSchema the {@link Schema} used to construct datum instances * @param writeSchema the {@link Schema} used to decode buffers */ public RawMessageDecoder(GenericData model, Schema writeSchema, Schema readSchema) { Schema writeSchema1 = writeSchema; Schema readSchema1 = readSchema; this.reader = model.createDatumReader(writeSchema1, readSchema1); } @Override public D decode(InputStream stream, D reuse) { BinaryDecoder decoder = DecoderFactory.get().directBinaryDecoder(stream, DECODER.get()); DECODER.set(decoder); try { return reader.read(reuse, decoder); } catch (IOException e) { throw new AvroRuntimeException("Decoding datum failed", e); } } }
7,376
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/generic/GenericContainer.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.generic; import org.apache.avro.Schema; /** Contains data of other types. */ public interface GenericContainer { /** The schema of this instance. */ Schema getSchema(); }
7,377
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/generic/GenericRecord.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.generic; /** * A generic instance of a record schema. Fields are accessible by name as well * as by index. */ public interface GenericRecord extends IndexedRecord { /** Set the value of a field given its name. */ void put(String key, Object v); /** Return the value of a field given its name. */ Object get(String key); /** Return true if record has field with name: key */ default boolean hasField(String key) { return getSchema().getField(key) != null; } }
7,378
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/generic/GenericArray.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.generic; import java.util.List; /** Array that permits reuse of contained elements. */ public interface GenericArray<T> extends List<T>, GenericContainer { /** * The current content of the location where {@link #add(Object)} would next * store an element, if any. This permits reuse of arrays and their elements * without allocating new objects. */ T peek(); /** reset size counter of array to zero */ default void reset() { clear(); } /** clean up reusable objects from array (if reset didn't already) */ default void prune() { } /** Reverses the order of the elements in this array. */ void reverse(); }
7,379
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/generic/GenericRecordBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.generic; import java.io.IOException; import org.apache.avro.AvroRuntimeException; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.data.RecordBuilderBase; import org.apache.avro.generic.GenericData.Record; /** * A RecordBuilder for generic records. GenericRecordBuilder fills in default * values for fields if they are not specified. */ public class GenericRecordBuilder extends RecordBuilderBase<Record> { private final GenericData.Record record; /** * Creates a GenericRecordBuilder for building Record instances. * * @param schema the schema associated with the record class. */ public GenericRecordBuilder(Schema schema) { super(schema, GenericData.get()); record = new GenericData.Record(schema); } /** * Creates a GenericRecordBuilder by copying an existing GenericRecordBuilder. * * @param other the GenericRecordBuilder to copy. */ public GenericRecordBuilder(GenericRecordBuilder other) { super(other, GenericData.get()); record = new GenericData.Record(other.record, /* deepCopy = */ true); } /** * Creates a GenericRecordBuilder by copying an existing record instance. * * @param other the record instance to copy. */ public GenericRecordBuilder(Record other) { super(other.getSchema(), GenericData.get()); record = new GenericData.Record(other, /* deepCopy = */ true); // Set all fields in the RecordBuilder that are set in the record for (Field f : schema().getFields()) { Object value = other.get(f.pos()); // Only set the value if it is not null, if the schema type is null, // or if the schema type is a union that accepts nulls. if (isValidValue(f, value)) { set(f, data().deepCopy(f.schema(), value)); } } } /** * Gets the value of a field. * * @param fieldName the name of the field to get. * @return the value of the field with the given name, or null if not set. */ public Object get(String fieldName) { return get(schema().getField(fieldName)); } /** * Gets the value of a field. * * @param field the field to get. * @return the value of the given field, or null if not set. */ public Object get(Field field) { return get(field.pos()); } /** * Gets the value of a field. * * @param pos the position of the field to get. * @return the value of the field with the given position, or null if not set. */ protected Object get(int pos) { return record.get(pos); } /** * Sets the value of a field. * * @param fieldName the name of the field to set. * @param value the value to set. * @return a reference to the RecordBuilder. */ public GenericRecordBuilder set(String fieldName, Object value) { return set(schema().getField(fieldName), value); } /** * Sets the value of a field. * * @param field the field to set. * @param value the value to set. * @return a reference to the RecordBuilder. */ public GenericRecordBuilder set(Field field, Object value) { return set(field, field.pos(), value); } /** * Sets the value of a field. * * @param pos the field to set. * @param value the value to set. * @return a reference to the RecordBuilder. */ protected GenericRecordBuilder set(int pos, Object value) { return set(fields()[pos], pos, value); } /** * Sets the value of a field. * * @param field the field to set. * @param pos the position of the field. * @param value the value to set. * @return a reference to the RecordBuilder. */ private GenericRecordBuilder set(Field field, int pos, Object value) { validate(field, value); record.put(pos, value); fieldSetFlags()[pos] = true; return this; } /** * Checks whether a field has been set. * * @param fieldName the name of the field to check. * @return true if the given field is non-null; false otherwise. */ public boolean has(String fieldName) { return has(schema().getField(fieldName)); } /** * Checks whether a field has been set. * * @param field the field to check. * @return true if the given field is non-null; false otherwise. */ public boolean has(Field field) { return has(field.pos()); } /** * Checks whether a field has been set. * * @param pos the position of the field to check. * @return true if the given field is non-null; false otherwise. */ protected boolean has(int pos) { return fieldSetFlags()[pos]; } /** * Clears the value of the given field. * * @param fieldName the name of the field to clear. * @return a reference to the RecordBuilder. */ public GenericRecordBuilder clear(String fieldName) { return clear(schema().getField(fieldName)); } /** * Clears the value of the given field. * * @param field the field to clear. * @return a reference to the RecordBuilder. */ public GenericRecordBuilder clear(Field field) { return clear(field.pos()); } /** * Clears the value of the given field. * * @param pos the position of the field to clear. * @return a reference to the RecordBuilder. */ protected GenericRecordBuilder clear(int pos) { record.put(pos, null); fieldSetFlags()[pos] = false; return this; } @Override public Record build() { Record record; try { record = new GenericData.Record(schema()); } catch (Exception e) { throw new AvroRuntimeException(e); } for (Field field : fields()) { Object value; try { value = getWithDefault(field); } catch (IOException e) { throw new AvroRuntimeException(e); } if (value != null) { record.put(field.pos(), value); } } return record; } /** * Gets the value of the given field. If the field has been set, the set value * is returned (even if it's null). If the field hasn't been set and has a * default value, the default value is returned. * * @param field the field whose value should be retrieved. * @return the value set for the given field, the field's default value, or * null. * @throws IOException */ private Object getWithDefault(Field field) throws IOException { return fieldSetFlags()[field.pos()] ? record.get(field.pos()) : defaultValue(field); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((record == null) ? 0 : record.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; GenericRecordBuilder other = (GenericRecordBuilder) obj; if (record == null) { return other.record == null; } else return record.equals(other.record); } }
7,380
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/generic/GenericFixed.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.generic; /** Fixed-size data. */ public interface GenericFixed extends GenericContainer { /** Return the data. */ byte[] bytes(); }
7,381
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/generic/IndexedRecord.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.generic; /** A record implementation that permits field access by integer index. */ public interface IndexedRecord extends GenericContainer { /** * Set the value of a field given its position in the schema. * <p> * This method is not meant to be called by user code, but only by * {@link org.apache.avro.io.DatumReader} implementations. */ void put(int i, Object v); /** * Return the value of a field given its position in the schema. * <p> * This method is not meant to be called by user code, but only by * {@link org.apache.avro.io.DatumWriter} implementations. */ Object get(int i); }
7,382
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/generic/PrimitivesArrays.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.generic; import org.apache.avro.AvroRuntimeException; import org.apache.avro.Schema; import java.util.Arrays; import java.util.Collection; public class PrimitivesArrays { public static class IntArray extends GenericData.AbstractArray<Integer> { private static final int[] EMPTY = new int[0]; private int[] elements = EMPTY; public IntArray(int capacity, Schema schema) { super(schema); if (!Schema.Type.INT.equals(schema.getElementType().getType())) throw new AvroRuntimeException("Not a int array schema: " + schema); if (capacity != 0) elements = new int[capacity]; } public IntArray(Schema schema, Collection<Integer> c) { super(schema); if (c != null) { elements = new int[c.size()]; addAll(c); } } @Override public void clear() { size = 0; } @Override public Integer get(int i) { return this.getInt(i); } /** * Direct primitive int access. * * @param i : index. * @return value at index. */ public int getInt(int i) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); return elements[i]; } @Override public void add(int location, Integer o) { if (o == null) { return; } this.add(location, o.intValue()); } public void add(int location, int o) { if (location > size || location < 0) { throw new IndexOutOfBoundsException("Index " + location + " out of bounds."); } if (size == elements.length) { // Increase size by 1.5x + 1 final int newSize = size + (size >> 1) + 1; elements = Arrays.copyOf(elements, newSize); } System.arraycopy(elements, location, elements, location + 1, size - location); elements[location] = o; size++; } @Override public Integer set(int i, Integer o) { if (o == null) { return null; } return this.set(i, o.intValue()); } public int set(int i, int o) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); int response = elements[i]; elements[i] = o; return response; } @Override public Integer remove(int i) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); int result = elements[i]; --size; System.arraycopy(elements, i + 1, elements, i, (size - i)); return result; } @Override public Integer peek() { return (size < elements.length) ? elements[size] : null; } @Override protected void swap(final int index1, final int index2) { int tmp = elements[index1]; elements[index1] = elements[index2]; elements[index2] = tmp; } } public static class LongArray extends GenericData.AbstractArray<Long> { private static final long[] EMPTY = new long[0]; private long[] elements = EMPTY; public LongArray(int capacity, Schema schema) { super(schema); if (!Schema.Type.LONG.equals(schema.getElementType().getType())) throw new AvroRuntimeException("Not a long array schema: " + schema); if (capacity != 0) elements = new long[capacity]; } public LongArray(Schema schema, Collection<Long> c) { super(schema); if (c != null) { elements = new long[c.size()]; addAll(c); } } @Override public void clear() { size = 0; } @Override public Long get(int i) { return getLong(i); } /** * Direct primitive int access. * * @param i : index. * @return value at index. */ public long getLong(int i) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); return elements[i]; } @Override public void add(int location, Long o) { if (o == null) { return; } this.add(location, o.longValue()); } public void add(int location, long o) { if (location > size || location < 0) { throw new IndexOutOfBoundsException("Index " + location + " out of bounds."); } if (size == elements.length) { // Increase size by 1.5x + 1 final int newSize = size + (size >> 1) + 1; elements = Arrays.copyOf(elements, newSize); } System.arraycopy(elements, location, elements, location + 1, size - location); elements[location] = o; size++; } @Override public Long set(int i, Long o) { if (o == null) { return null; } return this.set(i, o.longValue()); } public long set(int i, long o) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); long response = elements[i]; elements[i] = o; return response; } @Override public Long remove(int i) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); long result = elements[i]; --size; System.arraycopy(elements, i + 1, elements, i, (size - i)); return result; } @Override public Long peek() { return (size < elements.length) ? elements[size] : null; } @Override protected void swap(final int index1, final int index2) { long tmp = elements[index1]; elements[index1] = elements[index2]; elements[index2] = tmp; } } public static class BooleanArray extends GenericData.AbstractArray<Boolean> { private static final byte[] EMPTY = new byte[0]; private byte[] elements = EMPTY; public BooleanArray(int capacity, Schema schema) { super(schema); if (!Schema.Type.BOOLEAN.equals(schema.getElementType().getType())) throw new AvroRuntimeException("Not a boolean array schema: " + schema); if (capacity != 0) elements = new byte[1 + (capacity / Byte.SIZE)]; } public BooleanArray(Schema schema, Collection<Boolean> c) { super(schema); if (c != null) { elements = new byte[1 + (c.size() / 8)]; if (c instanceof BooleanArray) { BooleanArray other = (BooleanArray) c; this.size = other.size; System.arraycopy(other.elements, 0, this.elements, 0, other.elements.length); } else { addAll(c); } } } @Override public void clear() { size = 0; } @Override public Boolean get(int i) { return this.getBoolean(i); } /** * Direct primitive int access. * * @param i : index. * @return value at index. */ public boolean getBoolean(int i) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); return (elements[i / 8] & (1 << (i % 8))) > 0; } @Override public boolean add(final Boolean o) { if (o == null) { return false; } return this.add(o.booleanValue()); } public boolean add(final boolean o) { if (this.size == elements.length * 8) { final int newLength = elements.length + (elements.length >> 1) + 1; elements = Arrays.copyOf(elements, newLength); } this.size++; this.set(this.size - 1, o); return true; } @Override public void add(int location, Boolean o) { if (o == null) { return; } this.add(location, o.booleanValue()); } public void add(int location, boolean o) { if (location > size || location < 0) { throw new IndexOutOfBoundsException("Index " + location + " out of bounds."); } if (size == elements.length * 8) { // Increase size by 1.5x + 1 final int newLength = elements.length + (elements.length >> 1) + 1; elements = Arrays.copyOf(elements, newLength); } size++; for (int index = this.size / 8; index > (location / 8); index--) { elements[index] <<= 1; if (index > 0 && (elements[index - 1] & (1 << Byte.SIZE)) > 0) { elements[index] |= 1; } } byte pos = (byte) (1 << (location % Byte.SIZE)); byte highbits = (byte) ~(pos + (pos - 1)); byte lowbits = (byte) (pos - 1); byte currentHigh = (byte) ((elements[location / 8] & highbits) << 1); byte currentLow = (byte) (elements[location / 8] & lowbits); if (o) { elements[location / 8] = (byte) (currentHigh | currentLow | pos); } else { elements[location / 8] = (byte) (currentHigh | currentLow); } } @Override public Boolean set(int i, Boolean o) { if (o == null) { return null; } return this.set(i, o.booleanValue()); } public boolean set(int i, boolean o) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); boolean response = (elements[i / 8] & (1 << (i % 8))) > 0; if (o) { elements[i / 8] |= 1 << (i % 8); } else { elements[i / 8] &= 0xFF - (1 << (i % 8)); } return response; } @Override public Boolean remove(int i) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); boolean result = (elements[(i / 8)] & (1 << (i % 8))) > 0; --size; byte memo = 0; if ((i / 8) + 1 < elements.length) { memo = (byte) ((1 & (elements[(i / 8) + 1])) << 7); } for (int index = (i / 8) + 1; index <= (size / 8); index++) { elements[index] = (byte) ((elements[index] & 0xff) >>> 1); if (index + 1 < elements.length && (elements[index + 1] & 1) == 1) { elements[index] |= 1 << (Byte.SIZE - 1); } } // 87654321 => <memo>8764321 byte start = (byte) ((1 << ((i + 1) % 8)) - 1); byte end = (byte) ~start; elements[i / 8] = (byte) ((((start & 0xff) >>> 1) & elements[i / 8]) // 1234 | (end & (elements[i / 8] >> 1)) // 876 | memo); return result; } @Override public Boolean peek() { return (size < elements.length * Byte.SIZE) ? (elements[(size / 8)] & (1 << (size % 8))) > 0 : null; } @Override protected void swap(final int index1, final int index2) { boolean tmp = this.get(index1); this.set(index1, this.get(index2)); this.set(index2, tmp); } } public static class FloatArray extends GenericData.AbstractArray<Float> { private static final float[] EMPTY = new float[0]; private float[] elements = EMPTY; public FloatArray(int capacity, Schema schema) { super(schema); if (!Schema.Type.FLOAT.equals(schema.getElementType().getType())) throw new AvroRuntimeException("Not a float array schema: " + schema); if (capacity != 0) elements = new float[capacity]; } public FloatArray(Schema schema, Collection<Float> c) { super(schema); if (c != null) { elements = new float[c.size()]; addAll(c); } } @Override public void clear() { size = 0; } @Override public Float get(int i) { return this.getFloat(i); } /** * Direct primitive int access. * * @param i : index. * @return value at index. */ public float getFloat(int i) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); return elements[i]; } @Override public void add(int location, Float o) { if (o == null) { return; } this.add(location, o.floatValue()); } public void add(int location, float o) { if (location > size || location < 0) { throw new IndexOutOfBoundsException("Index " + location + " out of bounds."); } if (size == elements.length) { // Increase size by 1.5x + 1 final int newSize = size + (size >> 1) + 1; elements = Arrays.copyOf(elements, newSize); } System.arraycopy(elements, location, elements, location + 1, size - location); elements[location] = o; size++; } @Override public Float set(int i, Float o) { if (o == null) { return null; } return this.set(i, o.floatValue()); } public float set(int i, float o) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); float response = elements[i]; elements[i] = o; return response; } @Override public Float remove(int i) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); float result = elements[i]; --size; System.arraycopy(elements, i + 1, elements, i, (size - i)); return result; } @Override public Float peek() { return (size < elements.length) ? elements[size] : null; } @Override protected void swap(final int index1, final int index2) { float tmp = this.get(index1); this.set(index1, this.get(index2)); this.set(index2, tmp); } } public static class DoubleArray extends GenericData.AbstractArray<Double> { private static final double[] EMPTY = new double[0]; private double[] elements = EMPTY; public DoubleArray(int capacity, Schema schema) { super(schema); if (!Schema.Type.DOUBLE.equals(schema.getElementType().getType())) throw new AvroRuntimeException("Not a double array schema: " + schema); if (capacity != 0) elements = new double[capacity]; } public DoubleArray(Schema schema, Collection<Double> c) { super(schema); if (c != null) { elements = new double[c.size()]; addAll(c); } } @Override public void clear() { size = 0; } @Override public Double get(int i) { return this.getDouble(i); } /** * Direct primitive int access. * * @param i : index. * @return value at index. */ public double getDouble(int i) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); return elements[i]; } @Override public void add(int location, Double o) { if (o == null) { return; } this.add(location, o.floatValue()); } public void add(int location, double o) { if (location > size || location < 0) { throw new IndexOutOfBoundsException("Index " + location + " out of bounds."); } if (size == elements.length) { // Increase size by 1.5x + 1 final int newSize = size + (size >> 1) + 1; elements = Arrays.copyOf(elements, newSize); } System.arraycopy(elements, location, elements, location + 1, size - location); elements[location] = o; size++; } @Override public Double set(int i, Double o) { if (o == null) { return null; } return this.set(i, o.floatValue()); } public double set(int i, double o) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); double response = elements[i]; elements[i] = o; return response; } @Override public Double remove(int i) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); double result = elements[i]; --size; System.arraycopy(elements, i + 1, elements, i, (size - i)); return result; } @Override public Double peek() { return (size < elements.length) ? elements[size] : null; } @Override protected void swap(final int index1, final int index2) { double tmp = this.get(index1); this.set(index1, this.get(index2)); this.set(index2, tmp); } } }
7,383
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/generic/GenericData.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.generic; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.temporal.Temporal; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.UUID; import java.util.concurrent.ConcurrentMap; import org.apache.avro.AvroMissingFieldException; import org.apache.avro.AvroRuntimeException; import org.apache.avro.AvroTypeException; import org.apache.avro.Conversion; import org.apache.avro.Conversions; import org.apache.avro.JsonProperties; import org.apache.avro.LogicalType; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.Schema.Type; import org.apache.avro.UnresolvedUnionException; import org.apache.avro.io.BinaryData; import org.apache.avro.io.BinaryDecoder; import org.apache.avro.io.BinaryEncoder; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.DecoderFactory; import org.apache.avro.io.EncoderFactory; import org.apache.avro.io.FastReaderBuilder; import org.apache.avro.util.Utf8; import org.apache.avro.util.internal.Accessor; import com.fasterxml.jackson.databind.JsonNode; import org.apache.avro.util.springframework.ConcurrentReferenceHashMap; import static org.apache.avro.util.springframework.ConcurrentReferenceHashMap.ReferenceType.WEAK; /** * Utilities for generic Java data. See {@link GenericRecordBuilder} for a * convenient way to build {@link GenericRecord} instances. * * @see GenericRecordBuilder */ public class GenericData { private static final GenericData INSTANCE = new GenericData(); private static final Map<Class<?>, String> PRIMITIVE_DATUM_TYPES = new IdentityHashMap<>(); static { PRIMITIVE_DATUM_TYPES.put(Integer.class, Type.INT.getName()); PRIMITIVE_DATUM_TYPES.put(Long.class, Type.LONG.getName()); PRIMITIVE_DATUM_TYPES.put(Float.class, Type.FLOAT.getName()); PRIMITIVE_DATUM_TYPES.put(Double.class, Type.DOUBLE.getName()); PRIMITIVE_DATUM_TYPES.put(Boolean.class, Type.BOOLEAN.getName()); PRIMITIVE_DATUM_TYPES.put(String.class, Type.STRING.getName()); PRIMITIVE_DATUM_TYPES.put(Utf8.class, Type.STRING.getName()); } /** Used to specify the Java type for a string schema. */ public enum StringType { CharSequence, String, Utf8 }; public static final String STRING_PROP = "avro.java.string"; protected static final String STRING_TYPE_STRING = "String"; private final ClassLoader classLoader; /** * Set the Java type to be used when reading this schema. Meaningful only only * string schemas and map schemas (for the keys). */ public static void setStringType(Schema s, StringType stringType) { // Utf8 is the default and implements CharSequence, so we only need to add // a property when the type is String if (stringType == StringType.String) s.addProp(GenericData.STRING_PROP, GenericData.STRING_TYPE_STRING); } /** Return the singleton instance. */ public static GenericData get() { return INSTANCE; } /** For subclasses. Applications normally use {@link GenericData#get()}. */ public GenericData() { this(null); } /** For subclasses. GenericData does not use a ClassLoader. */ public GenericData(ClassLoader classLoader) { this.classLoader = (classLoader != null) ? classLoader : getClass().getClassLoader(); loadConversions(); } /** Return the class loader that's used (by subclasses). */ public ClassLoader getClassLoader() { return classLoader; } /** * Use the Java 6 ServiceLoader to load conversions. * * @see #addLogicalTypeConversion(Conversion) */ private void loadConversions() { for (Conversion<?> conversion : ServiceLoader.load(Conversion.class, classLoader)) { addLogicalTypeConversion(conversion); } } private Map<String, Conversion<?>> conversions = new HashMap<>(); private Map<Class<?>, Map<String, Conversion<?>>> conversionsByClass = new IdentityHashMap<>(); public Collection<Conversion<?>> getConversions() { return conversions.values(); } /** * Registers the given conversion to be used when reading and writing with this * data model. Conversions can also be registered automatically, as documented * on the class {@link Conversion Conversion&lt;T&gt;}. * * @param conversion a logical type Conversion. */ public void addLogicalTypeConversion(Conversion<?> conversion) { conversions.put(conversion.getLogicalTypeName(), conversion); Class<?> type = conversion.getConvertedType(); Map<String, Conversion<?>> conversionsForClass = conversionsByClass.computeIfAbsent(type, k -> new LinkedHashMap<>()); conversionsForClass.put(conversion.getLogicalTypeName(), conversion); } /** * Returns the first conversion found for the given class. * * @param datumClass a Class * @return the first registered conversion for the class, or null */ @SuppressWarnings("unchecked") public <T> Conversion<T> getConversionByClass(Class<T> datumClass) { Map<String, Conversion<?>> conversions = conversionsByClass.get(datumClass); if (conversions != null) { return (Conversion<T>) conversions.values().iterator().next(); } return null; } /** * Returns the conversion for the given class and logical type. * * @param datumClass a Class * @param logicalType a LogicalType * @return the conversion for the class and logical type, or null */ @SuppressWarnings("unchecked") public <T> Conversion<T> getConversionByClass(Class<T> datumClass, LogicalType logicalType) { Map<String, Conversion<?>> conversions = conversionsByClass.get(datumClass); if (conversions != null) { return (Conversion<T>) conversions.get(logicalType.getName()); } return null; } /** * Returns the Conversion for the given logical type. * * @param logicalType a logical type * @return the conversion for the logical type, or null */ @SuppressWarnings("unchecked") public <T> Conversion<T> getConversionFor(LogicalType logicalType) { if (logicalType == null) { return null; } return (Conversion<T>) conversions.get(logicalType.getName()); } public static final String FAST_READER_PROP = "org.apache.avro.fastread"; private boolean fastReaderEnabled = "true".equalsIgnoreCase(System.getProperty(FAST_READER_PROP)); private FastReaderBuilder fastReaderBuilder = null; public GenericData setFastReaderEnabled(boolean flag) { this.fastReaderEnabled = flag; return this; } public boolean isFastReaderEnabled() { return fastReaderEnabled && FastReaderBuilder.isSupportedData(this); } public FastReaderBuilder getFastReaderBuilder() { if (fastReaderBuilder == null) { fastReaderBuilder = new FastReaderBuilder(this); } return this.fastReaderBuilder; } /** * Default implementation of {@link GenericRecord}. Note that this * implementation does not fill in default values for fields if they are not * specified; use {@link GenericRecordBuilder} in that case. * * @see GenericRecordBuilder */ public static class Record implements GenericRecord, Comparable<Record> { private final Schema schema; private final Object[] values; public Record(Schema schema) { if (schema == null || !Type.RECORD.equals(schema.getType())) throw new AvroRuntimeException("Not a record schema: " + schema); this.schema = schema; this.values = new Object[schema.getFields().size()]; } public Record(Record other, boolean deepCopy) { schema = other.schema; values = new Object[schema.getFields().size()]; if (deepCopy) { for (int ii = 0; ii < values.length; ii++) { values[ii] = INSTANCE.deepCopy(schema.getFields().get(ii).schema(), other.values[ii]); } } else { System.arraycopy(other.values, 0, values, 0, other.values.length); } } @Override public Schema getSchema() { return schema; } @Override public void put(String key, Object value) { Schema.Field field = schema.getField(key); if (field == null) { throw new AvroRuntimeException("Not a valid schema field: " + key); } values[field.pos()] = value; } @Override public void put(int i, Object v) { values[i] = v; } @Override public Object get(String key) { Field field = schema.getField(key); if (field == null) { throw new AvroRuntimeException("Not a valid schema field: " + key); } return values[field.pos()]; } @Override public Object get(int i) { return values[i]; } @Override public boolean equals(Object o) { if (o == this) return true; // identical object if (!(o instanceof Record)) return false; // not a record Record that = (Record) o; if (!this.schema.equals(that.schema)) return false; // not the same schema return GenericData.get().compare(this, that, schema, true) == 0; } @Override public int hashCode() { return GenericData.get().hashCode(this, schema); } @Override public int compareTo(Record that) { return GenericData.get().compare(this, that, schema); } @Override public String toString() { return GenericData.get().toString(this); } } public static abstract class AbstractArray<T> extends AbstractList<T> implements GenericArray<T>, Comparable<GenericArray<T>> { private final Schema schema; protected int size = 0; public AbstractArray(Schema schema) { if (schema == null || !Type.ARRAY.equals(schema.getType())) throw new AvroRuntimeException("Not an array schema: " + schema); this.schema = schema; } @Override public Schema getSchema() { return schema; } @Override public int size() { return size; } @Override public void reset() { size = 0; } @Override public int compareTo(GenericArray<T> that) { return GenericData.get().compare(this, that, this.getSchema()); } @Override public boolean equals(final Object o) { if (!(o instanceof Collection)) { return false; } return GenericData.get().compare(this, o, this.getSchema()) == 0; } @Override public int hashCode() { return super.hashCode(); } @Override public Iterator<T> iterator() { return new Iterator<T>() { private int position = 0; @Override public boolean hasNext() { return position < size; } @Override public T next() { return AbstractArray.this.get(position++); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public void reverse() { int left = 0; int right = size - 1; while (left < right) { this.swap(left, right); left++; right--; } } protected abstract void swap(int index1, int index2); } /** Default implementation of an array. */ @SuppressWarnings(value = "unchecked") public static class Array<T> extends AbstractArray<T> { private static final Object[] EMPTY = new Object[0]; private Object[] elements = EMPTY; public Array(int capacity, Schema schema) { super(schema); if (capacity != 0) elements = new Object[capacity]; } public Array(Schema schema, Collection<T> c) { super(schema); if (c != null) { elements = new Object[c.size()]; addAll(c); } } @Override public void clear() { // Let GC do its work Arrays.fill(elements, 0, size, null); size = 0; } @Override public void prune() { if (size < elements.length) { Arrays.fill(elements, size, elements.length, null); } } @Override public T get(int i) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); return (T) elements[i]; } @Override public void add(int location, T o) { if (location > size || location < 0) { throw new IndexOutOfBoundsException("Index " + location + " out of bounds."); } if (size == elements.length) { // Increase size by 1.5x + 1 final int newSize = size + (size >> 1) + 1; elements = Arrays.copyOf(elements, newSize); } System.arraycopy(elements, location, elements, location + 1, size - location); elements[location] = o; size++; } @Override public T set(int i, T o) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); T response = (T) elements[i]; elements[i] = o; return response; } @Override public T remove(int i) { if (i >= size) throw new IndexOutOfBoundsException("Index " + i + " out of bounds."); T result = (T) elements[i]; --size; System.arraycopy(elements, i + 1, elements, i, (size - i)); elements[size] = null; return result; } @Override public T peek() { return (size < elements.length) ? (T) elements[size] : null; } @Override protected void swap(final int index1, final int index2) { Object tmp = elements[index1]; elements[index1] = elements[index2]; elements[index2] = tmp; } } /** Default implementation of {@link GenericFixed}. */ public static class Fixed implements GenericFixed, Comparable<Fixed> { private Schema schema; private byte[] bytes; public Fixed(Schema schema) { setSchema(schema); } public Fixed(Schema schema, byte[] bytes) { this.schema = schema; this.bytes = bytes; } protected Fixed() { } protected void setSchema(Schema schema) { this.schema = schema; this.bytes = new byte[schema.getFixedSize()]; } @Override public Schema getSchema() { return schema; } public void bytes(byte[] bytes) { this.bytes = bytes; } @Override public byte[] bytes() { return bytes; } @Override public boolean equals(Object o) { if (o == this) return true; return o instanceof GenericFixed && Arrays.equals(bytes, ((GenericFixed) o).bytes()); } @Override public int hashCode() { return Arrays.hashCode(bytes); } @Override public String toString() { return Arrays.toString(bytes); } @Override public int compareTo(Fixed that) { return BinaryData.compareBytes(this.bytes, 0, this.bytes.length, that.bytes, 0, that.bytes.length); } } /** Default implementation of {@link GenericEnumSymbol}. */ public static class EnumSymbol implements GenericEnumSymbol<EnumSymbol> { private Schema schema; private String symbol; public EnumSymbol(Schema schema, String symbol) { this.schema = schema; this.symbol = symbol; } /** * Maps existing Objects into an Avro enum by calling toString(), eg for Java * Enums */ public EnumSymbol(Schema schema, Object symbol) { this(schema, symbol.toString()); } @Override public Schema getSchema() { return schema; } @Override public boolean equals(Object o) { if (o == this) return true; return o instanceof GenericEnumSymbol && symbol.equals(o.toString()); } @Override public int hashCode() { return symbol.hashCode(); } @Override public String toString() { return symbol; } @Override public int compareTo(EnumSymbol that) { return GenericData.get().compare(this, that, schema); } } /** Returns a {@link DatumReader} for this kind of data. */ public DatumReader createDatumReader(Schema schema) { return createDatumReader(schema, schema); } /** Returns a {@link DatumReader} for this kind of data. */ public DatumReader createDatumReader(Schema writer, Schema reader) { return new GenericDatumReader(writer, reader, this); } /** Returns a {@link DatumWriter} for this kind of data. */ public DatumWriter createDatumWriter(Schema schema) { return new GenericDatumWriter(schema, this); } /** Returns true if a Java datum matches a schema. */ public boolean validate(Schema schema, Object datum) { switch (schema.getType()) { case RECORD: if (!isRecord(datum)) return false; for (Field f : schema.getFields()) { if (!validate(f.schema(), getField(datum, f.name(), f.pos()))) return false; } return true; case ENUM: if (!isEnum(datum)) return false; return schema.getEnumSymbols().contains(datum.toString()); case ARRAY: if (!(isArray(datum))) return false; for (Object element : getArrayAsCollection(datum)) if (!validate(schema.getElementType(), element)) return false; return true; case MAP: if (!(isMap(datum))) return false; @SuppressWarnings(value = "unchecked") Map<Object, Object> map = (Map<Object, Object>) datum; for (Map.Entry<Object, Object> entry : map.entrySet()) if (!validate(schema.getValueType(), entry.getValue())) return false; return true; case UNION: try { int i = resolveUnion(schema, datum); return validate(schema.getTypes().get(i), datum); } catch (UnresolvedUnionException e) { return false; } case FIXED: return datum instanceof GenericFixed && ((GenericFixed) datum).bytes().length == schema.getFixedSize(); case STRING: return isString(datum); case BYTES: return isBytes(datum); case INT: return isInteger(datum); case LONG: return isLong(datum); case FLOAT: return isFloat(datum); case DOUBLE: return isDouble(datum); case BOOLEAN: return isBoolean(datum); case NULL: return datum == null; default: return false; } } /** Renders a Java datum as <a href="https://www.json.org/">JSON</a>. */ public String toString(Object datum) { StringBuilder buffer = new StringBuilder(); toString(datum, buffer, new IdentityHashMap<>(128)); return buffer.toString(); } private static final String TOSTRING_CIRCULAR_REFERENCE_ERROR_TEXT = " \">>> CIRCULAR REFERENCE CANNOT BE PUT IN JSON STRING, ABORTING RECURSION <<<\" "; /** Renders a Java datum as <a href="https://www.json.org/">JSON</a>. */ protected void toString(Object datum, StringBuilder buffer, IdentityHashMap<Object, Object> seenObjects) { if (isRecord(datum)) { if (seenObjects.containsKey(datum)) { buffer.append(TOSTRING_CIRCULAR_REFERENCE_ERROR_TEXT); return; } seenObjects.put(datum, datum); buffer.append("{"); int count = 0; Schema schema = getRecordSchema(datum); for (Field f : schema.getFields()) { toString(f.name(), buffer, seenObjects); buffer.append(": "); toString(getField(datum, f.name(), f.pos()), buffer, seenObjects); if (++count < schema.getFields().size()) buffer.append(", "); } buffer.append("}"); seenObjects.remove(datum); } else if (isArray(datum)) { if (seenObjects.containsKey(datum)) { buffer.append(TOSTRING_CIRCULAR_REFERENCE_ERROR_TEXT); return; } seenObjects.put(datum, datum); Collection<?> array = getArrayAsCollection(datum); buffer.append("["); long last = array.size() - 1; int i = 0; for (Object element : array) { toString(element, buffer, seenObjects); if (i++ < last) buffer.append(", "); } buffer.append("]"); seenObjects.remove(datum); } else if (isMap(datum)) { if (seenObjects.containsKey(datum)) { buffer.append(TOSTRING_CIRCULAR_REFERENCE_ERROR_TEXT); return; } seenObjects.put(datum, datum); buffer.append("{"); int count = 0; @SuppressWarnings(value = "unchecked") Map<Object, Object> map = (Map<Object, Object>) datum; for (Map.Entry<Object, Object> entry : map.entrySet()) { buffer.append("\""); writeEscapedString(String.valueOf(entry.getKey()), buffer); buffer.append("\": "); toString(entry.getValue(), buffer, seenObjects); if (++count < map.size()) buffer.append(", "); } buffer.append("}"); seenObjects.remove(datum); } else if (isString(datum) || isEnum(datum)) { buffer.append("\""); writeEscapedString(datum.toString(), buffer); buffer.append("\""); } else if (isBytes(datum)) { buffer.append("\""); ByteBuffer bytes = ((ByteBuffer) datum).duplicate(); writeEscapedString(StandardCharsets.ISO_8859_1.decode(bytes), buffer); buffer.append("\""); } else if (isNanOrInfinity(datum) || isTemporal(datum) || datum instanceof UUID) { buffer.append("\""); buffer.append(datum); buffer.append("\""); } else if (datum instanceof GenericData) { if (seenObjects.containsKey(datum)) { buffer.append(TOSTRING_CIRCULAR_REFERENCE_ERROR_TEXT); return; } seenObjects.put(datum, datum); toString(datum, buffer, seenObjects); seenObjects.remove(datum); } else { buffer.append(datum); } } private boolean isTemporal(Object datum) { return datum instanceof Temporal; } private boolean isNanOrInfinity(Object datum) { return ((datum instanceof Float) && (((Float) datum).isInfinite() || ((Float) datum).isNaN())) || ((datum instanceof Double) && (((Double) datum).isInfinite() || ((Double) datum).isNaN())); } /* Adapted from https://code.google.com/p/json-simple */ private static void writeEscapedString(CharSequence string, StringBuilder builder) { for (int i = 0; i < string.length(); i++) { char ch = string.charAt(i); switch (ch) { case '"': builder.append("\\\""); break; case '\\': builder.append("\\\\"); break; case '\b': builder.append("\\b"); break; case '\f': builder.append("\\f"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; case '\t': builder.append("\\t"); break; default: // Reference: https://www.unicode.org/versions/Unicode5.1.0/ if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F') || (ch >= '\u2000' && ch <= '\u20FF')) { String hex = Integer.toHexString(ch); builder.append("\\u"); for (int j = 0; j < 4 - hex.length(); j++) builder.append('0'); builder.append(hex.toUpperCase()); } else { builder.append(ch); } } } } /** Create a schema given an example datum. */ public Schema induce(Object datum) { if (isRecord(datum)) { return getRecordSchema(datum); } else if (isArray(datum)) { Schema elementType = null; for (Object element : getArrayAsCollection(datum)) { if (elementType == null) { elementType = induce(element); } else if (!elementType.equals(induce(element))) { throw new AvroTypeException("No mixed type arrays."); } } if (elementType == null) { throw new AvroTypeException("Empty array: " + datum); } return Schema.createArray(elementType); } else if (isMap(datum)) { @SuppressWarnings(value = "unchecked") Map<Object, Object> map = (Map<Object, Object>) datum; Schema value = null; for (Map.Entry<Object, Object> entry : map.entrySet()) { if (value == null) { value = induce(entry.getValue()); } else if (!value.equals(induce(entry.getValue()))) { throw new AvroTypeException("No mixed type map values."); } } if (value == null) { throw new AvroTypeException("Empty map: " + datum); } return Schema.createMap(value); } else if (datum instanceof GenericFixed) { return Schema.createFixed(null, null, null, ((GenericFixed) datum).bytes().length); } else if (isString(datum)) return Schema.create(Type.STRING); else if (isBytes(datum)) return Schema.create(Type.BYTES); else if (isInteger(datum)) return Schema.create(Type.INT); else if (isLong(datum)) return Schema.create(Type.LONG); else if (isFloat(datum)) return Schema.create(Type.FLOAT); else if (isDouble(datum)) return Schema.create(Type.DOUBLE); else if (isBoolean(datum)) return Schema.create(Type.BOOLEAN); else if (datum == null) return Schema.create(Type.NULL); else throw new AvroTypeException("Can't create schema for: " + datum); } /** * Called by {@link GenericDatumReader#readRecord} to set a record fields value * to a record instance. The default implementation is for * {@link IndexedRecord}. */ public void setField(Object record, String name, int position, Object value) { ((IndexedRecord) record).put(position, value); } /** * Called by {@link GenericDatumReader#readRecord} to retrieve a record field * value from a reused instance. The default implementation is for * {@link IndexedRecord}. */ public Object getField(Object record, String name, int position) { return ((IndexedRecord) record).get(position); } /** * Produce state for repeated calls to * {@link #getField(Object,String,int,Object)} and * {@link #setField(Object,String,int,Object,Object)} on the same record. */ protected Object getRecordState(Object record, Schema schema) { return null; } /** Version of {@link #setField} that has state. */ protected void setField(Object record, String name, int position, Object value, Object state) { setField(record, name, position, value); } /** Version of {@link #getField} that has state. */ protected Object getField(Object record, String name, int pos, Object state) { return getField(record, name, pos); } /** * Return the index for a datum within a union. Implemented with * {@link Schema#getIndexNamed(String)} and {@link #getSchemaName(Object)}. */ public int resolveUnion(Schema union, Object datum) { // if there is a logical type that works, use it first // this allows logical type concrete classes to overlap with supported ones // for example, a conversion could return a map if (datum != null) { Map<String, Conversion<?>> conversions = conversionsByClass.get(datum.getClass()); if (conversions != null) { List<Schema> candidates = union.getTypes(); for (int i = 0; i < candidates.size(); i += 1) { LogicalType candidateType = candidates.get(i).getLogicalType(); if (candidateType != null) { Conversion<?> conversion = conversions.get(candidateType.getName()); if (conversion != null) { return i; } } } } } Integer i = union.getIndexNamed(getSchemaName(datum)); if (i != null) { return i; } throw new UnresolvedUnionException(union, datum); } /** * Return the schema full name for a datum. Called by * {@link #resolveUnion(Schema,Object)}. */ protected String getSchemaName(Object datum) { if (datum == null || datum == JsonProperties.NULL_VALUE) return Type.NULL.getName(); String primativeType = getPrimitiveTypeCache().get(datum.getClass()); if (primativeType != null) return primativeType; if (isRecord(datum)) return getRecordSchema(datum).getFullName(); if (isEnum(datum)) return getEnumSchema(datum).getFullName(); if (isArray(datum)) return Type.ARRAY.getName(); if (isMap(datum)) return Type.MAP.getName(); if (isFixed(datum)) return getFixedSchema(datum).getFullName(); if (isString(datum)) return Type.STRING.getName(); if (isBytes(datum)) return Type.BYTES.getName(); if (isInteger(datum)) return Type.INT.getName(); if (isLong(datum)) return Type.LONG.getName(); if (isFloat(datum)) return Type.FLOAT.getName(); if (isDouble(datum)) return Type.DOUBLE.getName(); if (isBoolean(datum)) return Type.BOOLEAN.getName(); throw new AvroRuntimeException(String.format("Unknown datum type %s: %s", datum.getClass().getName(), datum)); } /** * Called to obtain the primitive type cache. May be overridden for alternate * record representations. */ protected Map<Class<?>, String> getPrimitiveTypeCache() { return PRIMITIVE_DATUM_TYPES; } /** * Called by {@link #resolveUnion(Schema,Object)}. May be overridden for * alternate data representations. */ protected boolean instanceOf(Schema schema, Object datum) { switch (schema.getType()) { case RECORD: if (!isRecord(datum)) return false; return (schema.getFullName() == null) ? getRecordSchema(datum).getFullName() == null : schema.getFullName().equals(getRecordSchema(datum).getFullName()); case ENUM: if (!isEnum(datum)) return false; return schema.getFullName().equals(getEnumSchema(datum).getFullName()); case ARRAY: return isArray(datum); case MAP: return isMap(datum); case FIXED: if (!isFixed(datum)) return false; return schema.getFullName().equals(getFixedSchema(datum).getFullName()); case STRING: return isString(datum); case BYTES: return isBytes(datum); case INT: return isInteger(datum); case LONG: return isLong(datum); case FLOAT: return isFloat(datum); case DOUBLE: return isDouble(datum); case BOOLEAN: return isBoolean(datum); case NULL: return datum == null; default: throw new AvroRuntimeException("Unexpected type: " + schema); } } /** Called by the default implementation of {@link #instanceOf}. */ protected boolean isArray(Object datum) { return datum instanceof Collection; } /** Called to access an array as a collection. */ protected Collection getArrayAsCollection(Object datum) { return (Collection) datum; } /** Called by the default implementation of {@link #instanceOf}. */ protected boolean isRecord(Object datum) { return datum instanceof IndexedRecord; } /** * Called to obtain the schema of a record. By default calls * {GenericContainer#getSchema(). May be overridden for alternate record * representations. */ protected Schema getRecordSchema(Object record) { return ((GenericContainer) record).getSchema(); } /** Called by the default implementation of {@link #instanceOf}. */ protected boolean isEnum(Object datum) { return datum instanceof GenericEnumSymbol; } /** * Called to obtain the schema of a enum. By default calls * {GenericContainer#getSchema(). May be overridden for alternate enum * representations. */ protected Schema getEnumSchema(Object enu) { return ((GenericContainer) enu).getSchema(); } /** Called by the default implementation of {@link #instanceOf}. */ protected boolean isMap(Object datum) { return datum instanceof Map; } /** Called by the default implementation of {@link #instanceOf}. */ protected boolean isFixed(Object datum) { return datum instanceof GenericFixed; } /** * Called to obtain the schema of a fixed. By default calls * {GenericContainer#getSchema(). May be overridden for alternate fixed * representations. */ protected Schema getFixedSchema(Object fixed) { return ((GenericContainer) fixed).getSchema(); } /** Called by the default implementation of {@link #instanceOf}. */ protected boolean isString(Object datum) { return datum instanceof CharSequence; } /** Called by the default implementation of {@link #instanceOf}. */ protected boolean isBytes(Object datum) { return datum instanceof ByteBuffer; } /** * Called by the default implementation of {@link #instanceOf}. */ protected boolean isInteger(Object datum) { return datum instanceof Integer; } /** * Called by the default implementation of {@link #instanceOf}. */ protected boolean isLong(Object datum) { return datum instanceof Long; } /** * Called by the default implementation of {@link #instanceOf}. */ protected boolean isFloat(Object datum) { return datum instanceof Float; } /** * Called by the default implementation of {@link #instanceOf}. */ protected boolean isDouble(Object datum) { return datum instanceof Double; } /** * Called by the default implementation of {@link #instanceOf}. */ protected boolean isBoolean(Object datum) { return datum instanceof Boolean; } /** * Compute a hash code according to a schema, consistent with * {@link #compare(Object,Object,Schema)}. */ public int hashCode(Object o, Schema s) { HashCodeCalculator calculator = new HashCodeCalculator(); return calculator.hashCode(o, s); } class HashCodeCalculator { private int counter = 10; private int currentHashCode = 1; public int hashCode(Object o, Schema s) { if (o == null) return 0; // incomplete datum switch (s.getType()) { case RECORD: for (Field f : s.getFields()) { if (this.shouldStop()) { return this.currentHashCode; } if (f.order() == Field.Order.IGNORE) continue; Object fieldValue = ((IndexedRecord) o).get(f.pos()); this.currentHashCode = this.hashCodeAdd(fieldValue, f.schema()); } return currentHashCode; case ARRAY: Collection<?> a = (Collection<?>) o; Schema elementType = s.getElementType(); for (Object e : a) { if (this.shouldStop()) { return currentHashCode; } currentHashCode = this.hashCodeAdd(e, elementType); } return currentHashCode; case UNION: return hashCode(o, s.getTypes().get(GenericData.this.resolveUnion(s, o))); case ENUM: return s.getEnumOrdinal(o.toString()); case NULL: return 0; case STRING: return (o instanceof Utf8 ? o : new Utf8(o.toString())).hashCode(); default: return o.hashCode(); } } /** Add the hash code for an object into an accumulated hash code. */ protected int hashCodeAdd(Object o, Schema s) { return 31 * this.currentHashCode + hashCode(o, s); } private boolean shouldStop() { return --counter <= 0; } } /** * Compare objects according to their schema. If equal, return zero. If * greater-than, return 1, if less than return -1. Order is consistent with that * of {@link BinaryData#compare(byte[], int, byte[], int, Schema)}. */ public int compare(Object o1, Object o2, Schema s) { return compare(o1, o2, s, false); } protected int compareMaps(final Map<?, ?> m1, final Map<?, ?> m2) { if (m1 == m2) { return 0; } if (m1.isEmpty() && m2.isEmpty()) { return 0; } if (m1.size() != m2.size()) { return 1; } /** * Peek at keys, assuming they're all the same type within a Map */ final Object key1 = m1.keySet().iterator().next(); final Object key2 = m2.keySet().iterator().next(); boolean utf8ToString = false; boolean stringToUtf8 = false; if (key1 instanceof Utf8 && key2 instanceof String) { utf8ToString = true; } else if (key1 instanceof String && key2 instanceof Utf8) { stringToUtf8 = true; } try { for (Map.Entry e : m1.entrySet()) { final Object key = e.getKey(); Object lookupKey = key; if (utf8ToString) { lookupKey = key.toString(); } else if (stringToUtf8) { lookupKey = new Utf8((String) lookupKey); } final Object value = e.getValue(); if (value == null) { if (!(m2.get(lookupKey) == null && m2.containsKey(lookupKey))) { return 1; } } else { final Object value2 = m2.get(lookupKey); if (value instanceof Utf8 && value2 instanceof String) { if (!value.toString().equals(value2)) { return 1; } } else if (value instanceof String && value2 instanceof Utf8) { if (!new Utf8((String) value).equals(value2)) { return 1; } } else { if (!value.equals(value2)) { return 1; } } } } } catch (ClassCastException unused) { return 1; } catch (NullPointerException unused) { return 1; } return 0; } /** * Comparison implementation. When equals is true, only checks for equality, not * for order. */ @SuppressWarnings(value = "unchecked") protected int compare(Object o1, Object o2, Schema s, boolean equals) { if (o1 == o2) return 0; switch (s.getType()) { case RECORD: for (Field f : s.getFields()) { if (f.order() == Field.Order.IGNORE) continue; // ignore this field int pos = f.pos(); String name = f.name(); int compare = compare(getField(o1, name, pos), getField(o2, name, pos), f.schema(), equals); if (compare != 0) // not equal return f.order() == Field.Order.DESCENDING ? -compare : compare; } return 0; case ENUM: return s.getEnumOrdinal(o1.toString()) - s.getEnumOrdinal(o2.toString()); case ARRAY: Collection a1 = (Collection) o1; Collection a2 = (Collection) o2; Iterator e1 = a1.iterator(); Iterator e2 = a2.iterator(); Schema elementType = s.getElementType(); while (e1.hasNext() && e2.hasNext()) { int compare = compare(e1.next(), e2.next(), elementType, equals); if (compare != 0) return compare; } return e1.hasNext() ? 1 : (e2.hasNext() ? -1 : 0); case MAP: if (equals) return compareMaps((Map) o1, (Map) o2); throw new AvroRuntimeException("Can't compare maps!"); case UNION: int i1 = resolveUnion(s, o1); int i2 = resolveUnion(s, o2); return (i1 == i2) ? compare(o1, o2, s.getTypes().get(i1), equals) : Integer.compare(i1, i2); case NULL: return 0; case STRING: Utf8 u1 = o1 instanceof Utf8 ? (Utf8) o1 : new Utf8(o1.toString()); Utf8 u2 = o2 instanceof Utf8 ? (Utf8) o2 : new Utf8(o2.toString()); return u1.compareTo(u2); default: return ((Comparable) o1).compareTo(o2); } } private final ConcurrentMap<Field, Object> defaultValueCache = new ConcurrentReferenceHashMap<>(128, WEAK); /** * Gets the default value of the given field, if any. * * @param field the field whose default value should be retrieved. * @return the default value associated with the given field, or null if none is * specified in the schema. */ @SuppressWarnings({ "unchecked" }) public Object getDefaultValue(Field field) { JsonNode json = Accessor.defaultValue(field); if (json == null) throw new AvroMissingFieldException("Field " + field + " not set and has no default value", field); if (json.isNull() && (field.schema().getType() == Type.NULL || (field.schema().getType() == Type.UNION && field.schema().getTypes().get(0).getType() == Type.NULL))) { return null; } // Check the cache // If not cached, get the default Java value by encoding the default JSON // value and then decoding it: return defaultValueCache.computeIfAbsent(field, fieldToGetValueFor -> { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(baos, null); Accessor.encode(encoder, fieldToGetValueFor.schema(), json); encoder.flush(); BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(baos.toByteArray(), null); return createDatumReader(fieldToGetValueFor.schema()).read(null, decoder); } catch (IOException e) { throw new AvroRuntimeException(e); } }); } private static final Schema STRINGS = Schema.create(Type.STRING); /** * Makes a deep copy of a value given its schema. * <P> * Logical types are converted to raw types, copied, then converted back. * * @param schema the schema of the value to deep copy. * @param value the value to deep copy. * @return a deep copy of the given value. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public <T> T deepCopy(Schema schema, T value) { if (value == null) return null; LogicalType logicalType = schema.getLogicalType(); if (logicalType == null) // not a logical type -- use raw copy return (T) deepCopyRaw(schema, value); Conversion conversion = getConversionByClass(value.getClass(), logicalType); if (conversion == null) // no conversion defined -- try raw copy return (T) deepCopyRaw(schema, value); // logical type with conversion: convert to raw, copy, then convert back to // logical Object raw = Conversions.convertToRawType(value, schema, logicalType, conversion); Object copy = deepCopyRaw(schema, raw); // copy raw return (T) Conversions.convertToLogicalType(copy, schema, logicalType, conversion); } private Object deepCopyRaw(Schema schema, Object value) { if (value == null) { return null; } switch (schema.getType()) { case ARRAY: List<Object> arrayValue = (List) value; List<Object> arrayCopy = new GenericData.Array<>(arrayValue.size(), schema); for (Object obj : arrayValue) { arrayCopy.add(deepCopy(schema.getElementType(), obj)); } return arrayCopy; case BOOLEAN: return value; // immutable case BYTES: ByteBuffer byteBufferValue = (ByteBuffer) value; int start = byteBufferValue.position(); int length = byteBufferValue.limit() - start; byte[] bytesCopy = new byte[length]; byteBufferValue.get(bytesCopy, 0, length); ((Buffer) byteBufferValue).position(start); return ByteBuffer.wrap(bytesCopy, 0, length); case DOUBLE: return value; // immutable case ENUM: return createEnum(value.toString(), schema); case FIXED: return createFixed(null, ((GenericFixed) value).bytes(), schema); case FLOAT: return value; // immutable case INT: return value; // immutable case LONG: return value; // immutable case MAP: Map<Object, Object> mapValue = (Map) value; Map<Object, Object> mapCopy = new HashMap<>(mapValue.size()); for (Map.Entry<Object, Object> entry : mapValue.entrySet()) { mapCopy.put(deepCopy(STRINGS, entry.getKey()), deepCopy(schema.getValueType(), entry.getValue())); } return mapCopy; case NULL: return null; case RECORD: Object oldState = getRecordState(value, schema); Object newRecord = newRecord(null, schema); Object newState = getRecordState(newRecord, schema); for (Field f : schema.getFields()) { int pos = f.pos(); String name = f.name(); Object newValue = deepCopy(f.schema(), getField(value, name, pos, oldState)); setField(newRecord, name, pos, newValue, newState); } return newRecord; case STRING: return createString(value); case UNION: return deepCopy(schema.getTypes().get(resolveUnion(schema, value)), value); default: throw new AvroRuntimeException("Deep copy failed for schema \"" + schema + "\" and value \"" + value + "\""); } } /** * Called to create an fixed value. May be overridden for alternate fixed * representations. By default, returns {@link GenericFixed}. */ public Object createFixed(Object old, Schema schema) { if ((old instanceof GenericFixed) && ((GenericFixed) old).bytes().length == schema.getFixedSize()) return old; return new GenericData.Fixed(schema); } /** * Called to create an fixed value. May be overridden for alternate fixed * representations. By default, returns {@link GenericFixed}. */ public Object createFixed(Object old, byte[] bytes, Schema schema) { GenericFixed fixed = (GenericFixed) createFixed(old, schema); System.arraycopy(bytes, 0, fixed.bytes(), 0, schema.getFixedSize()); return fixed; } /** * Called to create an enum value. May be overridden for alternate enum * representations. By default, returns a GenericEnumSymbol. */ public Object createEnum(String symbol, Schema schema) { return new EnumSymbol(schema, symbol); } /** * Called to create new record instances. Subclasses may override to use a * different record implementation. The returned instance must conform to the * schema provided. If the old object contains fields not present in the schema, * they should either be removed from the old object, or it should create a new * instance that conforms to the schema. By default, this returns a * {@link GenericData.Record}. */ public Object newRecord(Object old, Schema schema) { if (old instanceof IndexedRecord) { IndexedRecord record = (IndexedRecord) old; if (record.getSchema() == schema) return record; } return new GenericData.Record(schema); } /** * Called to create an string value. May be overridden for alternate string * representations. */ public Object createString(Object value) { // Strings are immutable if (value instanceof String) { return value; } // Some CharSequence subclasses are mutable, so we still need to make // a copy else if (value instanceof Utf8) { // Utf8 copy constructor is more efficient than converting // to string and then back to Utf8 return new Utf8((Utf8) value); } return new Utf8(value.toString()); } /* * Called to create new array instances. Subclasses may override to use a * different array implementation. By default, this returns a {@link * GenericData.Array}. */ public Object newArray(Object old, int size, Schema schema) { if (old instanceof GenericArray) { ((GenericArray<?>) old).reset(); return old; } else if (old instanceof Collection) { ((Collection<?>) old).clear(); return old; } else { if (schema.getElementType().getType() == Type.INT) { return new PrimitivesArrays.IntArray(size, schema); } if (schema.getElementType().getType() == Type.BOOLEAN) { return new PrimitivesArrays.BooleanArray(size, schema); } if (schema.getElementType().getType() == Type.LONG) { return new PrimitivesArrays.LongArray(size, schema); } if (schema.getElementType().getType() == Type.FLOAT) { return new PrimitivesArrays.FloatArray(size, schema); } if (schema.getElementType().getType() == Type.DOUBLE) { return new PrimitivesArrays.DoubleArray(size, schema); } return new GenericData.Array<Object>(size, schema); } } /** * Called to create new array instances. Subclasses may override to use a * different map implementation. By default, this returns a {@link HashMap}. */ public Object newMap(Object old, int size) { if (old instanceof Map) { ((Map<?, ?>) old).clear(); return old; } else return new HashMap<>(size); } /** * create a supplier that allows to get new record instances for a given schema * in an optimized way */ public InstanceSupplier getNewRecordSupplier(Schema schema) { return this::newRecord; } public interface InstanceSupplier { public Object newInstance(Object oldInstance, Schema schema); } }
7,384
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/generic/GenericDatumReader.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.generic; import java.io.IOException; import java.lang.reflect.Constructor; import java.nio.ByteBuffer; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import org.apache.avro.AvroRuntimeException; import org.apache.avro.Conversion; import org.apache.avro.Conversions; import org.apache.avro.LogicalType; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.io.DatumReader; import org.apache.avro.io.Decoder; import org.apache.avro.io.DecoderFactory; import org.apache.avro.io.ResolvingDecoder; import org.apache.avro.util.Utf8; import org.apache.avro.util.WeakIdentityHashMap; import org.apache.avro.util.internal.ThreadLocalWithInitial; /** {@link DatumReader} for generic Java objects. */ public class GenericDatumReader<D> implements DatumReader<D> { private final GenericData data; private Schema actual; private Schema expected; private DatumReader<D> fastDatumReader = null; private ResolvingDecoder creatorResolver = null; private final Thread creator; public GenericDatumReader() { this(null, null, GenericData.get()); } /** Construct where the writer's and reader's schemas are the same. */ public GenericDatumReader(Schema schema) { this(schema, schema, GenericData.get()); } /** Construct given writer's and reader's schema. */ public GenericDatumReader(Schema writer, Schema reader) { this(writer, reader, GenericData.get()); } public GenericDatumReader(Schema writer, Schema reader, GenericData data) { this(data); this.actual = writer; this.expected = reader; } protected GenericDatumReader(GenericData data) { this.data = data; this.creator = Thread.currentThread(); } /** Return the {@link GenericData} implementation. */ public GenericData getData() { return data; } /** Return the writer's schema. */ public Schema getSchema() { return actual; } @Override public void setSchema(Schema writer) { this.actual = writer; if (expected == null) { expected = actual; } creatorResolver = null; fastDatumReader = null; } /** Get the reader's schema. */ public Schema getExpected() { return expected; } /** Set the reader's schema. */ public void setExpected(Schema reader) { this.expected = reader; creatorResolver = null; } private static final ThreadLocal<Map<Schema, Map<Schema, ResolvingDecoder>>> RESOLVER_CACHE = ThreadLocalWithInitial .of(WeakIdentityHashMap::new); /** * Gets a resolving decoder for use by this GenericDatumReader. Unstable API. * Currently uses a thread local cache to prevent constructing the resolvers too * often, because that is very expensive. */ protected final ResolvingDecoder getResolver(Schema actual, Schema expected) throws IOException { Thread currThread = Thread.currentThread(); ResolvingDecoder resolver; if (currThread == creator && creatorResolver != null) { return creatorResolver; } Map<Schema, ResolvingDecoder> cache = RESOLVER_CACHE.get().get(actual); if (cache == null) { cache = new WeakIdentityHashMap<>(); RESOLVER_CACHE.get().put(actual, cache); } resolver = cache.get(expected); if (resolver == null) { resolver = DecoderFactory.get().resolvingDecoder(Schema.applyAliases(actual, expected), expected, null); cache.put(expected, resolver); } if (currThread == creator) { creatorResolver = resolver; } return resolver; } @Override @SuppressWarnings("unchecked") public D read(D reuse, Decoder in) throws IOException { if (data.isFastReaderEnabled()) { if (this.fastDatumReader == null) { this.fastDatumReader = data.getFastReaderBuilder().createDatumReader(actual, expected); } return fastDatumReader.read(reuse, in); } ResolvingDecoder resolver = getResolver(actual, expected); resolver.configure(in); D result = (D) read(reuse, expected, resolver); resolver.drain(); return result; } /** Called to read data. */ protected Object read(Object old, Schema expected, ResolvingDecoder in) throws IOException { Object datum = readWithoutConversion(old, expected, in); LogicalType logicalType = expected.getLogicalType(); if (logicalType != null) { Conversion<?> conversion = getData().getConversionFor(logicalType); if (conversion != null) { return convert(datum, expected, logicalType, conversion); } } return datum; } protected Object readWithConversion(Object old, Schema expected, LogicalType logicalType, Conversion<?> conversion, ResolvingDecoder in) throws IOException { return convert(readWithoutConversion(old, expected, in), expected, logicalType, conversion); } protected Object readWithoutConversion(Object old, Schema expected, ResolvingDecoder in) throws IOException { switch (expected.getType()) { case RECORD: return readRecord(old, expected, in); case ENUM: return readEnum(expected, in); case ARRAY: return readArray(old, expected, in); case MAP: return readMap(old, expected, in); case UNION: return read(old, expected.getTypes().get(in.readIndex()), in); case FIXED: return readFixed(old, expected, in); case STRING: return readString(old, expected, in); case BYTES: return readBytes(old, expected, in); case INT: return readInt(old, expected, in); case LONG: return in.readLong(); case FLOAT: return in.readFloat(); case DOUBLE: return in.readDouble(); case BOOLEAN: return in.readBoolean(); case NULL: in.readNull(); return null; default: throw new AvroRuntimeException("Unknown type: " + expected); } } /** * Convert an underlying representation of a logical type (such as a ByteBuffer) * to a higher level object (such as a BigDecimal). * * @throws IllegalArgumentException if a null schema or logicalType is passed in * while datum and conversion are not null. * Please be noticed that the exception type * has changed. With version 1.8.0 and earlier, * in above circumstance, the exception thrown * out depends on the implementation of * conversion (most likely a * NullPointerException). Now, an * IllegalArgumentException will be thrown out * instead. */ protected Object convert(Object datum, Schema schema, LogicalType type, Conversion<?> conversion) { return Conversions.convertToLogicalType(datum, schema, type, conversion); } /** * Called to read a record instance. May be overridden for alternate record * representations. */ protected Object readRecord(Object old, Schema expected, ResolvingDecoder in) throws IOException { final Object record = data.newRecord(old, expected); final Object state = data.getRecordState(record, expected); for (Field field : in.readFieldOrder()) { int pos = field.pos(); String name = field.name(); Object oldDatum = null; if (old != null) { oldDatum = data.getField(record, name, pos, state); } readField(record, field, oldDatum, in, state); } return record; } /** * Called to read a single field of a record. May be overridden for more * efficient or alternate implementations. */ protected void readField(Object record, Field field, Object oldDatum, ResolvingDecoder in, Object state) throws IOException { data.setField(record, field.name(), field.pos(), read(oldDatum, field.schema(), in), state); } /** * Called to read an enum value. May be overridden for alternate enum * representations. By default, returns a GenericEnumSymbol. */ protected Object readEnum(Schema expected, Decoder in) throws IOException { return createEnum(expected.getEnumSymbols().get(in.readEnum()), expected); } /** * Called to create an enum value. May be overridden for alternate enum * representations. By default, returns a GenericEnumSymbol. */ protected Object createEnum(String symbol, Schema schema) { return data.createEnum(symbol, schema); } /** * Called to read an array instance. May be overridden for alternate array * representations. */ protected Object readArray(Object old, Schema expected, ResolvingDecoder in) throws IOException { Schema expectedType = expected.getElementType(); long l = in.readArrayStart(); long base = 0; if (l > 0) { LogicalType logicalType = expectedType.getLogicalType(); Conversion<?> conversion = getData().getConversionFor(logicalType); Object array = newArray(old, (int) l, expected); do { if (logicalType != null && conversion != null) { for (long i = 0; i < l; i++) { addToArray(array, base + i, readWithConversion(peekArray(array), expectedType, logicalType, conversion, in)); } } else { for (long i = 0; i < l; i++) { addToArray(array, base + i, readWithoutConversion(peekArray(array), expectedType, in)); } } base += l; } while ((l = in.arrayNext()) > 0); return pruneArray(array); } else { return pruneArray(newArray(old, 0, expected)); } } private Object pruneArray(Object object) { if (object instanceof GenericArray<?>) { ((GenericArray<?>) object).prune(); } return object; } /** * Called by the default implementation of {@link #readArray} to retrieve a * value from a reused instance. The default implementation is for * {@link GenericArray}. */ @SuppressWarnings("unchecked") protected Object peekArray(Object array) { return (array instanceof GenericArray) ? ((GenericArray) array).peek() : null; } /** * Called by the default implementation of {@link #readArray} to add a value. * The default implementation is for {@link Collection}. */ @SuppressWarnings("unchecked") protected void addToArray(Object array, long pos, Object e) { ((Collection) array).add(e); } /** * Called to read a map instance. May be overridden for alternate map * representations. */ protected Object readMap(Object old, Schema expected, ResolvingDecoder in) throws IOException { Schema eValue = expected.getValueType(); long l = in.readMapStart(); LogicalType logicalType = eValue.getLogicalType(); Conversion<?> conversion = getData().getConversionFor(logicalType); Object map = newMap(old, (int) l); if (l > 0) { do { if (logicalType != null && conversion != null) { for (int i = 0; i < l; i++) { addToMap(map, readMapKey(null, expected, in), readWithConversion(null, eValue, logicalType, conversion, in)); } } else { for (int i = 0; i < l; i++) { addToMap(map, readMapKey(null, expected, in), readWithoutConversion(null, eValue, in)); } } } while ((l = in.mapNext()) > 0); } return map; } /** * Called by the default implementation of {@link #readMap} to read a key value. * The default implementation returns delegates to * {@link #readString(Object, org.apache.avro.io.Decoder)}. */ protected Object readMapKey(Object old, Schema expected, Decoder in) throws IOException { return readString(old, expected, in); } /** * Called by the default implementation of {@link #readMap} to add a key/value * pair. The default implementation is for {@link Map}. */ @SuppressWarnings("unchecked") protected void addToMap(Object map, Object key, Object value) { ((Map) map).put(key, value); } /** * Called to read a fixed value. May be overridden for alternate fixed * representations. By default, returns {@link GenericFixed}. */ protected Object readFixed(Object old, Schema expected, Decoder in) throws IOException { GenericFixed fixed = (GenericFixed) data.createFixed(old, expected); in.readFixed(fixed.bytes(), 0, expected.getFixedSize()); return fixed; } /** * Called to create an fixed value. May be overridden for alternate fixed * representations. By default, returns {@link GenericFixed}. * * @deprecated As of Avro 1.6.0 this method has been moved to * {@link GenericData#createFixed(Object, Schema)} */ @Deprecated protected Object createFixed(Object old, Schema schema) { return data.createFixed(old, schema); } /** * Called to create an fixed value. May be overridden for alternate fixed * representations. By default, returns {@link GenericFixed}. * * @deprecated As of Avro 1.6.0 this method has been moved to * {@link GenericData#createFixed(Object, byte[], Schema)} */ @Deprecated protected Object createFixed(Object old, byte[] bytes, Schema schema) { return data.createFixed(old, bytes, schema); } /** * Called to create new record instances. Subclasses may override to use a * different record implementation. The returned instance must conform to the * schema provided. If the old object contains fields not present in the schema, * they should either be removed from the old object, or it should create a new * instance that conforms to the schema. By default, this returns a * {@link GenericData.Record}. * * @deprecated As of Avro 1.6.0 this method has been moved to * {@link GenericData#newRecord(Object, Schema)} */ @Deprecated protected Object newRecord(Object old, Schema schema) { return data.newRecord(old, schema); } /** * Called to create new array instances. Subclasses may override to use a * different array implementation. By default, this returns a * {@link GenericData.Array}. */ @SuppressWarnings("unchecked") protected Object newArray(Object old, int size, Schema schema) { return data.newArray(old, size, schema); } /** * Called to create new array instances. Subclasses may override to use a * different map implementation. By default, this returns a {@link HashMap}. */ @SuppressWarnings("unchecked") protected Object newMap(Object old, int size) { return data.newMap(old, size); } /** * Called to read strings. Subclasses may override to use a different string * representation. By default, this calls {@link #readString(Object,Decoder)}. */ protected Object readString(Object old, Schema expected, Decoder in) throws IOException { Class stringClass = this.getReaderCache().getStringClass(expected); if (stringClass == String.class) { return in.readString(); } if (stringClass == CharSequence.class) { return readString(old, in); } return this.newInstanceFromString(stringClass, in.readString()); } /** * Called to read strings. Subclasses may override to use a different string * representation. By default, this calls {@link Decoder#readString(Utf8)}. */ protected Object readString(Object old, Decoder in) throws IOException { return in.readString(old instanceof Utf8 ? (Utf8) old : null); } /** * Called to create a string from a default value. Subclasses may override to * use a different string representation. By default, this calls * {@link Utf8#Utf8(String)}. */ protected Object createString(String value) { return new Utf8(value); } /** * Determines the class to used to represent a string Schema. By default uses * {@link GenericData#STRING_PROP} to determine whether {@link Utf8} or * {@link String} is used. Subclasses may override for alternate * representations. */ protected Class findStringClass(Schema schema) { String name = schema.getProp(GenericData.STRING_PROP); if (name == null) return CharSequence.class; switch (GenericData.StringType.valueOf(name)) { case String: return String.class; default: return CharSequence.class; } } /** * This class is used to reproduce part of IdentityHashMap in ConcurrentHashMap * code. */ private static final class IdentitySchemaKey { private final Schema schema; private final int hashcode; public IdentitySchemaKey(Schema schema) { this.schema = schema; this.hashcode = System.identityHashCode(schema); } @Override public int hashCode() { return this.hashcode; } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof GenericDatumReader.IdentitySchemaKey)) { return false; } IdentitySchemaKey key = (IdentitySchemaKey) obj; return this == key || this.schema == key.schema; } } // VisibleForTesting static class ReaderCache { private final Map<IdentitySchemaKey, Class> stringClassCache = new ConcurrentHashMap<>(); private final Map<Class, Function<String, Object>> stringCtorCache = new ConcurrentHashMap<>(); private final Function<Schema, Class> findStringClass; public ReaderCache(Function<Schema, Class> findStringClass) { this.findStringClass = findStringClass; } public Object newInstanceFromString(Class c, String s) { final Function<String, Object> ctor = stringCtorCache.computeIfAbsent(c, this::buildFunction); return ctor.apply(s); } private Function<String, Object> buildFunction(Class c) { final Constructor ctor; try { ctor = c.getDeclaredConstructor(String.class); } catch (NoSuchMethodException e) { throw new AvroRuntimeException(e); } ctor.setAccessible(true); return (String s) -> { try { return ctor.newInstance(s); } catch (ReflectiveOperationException e) { throw new AvroRuntimeException(e); } }; } public Class getStringClass(final Schema s) { final IdentitySchemaKey key = new IdentitySchemaKey(s); return this.stringClassCache.computeIfAbsent(key, (IdentitySchemaKey k) -> this.findStringClass.apply(k.schema)); } } private final ReaderCache readerCache = new ReaderCache(this::findStringClass); // VisibleForTesting ReaderCache getReaderCache() { return readerCache; } @SuppressWarnings("unchecked") protected Object newInstanceFromString(Class c, String s) { return this.getReaderCache().newInstanceFromString(c, s); } /** * Called to read byte arrays. Subclasses may override to use a different byte * array representation. By default, this calls * {@link Decoder#readBytes(ByteBuffer)}. */ protected Object readBytes(Object old, Schema s, Decoder in) throws IOException { return readBytes(old, in); } /** * Called to read byte arrays. Subclasses may override to use a different byte * array representation. By default, this calls * {@link Decoder#readBytes(ByteBuffer)}. */ protected Object readBytes(Object old, Decoder in) throws IOException { return in.readBytes(old instanceof ByteBuffer ? (ByteBuffer) old : null); } /** * Called to read integers. Subclasses may override to use a different integer * representation. By default, this calls {@link Decoder#readInt()}. */ protected Object readInt(Object old, Schema expected, Decoder in) throws IOException { return in.readInt(); } /** * Called to create byte arrays from default values. Subclasses may override to * use a different byte array representation. By default, this calls * {@link ByteBuffer#wrap(byte[])}. */ protected Object createBytes(byte[] value) { return ByteBuffer.wrap(value); } /** Skip an instance of a schema. */ public static void skip(Schema schema, Decoder in) throws IOException { switch (schema.getType()) { case RECORD: for (Field field : schema.getFields()) skip(field.schema(), in); break; case ENUM: in.readEnum(); break; case ARRAY: Schema elementType = schema.getElementType(); for (long l = in.skipArray(); l > 0; l = in.skipArray()) { for (long i = 0; i < l; i++) { skip(elementType, in); } } break; case MAP: Schema value = schema.getValueType(); for (long l = in.skipMap(); l > 0; l = in.skipMap()) { for (long i = 0; i < l; i++) { in.skipString(); skip(value, in); } } break; case UNION: skip(schema.getTypes().get(in.readIndex()), in); break; case FIXED: in.skipFixed(schema.getFixedSize()); break; case STRING: in.skipString(); break; case BYTES: in.skipBytes(); break; case INT: in.readInt(); break; case LONG: in.readLong(); break; case FLOAT: in.readFloat(); break; case DOUBLE: in.readDouble(); break; case BOOLEAN: in.readBoolean(); break; case NULL: in.readNull(); break; default: throw new RuntimeException("Unknown type: " + schema); } } }
7,385
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/generic/GenericEnumSymbol.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.generic; /** An enum symbol. */ public interface GenericEnumSymbol<E extends GenericEnumSymbol<E>> extends GenericContainer, Comparable<E> { /** Return the symbol. */ @Override String toString(); }
7,386
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/generic/GenericDatumWriter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.generic; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.Collection; import org.apache.avro.AvroRuntimeException; import org.apache.avro.AvroTypeException; import org.apache.avro.Conversion; import org.apache.avro.Conversions; import org.apache.avro.LogicalType; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.path.TracingAvroTypeException; import org.apache.avro.UnresolvedUnionException; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.Encoder; import org.apache.avro.path.ArrayPositionPredicate; import org.apache.avro.path.LocationStep; import org.apache.avro.path.MapKeyPredicate; import org.apache.avro.path.TracingClassCastException; import org.apache.avro.path.TracingNullPointException; import org.apache.avro.path.UnionTypePredicate; import org.apache.avro.util.SchemaUtil; /** {@link DatumWriter} for generic Java objects. */ public class GenericDatumWriter<D> implements DatumWriter<D> { private final GenericData data; private Schema root; public GenericDatumWriter() { this(GenericData.get()); } protected GenericDatumWriter(GenericData data) { this.data = data; } public GenericDatumWriter(Schema root) { this(); setSchema(root); } public GenericDatumWriter(Schema root, GenericData data) { this(data); setSchema(root); } /** Return the {@link GenericData} implementation. */ public GenericData getData() { return data; } public void setSchema(Schema root) { this.root = root; } public void write(D datum, Encoder out) throws IOException { Objects.requireNonNull(out, "Encoder cannot be null"); try { write(root, datum, out); } catch (TracingNullPointException | TracingClassCastException | TracingAvroTypeException e) { throw e.summarize(root); } } /** Called to write data. */ protected void write(Schema schema, Object datum, Encoder out) throws IOException { LogicalType logicalType = schema.getLogicalType(); if (datum != null && logicalType != null) { Conversion<?> conversion = getData().getConversionByClass(datum.getClass(), logicalType); writeWithoutConversion(schema, convert(schema, logicalType, conversion, datum), out); } else { writeWithoutConversion(schema, datum, out); } } /** * Convert a high level representation of a logical type (such as a BigDecimal) * to its underlying representation object (such as a ByteBuffer). * * @throws IllegalArgumentException if a null schema or logicalType is passed in * while datum and conversion are not null. * Please be noticed that the exception type * has changed. With version 1.8.0 and earlier, * in above circumstance, the exception thrown * out depends on the implementation of * conversion (most likely a * NullPointerException). Now, an * IllegalArgumentException will be thrown out * instead. */ protected <T> Object convert(Schema schema, LogicalType logicalType, Conversion<T> conversion, Object datum) { try { if (conversion == null) { return datum; } else { return Conversions.convertToRawType(datum, schema, logicalType, conversion); } } catch (AvroRuntimeException e) { Throwable cause = e.getCause(); if (cause != null && cause.getClass() == ClassCastException.class) { // This is to keep backwards compatibility. The convert function here used to // throw CCE. After being moved to Conversions, it throws AvroRuntimeException // instead. To keep as much same behaviour as before, this function checks if // the cause is a CCE. If yes, rethrow it in case any child class checks it. // This // behaviour can be changed later in future versions to make it consistent with // reading path, which throws AvroRuntimeException throw (ClassCastException) cause; } else { throw e; } } } /** Called to write data. */ protected void writeWithoutConversion(Schema schema, Object datum, Encoder out) throws IOException { int unionIndex = -1; Schema.Type schemaType = schema.getType(); try { switch (schemaType) { case RECORD: writeRecord(schema, datum, out); break; case ENUM: writeEnum(schema, datum, out); break; case ARRAY: writeArray(schema, datum, out); break; case MAP: writeMap(schema, datum, out); break; case UNION: unionIndex = resolveUnion(schema, datum); out.writeIndex(unionIndex); write(schema.getTypes().get(unionIndex), datum, out); break; case FIXED: writeFixed(schema, datum, out); break; case STRING: writeString(schema, datum, out); break; case BYTES: writeBytes(datum, out); break; case INT: out.writeInt(((Number) datum).intValue()); break; case LONG: out.writeLong(((Number) datum).longValue()); break; case FLOAT: out.writeFloat(((Number) datum).floatValue()); break; case DOUBLE: out.writeDouble(((Number) datum).doubleValue()); break; case BOOLEAN: out.writeBoolean((Boolean) datum); break; case NULL: out.writeNull(); break; default: error(schema, datum); } } catch (TracingNullPointException | TracingClassCastException | TracingAvroTypeException e) { if (schemaType == Schema.Type.UNION) { e.tracePath(new UnionTypePredicate(schema.getTypes().get(unionIndex).getName())); } // writeArray() and writeMap() have their own handling throw e; } catch (NullPointerException e) { throw new TracingNullPointException(e, schema, false); } catch (ClassCastException e) { throw new TracingClassCastException(e, datum, schema, false); } catch (AvroTypeException e) { throw new TracingAvroTypeException(e); } } /** Helper method for adding a message to an NPE . */ protected NullPointerException npe(NullPointerException e, String s) { NullPointerException result = new NullPointerException(e.getMessage() + s); result.initCause(e.getCause() == null ? e : e.getCause()); return result; } /** Helper method for adding a message to an Class Cast Exception . */ protected ClassCastException addClassCastMsg(ClassCastException e, String s) { ClassCastException result = new ClassCastException(e.getMessage() + s); result.initCause(e.getCause() == null ? e : e.getCause()); return result; } /** Helper method for adding a message to an Avro Type Exception . */ protected AvroTypeException addAvroTypeMsg(AvroTypeException e, String s) { AvroTypeException result = new AvroTypeException(e.getMessage() + s); result.initCause(e.getCause() == null ? e : e.getCause()); return result; } /** * Called to write a record. May be overridden for alternate record * representations. */ protected void writeRecord(Schema schema, Object datum, Encoder out) throws IOException { Object state = data.getRecordState(datum, schema); for (Field f : schema.getFields()) { writeField(datum, f, out, state); } } /** * Called to write a single field of a record. May be overridden for more * efficient or alternate implementations. */ protected void writeField(Object datum, Field f, Encoder out, Object state) throws IOException { Object value = data.getField(datum, f.name(), f.pos(), state); try { write(f.schema(), value, out); } catch (final UnresolvedUnionException uue) { // recreate it with the right field info final UnresolvedUnionException unresolvedUnionException = new UnresolvedUnionException(f.schema(), f, value); unresolvedUnionException.addSuppressed(uue); throw unresolvedUnionException; } catch (TracingNullPointException | TracingClassCastException | TracingAvroTypeException e) { e.tracePath(new LocationStep(".", f.name())); throw e; } catch (NullPointerException e) { throw npe(e, " in field " + f.name()); } catch (ClassCastException cce) { throw addClassCastMsg(cce, " in field " + f.name()); } catch (AvroTypeException ate) { throw addAvroTypeMsg(ate, " in field " + f.name()); } } /** * Called to write an enum value. May be overridden for alternate enum * representations. */ protected void writeEnum(Schema schema, Object datum, Encoder out) throws IOException { if (!data.isEnum(datum)) { AvroTypeException cause = new AvroTypeException( "value " + SchemaUtil.describe(datum) + " is not a " + SchemaUtil.describe(schema)); throw new TracingAvroTypeException(cause); } out.writeEnum(schema.getEnumOrdinal(datum.toString())); } /** * Called to write a array. May be overridden for alternate array * representations. */ protected void writeArray(Schema schema, Object datum, Encoder out) throws IOException { Schema element = schema.getElementType(); long size = getArraySize(datum); long actualSize = 0; out.writeArrayStart(); out.setItemCount(size); for (Iterator<? extends Object> it = getArrayElements(datum); it.hasNext();) { out.startItem(); try { write(element, it.next(), out); } catch (TracingNullPointException | TracingClassCastException | TracingAvroTypeException e) { e.tracePath(new ArrayPositionPredicate(actualSize)); throw e; } actualSize++; } out.writeArrayEnd(); if (actualSize != size) { throw new ConcurrentModificationException( "Size of array written was " + size + ", but number of elements written was " + actualSize + ". "); } } /** * Called to find the index for a datum within a union. By default calls * {@link GenericData#resolveUnion(Schema,Object)}. */ protected int resolveUnion(Schema union, Object datum) { return data.resolveUnion(union, datum); } /** * Called by the default implementation of {@link #writeArray} to get the size * of an array. The default implementation is for {@link Collection}. */ protected long getArraySize(Object array) { return ((Collection<?>) array).size(); } /** * Called by the default implementation of {@link #writeArray} to enumerate * array elements. The default implementation is for {@link Collection}. */ protected Iterator<?> getArrayElements(Object array) { return ((Collection<?>) array).iterator(); } /** * Called to write a map. May be overridden for alternate map representations. */ protected void writeMap(Schema schema, Object datum, Encoder out) throws IOException { Schema value = schema.getValueType(); int size = getMapSize(datum); int actualSize = 0; out.writeMapStart(); out.setItemCount(size); for (Map.Entry<Object, Object> entry : getMapEntries(datum)) { out.startItem(); String key; try { key = entry.getKey().toString(); } catch (NullPointerException npe) { TracingNullPointException tnpe = new TracingNullPointException(npe, Schema.create(Schema.Type.STRING), false); tnpe.tracePath(new MapKeyPredicate(null)); throw tnpe; } writeString(key, out); try { write(value, entry.getValue(), out); } catch (TracingNullPointException | TracingClassCastException | TracingAvroTypeException e) { e.tracePath(new MapKeyPredicate(key)); throw e; } actualSize++; } out.writeMapEnd(); if (actualSize != size) { throw new ConcurrentModificationException( "Size of map written was " + size + ", but number of entries written was " + actualSize + ". "); } } /** * Called by the default implementation of {@link #writeMap} to get the size of * a map. The default implementation is for {@link Map}. */ @SuppressWarnings("unchecked") protected int getMapSize(Object map) { return ((Map) map).size(); } /** * Called by the default implementation of {@link #writeMap} to enumerate map * elements. The default implementation is for {@link Map}. */ @SuppressWarnings("unchecked") protected Iterable<Map.Entry<Object, Object>> getMapEntries(Object map) { return ((Map) map).entrySet(); } /** * Called to write a string. May be overridden for alternate string * representations. */ protected void writeString(Schema schema, Object datum, Encoder out) throws IOException { writeString(datum, out); } /** * Called to write a string. May be overridden for alternate string * representations. */ protected void writeString(Object datum, Encoder out) throws IOException { out.writeString((CharSequence) datum); } /** * Called to write a bytes. May be overridden for alternate bytes * representations. */ protected void writeBytes(Object datum, Encoder out) throws IOException { out.writeBytes((ByteBuffer) datum); } /** * Called to write a fixed value. May be overridden for alternate fixed * representations. */ protected void writeFixed(Schema schema, Object datum, Encoder out) throws IOException { out.writeFixed(((GenericFixed) datum).bytes(), 0, schema.getFixedSize()); } private void error(Schema schema, Object datum) { throw new AvroTypeException("value " + SchemaUtil.describe(datum) + " is not a " + SchemaUtil.describe(schema)); } }
7,387
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/data/RecordBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.data; /** Interface for record builders */ public interface RecordBuilder<T> { /** * Constructs a new instance using the values set in the RecordBuilder. If a * particular value was not set and the schema defines a default value, the * default value will be used. * * @return a new instance using values set in the RecordBuilder. */ T build(); }
7,388
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/data/Json.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.data; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import org.apache.avro.util.internal.JacksonUtils; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.LongNode; import com.fasterxml.jackson.databind.node.DoubleNode; import com.fasterxml.jackson.databind.node.TextNode; import com.fasterxml.jackson.databind.node.BooleanNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.avro.Schema; import org.apache.avro.AvroRuntimeException; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.Encoder; import org.apache.avro.io.Decoder; import org.apache.avro.io.DecoderFactory; import org.apache.avro.io.ResolvingDecoder; /** Utilities for reading and writing arbitrary Json data in Avro format. */ public class Json { private Json() { } // singleton: no public ctor static final JsonFactory FACTORY = new JsonFactory(); static final ObjectMapper MAPPER = new ObjectMapper(FACTORY); /** The schema for Json data. */ public static final Schema SCHEMA; static { try { try (InputStream in = Json.class.getResourceAsStream("/org/apache/avro/data/Json.avsc")) { SCHEMA = new Schema.Parser().parse(in); } } catch (IOException e) { throw new AvroRuntimeException(e); } } /** * {@link DatumWriter} for arbitrary Json data using the object model described * in {@link org.apache.avro.JsonProperties}. */ public static class ObjectWriter implements DatumWriter<Object> { @Override public void setSchema(Schema schema) { if (!SCHEMA.equals(schema)) throw new RuntimeException("Not the Json schema: " + schema); } @Override public void write(Object datum, Encoder out) throws IOException { Json.writeObject(datum, out); } } /** * {@link DatumReader} for arbitrary Json data using the object model described * in {@link org.apache.avro.JsonProperties}. */ public static class ObjectReader implements DatumReader<Object> { private Schema written; private ResolvingDecoder resolver; @Override public void setSchema(Schema schema) { this.written = SCHEMA.equals(written) ? null : schema; } @Override public Object read(Object reuse, Decoder in) throws IOException { if (written == null) // same schema return Json.readObject(in); // use a resolver to adapt alternate version of Json schema if (resolver == null) resolver = DecoderFactory.get().resolvingDecoder(written, SCHEMA, null); resolver.configure(in); Object result = Json.readObject(resolver); resolver.drain(); return result; } } /** * Parses a JSON string and converts it to the object model described in * {@link org.apache.avro.JsonProperties}. */ public static Object parseJson(String s) { try { return JacksonUtils.toObject(MAPPER.readTree(FACTORY.createParser(s))); } catch (IOException e) { throw new RuntimeException(e); } } /** * Converts an instance of the object model described in * {@link org.apache.avro.JsonProperties} to a JSON string. */ public static String toString(Object datum) { return JacksonUtils.toJsonNode(datum).toString(); } /** Note: this enum must be kept aligned with the union in Json.avsc. */ private enum JsonType { LONG, DOUBLE, STRING, BOOLEAN, NULL, ARRAY, OBJECT } /** * Write Json data as Avro data. */ private static void write(JsonNode node, Encoder out) throws IOException { switch (node.asToken()) { case VALUE_NUMBER_INT: out.writeIndex(JsonType.LONG.ordinal()); out.writeLong(node.longValue()); break; case VALUE_NUMBER_FLOAT: out.writeIndex(JsonType.DOUBLE.ordinal()); out.writeDouble(node.doubleValue()); break; case VALUE_STRING: out.writeIndex(JsonType.STRING.ordinal()); out.writeString(node.textValue()); break; case VALUE_TRUE: out.writeIndex(JsonType.BOOLEAN.ordinal()); out.writeBoolean(true); break; case VALUE_FALSE: out.writeIndex(JsonType.BOOLEAN.ordinal()); out.writeBoolean(false); break; case VALUE_NULL: out.writeIndex(JsonType.NULL.ordinal()); out.writeNull(); break; case START_ARRAY: out.writeIndex(JsonType.ARRAY.ordinal()); out.writeArrayStart(); out.setItemCount(node.size()); for (JsonNode element : node) { out.startItem(); write(element, out); } out.writeArrayEnd(); break; case START_OBJECT: out.writeIndex(JsonType.OBJECT.ordinal()); out.writeMapStart(); out.setItemCount(node.size()); Iterator<String> i = node.fieldNames(); while (i.hasNext()) { out.startItem(); String name = i.next(); out.writeString(name); write(node.get(name), out); } out.writeMapEnd(); break; default: throw new AvroRuntimeException(node.asToken() + " unexpected: " + node); } } /** * Read Json data from Avro data. */ private static JsonNode read(Decoder in) throws IOException { switch (JsonType.values()[in.readIndex()]) { case LONG: return new LongNode(in.readLong()); case DOUBLE: return new DoubleNode(in.readDouble()); case STRING: return new TextNode(in.readString()); case BOOLEAN: return in.readBoolean() ? BooleanNode.TRUE : BooleanNode.FALSE; case NULL: in.readNull(); return NullNode.getInstance(); case ARRAY: ArrayNode array = JsonNodeFactory.instance.arrayNode(); for (long l = in.readArrayStart(); l > 0; l = in.arrayNext()) for (long i = 0; i < l; i++) array.add(read(in)); return array; case OBJECT: ObjectNode object = JsonNodeFactory.instance.objectNode(); for (long l = in.readMapStart(); l > 0; l = in.mapNext()) for (long i = 0; i < l; i++) object.set(in.readString(), read(in)); return object; default: throw new AvroRuntimeException("Unexpected Json node type"); } } private static void writeObject(Object datum, Encoder out) throws IOException { write(JacksonUtils.toJsonNode(datum), out); } private static Object readObject(Decoder in) throws IOException { return JacksonUtils.toObject(read(in)); } }
7,389
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/data/TimeConversions.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.data; import org.apache.avro.Conversion; import org.apache.avro.LogicalType; import org.apache.avro.LogicalTypes; import org.apache.avro.Schema; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneOffset; import java.util.concurrent.TimeUnit; public class TimeConversions { public static class DateConversion extends Conversion<LocalDate> { @Override public Class<LocalDate> getConvertedType() { return LocalDate.class; } @Override public String getLogicalTypeName() { return "date"; } @Override public LocalDate fromInt(Integer daysFromEpoch, Schema schema, LogicalType type) { return LocalDate.ofEpochDay(daysFromEpoch); } @Override public Integer toInt(LocalDate date, Schema schema, LogicalType type) { long epochDays = date.toEpochDay(); return (int) epochDays; } @Override public Schema getRecommendedSchema() { return LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT)); } } public static class TimeMillisConversion extends Conversion<LocalTime> { @Override public Class<LocalTime> getConvertedType() { return LocalTime.class; } @Override public String getLogicalTypeName() { return "time-millis"; } @Override public String adjustAndSetValue(String varName, String valParamName) { return varName + " = " + valParamName + ".truncatedTo(java.time.temporal.ChronoUnit.MILLIS);"; } @Override public LocalTime fromInt(Integer millisFromMidnight, Schema schema, LogicalType type) { return LocalTime.ofNanoOfDay(TimeUnit.MILLISECONDS.toNanos(millisFromMidnight)); } @Override public Integer toInt(LocalTime time, Schema schema, LogicalType type) { return (int) TimeUnit.NANOSECONDS.toMillis(time.toNanoOfDay()); } @Override public Schema getRecommendedSchema() { return LogicalTypes.timeMillis().addToSchema(Schema.create(Schema.Type.INT)); } } public static class TimeMicrosConversion extends Conversion<LocalTime> { @Override public Class<LocalTime> getConvertedType() { return LocalTime.class; } @Override public String getLogicalTypeName() { return "time-micros"; } @Override public String adjustAndSetValue(String varName, String valParamName) { return varName + " = " + valParamName + ".truncatedTo(java.time.temporal.ChronoUnit.MICROS);"; } @Override public LocalTime fromLong(Long microsFromMidnight, Schema schema, LogicalType type) { return LocalTime.ofNanoOfDay(TimeUnit.MICROSECONDS.toNanos(microsFromMidnight)); } @Override public Long toLong(LocalTime time, Schema schema, LogicalType type) { return TimeUnit.NANOSECONDS.toMicros(time.toNanoOfDay()); } @Override public Schema getRecommendedSchema() { return LogicalTypes.timeMicros().addToSchema(Schema.create(Schema.Type.LONG)); } } public static class TimestampMillisConversion extends Conversion<Instant> { @Override public Class<Instant> getConvertedType() { return Instant.class; } @Override public String getLogicalTypeName() { return "timestamp-millis"; } @Override public String adjustAndSetValue(String varName, String valParamName) { return varName + " = " + valParamName + ".truncatedTo(java.time.temporal.ChronoUnit.MILLIS);"; } @Override public Instant fromLong(Long millisFromEpoch, Schema schema, LogicalType type) { return Instant.ofEpochMilli(millisFromEpoch); } @Override public Long toLong(Instant timestamp, Schema schema, LogicalType type) { return timestamp.toEpochMilli(); } @Override public Schema getRecommendedSchema() { return LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG)); } } public static class TimestampMicrosConversion extends Conversion<Instant> { @Override public Class<Instant> getConvertedType() { return Instant.class; } @Override public String getLogicalTypeName() { return "timestamp-micros"; } @Override public String adjustAndSetValue(String varName, String valParamName) { return varName + " = " + valParamName + ".truncatedTo(java.time.temporal.ChronoUnit.MICROS);"; } @Override public Instant fromLong(Long microsFromEpoch, Schema schema, LogicalType type) { long epochSeconds = microsFromEpoch / (1_000_000L); long nanoAdjustment = (microsFromEpoch % (1_000_000L)) * 1_000L; return Instant.ofEpochSecond(epochSeconds, nanoAdjustment); } @Override public Long toLong(Instant instant, Schema schema, LogicalType type) { long seconds = instant.getEpochSecond(); int nanos = instant.getNano(); if (seconds < 0 && nanos > 0) { long micros = Math.multiplyExact(seconds + 1, 1_000_000L); long adjustment = (nanos / 1_000L) - 1_000_000; return Math.addExact(micros, adjustment); } else { long micros = Math.multiplyExact(seconds, 1_000_000L); return Math.addExact(micros, nanos / 1_000L); } } @Override public Schema getRecommendedSchema() { return LogicalTypes.timestampMicros().addToSchema(Schema.create(Schema.Type.LONG)); } } public static class LocalTimestampMillisConversion extends Conversion<LocalDateTime> { private final TimestampMillisConversion timestampMillisConversion = new TimestampMillisConversion(); @Override public Class<LocalDateTime> getConvertedType() { return LocalDateTime.class; } @Override public String getLogicalTypeName() { return "local-timestamp-millis"; } @Override public LocalDateTime fromLong(Long millisFromEpoch, Schema schema, LogicalType type) { Instant instant = timestampMillisConversion.fromLong(millisFromEpoch, schema, type); return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); } @Override public Long toLong(LocalDateTime timestamp, Schema schema, LogicalType type) { Instant instant = timestamp.toInstant(ZoneOffset.UTC); return timestampMillisConversion.toLong(instant, schema, type); } @Override public Schema getRecommendedSchema() { return LogicalTypes.localTimestampMillis().addToSchema(Schema.create(Schema.Type.LONG)); } } public static class LocalTimestampMicrosConversion extends Conversion<LocalDateTime> { private final TimestampMicrosConversion timestampMicrosConversion = new TimestampMicrosConversion(); @Override public Class<LocalDateTime> getConvertedType() { return LocalDateTime.class; } @Override public String getLogicalTypeName() { return "local-timestamp-micros"; } @Override public LocalDateTime fromLong(Long microsFromEpoch, Schema schema, LogicalType type) { Instant instant = timestampMicrosConversion.fromLong(microsFromEpoch, schema, type); return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); } @Override public Long toLong(LocalDateTime timestamp, Schema schema, LogicalType type) { Instant instant = timestamp.toInstant(ZoneOffset.UTC); return timestampMicrosConversion.toLong(instant, schema, type); } @Override public Schema getRecommendedSchema() { return LogicalTypes.localTimestampMicros().addToSchema(Schema.create(Schema.Type.LONG)); } } }
7,390
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/data/ErrorBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.data; /** Interface for error builders */ public interface ErrorBuilder<T> extends RecordBuilder<T> { /** Gets the value */ Object getValue(); /** Sets the value */ ErrorBuilder<T> setValue(Object value); /** Checks whether the value has been set */ boolean hasValue(); /** Clears the value */ ErrorBuilder<T> clearValue(); /** Gets the error cause */ Throwable getCause(); /** Sets the error cause */ ErrorBuilder<T> setCause(Throwable cause); /** Checks whether the cause has been set */ boolean hasCause(); /** Clears the cause */ ErrorBuilder<T> clearCause(); }
7,391
0
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro
Create_ds/avro/lang/java/avro/src/main/java/org/apache/avro/data/RecordBuilderBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.data; import org.apache.avro.AvroRuntimeException; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.Schema.Type; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.IndexedRecord; import java.io.IOException; import java.util.Arrays; /** Abstract base class for RecordBuilder implementations. Not thread-safe. */ public abstract class RecordBuilderBase<T extends IndexedRecord> implements RecordBuilder<T> { private final Schema schema; private final Field[] fields; private final boolean[] fieldSetFlags; private final GenericData data; protected final Schema schema() { return schema; } protected final Field[] fields() { return fields; } protected final boolean[] fieldSetFlags() { return fieldSetFlags; } protected final GenericData data() { return data; } /** * Creates a RecordBuilderBase for building records of the given type. * * @param schema the schema associated with the record class. */ protected RecordBuilderBase(Schema schema, GenericData data) { this.schema = schema; this.data = data; fields = schema.getFields().toArray(new Field[0]); fieldSetFlags = new boolean[fields.length]; } /** * RecordBuilderBase copy constructor. Makes a deep copy of the values in the * other builder. * * @param other RecordBuilderBase instance to copy. */ protected RecordBuilderBase(RecordBuilderBase<T> other, GenericData data) { this.schema = other.schema; this.data = data; fields = schema.getFields().toArray(new Field[0]); fieldSetFlags = Arrays.copyOf(other.fieldSetFlags, other.fieldSetFlags.length); } /** * Validates that a particular value for a given field is valid according to the * following algorithm: 1. If the value is not null, or the field type is null, * or the field type is a union which accepts nulls, returns. 2. Else, if the * field has a default value, returns. 3. Otherwise throws AvroRuntimeException. * * @param field the field to validate. * @param value the value to validate. * @throws AvroRuntimeException if value is null and the given field does not * accept null values. */ protected void validate(Field field, Object value) { if (!isValidValue(field, value) && field.defaultVal() == null) { throw new AvroRuntimeException("Field " + field + " does not accept null values"); } } /** * Tests whether a value is valid for a specified field. * * @param f the field for which to test the value. * @param value the value to test. * @return true if the value is valid for the given field; false otherwise. */ protected static boolean isValidValue(Field f, Object value) { if (value != null) { return true; } Schema schema = f.schema(); Type type = schema.getType(); // If the type is null, any value is valid if (type == Type.NULL) { return true; } // If the type is a union that allows nulls, any value is valid if (type == Type.UNION) { for (Schema s : schema.getTypes()) { if (s.getType() == Type.NULL) { return true; } } } // The value is null but the type does not allow nulls return false; } /** * Gets the default value of the given field, if any. * * @param field the field whose default value should be retrieved. * @return the default value associated with the given field, or null if none is * specified in the schema. * @throws IOException */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected Object defaultValue(Field field) throws IOException { return data.deepCopy(field.schema(), data.getDefaultValue(field)); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(fieldSetFlags); result = prime * result + ((schema == null) ? 0 : schema.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; @SuppressWarnings("rawtypes") RecordBuilderBase other = (RecordBuilderBase) obj; if (!Arrays.equals(fieldSetFlags, other.fieldSetFlags)) return false; if (schema == null) { return other.schema == null; } else { return schema.equals(other.schema); } } }
7,392
0
Create_ds/avro/lang/java/trevni/core/src/test/java/org/apache
Create_ds/avro/lang/java/trevni/core/src/test/java/org/apache/trevni/TestColumnFile.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.trevni; import java.io.File; import java.util.Random; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.runners.Parameterized.Parameters; public class TestColumnFile { private static final File FILE = new File("target", "test.trv"); private static final int COUNT = 1024 * 64; @Parameters public static Stream<Arguments> codecs() { return Stream.of(Arguments.of(createFileMeta("null", "null")), Arguments.of(createFileMeta("snappy", "crc32")), Arguments.of(createFileMeta("deflate", "crc32"))); } private static ColumnFileMetaData createFileMeta(String codec, String checksum) { return new ColumnFileMetaData().setCodec(codec).setChecksum(checksum); } @ParameterizedTest @MethodSource("codecs") void emptyFile(ColumnFileMetaData fileMeta) throws Exception { FILE.delete(); ColumnFileWriter out = new ColumnFileWriter(fileMeta); out.writeTo(FILE); ColumnFileReader in = new ColumnFileReader(FILE); Assertions.assertEquals(0, in.getRowCount()); Assertions.assertEquals(0, in.getColumnCount()); in.close(); } @ParameterizedTest @MethodSource("codecs") void emptyColumn(ColumnFileMetaData fileMeta) throws Exception { FILE.delete(); ColumnFileWriter out = new ColumnFileWriter(fileMeta, new ColumnMetaData("test", ValueType.INT)); out.writeTo(FILE); ColumnFileReader in = new ColumnFileReader(FILE); Assertions.assertEquals(0, in.getRowCount()); Assertions.assertEquals(1, in.getColumnCount()); ColumnValues<Integer> values = in.getValues("test"); for (int i : values) throw new Exception("no value should be found"); in.close(); } @ParameterizedTest @MethodSource("codecs") void ints(ColumnFileMetaData fileMeta) throws Exception { FILE.delete(); ColumnFileWriter out = new ColumnFileWriter(fileMeta, new ColumnMetaData("test", ValueType.INT)); Random random = TestUtil.createRandom(); for (int i = 0; i < COUNT; i++) out.writeRow(TestUtil.randomLength(random)); out.writeTo(FILE); random = TestUtil.createRandom(); ColumnFileReader in = new ColumnFileReader(FILE); Assertions.assertEquals(COUNT, in.getRowCount()); Assertions.assertEquals(1, in.getColumnCount()); Iterator<Integer> i = in.getValues("test"); int count = 0; while (i.hasNext()) { Assertions.assertEquals(TestUtil.randomLength(random), (int) i.next()); count++; } Assertions.assertEquals(COUNT, count); } @ParameterizedTest @MethodSource("codecs") void longs(ColumnFileMetaData fileMeta) throws Exception { FILE.delete(); ColumnFileWriter out = new ColumnFileWriter(fileMeta, new ColumnMetaData("test", ValueType.LONG)); Random random = TestUtil.createRandom(); for (int i = 0; i < COUNT; i++) out.writeRow(random.nextLong()); out.writeTo(FILE); random = TestUtil.createRandom(); ColumnFileReader in = new ColumnFileReader(FILE); Assertions.assertEquals(COUNT, in.getRowCount()); Assertions.assertEquals(1, in.getColumnCount()); Iterator<Long> i = in.getValues("test"); int count = 0; while (i.hasNext()) { Assertions.assertEquals(random.nextLong(), (long) i.next()); count++; } Assertions.assertEquals(COUNT, count); } @ParameterizedTest @MethodSource("codecs") void strings(ColumnFileMetaData fileMeta) throws Exception { FILE.delete(); ColumnFileWriter out = new ColumnFileWriter(fileMeta, new ColumnMetaData("test", ValueType.STRING)); Random random = TestUtil.createRandom(); for (int i = 0; i < COUNT; i++) out.writeRow(TestUtil.randomString(random)); out.writeTo(FILE); random = TestUtil.createRandom(); ColumnFileReader in = new ColumnFileReader(FILE); Assertions.assertEquals(COUNT, in.getRowCount()); Assertions.assertEquals(1, in.getColumnCount()); Iterator<String> i = in.getValues("test"); int count = 0; while (i.hasNext()) { Assertions.assertEquals(TestUtil.randomString(random), i.next()); count++; } Assertions.assertEquals(COUNT, count); } @ParameterizedTest @MethodSource("codecs") void twoColumn(ColumnFileMetaData fileMeta) throws Exception { FILE.delete(); ColumnFileWriter out = new ColumnFileWriter(fileMeta, new ColumnMetaData("a", ValueType.FIXED32), new ColumnMetaData("b", ValueType.STRING)); Random random = TestUtil.createRandom(); for (int i = 0; i < COUNT; i++) out.writeRow(random.nextInt(), TestUtil.randomString(random)); out.writeTo(FILE); random = TestUtil.createRandom(); ColumnFileReader in = new ColumnFileReader(FILE); Assertions.assertEquals(COUNT, in.getRowCount()); Assertions.assertEquals(2, in.getColumnCount()); Iterator<String> i = in.getValues("a"); Iterator<String> j = in.getValues("b"); int count = 0; while (i.hasNext() && j.hasNext()) { Assertions.assertEquals(random.nextInt(), i.next()); Assertions.assertEquals(TestUtil.randomString(random), j.next()); count++; } Assertions.assertEquals(COUNT, count); } @ParameterizedTest @MethodSource("codecs") void seekLongs(ColumnFileMetaData fileMeta) throws Exception { FILE.delete(); ColumnFileWriter out = new ColumnFileWriter(fileMeta, new ColumnMetaData("test", ValueType.LONG)); Random random = TestUtil.createRandom(); int seekCount = COUNT / 1024; int[] seekRows = new int[seekCount]; Map<Integer, Integer> seekRowMap = new HashMap<>(seekCount); while (seekRowMap.size() < seekCount) { int row = random.nextInt(COUNT); if (!seekRowMap.containsKey(row)) { seekRows[seekRowMap.size()] = row; seekRowMap.put(row, seekRowMap.size()); } } Long[] seekValues = new Long[seekCount]; for (int i = 0; i < COUNT; i++) { long l = random.nextLong(); out.writeRow(l); if (seekRowMap.containsKey(i)) seekValues[seekRowMap.get(i)] = l; } out.writeTo(FILE); ColumnFileReader in = new ColumnFileReader(FILE); ColumnValues<Long> v = in.getValues("test"); for (int i = 0; i < seekCount; i++) { v.seek(seekRows[i]); Assertions.assertEquals(seekValues[i], v.next()); } } @ParameterizedTest @MethodSource("codecs") void seekStrings(ColumnFileMetaData fileMeta) throws Exception { FILE.delete(); ColumnFileWriter out = new ColumnFileWriter(fileMeta, new ColumnMetaData("test", ValueType.STRING).hasIndexValues(true)); Random random = TestUtil.createRandom(); int seekCount = COUNT / 1024; Map<Integer, Integer> seekRowMap = new HashMap<>(seekCount); while (seekRowMap.size() < seekCount) { int row = random.nextInt(COUNT); if (!seekRowMap.containsKey(row)) seekRowMap.put(row, seekRowMap.size()); } String[] values = new String[COUNT]; for (int i = 0; i < COUNT; i++) values[i] = TestUtil.randomString(random); Arrays.sort(values); String[] seekValues = new String[seekCount]; for (int i = 0; i < COUNT; i++) { out.writeRow(values[i]); if (seekRowMap.containsKey(i)) seekValues[seekRowMap.get(i)] = values[i]; } out.writeTo(FILE); ColumnFileReader in = new ColumnFileReader(FILE); ColumnValues<String> v = in.getValues("test"); for (int i = 0; i < seekCount; i++) { v.seek(seekValues[i]); Assertions.assertEquals(seekValues[i], v.next()); } } }
7,393
0
Create_ds/avro/lang/java/trevni/core/src/test/java/org/apache
Create_ds/avro/lang/java/trevni/core/src/test/java/org/apache/trevni/TestAllCodecs.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.trevni; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; import java.nio.Buffer; import java.nio.ByteBuffer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class TestAllCodecs { public static Codec getCodec(String name) { MetaData m = new MetaData(); m.put(MetaData.CODEC_KEY, name.getBytes()); return Codec.get(m); } @ParameterizedTest @ValueSource(strings = { "bzip2", "null", "snappy", "deflate" }) public void testCodec(String codec) throws IOException { int inputSize = 500_000; byte[] input = generateTestData(inputSize); Codec codecInstance = getCodec(codec); ByteBuffer inputByteBuffer = ByteBuffer.wrap(input); ByteBuffer compressedBuffer = codecInstance.compress(inputByteBuffer); int compressedSize = compressedBuffer.remaining(); // Make sure something returned assertTrue(compressedSize > 0); // While the compressed size could in many real cases // *increase* compared to the input size, our input data // is extremely easy to compress and all Avro's compression algorithms // should have a compression ratio greater than 1 (except 'null'). assertTrue(compressedSize < inputSize || codec.equals("null")); // Decompress the data ByteBuffer decompressedBuffer = codecInstance.decompress(compressedBuffer); // Validate the the input and output are equal. ((Buffer) inputByteBuffer).rewind(); assertEquals(decompressedBuffer, inputByteBuffer); } @ParameterizedTest @ValueSource(strings = { "bzip2", "null", "snappy", "deflate" }) public void testCodecSlice(String codec) throws IOException { int inputSize = 500_000; byte[] input = generateTestData(inputSize); Codec codecInstance = getCodec(codec); ByteBuffer partialBuffer = ByteBuffer.wrap(input); ((Buffer) partialBuffer).position(17); ByteBuffer inputByteBuffer = partialBuffer.slice(); ByteBuffer compressedBuffer = codecInstance.compress(inputByteBuffer); int compressedSize = compressedBuffer.remaining(); // Make sure something returned assertTrue(compressedSize > 0); // Create a slice from the compressed buffer ByteBuffer sliceBuffer = ByteBuffer.allocate(compressedSize + 100); ((Buffer) sliceBuffer).position(50); sliceBuffer.put(compressedBuffer); ((Buffer) sliceBuffer).limit(compressedSize + 50); ((Buffer) sliceBuffer).position(50); // Decompress the data ByteBuffer decompressedBuffer = codecInstance.decompress(sliceBuffer.slice()); // Validate the the input and output are equal. ((Buffer) inputByteBuffer).rewind(); assertEquals(decompressedBuffer, inputByteBuffer); } // Generate some test data that will compress easily public static byte[] generateTestData(int inputSize) { byte[] arr = new byte[inputSize]; for (int i = 0; i < arr.length; i++) { arr[i] = (byte) (65 + i % 10); } return arr; } }
7,394
0
Create_ds/avro/lang/java/trevni/core/src/test/java/org/apache
Create_ds/avro/lang/java/trevni/core/src/test/java/org/apache/trevni/TestIOBuffers.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.trevni; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Random; import java.io.ByteArrayOutputStream; import org.junit.jupiter.api.Test; public class TestIOBuffers { private static final int COUNT = 1001; @Test void empty() throws Exception { OutputBuffer out = new OutputBuffer(); ByteArrayOutputStream temp = new ByteArrayOutputStream(); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); assertEquals(0, in.tell()); assertEquals(0, in.length()); out.close(); } @Test void zero() throws Exception { Random random = TestUtil.createRandom(); OutputBuffer out = new OutputBuffer(); out.writeInt(0); byte[] bytes = out.toByteArray(); assertEquals(1, bytes.length); assertEquals(0, bytes[0]); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); assertEquals(0, in.readInt()); out.close(); } @Test void testBoolean() throws Exception { Random random = TestUtil.createRandom(); OutputBuffer out = new OutputBuffer(); for (int i = 0; i < COUNT; i++) out.writeValue(random.nextBoolean(), ValueType.BOOLEAN); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); random = TestUtil.createRandom(); for (int i = 0; i < COUNT; i++) assertEquals(random.nextBoolean(), in.readValue(ValueType.BOOLEAN)); out.close(); } @Test void testInt() throws Exception { Random random = TestUtil.createRandom(); OutputBuffer out = new OutputBuffer(); for (int i = 0; i < COUNT; i++) out.writeInt(random.nextInt()); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); random = TestUtil.createRandom(); for (int i = 0; i < COUNT; i++) assertEquals(random.nextInt(), in.readInt()); out.close(); } @Test void testLong() throws Exception { Random random = TestUtil.createRandom(); OutputBuffer out = new OutputBuffer(); for (int i = 0; i < COUNT; i++) out.writeLong(random.nextLong()); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); random = TestUtil.createRandom(); for (int i = 0; i < COUNT; i++) assertEquals(random.nextLong(), in.readLong()); out.close(); } @Test void fixed32() throws Exception { Random random = TestUtil.createRandom(); OutputBuffer out = new OutputBuffer(); for (int i = 0; i < COUNT; i++) out.writeFixed32(random.nextInt()); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); random = TestUtil.createRandom(); for (int i = 0; i < COUNT; i++) assertEquals(random.nextInt(), in.readFixed32()); out.close(); } @Test void fixed64() throws Exception { Random random = TestUtil.createRandom(); OutputBuffer out = new OutputBuffer(); for (int i = 0; i < COUNT; i++) out.writeFixed64(random.nextLong()); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); random = TestUtil.createRandom(); for (int i = 0; i < COUNT; i++) assertEquals(random.nextLong(), in.readFixed64()); out.close(); } @Test void testFloat() throws Exception { Random random = TestUtil.createRandom(); OutputBuffer out = new OutputBuffer(); for (int i = 0; i < COUNT; i++) out.writeFloat(random.nextFloat()); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); random = TestUtil.createRandom(); for (int i = 0; i < COUNT; i++) assertEquals(random.nextFloat(), in.readFloat(), 0); out.close(); } @Test void testDouble() throws Exception { OutputBuffer out = new OutputBuffer(); for (int i = 0; i < COUNT; i++) out.writeDouble(Double.MIN_VALUE); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); for (int i = 0; i < COUNT; i++) assertEquals(Double.MIN_VALUE, in.readDouble(), 0); out.close(); } @Test void bytes() throws Exception { Random random = TestUtil.createRandom(); OutputBuffer out = new OutputBuffer(); for (int i = 0; i < COUNT; i++) out.writeBytes(TestUtil.randomBytes(random)); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); random = TestUtil.createRandom(); for (int i = 0; i < COUNT; i++) assertEquals(TestUtil.randomBytes(random), in.readBytes(null)); out.close(); } @Test void string() throws Exception { Random random = TestUtil.createRandom(); OutputBuffer out = new OutputBuffer(); for (int i = 0; i < COUNT; i++) out.writeString(TestUtil.randomString(random)); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); random = TestUtil.createRandom(); for (int i = 0; i < COUNT; i++) assertEquals(TestUtil.randomString(random), in.readString()); out.close(); } @Test void skipNull() throws Exception { long sentinel = Long.MAX_VALUE; OutputBuffer out = new OutputBuffer(); out.writeValue(null, ValueType.NULL); out.writeLong(sentinel); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); in.skipValue(ValueType.NULL); assertEquals(sentinel, in.readLong()); out.close(); } @Test void skipBoolean() throws Exception { long sentinel = Long.MAX_VALUE; OutputBuffer out = new OutputBuffer(); out.writeValue(false, ValueType.BOOLEAN); out.writeLong(sentinel); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); in.skipValue(ValueType.BOOLEAN); assertEquals(sentinel, in.readLong()); out.close(); } @Test void skipInt() throws Exception { long sentinel = Long.MAX_VALUE; OutputBuffer out = new OutputBuffer(); out.writeValue(Integer.MAX_VALUE, ValueType.INT); out.writeLong(sentinel); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); in.skipValue(ValueType.INT); assertEquals(sentinel, in.readLong()); out.close(); } @Test void skipLong() throws Exception { long sentinel = Long.MAX_VALUE; OutputBuffer out = new OutputBuffer(); out.writeValue(Long.MAX_VALUE, ValueType.LONG); out.writeLong(sentinel); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); in.skipValue(ValueType.LONG); assertEquals(sentinel, in.readLong()); out.close(); } @Test void skipFixed32() throws Exception { long sentinel = Long.MAX_VALUE; OutputBuffer out = new OutputBuffer(); out.writeValue(Integer.MAX_VALUE, ValueType.FIXED32); out.writeLong(sentinel); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); in.skipValue(ValueType.LONG); assertEquals(sentinel, in.readLong()); out.close(); } @Test void skipFixed64() throws Exception { long sentinel = Long.MAX_VALUE; OutputBuffer out = new OutputBuffer(); out.writeValue(Long.MAX_VALUE, ValueType.FIXED64); out.writeLong(sentinel); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); in.skipValue(ValueType.LONG); assertEquals(sentinel, in.readLong()); out.close(); } @Test void skipFloat() throws Exception { long sentinel = Long.MAX_VALUE; OutputBuffer out = new OutputBuffer(); out.writeValue(Float.MAX_VALUE, ValueType.FLOAT); out.writeLong(sentinel); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); in.skipValue(ValueType.FLOAT); assertEquals(sentinel, in.readLong()); out.close(); } @Test void skipDouble() throws Exception { long sentinel = Long.MAX_VALUE; OutputBuffer out = new OutputBuffer(); out.writeValue(Double.MAX_VALUE, ValueType.DOUBLE); out.writeLong(sentinel); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); in.skipValue(ValueType.DOUBLE); assertEquals(sentinel, in.readLong()); out.close(); } @Test void skipString() throws Exception { long sentinel = Long.MAX_VALUE; OutputBuffer out = new OutputBuffer(); out.writeValue("trevni", ValueType.STRING); out.writeLong(sentinel); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); in.skipValue(ValueType.STRING); assertEquals(sentinel, in.readLong()); out.close(); } @Test void skipBytes() throws Exception { long sentinel = Long.MAX_VALUE; OutputBuffer out = new OutputBuffer(); out.writeValue("trevni".getBytes(UTF_8), ValueType.BYTES); out.writeLong(sentinel); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); in.skipValue(ValueType.BYTES); assertEquals(sentinel, in.readLong()); out.close(); } @Test void initPos() throws Exception { long sentinel = Long.MAX_VALUE; OutputBuffer out = new OutputBuffer(); out.writeValue(Integer.MAX_VALUE, ValueType.INT); out.writeLong(sentinel); InputBuffer in = new InputBuffer(new InputBytes(out.toByteArray())); in.readInt(); long pos = in.tell(); in = new InputBuffer(new InputBytes(out.toByteArray()), pos); assertEquals(sentinel, in.readLong()); out.close(); } }
7,395
0
Create_ds/avro/lang/java/trevni/core/src/test/java/org/apache
Create_ds/avro/lang/java/trevni/core/src/test/java/org/apache/trevni/TestUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.trevni; import java.util.Random; import java.nio.ByteBuffer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class TestUtil { private static long seed; private static boolean seedSet; /** * Returns the random seed for this test run. By default uses the current time, * but a test run can be replicated by specifying the "test.seed" system * property. The seed is printed the first time it's accessed so that failures * can be replicated if needed. */ public static long getRandomSeed() { if (!seedSet) { String configured = System.getProperty("test.seed"); if (configured != null) seed = Long.valueOf(configured); else seed = System.currentTimeMillis(); System.err.println("test.seed=" + seed); seedSet = true; } return seed; } public static void resetRandomSeed() { seedSet = false; } public static Random createRandom() { return new Random(getRandomSeed()); } public static ByteBuffer randomBytes(Random random) { byte[] bytes = new byte[randomLength(random)]; random.nextBytes(bytes); return ByteBuffer.wrap(bytes); } public static String randomString(Random random) { int length = randomLength(random); char[] chars = new char[length]; for (int i = 0; i < length; i++) chars[i] = (char) ('a' + random.nextInt('z' - 'a')); return new String(chars); } /** * Returns [0-15] 15/16 times. Returns [0-255] 255/256 times. Returns [0-4095] * 4095/4096 times. Returns [0-65535] every time. */ public static int randomLength(Random random) { int n = random.nextInt(); if (n < 0) n = -n; return n & ((n & 0xF0000) != 0 ? 0xF : ((n & 0xFF0000) != 0 ? 0xFF : ((n & 0xFFF0000) != 0 ? 0xFFF : 0xFFFF))); } @Test void randomLength() { long total = 0; int count = 1024 * 1024; int min = Short.MAX_VALUE; int max = 0; Random r = createRandom(); for (int i = 0; i < count; i++) { int length = randomLength(r); if (min > length) min = length; if (max < length) max = length; total += length; } assertEquals(0, min); assertTrue(max > 1024 * 32); float average = total / (float) count; assertTrue(average > 16.0f); assertTrue(average < 64.0f); } }
7,396
0
Create_ds/avro/lang/java/trevni/core/src/test/java/org/apache
Create_ds/avro/lang/java/trevni/core/src/test/java/org/apache/trevni/TestInputBytes.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.trevni; import java.util.Random; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; public class TestInputBytes { private static final int SIZE = 1000; private static final int COUNT = 100; @Test void randomReads() throws Exception { Random random = new Random(19820210); int length = random.nextInt(SIZE) + 1; byte[] data = new byte[length]; random.nextBytes(data); Input in = new InputBytes(data); for (int i = 0; i < COUNT; i++) { int p = random.nextInt(length); int l = Math.min(random.nextInt(SIZE / 10), length - p); byte[] buffer = new byte[l]; in.read(p, buffer, 0, l); assertArrayEquals(Arrays.copyOfRange(data, p, p + l), buffer); } in.close(); } }
7,397
0
Create_ds/avro/lang/java/trevni/core/src/main/java/org/apache
Create_ds/avro/lang/java/trevni/core/src/main/java/org/apache/trevni/TrevniRuntimeException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.trevni; /** Base runtime exception thrown by Trevni. */ public class TrevniRuntimeException extends RuntimeException { public TrevniRuntimeException(Throwable cause) { super(cause); } public TrevniRuntimeException(String message) { super(message); } public TrevniRuntimeException(String message, Throwable cause) { super(message, cause); } }
7,398
0
Create_ds/avro/lang/java/trevni/core/src/main/java/org/apache
Create_ds/avro/lang/java/trevni/core/src/main/java/org/apache/trevni/ArrayColumnOutputBuffer.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.trevni; import java.io.IOException; /** A column output buffer for array columns. */ class ArrayColumnOutputBuffer extends ColumnOutputBuffer { private int length; // remaining in current array private static final int NONE = -1; private int runLength; // length of current run private int runValue = NONE; // what kind of run public ArrayColumnOutputBuffer(ColumnFileWriter writer, ColumnMetaData meta) throws IOException { super(writer, meta); assert getMeta().isArray() || getMeta().getParent() != null; assert !getMeta().hasIndexValues(); } @Override public void writeLength(int l) throws IOException { assert this.length == 0; assert l >= 0; this.length = l; if (l == runValue) { runLength++; // continue a run return; } flushRun(); // end a run if (l == 1 || l == 0) { runLength = 1; // start a run runValue = l; } else { getBuffer().writeLength(l); // not a run } } @Override public void writeValue(Object value) throws IOException { assert length > 0; if (getMeta().getType() != ValueType.NULL) { flushRun(); getBuffer().writeValue(value, getMeta().getType()); } length -= 1; } @Override void flushBuffer() throws IOException { flushRun(); super.flushBuffer(); } private void flushRun() throws IOException { if (runLength == 0) // not in run return; else if (runLength == 1) // single value getBuffer().writeLength(runValue); else // a run getBuffer().writeLength((3 - runValue) - (runLength << 1)); runLength = 0; // reset runValue = NONE; } }
7,399