Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/**
* 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.generic;
import java.nio.ByteBuffer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.WeakHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.avro.AvroRuntimeException;
import org.apache.avro.AvroTypeException;
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.DecoderFactory;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.parsing.ResolvingGrammarGenerator;
import org.apache.avro.util.Utf8;
import org.codehaus.jackson.JsonNode;
/** 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();
/** Used to specify the Java type for a string schema. */
public enum StringType { CharSequence, String, Utf8 };
protected 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();
}
/** Return the class loader that's used (by subclasses). */
public ClassLoader getClassLoader() { return classLoader; }
/** 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 {
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) return null;
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);
}
}
/** Default implementation of an array. */
@SuppressWarnings(value="unchecked")
public static class Array extends AbstractList
implements GenericArray, Comparable> {
private static final Object[] EMPTY = new Object[0];
private final Schema schema;
private int size;
private Object[] elements = EMPTY;
public Array(int capacity, Schema schema) {
if (schema == null || !Type.ARRAY.equals(schema.getType()))
throw new AvroRuntimeException("Not an array schema: "+schema);
this.schema = schema;
if (capacity != 0)
elements = new Object[capacity];
}
public Array(Schema schema, Collection c) {
if (schema == null || !Type.ARRAY.equals(schema.getType()))
throw new AvroRuntimeException("Not an array schema: "+schema);
this.schema = schema;
if (c != null) {
elements = new Object[c.size()];
addAll(c);
}
}
@Override
public Schema getSchema() { return schema; }
@Override public int size() { return size; }
@Override public void clear() { size = 0; }
@Override public Iterator iterator() {
return new Iterator() {
private int position = 0;
@Override
public boolean hasNext() { return position < size; }
@Override
public T next() { return (T)elements[position++]; }
@Override
public void remove() { throw new UnsupportedOperationException(); }
};
}
@Override public T get(int i) {
if (i >= size)
throw new IndexOutOfBoundsException("Index " + i + " out of bounds.");
return (T)elements[i];
}
@Override public boolean add(T o) {
if (size == elements.length) {
Object[] newElements = new Object[(size * 3)/2 + 1];
System.arraycopy(elements, 0, newElements, 0, size);
elements = newElements;
}
elements[size++] = o;
return true;
}
@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) {
Object[] newElements = new Object[(size * 3)/2 + 1];
System.arraycopy(elements, 0, newElements, 0, size);
elements = newElements;
}
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
public int compareTo(GenericArray that) {
return GenericData.get().compare(this, that, this.getSchema());
}
@Override
public void reverse() {
int left = 0;
int right = elements.length - 1;
while (left < right) {
Object tmp = elements[left];
elements[left] = elements[right];
elements[right] = tmp;
left++;
right--;
}
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append("[");
int count = 0;
for (T e : this) {
buffer.append(e==null ? "null" : e.toString());
if (++count < size())
buffer.append(", ");
}
buffer.append("]");
return buffer.toString();
}
}
/** Default implementation of {@link GenericFixed}. */
public static class Fixed implements GenericFixed, Comparable {
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, Comparable {
private Schema schema;
private String symbol;
public EnumSymbol(Schema schema, String symbol) {
this.schema = schema;
this.symbol = symbol;
}
@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(GenericEnumSymbol that) {
return GenericData.get().compare(this, that, schema);
}
}
/** Returns a {@link DatumReader} for this kind of data. */
public DatumReader createDatumReader(Schema schema) {
return new GenericDatumReader(schema, schema, this);
}
/** 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:
return schema.getEnumSymbols().contains(datum.toString());
case ARRAY:
if (!(isArray(datum))) return false;
for (Object element : (Collection>)datum)
if (!validate(schema.getElementType(), element))
return false;
return true;
case MAP:
if (!(isMap(datum))) return false;
@SuppressWarnings(value="unchecked")
Map