Java warning and error (read object) - java

My goal: save one ArrayList to a .dat file, after read this file and in the end print this array.
To save the ArrayList, "equipas" is one ArrayList< Equipa>, I use this function:
saveMyFile("Equipas.dat", (Object) equipas);
To read:
public static ArrayList<Equipa> readMyFile(String s){
ArrayList<Equipa> novo = new ArrayList<Equipa>();
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(s));
novo = (ArrayList<Equipa>) ois.readObject();
ois.close();
}
catch(IOException er) { System.out.println(er.getMessage()); }
catch(ClassNotFoundException er) { System.out.println(er.getMessage()); }
return novo;}
In this read function, I have one Compilation Warning: "…uses unchecked or unsafe operations. Recompile with - Xlint:unchecked for details."
To save:
public static void saveMyFile(String s, Object o)
{
try {
ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(s));
oos.writeObject(o);
oos.flush();
oos.close();
}
catch(IOException e) { System.out.println(e.getMessage()); }
}
Finally, I want to print the ArrayList's info:
ArrayList<Equipa> cena = new ArrayList<Equipa>();
cena=(ArrayList<Equipa>) readMyFile("Equipas.dat");
for(Equipa e:cena)
e.toString();
Error when I try to run:
" writing aborted; java.io.NotSerializableException: Equipa"
Equipa havs the Serializable:
import java.util.*;
import java.io.*;
public class Equipa implements Serializable
{
private String nome;
private Carro carro;
private ArrayList<Piloto> pilotos;
private double tempoDecorrido;
private int pontos;
private boolean desistiu;
private int voltaDesistencia;
private Piloto piloto;
/**
* Constructor for objects of class Equipa
*/
public Equipa()
{
this.nome = "NA";
this.carro = null;
this.pilotos = new ArrayList<Piloto>();
this.tempoDecorrido = 0;
this.pontos = 0;
this.desistiu = false;
this.voltaDesistencia = 0;
this.piloto = null;
}
public Equipa(String nome, Carro carro, ArrayList<Piloto> pilotos)
{
this.nome = nome;
this.carro = carro;
//this.pilotos = new ArrayList<Piloto>(pilotos);
this.pilotos = pilotos;
this.tempoDecorrido = 0;
this.pontos = 0;
this.desistiu = false;
this.voltaDesistencia = 0;
//this.piloto = pilotos.get(0);
}
public Equipa (Equipa e)
{
this.nome = e.getNome();
this.carro = e.getCarro();
this.pilotos = e.getPilotos();
this.tempoDecorrido = e.getTempoDecorrido();
this.pontos = e.getPontos();
this.desistiu = e.getDesistiu();
this.voltaDesistencia = e.getVoltaDesistencia();
//this.piloto = e.getPiloto();
}
/** Getters */
public String getNome()
{
return this.nome;
}
public Carro getCarro()
{
return this.carro;
}
public ArrayList<Piloto> getPilotos()
{
return new ArrayList<Piloto>(this.pilotos);
}
public double getTempoDecorrido()
{
return this.tempoDecorrido;
}
public int getPontos()
{
return this.pontos;
}
public boolean getDesistiu()
{
return this.desistiu;
}
public int getVoltaDesistencia()
{
return this.voltaDesistencia;
}
public Piloto getPiloto()
{
return this.piloto;
}
/** Setters */
public void setNome(String nome)
{
this.nome = nome;
}
public void setCarro(Carro carro)
{
this.carro = carro;
}
public void setPilotos(ArrayList<Piloto> pilotos)
{
this.pilotos = new ArrayList<Piloto>(pilotos);
}
public void setTempoDecorrido(double tempoDecorrido)
{
this.tempoDecorrido = tempoDecorrido;
}
public void setPontos(int pontos)
{
this.pontos = pontos;
}
public void setDesistiu(boolean desistiu)
{
this.desistiu = desistiu;
}
public void setVoltaDesistencia(int voltaDesistencia)
{
this.voltaDesistencia = voltaDesistencia;
}
public void setPiloto(Piloto piloto)
{
this.piloto = piloto;
}
/** Outros Métodos */
public Equipa clone()
{
return new Equipa(this);
}
public boolean equals(Equipa e)
{
if(this.nome == e.getNome())
return true;
else
return false;
}
public String getStringPilotos()
{
String s = new String();
for(Piloto p: this.pilotos)
s = (s + ", " + p.getNome());
return s;
}
public String toString()
{
return new String("Nome da equipa: " + nome + "; Categoria do carro: " + carro.getClass().getName() + "; Marca e modelo: " + carro.getMarca() + " " + carro.getModelo() + "; Pilotos: " + getStringPilotos())+"\n";
}

Implementing Serializable means that serialization is permitted, but not necessarily that it is possible. For it to work, everything referenced by Equipa must also be either primitive or Serializable (and so on, recursively). Is this the case?

Warning in the read function is the result of generics in java. You won't be able to suppress it, unless you use #SuppressWarnings("unchecked") to ignore it.
If you are sure you are reading an ArrayList<Equipa>, you can ignore it without any problem.
With the Equipa code, I can try to point to the Serializable problem: make sure that Carro and Piloto classes are also Serializables. You can add the code of theses classes if you are not sure.

The only type-safer way would be do a custom serialization, using writeObject(OutputStream) and readObjectInputStream say on a class ArrayListOfEquipa maybe using Equipa[] (ArrayList.toArray()).
Not really attractive, if the warning would be the only reason.

Related

How to add remaining batch of n elements into arrayList?

I'm currently learning to develop a simple blockchain program that reads sample data from .txt and creates a new block for every 10 transactions. I was wondering if the given sample data was 23 lines of transactions, is there a way to make a new block that consist of the last 3 transactions ?
Current Output
Block[header=Header[index=0,currHash=51aa6b7cf5fb821189d58b5c995b4308370888efcaac469d79ad0a5d94fb0432, prevHash=0, timestamp=1654785847112], tranx=null]
Block[header=Header[index=0,currHash=92b3582095e2403c68401448e8a34864e8465d0ea51c05f11c23810ec36b4868, prevHash=0, timestamp=1654785847385], tranx=Transaction [tranxLst=[alice|bob|credit|1.0, alice|bob|debit|2.0, alice|bob|debit|3.0, alice|bob|credit|4.0, alice|bob|debit|5.0, alice|bob|credit|6.0, alice|bob|debit|7.0, alice|bob|debit|8.0, alice|bob|debit|9.0, alice|bob|debit|10.0]]]
Block[header=Header[index=0,currHash=7488c600433d78e0fb8586e71a010b1d39a040cb101cc6e3418668d21b614519, prevHash=0, timestamp=1654785847386], tranx=Transaction [tranxLst=[alice|bob|credit|11.0, alice|bob|credit|12.0, alice|bob|debit|13.0, alice|bob|debit|14.0, alice|bob|credit|15.0, alice|bob|credit|16.0, alice|bob|credit|17.0, alice|bob|debit|18.0, alice|bob|credit|19.0, alice|bob|credit|20.0]]]
What I want
Block[header=Header[index=0,currHash=51aa6b7cf5fb821189d58b5c995b4308370888efcaac469d79ad0a5d94fb0432, prevHash=0, timestamp=1654785847112], tranx=null]
Block[header=Header[index=0,currHash=92b3582095e2403c68401448e8a34864e8465d0ea51c05f11c23810ec36b4868, prevHash=0, timestamp=1654785847385], tranx=Transaction [tranxLst=[alice|bob|credit|1.0, alice|bob|debit|2.0, alice|bob|debit|3.0, alice|bob|credit|4.0, alice|bob|debit|5.0, alice|bob|credit|6.0, alice|bob|debit|7.0, alice|bob|debit|8.0, alice|bob|debit|9.0, alice|bob|debit|10.0]]]
Block[header=Header[index=0,currHash=7488c600433d78e0fb8586e71a010b1d39a040cb101cc6e3418668d21b614519, prevHash=0, timestamp=1654785847386], tranx=Transaction [tranxLst=[alice|bob|credit|11.0, alice|bob|credit|12.0, alice|bob|debit|13.0, alice|bob|debit|14.0, alice|bob|credit|15.0, alice|bob|credit|16.0, alice|bob|credit|17.0, alice|bob|debit|18.0, alice|bob|credit|19.0, alice|bob|credit|20.0]]]
Block[header=Header[index=0,currHash=7488c600433d78e0fb8586e71a010b1d39a040cb101cc6e3418668d21b614520, prevHash=0, timestamp=1654785847387], tranx=Transaction [tranxLst=[alice|bob|credit|21.0, alice|bob|credit|22.0, alice|bob|debit|23.0]]]
my code:
Client app
public static void main(String[] args) throws IOException {
homework();
}
static void homework() throws IOException {
int count = 0;
Transaction tranxLst = new Transaction();
Block genesis = new Block("0");
System.out.println(genesis);
BufferedReader bf = new BufferedReader(new FileReader("dummytranx.txt"));
String line = bf.readLine();
while (line != null) {
tranxLst.add(line);
line = bf.readLine();
count++;
if (count % 10 == 0) {
Block newBlock = new Block(genesis.getHeader().getPrevHash());
newBlock.setTranx(tranxLst);
System.out.println(newBlock);
tranxLst.getTranxLst().clear();
}
}
bf.close();
}
Transaction class
public class Transaction implements Serializable {
public static final int SIZE = 10;
/**
* we will comeback to generate the merkle root ie., hash of merkle tree
* merkleRoot = hash
*/
private String merkleRoot = "9a0885f8cd8d94a57cd76150a9c4fa8a4fed2d04c244f259041d8166cdfeca1b8c237b2c4bca57e87acb52c8fa0777da";
// private String merkleRoot;
public String getMerkleRoot() {
return merkleRoot;
}
public void setMerkleRoot(String merkleRoot) {
this.merkleRoot = merkleRoot;
}
/**
* For the data collection, u may want to choose classic array or collection api
*/
private List<String> tranxLst;
public List<String> getTranxLst() {
return tranxLst;
}
public Transaction() {
tranxLst = new ArrayList<>(SIZE);
}
/**
* add()
*/
public void add(String tranx) {
tranxLst.add(tranx);
}
#Override
public String toString() {
return "Transaction [tranxLst=" + tranxLst + "]";
}
}
Block class
public class Block implements Serializable {
private Header header;
public Header getHeader() {
return header;
}
private Transaction tranx;
public Block(String previousHash) {
header = new Header();
header.setTimestamp(new Timestamp(System.currentTimeMillis()).getTime());
header.setPrevHash(previousHash);
String blockHash = Hasher.sha256(getBytes());
header.setCurrHash(blockHash);
}
/**
* getBytes of the Block object
*/
private byte[] getBytes() {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);) {
out.writeObject(this);
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Transaction getTranx() {
return tranx;
}
/**
* aggregation rel
*/
public void setTranx(Transaction tranx) {
this.tranx = tranx;
}
/**
* composition rel
*/
public class Header implements Serializable {
private int index;
private String currHash, prevHash;
private long timestamp;
// getset methods
public String getCurrHash() {
return currHash;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public void setCurrHash(String currHash) {
this.currHash = currHash;
}
public String getPrevHash() {
return prevHash;
}
public void setPrevHash(String prevHash) {
this.prevHash = prevHash;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
#Override
public String toString() {
return "Header [index=" + index + ", currHash=" + currHash + ", prevHash=" + prevHash + ", timestamp="
+ timestamp + "]";
}
}
#Override
public String toString() {
return "Block [header=" + header + ", tranx=" + tranx + "]";
}
}
enter code here
Instead of using a counter in the conditional statement, try ForLoop.
static void homework() throws IOException {
Transaction tranxLst = new Transaction();
Block genesis = new Block("0");
System.out.println(genesis);
BufferedReader bf = new BufferedReader(new FileReader("dummytranx.txt"));
String line = bf.readLine();
while (line != null) {
for (int i = 0; i < 10; i++) {
tranxLst.add(line);
line = bf.readLine();
if (line == null) {
break;
}
}
Block newBlock = new Block(genesis.getHeader().getPrevHash());
newBlock.setTranx(tranxLst);
System.out.println(newBlock);
tranxLst.getTranxLst().clear();
}
bf.close();
}

Implementing Iterator interface with exception handling

I need to create a class library which enables me to read different files (.dat-files with different data representations inside them) and create objects with their content (for every line one object).
I also have to create a unit test which starts the reading of the file, so I dont have to read to whole file first and save the content in an array. I want to use the factory pattern.
Here is my implementation of the class that implements the Iterator-Interface
package klassenbibliothek;
public class MyReader implements Iterator<Object>
{
BufferedReader reader;
MyReader(BufferedReader myReader)
{
reader = myReader;
}
#Override
public boolean hasNext() // aus Stackoverflow, von mir abgeändert
{
try {
return reader.ready();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
throw new NoSuchElementException();
}
}
#Override
public String next()
{
//return SubstancesFileObjectCreator(reader.readLine());
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
// return null;
throw new NoSuchElementException();
}
}
}
My question is: why do I get this error message "finally block does not complete normally"? I am not returning something, I am just throwing an exception.
I want to use the methods hasNext() and next() in my unit test, so that the unit test can controll when it starts to read the file. The unit test is in a different package.
Here are my other classes:
class AbstractFileObjectCreator
package klassenbibliothek;
public abstract class AbstractFileObjectCreator
{
public abstract AbstractFileObject createFileObject(String line);
}
class SubstancesFileObjectCreator
package klassenbibliothek;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SubstancesFileObjectCreator extends AbstractFileObjectCreator
{
MyReader myReader;
public void makeReader() throws IOException
{
String dataFileName = "C:/temp/Substances.dat";
BufferedReader bReader = new BufferedReader(new FileReader(dataFileName));
myReader = new MyReader(bReader);
}
#SuppressWarnings("null")
public AbstractFileObject createFileObject(String line)
{
AbstractFileObject mySubstance = null;
String lineValues[] = myReader.next().split("\t");
if(lineValues[0].equals("R"))
{
boolean dutyToDeclare_local;
boolean isUnwanted_local;
boolean isProhibited_local;
boolean isReach_local;
boolean isDeleted_local;
boolean isHidden_local;
String nodeidRaw = lineValues[1];
float nodeid = Float.parseFloat(nodeidRaw);
String casNrRaw = lineValues[2];
String euIndexCodeRaw = lineValues[3];
String einecsCodeRaw = lineValues[4];
String dutyToDeclareRaw = lineValues[5];
if(dutyToDeclareRaw.equals(1))
{
dutyToDeclare_local = true;
}
else
{
dutyToDeclare_local = false;
}
String isUnwantedRaw = lineValues[6];
if(isUnwantedRaw.equals("1"))
{
isUnwanted_local = true;
}
else
{
isUnwanted_local = false;
}
String isProhibitedRaw = lineValues[7];
if(isProhibitedRaw.equals("1"))
{
isProhibited_local = true;
}
else
{
isProhibited_local = false;
}
String isReachRaw = lineValues[8];
if(isReachRaw.equals("1"))
{
isReach_local = true;
}
else
{
isReach_local = false;
}
String isDeletedRaw = lineValues[9];
if(isDeletedRaw.equals("1"))
{
isDeleted_local = true;
}
else
{
isDeleted_local = false;
}
String isHiddenRaw = lineValues[10];
if(isHiddenRaw.equals("1"))
{
isHidden_local = true;
}
else
{
isHidden_local = false;
}
mySubstance = new Substance(nodeid, casNrRaw, euIndexCodeRaw, einecsCodeRaw, dutyToDeclare_local, isUnwanted_local, isProhibited_local, isReach_local, isDeleted_local, isHidden_local);
// und weiter...
}
else
{
String languageCode = lineValues[1];
String name = lineValues[2];
// Synonym-Objekt erzeugen und zu Substance-Objekt hinzufügen
Synonym newSynonym = new Synonym(languageCode, name);
mySubstance.addAppendix(newSynonym);
while(myReader.hasNext())
{
String lineValues_synonyms[] = myReader.next().split("\t");
String lineValuesZero = lineValues_synonyms[0];
if(lineValuesZero.equals("R"))
{
break; // nicht so gut glaube ich!!!
}
String languageCode_next = lineValues_synonyms[1];
String name_next = lineValues_synonyms[2];
Synonym newSynonym_next = new Synonym(languageCode_next, name_next);
mySubstance.addAppendix(newSynonym_next);
}
}
return mySubstance;
}
}
class AbstractFileObject
package klassenbibliothek;
public abstract class AbstractFileObject
{
boolean isDeleted;
public AbstractFileObject(boolean isDeleted)
{
this.isDeleted = isDeleted;
}
public boolean getIsDeleted()
{
return isDeleted;
}
public abstract void addAppendix(Object newAppendix);
}
class Substance
public class Substance extends AbstractFileObject
{
private float nodeid;
private String casNr;
private String euIndexCode;
private String einecsCode;
private boolean dutyToDeclare;
private boolean isUnwanted;
private boolean isProhibited;
private boolean isReach;
private boolean isDeleted;
private boolean isHidden;
private ArrayList<Synonym> synonymList;
public Substance(float nodeid, String casNr, String euIndexCode, String einecsCode,
boolean dutyToDeclare, boolean isUnwanted, boolean isProhibited, boolean isReach,
boolean isDeleted, boolean isHidden)
{
super(isDeleted);
this.nodeid = nodeid;
this.casNr = casNr;
this.euIndexCode = euIndexCode;
this.einecsCode = einecsCode;
this.dutyToDeclare = dutyToDeclare;
this.isUnwanted = isUnwanted;
this.isProhibited = isProhibited;
this.isReach = isReach;
//this.isDeleted = isDeleted;
this.isHidden = isHidden;
}
// getter and setter
}
class Synonym
package klassenbibliothek;
public class Synonym
{
private String languageCode;
private String name;
public Synonym(String languageCode, String name)
{
this.languageCode = languageCode;
this.name = name;
}
public String getLanguageCode()
{
return languageCode;
}
public String getName()
{
return name;
}
}
unit test
package klassenbibliothek.test;
import static org.junit.Assert.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class SubstancesTest {
#Test
public void test() {
//fail("Not yet implemented");
long startTimeNanos = System.nanoTime();
/*
* While... iterator over data file
*/
}
}
Am I using the factory pattern in the right way? I'm very confused.
A finally block always executes if there is a try-block before it. So yours always throws a NoSuchElementException().
finally
{
// return null;
throw new NoSuchElementException();
}
You should do something in it and not throw an Exception.
Finally blocks are for cleanup. They should not specifically throw exceptions like that. Move the exception throwing out of the finally block.
Remove the throw exception from the finally block and put it in catch block or some other place. Finally block is to release resources that you might be using in your program.

How can I find the line numbers of a method invocation in Java

I need to get the line numbers a specific method is invoked in a .class file.
I took a look at How can I find all the methods that call a given method in Java? It returns the methods that call a method but I need the line numbers in the caller methods, as well.
I solved it by manipulating the code on that link a little
import java.io.InputStream;
import org.objectweb.asm.*;
import org.objectweb.asm.commons.*;
public class App{
public static void main( String[] args ) {
try {
Test test = new Test();
test.findCallers();
}catch (Exception e){
e.printStackTrace();
}
}
}
class Test {
private String targetClass;
private Method targetMethod;
private AppClassVisitor cv;
class AppMethodVisitor extends MethodVisitor {
boolean callsTarget;
int line;
public AppMethodVisitor() {
super(Opcodes.ASM5);
}
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
if (owner.equals("Fibonacci") && name.equals("join") && desc.equals("()V")) {
callsTarget = true;
System.out.println("Function join called on " + this.line);
}
super.visitMethodInsn(opcode, owner, name, desc, itf);
}
public void visitCode() {
callsTarget = false;
}
public void visitLineNumber(int line, Label start) {
this.line = line;
}
public void visitEnd() {
if (callsTarget){
System.out.println(cv.className + cv.methodName + cv.methodDesc + line);
}
}
}
class AppClassVisitor extends ClassVisitor {
private AppMethodVisitor mv = new AppMethodVisitor();
public String className;
public String methodName;
public String methodDesc;
public AppClassVisitor() {
super(Opcodes.ASM5);
}
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
className = name;
}
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
methodName = name;
methodDesc = desc;
return mv;
}
}
public void findCallers() throws Exception {
InputStream stream = App.class.getResourceAsStream("Fibonacci.class");
ClassReader reader = new ClassReader(stream);
cv = new AppClassVisitor();
reader.accept(cv, 0);
stream.close();
}
}
Fibonacci.java content:
public class Fibonacci extends Thread{
int n;
int result;
public Fibonacci(int n){
this.n = n;
}
public void run(){
if((n == 0) || (n == 1)){
result = 1;
}else{
Fibonacci f1 = new Fibonacci(n - 1);
Fibonacci f2 = new Fibonacci(n - 2);
f1.start();
f2.start();
try{
f1.join();
f2.join();
}catch(InterruptedException e){
e.printStackTrace();
}
result = f1.getResult() + f2.getResult();
}
}
public int getResult(){
return result;
}
public static void main(String[] args) {
Fibonacci f1 = new Fibonacci(5);
f1.start();
try{
f1.join();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Answer is " + f1.getResult());
}
}

c# Marshal structure equivalent of java

I would like to create that object same for java. Is it possible to create it?
How it works :
you can find more informaiton how I used it.
using System;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Common.Models;
using System.Text;
namespace Common.Utilities.Helpers
{
public partial class CommareaHelper
{
public static T StringToObject<T>(string buffer)
{
IntPtr pBuf = IntPtr.Zero;
try
{
pBuf = Marshal.StringToBSTR(buffer);
return (T)Marshal.PtrToStructure(pBuf, typeof(T));
}
catch
{
throw;
}
finally
{
pBuf = IntPtr.Zero;
}
}
public static string ObjectToString(Object conversionObject)
{
int size = 0;
IntPtr pBuf = IntPtr.Zero;
try
{
size = Marshal.SizeOf(conversionObject);
pBuf = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(conversionObject, pBuf, false);
return Marshal.PtrToStringAuto(pBuf, size).Substring(0, size/2);
}
catch
{
throw;
}
finally
{
Marshal.FreeHGlobal(pBuf);
}
}
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class Comarea
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)]
private string status;
public string Status
{
get
{
return new string(status).Trim();
}
set
{
status = value.ToFixedCharArray(1, true);
}
}
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
private string operationName;
public string OperationName
{
get
{
return new string(operationName).Trim();
}
set
{
operationName = value.ToFixedCharArray(5, true);
}
}
}
I can fill any object using single line of string and opposite of that operation
string commareaStr = "0TR231";
Commarea commarea = CommareaHelper.StringToObject<Commarea>(commareaStr);

