This question already has answers here:
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException
(2 answers)
Closed 5 years ago.
I was trying to figure out why my code is throwing a "java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: core.FlightOrder$FlightTicket" exception.
I have class declared as:
public class FlightOrder implements Serializable
that contains a private Set of FlightTickets.
And an inner class declared as:
public class FlightTicket
The solution i read about, was to make the inner class "FlightTicket" a static class, but im not sure thats what I'm supose to do to make my code work properly.
can someone help me figure out whats the right way to approach this problem?
public class FlightTicket
{
/**
* The passenger for this ticket
*/
private Customer passenger;
/**
* passenger's seat
*/
private int seat;
/**
* passenger's row
*/
private int row;
/**
* The passenger's class in the plane
*/
private E_ClassType classType;
/**
* Full constructor
* #param passenger
* #param seat
* #param row
* #param classType
*/
public FlightTicket(Customer passenger, int seat, int row , String classType)
{
this.passenger = passenger;
setSeat(seat);
setRow(row);
setClassType(classType);
}
/**
* Partial constructor
* #param seat
* #param row
*/
public FlightTicket(int seat, int row)
{
setSeat(seat);
setRow(row);
}
//-------------------------------Getters And Setters------------------------------
/**
* seat has to be positive number
* #param seat
*/
public void setSeat(int seat) {
if(seat>0)
this.seat = seat;
}
/**
* row has to be positive number
* #param row
*/
public void setRow(int row) {
if(row>0)
this.row = row;
}
/**
*
* #return classType
*/
public E_ClassType getClassType() {
return classType;
}
public int getSeat(){
return seat;
}
public int getRow(){
return row;
}
/**
* set the class type from the array classType located in Constants.
* if the classType not exists, the default value is Economy.
* #param classType
*/
public void setClassType(String classType) {
for(E_ClassType c : E_ClassType.values())
{
if(c.toString().equals(classType))
{
this.classType = E_ClassType.valueOf(classType);
return;
}
}
this.classType = E_ClassType.Tourists;
}
public FlightOrder getOuterType() {
return FlightOrder.this;
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + row;
result = prime * result + seat;
return result;
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FlightTicket other = (FlightTicket) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (row != other.row)
return false;
if (seat != other.seat)
return false;
return true;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "FlightTicket [passenger=" + passenger + ", seat=" + seat
+ ", row=" + row + ", flight number=" + getFlight().getFlightNumber() + "]";
}
}// ~ END OF Inner Class FlightTicket
Making inner class Serializable will work and this is exactly that you are supposed to do if you want to serialize it together with the outer class. The following code demonstrates:
public class Outer implements Serializable {
class Inner implements Serializable {
int value = 17;
}
Inner inner = new Inner();
public static void main(String[] args) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(out);
Outer obj = new Outer();
obj.inner.value = 22;
oout.writeObject(obj);
Outer r = (Outer) new ObjectInputStream(new ByteArrayInputStream(
out.toByteArray())).readObject();
System.out.println(r.inner.value);
}
}
The output is 22, the value that has been correctly serialized and deserialized from the inner class field.
You just need to implement Serializable interface by all the classes which will be serialized. I mean all classes of instance variables declared in your serializable class should also implement Serializable.
In your case FlightTicket and Customer need implement Serializable.
Related
I'm trying to convert a HashMap<String, Object> to an Avro record. I get this runtime exception when I do a
DataStream<AvroRecord> dsRpvSchema = filteredVlfRPV.flatMap(new MessageFlattener()) .name("ToAvroSchema").uid("ToAvroSchema").startNewChain();
Not sure what the issue is with Flink converting the valid avro record to Flink Avro.
java.lang.IllegalStateException: Expecting type to be a PojoTypeInfo
at org.apache.flink.formats.avro.typeutils.AvroTypeInfo.generateFieldsFromAvroSchema(AvroTypeInfo.java:71)
at org.apache.flink.formats.avro.typeutils.AvroTypeInfo.<init>(AvroTypeInfo.java:55)
at org.apache.flink.formats.avro.utils.AvroKryoSerializerUtils.createAvroTypeInfo(AvroKryoSerializerUtils.java:81)
at org.apache.flink.api.java.typeutils.TypeExtractor.privateGetForClass(TypeExtractor.java:1653)
at org.apache.flink.api.java.typeutils.TypeExtractor.privateGetForClass(TypeExtractor.java:1559)
at org.apache.flink.api.java.typeutils.TypeExtractor.createTypeInfoWithTypeHierarchy(TypeExtractor.java:866)
at org.apache.flink.api.java.typeutils.TypeExtractor.privateCreateTypeInfo(TypeExtractor.java:747)
at org.apache.flink.api.java.typeutils.TypeExtractor.getUnaryOperatorReturnType(TypeExtractor.java:531)
at org.apache.flink.api.java.typeutils.TypeExtractor.getFlatMapReturnTypes(TypeExtractor.java:168)
at org.apache.flink.streaming.api.datastream.DataStream.flatMap(DataStream.java:637)
I do see two questions on this but no answers provided:
Flink Kafka : Expecting type to be a PojoTypeInfo
Deserialize Avro from kafka as SpecificRecord Failing. Expecting type to be a PojoTypeInfo
UPDATE: 02/01/2022. Below is the AvroRecord class definition.
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
#org.apache.avro.specific.AvroGenerated
public class AvroRecord extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = 9071485731787422200L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"AvroRecord\",\"namespace\":\"com.sample.dataplatform.stream.avro\",\"fields\":[{\"name\":\"_id\",\"type\":\"string\",\"doc\":\"car_id\"}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<AvroRecord> ENCODER =
new BinaryMessageEncoder<AvroRecord>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<AvroRecord> DECODER =
new BinaryMessageDecoder<AvroRecord>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* #return the message encoder used by this class
*/
public static BinaryMessageEncoder<AvroRecord> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* #return the message decoder used by this class
*/
public static BinaryMessageDecoder<AvroRecord> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {#link SchemaStore}.
* #param resolver a {#link SchemaStore} used to find schemas by fingerprint
* #return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<AvroRecord> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<AvroRecord>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this AvroRecord to a ByteBuffer.
* #return a buffer holding the serialized data for this instance
* #throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a AvroRecord from a ByteBuffer.
* #param b a byte buffer holding serialized data for an instance of this class
* #return a AvroRecord instance decoded from the given buffer
* #throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static AvroRecord fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
/** car_id */
private java.lang.CharSequence _id;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public AvroRecord() {}
/**
* All-args constructor.
* #param _id car_id
*/
public AvroRecord(java.lang.CharSequence _id) {
this._id = _id;
}
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return _id;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
// Used by DatumReader. Applications should not call.
#SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: _id = (java.lang.CharSequence)value$; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the '_id' field.
* #return car_id
*/
public java.lang.CharSequence getId$1() {
return _id;
}
/**
* Sets the value of the '_id' field.
* car_id
* #param value the value to set.
*/
public void setId$1(java.lang.CharSequence value) {
this._id = value;
}
/**
* Creates a new AvroRecord RecordBuilder.
* #return A new AvroRecord RecordBuilder
*/
public static com.sample.dataplatform.stream.avro.AvroRecord.Builder newBuilder() {
return new com.sample.dataplatform.stream.avro.AvroRecord.Builder();
}
/**
* Creates a new AvroRecord RecordBuilder by copying an existing Builder.
* #param other The existing builder to copy.
* #return A new AvroRecord RecordBuilder
*/
public static com.sample.dataplatform.stream.avro.AvroRecord.Builder newBuilder(com.sample.dataplatform.stream.avro.AvroRecord.Builder other) {
if (other == null) {
return new com.sample.dataplatform.stream.avro.AvroRecord.Builder();
} else {
return new com.sample.dataplatform.stream.avro.AvroRecord.Builder(other);
}
}
/**
* Creates a new AvroRecord RecordBuilder by copying an existing AvroRecord instance.
* #param other The existing instance to copy.
* #return A new AvroRecord RecordBuilder
*/
public static com.sample.dataplatform.stream.avro.AvroRecord.Builder newBuilder(com.sample.dataplatform.stream.avro.AvroRecord other) {
if (other == null) {
return new com.sample.dataplatform.stream.avro.AvroRecord.Builder();
} else {
return new com.sample.dataplatform.stream.avro.AvroRecord.Builder(other);
}
}
/**
* RecordBuilder for AvroRecord instances.
*/
#org.apache.avro.specific.AvroGenerated
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<AvroRecord>
implements org.apache.avro.data.RecordBuilder<AvroRecord> {
/** car_id */
private java.lang.CharSequence _id;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$);
}
/**
* Creates a Builder by copying an existing Builder.
* #param other The existing Builder to copy.
*/
private Builder(com.sample.dataplatform.stream.avro.AvroRecord.Builder other) {
super(other);
if (isValidValue(fields()[0], other._id)) {
this._id = data().deepCopy(fields()[0].schema(), other._id);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
}
/**
* Creates a Builder by copying an existing AvroRecord instance
* #param other The existing instance to copy.
*/
private Builder(com.sample.dataplatform.stream.avro.AvroRecord other) {
super(SCHEMA$);
if (isValidValue(fields()[0], other._id)) {
this._id = data().deepCopy(fields()[0].schema(), other._id);
fieldSetFlags()[0] = true;
}
}
/**
* Gets the value of the '_id' field.
* car_id
* #return The value.
*/
public java.lang.CharSequence getId$1() {
return _id;
}
/**
* Sets the value of the '_id' field.
* car_id
* #param value The value of '_id'.
* #return This builder.
*/
public com.sample.dataplatform.stream.avro.AvroRecord.Builder setId$1(java.lang.CharSequence value) {
validate(fields()[0], value);
this._id = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the '_id' field has been set.
* car_id
* #return True if the '_id' field has been set, false otherwise.
*/
public boolean hasId$1() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the '_id' field.
* car_id
* #return This builder.
*/
public com.sample.dataplatform.stream.avro.AvroRecord.Builder clearId$1() {
_id = null;
fieldSetFlags()[0] = false;
return this;
}
#Override
#SuppressWarnings("unchecked")
public AvroRecord build() {
try {
AvroRecord record = new AvroRecord();
record._id = fieldSetFlags()[0] ? this._id : (java.lang.CharSequence) defaultValue(fields()[0]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
#SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<AvroRecord>
WRITER$ = (org.apache.avro.io.DatumWriter<AvroRecord>)MODEL$.createDatumWriter(SCHEMA$);
#Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
#SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<AvroRecord>
READER$ = (org.apache.avro.io.DatumReader<AvroRecord>)MODEL$.createDatumReader(SCHEMA$);
#Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
#Override protected boolean hasCustomCoders() { return true; }
#Override public void customEncode(org.apache.avro.io.Encoder out)
throws java.io.IOException
{
out.writeString(this._id);
}
#Override public void customDecode(org.apache.avro.io.ResolvingDecoder in)
throws java.io.IOException
{
org.apache.avro.Schema.Field[] fieldOrder = in.readFieldOrderIfDiff();
if (fieldOrder == null) {
this._id = in.readString(this._id instanceof Utf8 ? (Utf8)this._id : null);
} else {
for (int i = 0; i < 1; i++) {
switch (fieldOrder[i].pos()) {
case 0:
this._id = in.readString(this._id instanceof Utf8 ? (Utf8)this._id : null);
break;
default:
throw new java.io.IOException("Corrupt ResolvingDecoder.");
}
}
}
}
}
The AVRO schema (.avsc) file looks like this:
{
"namespace": "com.sample.dataplatform.stream.avro",
"type": "record",
"name": "AvroRecord",
"fields": [
{
"name": "_id",
"type": "string",
"doc": "car_id"
}
]
}
Any help is appreciated!
You are now going to write the various methods in WizardController that animate the wizards. In order to follow the motion of the wizards properly you will need to slow the animation down. To help you do this we have provided a class method delay() in the WizardController class.
WizardController.delay(100);
So the question is write a public class method jump() that returns nothing. It should make the wizard passed as argument jump up one cell position from its current cell then return to its original cell. I have tried the code below and it compiles but not 100% sure if its correct..
public static void jump(Wizard wizard1)
{
wizard1.up();
WizardController.delay(1000);
wizard1.down(1);
}
...also I need to create an instance of wizard and execute the jump() method passing it as argument to check this works as expected. This I am unsure how to do.
here is the full code:
public class WizardController
{
/**
* instance variables
*/
private Wizard wizard1;
private Wizard wizard2;
private int numOfRepeats;
private static final int MIN_NUM_REPEATS = 1;
private static final int MAX_NUM_REPEATS = 3;
public static final int LAST_CELL = 11;
/**
* Constructor for objects of class WizardController.
*/
public WizardController(Wizard aWizard1, Wizard aWizard2)
{
super();
this.wizard1 = aWizard1;
this.wizard2 = aWizard2;
this.numOfRepeats = 0;
}
/* instance methods */
/**
* Prompts the user for a number of action repeats
* in the range 1 to 3 inclusive, and returns this number.
*/
public int promptForNumOfRepeats()
{
int moves;
moves = Integer.parseInt(OUDialog.request("Please enter the number of"
+ " action repeats to be performed - between 1 and 3 (inclusive)"));
try
{
moves = Integer.parseInt(OUDialog.request("Please enter the number of"
+ " action repeats to be performed - between 1 and 3 (inclusive)"));
}
catch (NumberFormatException anException)
{
moves = 0;
}
return moves;
}
/**
* Returns true if the argument is in the range 1 to 3 (inclusive),
* otherwise false.
*/
public boolean isValidNumOfRepeats(int aNumber)
{
return ((aNumber >= WizardController.MIN_NUM_REPEATS)
&& (aNumber <= WizardController.MAX_NUM_REPEATS));
}
/**
* Repeatedly prompts the user for a number of repeats of the moves,
* until they enter a valid input representing a number in the range 1 to 3
* inclusive, and then returns this number.
*/
public int getNumOfRepeats()
{
int repeats = this.promptForNumOfRepeats();
while (!this.isValidNumOfRepeats(repeats))
{
OUDialog.alert("That is not a valid number of game repeats");
repeats = this.promptForNumOfRepeats();
}
return repeats;
}
public static void jump(Wizard wizard1)
{
wizard1.up();
WizardController.delay(1000);
wizard1.down(1);
}
public static void delay(int ms)
{
try{
Thread.sleep(ms);
}
catch(Exception e)
{
System.out.println("Problem in delay methods");
}
}
}
here is the Wizard class for any wxtra help:
public class Wizard
{
/* instance variables */
private Triangle persona;
private int startCellX;
private int startCellY;
private OUColour startColour;
public static final int CELL_SIZE_X = 20;
public static final int CELL_SIZE_Y = 30;
/**
* Constructor for objects of class Wizard
*/
public Wizard(OUColour aColour, int cellY)
{
super();
this.persona = new Triangle(30, 30, aColour);
this.persona.setXPos(0);
this.persona.setYPos(cellY * Wizard.CELL_SIZE_Y);
this.startCellX = 0;
this.startCellY = cellY;
this.startColour = aColour;
}
/* instance methods */
/**
* returns the persona of the Wizard - so that it can be displayed
* in the graphical display window
*/
public Triangle getPersona()
{
return this.persona;
}
/**
* Resets the receiver to its "home" X position of 0.
*/
public void homeX()
{
this.persona.setXPos(this.startCellX * Wizard.CELL_SIZE_X);
}
/**
* Resets the receiver to its "home" Y position of startCellY * CELL_SIZE.
*/
public void homeY()
{
this.persona.setYPos(this.startCellY * Wizard.CELL_SIZE_Y);
}
/**
* Decrements the X position of the receiver by CELL_SIZE.
*/
public void left()
{
this.persona.setXPos(this.persona.getXPos() - Wizard.CELL_SIZE_X);
}
/**
* Increments the X position of the receiver by CELL_SIZE.
*/
public void right()
{
this.persona.setXPos(this.persona.getXPos() + Wizard.CELL_SIZE_X);
}
/**
* Decrements the Y position of the receiver by CELL_SIZE.
*/
public void up()
{
this.persona.setYPos(this.persona.getYPos() - Wizard.CELL_SIZE_Y);
}
/**
* Increments the Y position of the receiver by CELL_SIZE.
*/
public void down()
{
this.persona.setYPos(this.persona.getYPos() + Wizard.CELL_SIZE_Y);
}
/**
* Decrements the X position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void leftBy(int numCells)
{
this.persona.setXPos(this.persona.getXPos() - Wizard.CELL_SIZE_X * numCells);
}
/**
* Increments the X position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void rightBy(int numCells)
{
this.persona.setXPos(this.persona.getXPos() + Wizard.CELL_SIZE_X * numCells);
}
/**
* Decrements the Y position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void upBy(int numCells)
{
this.persona.setYPos(this.persona.getYPos() - Wizard.CELL_SIZE_Y * numCells);
}
/**
* Increments the Y position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void downBy(int numCells)
{
this.persona.setYPos(this.persona.getYPos() + Wizard.CELL_SIZE_Y * numCells);
}
/**
* returns the cellX the wizard is currently on
*/
public int getCellX()
{
return this.persona.getXPos()/ Wizard.CELL_SIZE_X;
}
/**
* returns the cellY the wizard is currently on
*/
public int getCellY()
{
return this.persona.getYPos()/ Wizard.CELL_SIZE_Y;
}
/**
* sets the cellY the wizard is on to the argument
*/
public void setCellY(int aCellNumber)
{
this.persona.setYPos(aCellNumber * Wizard.CELL_SIZE_Y);
}
/**
* Returns a string representation of the receiver.
*/
#Override
public String toString()
{
return "An instance of class " + this.getClass().getName()
+ " in cell X:" + this.getCellX() + ", Y:" + this.getCellY()
+ ", colour " + this.persona.getColour();
}
I'm having a strange issue with marshalling/unmarshalling an avro generated class. The error I'm getting is throwing a not an enum error - except there aren't any enum's in my class.
The error is specifically this:
com.fasterxml.jackson.databind.JsonMappingException: Not an enum: {"type":"record","name":"TimeUpdateTopic","namespace":"org.company.mmd.time","fields":[{"name":"time","type":"double"}]} (through reference chain: org.company.mmd.time.TimeUpdateTopic["schema"]->org.apache.avro.Schema$RecordSchema["enumDefault"])
Test Case
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import org.junit.Test
class TimeUpdateTopicTest {
val objectMapper = ObjectMapper().registerModule(JavaTimeModule())
#Test
fun decode() {
val t = TimeUpdateTopic(1.0)
objectMapper.writeValueAsString(t)
}
}
AVDL
#namespace("org.company.mmd.time")
protocol TimeMonitor {
record TimeUpdateTopic {
double time;
}
}
Java class generated by the avro task
/**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package org.company.mmd.time;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
#org.apache.avro.specific.AvroGenerated
public class TimeUpdateTopic extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = -4648318619505855037L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"TimeUpdateTopic\",\"namespace\":\"org.company.mmd.time\",\"fields\":[{\"name\":\"time\",\"type\":\"double\"}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<TimeUpdateTopic> ENCODER =
new BinaryMessageEncoder<TimeUpdateTopic>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<TimeUpdateTopic> DECODER =
new BinaryMessageDecoder<TimeUpdateTopic>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* #return the message encoder used by this class
*/
public static BinaryMessageEncoder<TimeUpdateTopic> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* #return the message decoder used by this class
*/
public static BinaryMessageDecoder<TimeUpdateTopic> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {#link SchemaStore}.
* #param resolver a {#link SchemaStore} used to find schemas by fingerprint
* #return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<TimeUpdateTopic> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<TimeUpdateTopic>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this TimeUpdateTopic to a ByteBuffer.
* #return a buffer holding the serialized data for this instance
* #throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a TimeUpdateTopic from a ByteBuffer.
* #param b a byte buffer holding serialized data for an instance of this class
* #return a TimeUpdateTopic instance decoded from the given buffer
* #throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static TimeUpdateTopic fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
#Deprecated public double time;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public TimeUpdateTopic() {}
/**
* All-args constructor.
* #param time The new value for time
*/
public TimeUpdateTopic(java.lang.Double time) {
this.time = time;
}
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return time;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
// Used by DatumReader. Applications should not call.
#SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: time = (java.lang.Double)value$; break;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
/**
* Gets the value of the 'time' field.
* #return The value of the 'time' field.
*/
public double getTime() {
return time;
}
/**
* Sets the value of the 'time' field.
* #param value the value to set.
*/
public void setTime(double value) {
this.time = value;
}
/**
* Creates a new TimeUpdateTopic RecordBuilder.
* #return A new TimeUpdateTopic RecordBuilder
*/
public static org.company.mmd.time.TimeUpdateTopic.Builder newBuilder() {
return new org.company.mmd.time.TimeUpdateTopic.Builder();
}
/**
* Creates a new TimeUpdateTopic RecordBuilder by copying an existing Builder.
* #param other The existing builder to copy.
* #return A new TimeUpdateTopic RecordBuilder
*/
public static org.company.mmd.time.TimeUpdateTopic.Builder newBuilder(org.company.mmd.time.TimeUpdateTopic.Builder other) {
if (other == null) {
return new org.company.mmd.time.TimeUpdateTopic.Builder();
} else {
return new org.company.mmd.time.TimeUpdateTopic.Builder(other);
}
}
/**
* Creates a new TimeUpdateTopic RecordBuilder by copying an existing TimeUpdateTopic instance.
* #param other The existing instance to copy.
* #return A new TimeUpdateTopic RecordBuilder
*/
public static org.company.mmd.time.TimeUpdateTopic.Builder newBuilder(org.company.mmd.time.TimeUpdateTopic other) {
if (other == null) {
return new org.company.mmd.time.TimeUpdateTopic.Builder();
} else {
return new org.company.mmd.time.TimeUpdateTopic.Builder(other);
}
}
/**
* RecordBuilder for TimeUpdateTopic instances.
*/
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<TimeUpdateTopic>
implements org.apache.avro.data.RecordBuilder<TimeUpdateTopic> {
private double time;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$);
}
/**
* Creates a Builder by copying an existing Builder.
* #param other The existing Builder to copy.
*/
private Builder(org.company.mmd.time.TimeUpdateTopic.Builder other) {
super(other);
if (isValidValue(fields()[0], other.time)) {
this.time = data().deepCopy(fields()[0].schema(), other.time);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
}
/**
* Creates a Builder by copying an existing TimeUpdateTopic instance
* #param other The existing instance to copy.
*/
private Builder(org.company.mmd.time.TimeUpdateTopic other) {
super(SCHEMA$);
if (isValidValue(fields()[0], other.time)) {
this.time = data().deepCopy(fields()[0].schema(), other.time);
fieldSetFlags()[0] = true;
}
}
/**
* Gets the value of the 'time' field.
* #return The value.
*/
public double getTime() {
return time;
}
/**
* Sets the value of the 'time' field.
* #param value The value of 'time'.
* #return This builder.
*/
public org.company.mmd.time.TimeUpdateTopic.Builder setTime(double value) {
validate(fields()[0], value);
this.time = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'time' field has been set.
* #return True if the 'time' field has been set, false otherwise.
*/
public boolean hasTime() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'time' field.
* #return This builder.
*/
public org.company.mmd.time.TimeUpdateTopic.Builder clearTime() {
fieldSetFlags()[0] = false;
return this;
}
#Override
#SuppressWarnings("unchecked")
public TimeUpdateTopic build() {
try {
TimeUpdateTopic record = new TimeUpdateTopic();
record.time = fieldSetFlags()[0] ? this.time : (java.lang.Double) defaultValue(fields()[0]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
#SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<TimeUpdateTopic>
WRITER$ = (org.apache.avro.io.DatumWriter<TimeUpdateTopic>)MODEL$.createDatumWriter(SCHEMA$);
#Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
#SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<TimeUpdateTopic>
READER$ = (org.apache.avro.io.DatumReader<TimeUpdateTopic>)MODEL$.createDatumReader(SCHEMA$);
#Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
#Override protected boolean hasCustomCoders() { return true; }
#Override public void customEncode(org.apache.avro.io.Encoder out)
throws java.io.IOException
{
out.writeDouble(this.time);
}
#Override public void customDecode(org.apache.avro.io.ResolvingDecoder in)
throws java.io.IOException
{
org.apache.avro.Schema.Field[] fieldOrder = in.readFieldOrderIfDiff();
if (fieldOrder == null) {
this.time = in.readDouble();
} else {
for (int i = 0; i < 1; i++) {
switch (fieldOrder[i].pos()) {
case 0:
this.time = in.readDouble();
break;
default:
throw new java.io.IOException("Corrupt ResolvingDecoder.");
}
}
}
}
}
Am I doing something stupid and/or wrong here? Or is this an actual bug
Updates
I'm able to get JSON out using this function:
inline fun <reified T: SpecificRecordBase> StringFromAvroGenerated(obj: T) : String {
val schema = obj.schema
val writer = SpecificDatumWriter(T::class.java)
val stream = ByteArrayOutputStream()
var jsonEncoder = EncoderFactory.get().jsonEncoder(schema, stream)
writer.write(obj, jsonEncoder)
jsonEncoder.flush()
return stream.toString("UTF-8")
}
but I was assuming this should be automatic with Jackson
So it appears there are two ways to solve my issues (thanks to JsonMappingException when serializing avro generated object to json)
Write a Jackson MixIn to handle the getSchema call
So the first option required me to create a Mixin such as this:
abstract class AvroMixIn {
#JsonIgnore
abstract fun getSchema(): org.apache.avro.Schema
#JsonIgnore
abstract fun getSpecificData() : org.apache.avro.specific.SpecificData
}
And then when i make an object mapper:
val objectMapper = ObjectMapper()
.registerModule(JavaTimeModule())
.addMixIn(Object::class.java, AvroMixIn::class.java)
I chose Object::class.java instead of the actual class because it should apply to all classes. Probably a better solution is to apply it to a shared base-class all the AvroGenerated stuff has.
Rewrite the Avro Velocity Templates to automatically add this
This is actually the 1st approach I took because it seemed more "seemless".
1) Check out the avro project
2) Copy enum.vm, fixed.vm, protocol.vm, record.vm into a /avro_templates directory off the main root of my project
3) Add the #com.fasterxml.jackson.annotation.JsonIgnore property to the template:
#end
#com.fasterxml.jackson.annotation.JsonIgnore
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
#com.fasterxml.jackson.annotation.JsonIgnore
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
4) Update the gradle task:
avro {
dateTimeLogicalType="JSR310"
templateDirectory = "avro_templates/"
}
5) re-build avro classes
(everything now works)
As the title suggests, I am trying to Sort my ArrayList of objects, and those objects have implemented comparable and have overriden CompareTo
However when I got to sort my arraylist i get this error
I can't seem to understand why I am getting this problem? Can anybody help?
ItemList Class:
package stories.cs2800;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.AbstractListModel;
#SuppressWarnings("serial")
public class ItemList extends AbstractListModel<Item> {
private ArrayList<Item> items;
/**
* Constructor that initializes the array list.
*/
public ItemList() {
items = new ArrayList<Item>();
}
#Override
public int getSize() {
return items.size();
}
/**
* Method to get item based on the index.
* #param argIndex - Takes parameter of type int.
* #return Returns item at the index.
*/
#Override
public Item getElementAt(int argIndex) throws IndexOutOfBoundsException {
if (argIndex < 0 || argIndex >= items.size()) {
throw new IndexOutOfBoundsException();
}
return items.get(argIndex);
}
/**
* Method that gets and Item element based on the name.
*
* #param argName - takes parameter of type String.
* #return Returns the entire item object if name matches, else null.
*/
public Item getElementByName(String argName) {
for (Item i : items) {
if (i.getName().equals(argName)) {
return i;
}
}
return null;
}
/**
* Method to add another Item into the array list.
* #param Takes parameter of type item.
* #see ArrayList#add
*/
public void add(Item next) {
items.add(next);
Collections.sort(items);
}
/**
* Boolean method to check if list contains the item of type Item.
*
* #param Takes parameter of type item.
* #return returns boolean value of true or false if item is contained.
*/
public Boolean contains(Item argItem) {
return items.contains(argItem);
}
/**
* Boolean method remove to remove item of type Item from list.
*
* #param Takes parameter of type Item.
* #return returns boolean value of true or false if item is removed.
*/
public Boolean remove(Item argItem) {
return items.remove(argItem);
}
/**
* Boolean method that removes and item based on its index.
*
* #argIndex Takes a parameter of type int.
* #return returns boolean value of true or false if item was removed based on index.
*/
public Boolean remove(int argIndex) throws IndexOutOfBoundsException {
if (argIndex < 0 || argIndex >= items.size()) {
throw new IndexOutOfBoundsException();
}
return items.remove(items.get(argIndex));
}
/**
* Method to find the index of an item object.
*
* #param Takes parameter of type Item.
* #return Returns item index based on the item object entered.
*/
public int indexOf(Item argItem) {
return items.indexOf(argItem);
}
/**
* Method to check if item changed.
*
* #param Takes parameter of type Item.
*/
public void changed(Item argItem) {
fireContentsChanged(this, items.indexOf(items), items.indexOf(items));
/*Method called when one or more items have changed */
}
}
SingleItem Class:
package stories.cs2800
public class SingleItem implements Comparable<Item>, Item {
private String name;
private float value;
private Item child;
/**
* Constructor for the SingleItem object.
*
* #param argName Stores the name that is set in constructor
* #param argValue Stores the float value that is set in Constructor
* #param argChild Stores the value of the child element
*/
public SingleItem(String argName, float argValue, Item argChild) {
name = argName;
value = argValue;
child = argChild;
}
/**
* Getter method to get the value of the name variable.
*
* #return returns the name
*/
#Override
public String getName() {
return this.name;
}
/**
* Getter method to get the value of the Float variable.
*
* #return value set in the value variable
*
*/
#Override
public Float getValue() {
return this.value;
}
/**
* Setter method to set the value of the Float - No return type.
* #param argFloat - Takes parameter of type Float using Wrapper class.
*/
#Override
public void setValue(Float argFloat) {
this.value = argFloat;
}
/**
* Method to get the description.
*
* #return Returns the a string with the description
*/
#Override
public String getDescription() {
return "Single items have no description";
}
/**
* Getter method for child element.
*
* #return returns the value of child element
*/
public Item getChild() {
return this.child;
}
/**
* Method for adding items.
* #param child - Takes parameter of type Item.
* #return Returns Exception when child is null.
*
*/
#Override
public void add(Item child) {
if (this.child != null) {
throw new IllegalStateException();
}
this.child = child;
}
/**
* Method for ItemVisitor.
* #param argVisitor - Takes parameter of ItemVisitor to add current class.
* #return Currently no valid method!.
*
*/
#Override
public <T> void accept(ItemVisitor<T> argVisitor) {
argVisitor.add(this);
}
/**
* Method that takes Boolean as a parameter.
* #param argBool - Takes parameter of type boolean.
* #return Returns exception.
*/
#Override
public void open(boolean argBool) throws IllegalStateException {
throw new IllegalStateException();
}
/**
* Method that compares name to name entered as a parameter.
* #param item - Takes parameter of type item.
* #return Returns an int based on comparison of name. E.g. 0 = same, 1 = different.
*/
#Override
public int compareTo(Item item) {
return this.name.compareTo(item.getName());
}
/**
* Method to check if Open.
*
* #return Always returns true.
*/
#Override
public boolean isOpen() {
return true;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.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;
}
SingleItem other = (SingleItem) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
/**
* toString method to get values of elements.
*
* #return Returns a sentence with the values of all elements.
*/
#Override
public String toString() {
return "Name: " + getName() + ", Value: " + getValue()
+ ", Description: "
+ getDescription();
}
}
In short, Item doesn't implement Comparable. And the list is a list of Item.
Details here. In the code above, items = new ArrayList<Item>();. Which means compiler only knows that in list items, the type is Item. So when invoke Collections.sort(items), java compiler found Item doesn't implement Comparable. And there will be an error as shown at the beginning.
How to fix? Change definition of Item, make it implement Comparable.
So as you can see, there is nothing about SingleItem. Because it is the impl and items sees only interface Item.
Referring to an earlier question i asked
lining up data in console output java
I wish to put my output in an array so that i can then further put this into a JTable
The extract for my code so far is, i am currently printing out the output to the console.
String assd = null;
String eventy = null;
String assdFT = null;
for (int i = 0; i < list.getLength(); i++) {
Element element = (Element)list.item(i);
String nodeName = element.getNodeName();
switch (nodeName) {
case "assd":
assd = element.getChildNodes().item(0).getNodeValue();
break;
case "eventy":
eventy = element.getChildNodes().item(0).getNodeValue();
break;
case "assdFT":
assdFT = element.getChildNodes().item(0).getNodeValue();
break;
System.out.printf("%-30s %-20s %s%n", assd, eventy,assdFT);
Object[][] data = {{assd, eventy,assdFT}};//this only appears to put the elements in row 1, since System.out.println(data[1][0]) causes an out of array exception but System.out.println(data[0][0]) prints out all the elements of assd
To put data directly into a JTable pass an instance of your custom AbstractTableModel to the JTable constructor. Within TableModel, you can define what data is displayed and how it is accessed.
It would probably look something like this:
public class HeaderTableModel extends AbstractTableModel {
/**
*
*/
private static final long serialVersionUID = 8974549762036798969L;
private Object[][] myData;
public HeaderTableModel(final Object[][] theRows) {
myHeaderRows = theRows;
}
/*
* (non-Javadoc)
*
* #see javax.swing.table.TableModel#getColumnCount()
*/
#Override
public int getColumnCount() {
return LocalStorage.getNumColumns();
}
/*
* (non-Javadoc)
*
* #see javax.swing.table.TableModel#getRowCount()
*/
#Override
public int getRowCount() {
return LocalStorage.getNumRows();
}
/*
* (non-Javadoc)
*
* #see javax.swing.table.TableModel#getValueAt(int, int)
*/
#Override
public Object getValueAt(final int theRow, final int theColumn) {
return myHeaderRows[theRow][theColumn];
}