I have generated an Apache Avro class which is used to produce and consume the Avro messages by the client application as well as the server side code.
I have been searching on the internet for achieving a couple of use cases.
writing the Avro messages as binary data on the HDFS.
Converting the byte array binary data by using the Avro generated
class to get the messages as a string and write them to HDFS.
Are there any other ways of achieving the above use cases without any third party libraries like Confluent or Twitter Bijection API.
Btw, I would like to write all the Avro messages to a single HDFS file.
Avro Generated class:
/**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package com.avrotohdfs.classes.avro;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.SchemaStore;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.specific.SpecificRecordBase;
#SuppressWarnings("all")
#org.apache.avro.specific.AvroGenerated
public class AvroSyslogMessage extends SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = -793689732516755717L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"AvroSyslogMessage\",\"namespace\":\"com.cisco.sso.ssodata.avro\",\"fields\":[{\"name\":\"partyID\",\"type\":\"string\"},{\"name\":\"partyName\",\"type\":[\"string\",\"null\"]},{\"name\":\"applianceID\",\"type\":\"string\"},{\"name\":\"message\",\"type\":\"string\"},{\"name\":\"inventoryName\",\"type\":[\"string\",\"null\"]},{\"name\":\"senttime\",\"type\":[\"string\",\"null\"]}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<AvroSyslogMessage> ENCODER =
new BinaryMessageEncoder<AvroSyslogMessage>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<AvroSyslogMessage> DECODER =
new BinaryMessageDecoder<AvroSyslogMessage>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageDecoder instance used by this class.
*/
public static BinaryMessageDecoder<AvroSyslogMessage> 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
*/
public static BinaryMessageDecoder<AvroSyslogMessage> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<AvroSyslogMessage>(MODEL$, SCHEMA$, resolver);
}
/** Serializes this AvroSyslogMessage to a ByteBuffer. */
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/** Deserializes a AvroSyslogMessage from a ByteBuffer. */
public static AvroSyslogMessage fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
#Deprecated public java.lang.CharSequence partyID;
#Deprecated public java.lang.CharSequence partyName;
#Deprecated public java.lang.CharSequence applianceID;
#Deprecated public java.lang.CharSequence message;
#Deprecated public java.lang.CharSequence inventoryName;
#Deprecated public java.lang.CharSequence senttime;
/**
* 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 AvroSyslogMessage() {}
/**
* All-args constructor.
* #param partyID The new value for partyID
* #param partyName The new value for partyName
* #param applianceID The new value for applianceID
* #param message The new value for message
* #param inventoryName The new value for inventoryName
* #param senttime The new value for senttime
*/
public AvroSyslogMessage(java.lang.CharSequence partyID, java.lang.CharSequence partyName, java.lang.CharSequence applianceID, java.lang.CharSequence message, java.lang.CharSequence inventoryName, java.lang.CharSequence senttime) {
this.partyID = partyID;
this.partyName = partyName;
this.applianceID = applianceID;
this.message = message;
this.inventoryName = inventoryName;
this.senttime = senttime;
}
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 partyID;
case 1: return partyName;
case 2: return applianceID;
case 3: return message;
case 4: return inventoryName;
case 5: return senttime;
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: partyID = (java.lang.CharSequence)value$; break;
case 1: partyName = (java.lang.CharSequence)value$; break;
case 2: applianceID = (java.lang.CharSequence)value$; break;
case 3: message = (java.lang.CharSequence)value$; break;
case 4: inventoryName = (java.lang.CharSequence)value$; break;
case 5: senttime = (java.lang.CharSequence)value$; break;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
/**
* Gets the value of the 'partyID' field.
* #return The value of the 'partyID' field.
*/
public java.lang.CharSequence getPartyID() {
return partyID;
}
/**
* Sets the value of the 'partyID' field.
* #param value the value to set.
*/
public void setPartyID(java.lang.CharSequence value) {
this.partyID = value;
}
/**
* Gets the value of the 'partyName' field.
* #return The value of the 'partyName' field.
*/
public java.lang.CharSequence getPartyName() {
return partyName;
}
/**
* Sets the value of the 'partyName' field.
* #param value the value to set.
*/
public void setPartyName(java.lang.CharSequence value) {
this.partyName = value;
}
/**
* Gets the value of the 'applianceID' field.
* #return The value of the 'applianceID' field.
*/
public java.lang.CharSequence getApplianceID() {
return applianceID;
}
/**
* Sets the value of the 'applianceID' field.
* #param value the value to set.
*/
public void setApplianceID(java.lang.CharSequence value) {
this.applianceID = value;
}
/**
* Gets the value of the 'message' field.
* #return The value of the 'message' field.
*/
public java.lang.CharSequence getMessage() {
return message;
}
/**
* Sets the value of the 'message' field.
* #param value the value to set.
*/
public void setMessage(java.lang.CharSequence value) {
this.message = value;
}
/**
* Gets the value of the 'inventoryName' field.
* #return The value of the 'inventoryName' field.
*/
public java.lang.CharSequence getInventoryName() {
return inventoryName;
}
/**
* Sets the value of the 'inventoryName' field.
* #param value the value to set.
*/
public void setInventoryName(java.lang.CharSequence value) {
this.inventoryName = value;
}
/**
* Gets the value of the 'senttime' field.
* #return The value of the 'senttime' field.
*/
public java.lang.CharSequence getSenttime() {
return senttime;
}
/**
* Sets the value of the 'senttime' field.
* #param value the value to set.
*/
public void setSenttime(java.lang.CharSequence value) {
this.senttime = value;
}
/**
* Creates a new AvroSyslogMessage RecordBuilder.
* #return A new AvroSyslogMessage RecordBuilder
*/
public static com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder newBuilder() {
return new com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder();
}
/**
* Creates a new AvroSyslogMessage RecordBuilder by copying an existing Builder.
* #param other The existing builder to copy.
* #return A new AvroSyslogMessage RecordBuilder
*/
public static com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder newBuilder(com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder other) {
return new com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder(other);
}
/**
* Creates a new AvroSyslogMessage RecordBuilder by copying an existing AvroSyslogMessage instance.
* #param other The existing instance to copy.
* #return A new AvroSyslogMessage RecordBuilder
*/
public static com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder newBuilder(com.cisco.sso.ssodata.avro.AvroSyslogMessage other) {
return new com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder(other);
}
/**
* RecordBuilder for AvroSyslogMessage instances.
*/
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<AvroSyslogMessage>
implements org.apache.avro.data.RecordBuilder<AvroSyslogMessage> {
private java.lang.CharSequence partyID;
private java.lang.CharSequence partyName;
private java.lang.CharSequence applianceID;
private java.lang.CharSequence message;
private java.lang.CharSequence inventoryName;
private java.lang.CharSequence senttime;
/** 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.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder other) {
super(other);
if (isValidValue(fields()[0], other.partyID)) {
this.partyID = data().deepCopy(fields()[0].schema(), other.partyID);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.partyName)) {
this.partyName = data().deepCopy(fields()[1].schema(), other.partyName);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.applianceID)) {
this.applianceID = data().deepCopy(fields()[2].schema(), other.applianceID);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.message)) {
this.message = data().deepCopy(fields()[3].schema(), other.message);
fieldSetFlags()[3] = true;
}
if (isValidValue(fields()[4], other.inventoryName)) {
this.inventoryName = data().deepCopy(fields()[4].schema(), other.inventoryName);
fieldSetFlags()[4] = true;
}
if (isValidValue(fields()[5], other.senttime)) {
this.senttime = data().deepCopy(fields()[5].schema(), other.senttime);
fieldSetFlags()[5] = true;
}
}
/**
* Creates a Builder by copying an existing AvroSyslogMessage instance
* #param other The existing instance to copy.
*/
private Builder(com.cisco.sso.ssodata.avro.AvroSyslogMessage other) {
super(SCHEMA$);
if (isValidValue(fields()[0], other.partyID)) {
this.partyID = data().deepCopy(fields()[0].schema(), other.partyID);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.partyName)) {
this.partyName = data().deepCopy(fields()[1].schema(), other.partyName);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.applianceID)) {
this.applianceID = data().deepCopy(fields()[2].schema(), other.applianceID);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.message)) {
this.message = data().deepCopy(fields()[3].schema(), other.message);
fieldSetFlags()[3] = true;
}
if (isValidValue(fields()[4], other.inventoryName)) {
this.inventoryName = data().deepCopy(fields()[4].schema(), other.inventoryName);
fieldSetFlags()[4] = true;
}
if (isValidValue(fields()[5], other.senttime)) {
this.senttime = data().deepCopy(fields()[5].schema(), other.senttime);
fieldSetFlags()[5] = true;
}
}
/**
* Gets the value of the 'partyID' field.
* #return The value.
*/
public java.lang.CharSequence getPartyID() {
return partyID;
}
/**
* Sets the value of the 'partyID' field.
* #param value The value of 'partyID'.
* #return This builder.
*/
public com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder setPartyID(java.lang.CharSequence value) {
validate(fields()[0], value);
this.partyID = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'partyID' field has been set.
* #return True if the 'partyID' field has been set, false otherwise.
*/
public boolean hasPartyID() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'partyID' field.
* #return This builder.
*/
public com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder clearPartyID() {
partyID = null;
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'partyName' field.
* #return The value.
*/
public java.lang.CharSequence getPartyName() {
return partyName;
}
/**
* Sets the value of the 'partyName' field.
* #param value The value of 'partyName'.
* #return This builder.
*/
public com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder setPartyName(java.lang.CharSequence value) {
validate(fields()[1], value);
this.partyName = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'partyName' field has been set.
* #return True if the 'partyName' field has been set, false otherwise.
*/
public boolean hasPartyName() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'partyName' field.
* #return This builder.
*/
public com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder clearPartyName() {
partyName = null;
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'applianceID' field.
* #return The value.
*/
public java.lang.CharSequence getApplianceID() {
return applianceID;
}
/**
* Sets the value of the 'applianceID' field.
* #param value The value of 'applianceID'.
* #return This builder.
*/
public com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder setApplianceID(java.lang.CharSequence value) {
validate(fields()[2], value);
this.applianceID = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'applianceID' field has been set.
* #return True if the 'applianceID' field has been set, false otherwise.
*/
public boolean hasApplianceID() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'applianceID' field.
* #return This builder.
*/
public com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder clearApplianceID() {
applianceID = null;
fieldSetFlags()[2] = false;
return this;
}
/**
* Gets the value of the 'message' field.
* #return The value.
*/
public java.lang.CharSequence getMessage() {
return message;
}
/**
* Sets the value of the 'message' field.
* #param value The value of 'message'.
* #return This builder.
*/
public com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder setMessage(java.lang.CharSequence value) {
validate(fields()[3], value);
this.message = value;
fieldSetFlags()[3] = true;
return this;
}
/**
* Checks whether the 'message' field has been set.
* #return True if the 'message' field has been set, false otherwise.
*/
public boolean hasMessage() {
return fieldSetFlags()[3];
}
/**
* Clears the value of the 'message' field.
* #return This builder.
*/
public com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder clearMessage() {
message = null;
fieldSetFlags()[3] = false;
return this;
}
/**
* Gets the value of the 'inventoryName' field.
* #return The value.
*/
public java.lang.CharSequence getInventoryName() {
return inventoryName;
}
/**
* Sets the value of the 'inventoryName' field.
* #param value The value of 'inventoryName'.
* #return This builder.
*/
public com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder setInventoryName(java.lang.CharSequence value) {
validate(fields()[4], value);
this.inventoryName = value;
fieldSetFlags()[4] = true;
return this;
}
/**
* Checks whether the 'inventoryName' field has been set.
* #return True if the 'inventoryName' field has been set, false otherwise.
*/
public boolean hasInventoryName() {
return fieldSetFlags()[4];
}
/**
* Clears the value of the 'inventoryName' field.
* #return This builder.
*/
public com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder clearInventoryName() {
inventoryName = null;
fieldSetFlags()[4] = false;
return this;
}
/**
* Gets the value of the 'senttime' field.
* #return The value.
*/
public java.lang.CharSequence getSenttime() {
return senttime;
}
/**
* Sets the value of the 'senttime' field.
* #param value The value of 'senttime'.
* #return This builder.
*/
public com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder setSenttime(java.lang.CharSequence value) {
validate(fields()[5], value);
this.senttime = value;
fieldSetFlags()[5] = true;
return this;
}
/**
* Checks whether the 'senttime' field has been set.
* #return True if the 'senttime' field has been set, false otherwise.
*/
public boolean hasSenttime() {
return fieldSetFlags()[5];
}
/**
* Clears the value of the 'senttime' field.
* #return This builder.
*/
public com.cisco.sso.ssodata.avro.AvroSyslogMessage.Builder clearSenttime() {
senttime = null;
fieldSetFlags()[5] = false;
return this;
}
#Override
#SuppressWarnings("unchecked")
public AvroSyslogMessage build() {
try {
AvroSyslogMessage record = new AvroSyslogMessage();
record.partyID = fieldSetFlags()[0] ? this.partyID : (java.lang.CharSequence) defaultValue(fields()[0]);
record.partyName = fieldSetFlags()[1] ? this.partyName : (java.lang.CharSequence) defaultValue(fields()[1]);
record.applianceID = fieldSetFlags()[2] ? this.applianceID : (java.lang.CharSequence) defaultValue(fields()[2]);
record.message = fieldSetFlags()[3] ? this.message : (java.lang.CharSequence) defaultValue(fields()[3]);
record.inventoryName = fieldSetFlags()[4] ? this.inventoryName : (java.lang.CharSequence) defaultValue(fields()[4]);
record.senttime = fieldSetFlags()[5] ? this.senttime : (java.lang.CharSequence) defaultValue(fields()[5]);
return record;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
#SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<AvroSyslogMessage>
WRITER$ = (org.apache.avro.io.DatumWriter<AvroSyslogMessage>)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<AvroSyslogMessage>
READER$ = (org.apache.avro.io.DatumReader<AvroSyslogMessage>)MODEL$.createDatumReader(SCHEMA$);
#Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
}
Code to write the Avro messages as a byte array to HDFS:
#Autowired
private PropertyConfig config;
FSDataOutputStream out = null;
public void consume() throws IOException {
String topic = config.getDedupServiceConsumerTopic();
String consGroup = config.getDedupServiceConsGroup();
KafkaConsumer<String, AvroSyslogMessage> consumer = new GenericConsumer<String, AvroSyslogMessage>()
.initialize(topic, consGroup, STREAMSERDE.STRINGDESER, STREAMSERDE.AVRODESER);
logger.debug("Dedupe Kafka Consumer Initialized......");
try {
while (true) {
ConsumerRecords<String, AvroSyslogMessage> records = consumer.poll(100);
for (ConsumerRecord<String, AvroSyslogMessage> record : records) {
logger.debug("record.offset() = " + record.offset() + " : record.key() = " + record.key());
AvroSyslogMessage avroMessage = record.value();
logger.info("avro Message = " + avroMessage);
Configuration config = new Configuration();
FileSystem fs = FileSystem.get(config);
String s = fs.getHomeDirectory() + "/syslog";
Path path = new Path(s);
DistributedFileSystem dfs = new DistributedFileSystem();
if (!dfs.exists(path)) {
dfs.createNewFile(path);
out = fs.create(path);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput ooput = new ObjectOutputStream(bos);
ooput.writeObject(avroMessage);
logger.info("Writing avro message to hdfs");
out.write(bos.toByteArray());
}
}
} catch (Exception e) {
logger.error("Error occured while processing message", e);
} finally {
logger.debug("debupe kafka consume is closing");
consumer.close();
out.close();
}
}
My question is to understand if this is the right approach to write Avro messages as byte arrays to the HDFS.
I am getting this warning when using Gson to convert a JSON string to a Java object. Why am I getting it and how can I solve it?
This is the warning I getting in code:
Unchecked assignment:
'net.brawtasports.brawtasportsgps.model.JSONKeys' to
'net.brawtasports.brawtasportsgps.model.JSONKeys<net.brawtasports.brawtasportsgps.model.team.Object>'
This is the error I get at runtime:
java.lang.ClassCastException:
com.google.gson.internal.LinkedTreeMap cannot be cast to
net.brawtasports.brawtasportsgps.model.team.Object
And this is my code:
String jsonString = Preferences.readFromPreferences(ApplicationConstants.team_data,"");
Gson gson = new Gson();
JSONKeys<Object> teamMembers = gson.fromJson(jsonString, JSONKeys.class); //converts json string to java object
Object players = teamMembers.getObject();//object is my custom class
//ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_dropdown_item,players);
ArrayAdapter arrayAdapter = new ArrayAdapter(getActivity(),android.R.layout.simple_spinner_dropdown_item,players.getPlayersSummary());
player1.setAdapter(arrayAdapter);
Here is the code for my JSONKeys POJO:
public class JSONKeys<T> {
private boolean Success;
private String Message;
private int ObjectIdentifier;
private T Object;
private java.util.List<List> List = new ArrayList<List>();
private int TotalRecords;
private String ErrorMessage;
private int Code;
private net.brawtasports.brawtasportsgps.model.match.Criteria Criteria;
private net.brawtasports.brawtasportsgps.model.match.SearchInfo SearchInfo;
//Add Object from match class
/**
* #return The Criteria
*/
public net.brawtasports.brawtasportsgps.model.match.Criteria getCriteria() {
return Criteria;
}
/**
* #param Criteria The Criteria
*/
public void setCriteria(net.brawtasports.brawtasportsgps.model.match.Criteria Criteria) {
this.Criteria = Criteria;
}
/**
* #return The SearchInfo
*/
public net.brawtasports.brawtasportsgps.model.match.SearchInfo getSearchInfo() {
return SearchInfo;
}
/**
* #param SearchInfo The SearchInfo
*/
public void setSearchInfo(net.brawtasports.brawtasportsgps.model.match.SearchInfo SearchInfo) {
this.SearchInfo = SearchInfo;
}
/**
* #return The List
*/
public java.util.List<List> getList() {
return List;
}
/**
* #param List The List
*/
public void setLArrayListList(java.util.List<List> List) {
this.List = List;
}
/**
* #return The Code
*/
public int getCode() {
return Code;
}
/**
* #param Code The Code
*/
public void setCode(int Code) {
this.Code = Code;
}
/**
* #return The TotalRecords
*/
public int getTotalRecords() {
return TotalRecords;
}
/**
* #param TotalRecords The TotalRecords
*/
public void setTotalRecords(int TotalRecords) {
this.TotalRecords = TotalRecords;
}
/**
* #return The ErrorMessage
*/
public String getErrorMessage() {
return ErrorMessage;
}
/**
* #param ErrorMessage The ErrorMessage
*/
public void setErrorMessage(String ErrorMessage) {
this.ErrorMessage = ErrorMessage;
}
/**
*
* #return
* The message
*/
public String getMessage() {
return Message;
}
/**
*
* #param message
* The message
*/
public void setMessage(String message) {
this.Message = message;
}
/**
*
* #return
* The Success
*/
public boolean isSuccess() {
return Success;
}
/**
*
* #param Success
* The Success
*/
public void setSuccess(boolean Success) {
this.Success = Success;
}
/**
*
* #return
* The ObjectIdentifier
*/
public int getObjectIdentifier() {
return ObjectIdentifier;
}
/**
*
* #param ObjectIdentifier
* The ObjectIdentifier
*/
public void setObjectIdentifier(int ObjectIdentifier) {
this.ObjectIdentifier = ObjectIdentifier;
}
/**
*
* #return
* The Object
*/
public T getObject() {
return Object;
}
/**
*
* #param Object
* The Object
*/
public void setObject(T Object) {
this.Object = Object;
}
}
and for my Object POJO it is:
public class Object {
private HomeTeamGoals HomeTeamGoals;
private AwayTeamGoals AwayTeamGoals;
private List<PlayersSummary> PlayersSummary = new ArrayList<PlayersSummary>();
private TeamSummary TeamSummary;
/**
*
* #return
* The HomeTeamGoals
*/
public HomeTeamGoals getHomeTeamGoals() {
return HomeTeamGoals;
}
/**
*
* #param HomeTeamGoals
* The HomeTeamGoals
*/
public void setHomeTeamGoals(HomeTeamGoals HomeTeamGoals) {
this.HomeTeamGoals = HomeTeamGoals;
}
/**
*
* #return
* The AwayTeamGoals
*/
public AwayTeamGoals getAwayTeamGoals() {
return AwayTeamGoals;
}
/**
*
* #param AwayTeamGoals
* The AwayTeamGoals
*/
public void setAwayTeamGoals(AwayTeamGoals AwayTeamGoals) {
this.AwayTeamGoals = AwayTeamGoals;
}
/**
*
* #return
* The PlayersSummary
*/
public List<PlayersSummary> getPlayersSummary() {
return PlayersSummary;
}
/**
*
* #param PlayersSummary
* The PlayersSummary
*/
public void setPlayersSummary(List<PlayersSummary> PlayersSummary) {
this.PlayersSummary = PlayersSummary;
}
/**
*
* #return
* The TeamSummary
*/
public TeamSummary getTeamSummary() {
return TeamSummary;
}
/**
*
* #param TeamSummary
* The TeamSummary
*/
public void setTeamSummary(TeamSummary TeamSummary) {
this.TeamSummary = TeamSummary;
}
}
You need to use a fully specified type when deserializing generics. They key line that needs changing is here:
JSONKeys<Object> teamMembers = gson.fromJson(jsonString, JSONKeys.class);
Because you're using JSONKeys.class, Gson doesn't know what the generic type of JSONKeys is. Instead, use this:
JSONKeys<Object> teamMembers = gson.fromJson(jsonString,
new TypeToken<JSONKeys<net.brawtasports.brawtasportsgps.model.team.Object>>(){}.getType());
This will tell Gson which generic type you need to use. See my explanation for why this works here: How does Gson TypeToken work?
As an aside, don't name your classes the same thing as anything in the java.lang package. It makes your code really confusing for people reading it and can cause unforseen bugs when you accidentally refer to the wrong one by forgetting an import statement.
This table is produced by my code below. (The table's data is rubbish)
Question:
How can I get a list of the items under a certain column in the order they appear?
I want to do something like table.GetListFromColumn("carmake") so I would have ["Aston Martin" , "Porche 911", "ferrari"].
Or beanItemContainer.GetListFromColumn("carmake")?
#Override
public void init(VaadinRequest request) {
BrakeResponseTime time1 = new BrakeResponseTime(0.2f);
BrakeResponseTime time2 = new BrakeResponseTime(0.8f);
BrakeResponseTime time3 = new BrakeResponseTime(0.5f);
Collection<SportsCar>c = new ArrayList<SportsCar>();
c.add(new SportsCar("ferrari", 180.0, "Tom", time1));
c.add(new SportsCar("Aston Martin", 165.0, "Harry", time2));
c.add(new SportsCar("Porche 911", 145.0, "Dick", time3));
MyBeanItemContainer container = new MyBeanItemContainer(SportsCar.class,c);
Table table = new Table();
t.setContainerDataSource(container);
this.setContent(table);
}
.
public class BrakeResponseTime implements Comparable<BrakeResponseTime> {
float time;
/**
* Create a Demo.BrakeResponseTime.
*/
public BrakeResponseTime(float time) {
this.time = time;
}
/**
* Get the time.
*
* #return the time.
*/
public float getTime() {
return time;
}
/**
* Set the time.
*
* #param time
* the time.
*/
public void setTime(float time) {
this.time = time;
}
#Override
public String toString() {
return time +"/%";
}
/*
* (non-Javadoc)
*
* #see java.lang.Comparable#compareTo(java.lang.Object)
*/
#Override
public int compareTo(BrakeResponseTime o) {
if (null == o) {
return 1;
}
if(time==o.getTime()){
return 0;
}
return (time < o.getTime() ? -1 : 1);
}
}
.
public class MyBeanItemContainer extends BeanItemContainer<SportsCar> {
/**
* Create a Demo.MyBeanItemContainer.
*/
public MyBeanItemContainer(Class<SportsCar> type, Collection<SportsCar> collection) {
super(type, collection);
}
private int compareBrakeResponseTimeWithNullCheck(BrakeResponseTime o1, BrakeResponseTime o2) {
if (null == o1 && (null == o2)) {
return 0;
} else if (null == o1 && (null != o2)) {
return -1;
}else if(null != o1 && (null == o2)){
return 1;
} else {
return o1.compareTo(o2);
}
}
#Override
public void sort(final Object[] propertyId, final boolean[] ascending) {
super.sort(propertyId, ascending);
System.out.println(Arrays.toString(propertyId));
final boolean sortAscending = ascending[0];
final Object sortContainerPropertyId = propertyId[0];
List<SportsCar> list = super.getAllItemIds();
Collections.sort(list, new Comparator<SportsCar>() {
#Override
public int compare(final SportsCar o1, final SportsCar o2) {
int result = 0;
if ("responseTime".equals(sortContainerPropertyId)) {
result = compareBrakeResponseTimeWithNullCheck(o1.getResponseTime(), o2.getResponseTime());
}
if (!sortAscending) {
result *= -1;
}
return result;
}
});
}
}
public class SportsCar {
String carMake;
double topspeed;
String driver;
BrakeResponseTime responseTime;
public SportsCar(String carMake, double topspeed, String driver, BrakeResponseTime responseTime) {
this.carMake = carMake;
this.topspeed = topspeed;
this.driver = driver;
this.responseTime = responseTime;
}
/**
* Get the carMake.
*
* #return the carMake.
*/
public String getcarMake() {
return carMake;
}
/**
* Set the carMake.
*
* #param carMake
* the carMake.
*/
public void setcarMake(String carMake) {
this.carMake = carMake;
}
/**
* Get the topspeed.
*
* #return the topspeed.
*/
public double getTopspeed() {
return topspeed;
}
/**
* Set the topspeed.
*
* #param topspeed
* the topspeed.
*/
public void setTopspeed(double topspeed) {
this.topspeed = topspeed;
}
/**
* Get the driver.
*
* #return the driver.
*/
public String getDriver() {
return driver;
}
/**
* Set the driver.
*
* #param driver
* the driver.
*/
public void setDriver(String driver) {
this.driver = driver;
}
/**
* Get the responseTime.
* #return the responseTime.
*/
public BrakeResponseTime getResponseTime() {
return responseTime;
}
/**
* Set the responseTime.
* #param responseTime the responseTime.
*/
public void setResponseTime(BrakeResponseTime responseTime) {
this.responseTime = responseTime;
}
}
I hadn't realised I could access the bean container's properties in this way.
container.getIdByIndex(0).getCarMake()
This is what I was looking for!
I'm creating small javaEE Application I have problem with vendorsProdcut name dropdownbox is not showing name only array object like this see the images
Just want to ask how can I get the product name from arraylist to fix my problem?
just wondering is there are away to bring arraylist product name from
productViewModel.getAllProductForVendor
HTML
<div class="ui-block-a">
<h:selectOneMenu id="productname" value="#{productViewModel.prodname}" onchange="javascript: return this.form.submit();">
<f:selectItems value="#{productViewModel.getAllProductForVendor(vendorViewModel.vendorno)}"></f:selectItems>
</h:selectOneMenu>
</div>
Java Beans
public ArrayList<ProductEJBDTO> getAllProductForVendor(int vendorno) {
ArrayList<ProductEJBDTO> Products = new ArrayList() ;
//model.getProducts(vendorno);
try
{
Products = productFacadeBean.getAllProductsForVendor(vendorno);
}
catch(Exception e)
{
System.out.println("can't get products for vendors " + e);
}
return Products;
}
DTO
package case2dtos;
import java.io.Serializable;
import java.math.BigDecimal;
/**
*
* #author abdallaelnajjar
*/
public class ProductEJBDTO implements Serializable {
public ProductEJBDTO(){}
private int vendorno;
private String prodcd;
private String vensku;
private String prodnam;
private BigDecimal costprice;
private BigDecimal msrp;
private int rop;
private int eoq;
private int qoh;
private int qoo;
private byte[] qrcode;
/**
* #return the prodcd
*/
public String getProdcd() {
return prodcd;
}
/**
* #param prodcd the prodcd to set
*/
public void setProdcd(String prodcd) {
this.prodcd = prodcd;
}
/**
* #return the vensku
*/
public String getVensku() {
return vensku;
}
/**
* #param vensku the vensku to set
*/
public void setVensku(String vensku) {
this.vensku = vensku;
}
/**
* #return the prodnam
*/
public String getProdnam() {
return prodnam;
}
/**
* #param prodnam the prodnam to set
*/
public void setProdnam(String prodnam) {
this.prodnam = prodnam;
}
/**
* #return the costprice
*/
public BigDecimal getCostprice() {
return costprice;
}
/**
* #param costprice the costprice to set
*/
public void setCostprice(BigDecimal costprice) {
this.costprice = costprice;
}
/**
* #return the msrp
*/
public BigDecimal getMsrp() {
return msrp;
}
/**
* #param msrp the msrp to set
*/
public void setMsrp(BigDecimal msrp) {
this.msrp = msrp;
}
/**
* #return the rop
*/
public int getRop() {
return rop;
}
/**
* #param rop the rop to set
*/
public void setRop(int rop) {
this.rop = rop;
}
/**
* #return the eoq
*/
public int getEoq() {
return eoq;
}
/**
* #param eoq the eoq to set
*/
public void setEoq(int eoq) {
this.eoq = eoq;
}
/**
* #return the qoh
*/
public int getQoh() {
return qoh;
}
/**
* #param qoh the qoh to set
*/
public void setQoh(int qoh) {
this.qoh = qoh;
}
/**
* #return the qoo
*/
public int getQoo() {
return qoo;
}
/**
* #param qoo the qoo to set
*/
public void setQoo(int qoo) {
this.qoo = qoo;
}
/**
* #return the qrcode
*/
public byte[] getQrcode() {
return qrcode;
}
/**
* #param qrcode the qrcode to set
*/
public void setQrcode(byte[] qrcode) {
this.qrcode = qrcode;
}
/**
* #return the vendorno
*/
public int getVendorno() {
return vendorno;
}
/**
* #param vendorno the vendorno to set
*/
public void setVendorno(int vendorno) {
this.vendorno = vendorno;
}
}
Override the toString() method in the ProductEJBDTO to return the name.
public class ProductEJBDTO implements Serializable {
...
...
#Override
public String toString() {
return this.prodnam; // The product name you want to display.
}
}
Use the itemLabel attribute (docs):
<f:selectItems value="..." var="x" itemLabel="#{x.prodnam}"></f:selectItems>
(I assume the prodnam property is the desired display name; any EL expression will do though)
I am having some difficult on a jtable bound on a observablelist of objects called EntradaMercadoriaList. After adding all objects in this list, jtable shows only empty rows equivalent of the list size
here is my code:
List <EntradaMercadoria> merc = new ArrayList<EntradaMercadoria>();
for (int i = 0; i < entradasList.size(); i++) {
int nf = entradasList.get(i).getDocOrigem();
int tipo = entradasList.get(i).getTipoDocOrigem().getIdesPecasTipoOrigem();
String fornecedor = "não-aplicado";
if (tipo == 2) {
NfTerc nfTerc;
nfTerc = entityManager.find(NfTerc.class, entradasList.get(i).getDocOrigem());
fornecedor = nfTerc.getFornecedoresNumForn().getNumForn() + " - " + nfTerc.getFornecedoresNumForn().getCodPessoa().getNomePessoa();
}
boolean novo = true;
for (int j = 0; j < merc.size(); j++) {
if (nf == merc.get(j).getnDoc() && fornecedor.equals(merc.get(j).getFornecedor())) {
merc.get(j).setQuantidade(merc.get(j).getQuantidade() + 1.00);
novo = false;
}
}
if (novo) {
EntradaMercadoria em = new EntradaMercadoria();
em.setDataEmissao(entradasList.get(i).getDataOrigem());
em.setFornecedor(fornecedor);
em.setQuantidade(1.00);
em.setTipoDoc(tipo);
em.setnDoc(nf);
merc.add(em);
}
}
entradaMercadoriaList.clear();
entradaMercadoriaList.addAll(merc);
Here is my EntadaMercadoria object:
import java.util.Date;
/**
*
* #author Bernardo
*/
class EntradaMercadoria {
private int nDoc;
private int tipoDoc;
private String fornecedor;
private double quantidade;
private Date dataEmissao;
public EntradaMercadoria() {
}
/**
* #return the nDoc
*/
public int getnDoc() {
return nDoc;
}
/**
* #param nDoc the nDoc to set
*/
public void setnDoc(int nDoc) {
this.nDoc = nDoc;
}
/**
* #return the tipoDoc
*/
public int getTipoDoc() {
return tipoDoc;
}
/**
* #param tipoDoc the tipoDoc to set
*/
public void setTipoDoc(int tipoDoc) {
this.tipoDoc = tipoDoc;
}
/**
* #return the fornecedor
*/
public String getFornecedor() {
return fornecedor;
}
/**
* #param fornecedor the fornecedor to set
*/
public void setFornecedor(String fornecedor) {
this.fornecedor = fornecedor;
}
/**
* #return the quantidade
*/
public double getQuantidade() {
return quantidade;
}
/**
* #param quantidade the quantidade to set
*/
public void setQuantidade(double quantidade) {
this.quantidade = quantidade;
}
/**
* #return the dataEmissao
*/
public Date getDataEmissao() {
return dataEmissao;
}
/**
* #param dataEmissao the dataEmissao to set
*/
public void setDataEmissao(Date dataEmissao) {
this.dataEmissao = dataEmissao;
}
}
What is wrong? is There a way to refresh table to show data in lines?
Thanks.