Simple-XML: Overriding an element name at runtime

I am using simple-xml to perform XML serialization/deserialization in my Java application. I have a class as follows:
#Root(name="config")
public class Config{
#Element(name="update_interval")
private int updateInterval;
#Element(name="timestamp")
private long timestamp;
//...
//...
}
Now, this would produce XML like the following:
<config>
<update_interval>2000</update_interval>
<timestamp>1234567890</timestamp>
</config>
Question:
How can I override the element name at runtime, so that in some cases, the XML reads as follows?
<config>
<updt_int>2000</updt_int>
<ts>1234567890</ts>
</config>
Edit:
To clarify, I want to override the element names only in some cases. So basically,
if(condition){
//Override Element Names
} else {
//Serialize Normally
}
I found an easy way to achieve serialization in this case, thanks to this comment.
However, I haven't been able to de-serialize such an XML document. Here's my partial solution:
/*
* Config.java
*/
#Root(name="config", strict = false)
public class Config {
#Element(name="timestamp", required = false)
private long timestamp;
#Element(name = "update_interval", required = false)
private int updateInterval;
public Config() {
}
public int getUpdateInterval() {
return updateInterval;
}
public void setUpdateInterval(int updateInterval) {
this.updateInterval = updateInterval;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
#Override
public String toString() {
return "Config{" +
"timestamp=" + timestamp +
", updateInterval=" + updateInterval +
'}';
}
}
/*
* Custom Visitor implementation
*/
public class MyInterceptor implements Visitor {
private static int sReadCount = 0;
private static int sWriteCount = 0;
#Override
public void read(Type field, NodeMap<InputNode> node) throws Exception {
/*
* This is where I need help!
*
*
* This method is only called once: for the <config> node
* It is not called for the other nodes since they are not "recognized"
* i.e., there are no annotations for the nodes <ts> and <updt_int>
*/
System.out.println("Read Count : "+ (++sReadCount));
System.out.println(node.getName());
System.out.println(node.getNode());
}
#Override
public void write(Type field, NodeMap<OutputNode> node) throws Exception {
/*
* This works like a charm.
*/
System.out.println("Write Count : "+ (++sWriteCount));
OutputNode opNode = node.getNode();
if("timestamp".equals(opNode.getName())){
opNode.setName("ts");
}
if("update_interval".equals(opNode.getName())){
opNode.setName("updt_int");
}
}
}
/*
*
*/ Main class
public class Bootstrap {
static final Random RANDOM = new Random();
public static void main(String [] args){
Config cfg = new Config();
cfg.setTimestamp(RANDOM.nextLong());
cfg.setUpdateInterval(1000);
Serializer serializer = new Persister(new VisitorStrategy(new MyInterceptor()));
StringWriter writer = new StringWriter();
try {
serializer.write(cfg, writer);
} catch (Exception e) {
e.printStackTrace();
}
String serialized = writer.toString();
System.out.println(serialized);
Config desCfg = null;
try {
desCfg = serializer.read(Config.class, serialized);
} catch (Exception e) {
e.printStackTrace();
}
if(desCfg != null){
System.out.println(desCfg.toString());
}
}
}

Categories