equivalent to python's shelve module in Java - java

Is there any module in Java equivalent to python's shelve module? I need this to achieve dictionary like taxonomic data access. Dictionary-like taxonomic data access is a powerful way to save Python objects in a persistently easy access database format. I need something for the same purpose but in Java.

I also needed this, so I wrote one. A bit late, but maybe it'll help.
It doesn't implement the close() method, but just use sync() since it only hold the file open when actually writing it.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
public class Shelf extends HashMap<String, Object> {
private static final long serialVersionUID = 7127639025670585367L;
private final File file;
public static Shelf open(File file) {
Shelf shelf = null;
try {
if (file.exists()) {
final FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
shelf = (Shelf) ois.readObject();
ois.close();
fis.close();
} else {
shelf = new Shelf(file);
shelf.sync();
}
} catch (Exception e) {
// TODO: handle errors
}
return shelf;
}
// Shelf objects can only be created or opened by the Shelf.open method
private Shelf(File file) {
this.file = file;
sync();
}
public void sync() {
try {
final FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this);
oos.close();
fos.close();
} catch (Exception e) {
// TODO: handle errors
}
}
// Simple Test Case
public static void main(String[] args) {
Shelf shelf = Shelf.open(new File("test.obj"));
if (shelf.containsKey("test")) {
System.out.println(shelf.get("test"));
} else {
System.out.println("Creating test string. Run the program again.");
shelf.put("test", "Hello Shelf!");
shelf.sync();
}
}
}

You could use a serialisation library like Jackson which serialises POJOs to JSON.
An example from the tutorial:
Jackson's org.codehaus.jackson.map.ObjectMapper "just works" for
mapping JSON data into plain old Java objects ("POJOs"). For example,
given JSON data
{
"name" : { "first" : "Joe", "last" : "Sixpack" },
"gender" : "MALE",
"verified" : false,
"userImage" : "Rm9vYmFyIQ=="
}
It takes two lines of Java to turn it into a User instance:
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);
Where the User class looks something like this (from an entry on Tatu's blog):
public class User {
public enum Gender { MALE, FEMALE };
public static class Name {
private String _first, _last;
public String getFirst() { return _first; }
public String getLast() { return _last; }
public void setFirst(String s) { _first = s; }
public void setLast(String s) { _last = s; }
}
private Gender _gender;
private Name _name;
private boolean _isVerified;
private byte[] _userImage;
public Name getName() { return _name; }
public boolean isVerified() { return _isVerified; }
public Gender getGender() { return _gender; }
public byte[] getUserImage() { return _userImage; }
public void setName(Name n) { _name = n; }
public void setVerified(boolean b) { _isVerified = b; }
public void setGender(Gender g) { _gender = g; }
public void setUserImage(byte[] b) { _userImage = b; }
}

Related

getting error on desirializing java object from Kafka

I started to learn Kafka, and now,
I'm on sending/receiving serialized/desirialised java class.
My question is about: what have I missed in my config, so I can't deserialize the object from Kafka
here is my class:
public class Foo {
private String item;
private int quantity;
private Double price;
public Foo(String item, int quantity, final double price) {
this.item = item;
this.quantity = quantity;
this.price = price;
}
public String getItem() { return item; }
public int getQuantity() { return quantity; }
public Double getPrice() { return price; }
public void setQuantity(int quantity) { this.quantity = quantity; }
public void setPrice(double price) { this.price = price; }
#Override
public String toString() {
return "item=" + item + ", quantity=" + quantity + ", price=" + price;
}
}
my Properties in main class:
producerPropsObject.put(ProducerConfig.CLIENT_ID_CONFIG,
AppConfigs.applicationProducerSerializedObject);
producerPropsObject.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,
AppConfigs.bootstrapServers);
producerPropsObject.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
StringSerializer.class.getName());
producerPropsObject.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
FooSerializer.class.getName());
producerPropsObject.put("topic", AppConfigs.topicNameForSerializedObject);
consumerPropsObject.put(ConsumerConfig.GROUP_ID_CONFIG, AppConfigs.applicationProducerSerializedObject);
consumerPropsObject.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, AppConfigs.bootstrapServers);
consumerPropsObject.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerPropsObject.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,FooDeserializer.class.getName());
consumerPropsObject.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 300000);
consumerPropsObject.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
consumerPropsObject.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
consumerPropsObject.put("topic", AppConfigs.topicNameForSerializedObject);
following are serializer/deserializer implementations:
public class FooSerializer implements org.apache.kafka.common.serialization.Serializer {
public void configure(Map map, boolean b) { }
public byte[] serialize(String s, Object o) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
byte[] b = baos.toByteArray();
return b;
} catch (IOException e) { return new byte[0]; }
}
public void close() { }
}
public class FooDeserializer implements org.apache.kafka.common.serialization.Deserializer {
#Override
public void close() { }
#Override
public Foo deserialize(String arg0, byte[] arg1) {
//Option #1:
//ObjectMapper mapper = new ObjectMapper();
//Option #2:
JsonFactory factory = new JsonFactory();
factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
ObjectMapper mapper = new ObjectMapper(factory);
Foo fooObj = null;
try {
//Option #1:
//fooObj = mapper.readValue(arg1, Foo.class); // BREAKS HERE!!!
//Option #2:
fooObj = mapper.reader().forType(Foo.class).readValue(arg1); // BREAKS HERE!!!
}
catch (Exception e) { e.printStackTrace(); }
return fooObj;
}
}
and finally the way I'm trying to produce and consume my Foo from main:
seems, like it works fine, cause I see in kafka-topic my Key && Value later on
public void produceObjectToKafka(final Properties producerProps) {
final String[] ar = new String[]{"Matrix", "Naked Gun", "5th Element", "Die Hard", "Gone with a wind"};
KafkaProducer<String, byte[]> producer = new KafkaProducer<>(producerProps);
final Foo j = new Foo(ar[getAnInt(4)], getAnInt(10), getAnDouble());
producer.send(new ProducerRecord<>(producerProps.getProperty("topic"), j.getItem(), j.toString().getBytes()));
producer.flush();
producer.close();
}
however, while my Consumer is catching the output:
public void consumeFooFromKafka(final Properties consumerProps) {
final Consumer<String, Foo> myConsumer = new KafkaConsumer<>(consumerProps);
final Thread separateThread = new Thread(() -> {
try {
myConsumer.subscribe(Collections.singletonList(consumerProps.getProperty("topic")));
while (continueToRunFlag) {
final StringBuilder sb = new StringBuilder();
final ConsumerRecords<String, Foo> consumerRecords = myConsumer.poll(Duration.ofMillis(10));
if (consumerRecords.count() > 0) {
for (ConsumerRecord<String, Foo> cRec : consumerRecords) {
sb.append( cRec.key() ).append("<<").append(cRec.value().getItem() + ",").append(cRec.value().getQuantity() + ",").append(cRec.value().getPrice()).append("|");
}
}
if (sb.length() > 0) { System.out.println(sb.toString()); }
}
}
finally {
myConsumer.close();
}
});
separateThread.start();
}
=======================================
so, actually by running "consumeFooFromKafka" , when it trigger "FooDeserializer" ...... there, I always have same error(regardless of Option #1, or Option #2):
exception:
Method threw 'com.fasterxml.jackson.core.JsonParseException' exception.
detailedMessage:
Unexpected character ('¬' (code 172)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or
'false')
will be very appresiated for help.......
Thank you in advance,
Steve
If you want to deserialize from json, than u need to serialize it to json, use jackson in ur serializer also, and everything should be fine
public class FooSerializer implements org.apache.kafka.common.serialization.Serializer {
public void configure(Map map, boolean b) { }
public byte[] serialize(String s, Object o) {
try {
ObjectMapper om = new ObjectMapper();//objectmapper from jackson
byte[] b = om.writeValueAsString(o).getBytes();
return b;
} catch (IOException e) { return new byte[0]; }
}
public void close() { }
}
I don't know why you're using a bytearray outputstream, but trying to read JSON in the deserializer, but that explains the error. You could even test that without using Kafka at all by invoking the serialize/deserialize methods directly
In the link provided, the serializer uses objectMapper.writeValueAsString, which returns JSON text, and not the Java specific outputstream. If you wanted to consume and produce data between different programming languages (as is often the case in most companies), you'd want to avoid such specific serialization formats
Note: Confluent provides Avro, Protobuf, and JSON serializers for Kafka, so you shouldn't need to write your own if you want to use one of those formats

How to define array of objects in a properties file and read from Java program

I have a properties file like this.
property[0].name=A
property[0].value=1
property[1].name=B
property[1].value=2
property[2].name=C
property[2].value=3
How to read this file as a list of objects of a class {name, value} in plain java program using ResourceBundle or Properties?
Here is the class.
public class XYZ {
private String name;
private String value;
// Getters & Setters
}
I need to get like this.
ArrayList<XYZ> propertiesList = SomeUtility.getProperties("property", XYZ.class);
Utility class might be like this.
public class SomeUtility {
public static ArrayList getProperties(String key, Class cls) {
//logic
}
}
I might not understand exactly what you want so feel free to correct me and give me more constraints to work with but here is a simple way to read a Properties file located somewhere in your project:
private static void readPropertiesFile(String path) throws IOException {
java.util.Map<String, String> map = new java.util.LinkedHashMap<>();
Properties properties = new Properties();
InputStream inputStream = new FileInputStream(path);
properties.load(inputStream);
for (String name : properties.stringPropertyNames()) {
map.put(name, properties.getProperty(name));
}
for (java.util.Map.Entry<String, String> entry : map.entrySet()) {
System.out.printf("Property Key: %s, Property Value: %s%n", entry.getKey(), entry.getValue());
}
}
Output
Property Key: property[0].name, Property Value: A
Property Key: property[1].name, Property Value: B
Property Key: property[0].value, Property Value: 1
Property Key: property[1].value, Property Value: 2
Property Key: property[2].name, Property Value: C
Property Key: property[2].value, Property Value: 3
This is the solution I wrote, but it involves Reflect and Gson. Is there any better way to do this? Anything already available which is fine tuned like Apache's.
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.lang.reflect.Field;
import java.util.*;
public class ListResourceBundle {
public static final Gson gson = new Gson();
private final ResourceBundle bundle;
public ListResourceBundle(ResourceBundle bundle) {
this.bundle = bundle;
}
public List<?> getProperties(String key, Class<?> cls) {
final int maxArraySize = getMaxArraySize(key, getMatchingKeys(key));
final List<String> fields = getFields(cls);
final List<Object> result = new ArrayList<>();
for (int i = 0; i < maxArraySize; i++) {
JsonObject jsonObject = new JsonObject();
for (String field : fields) {
jsonObject.addProperty(field, getStringOrNull(key + "[" + i + "]." + field));
}
result.add(gson.fromJson(jsonObject, cls));
}
System.out.println("result.toString() = " + result.toString());
return result;
}
public List<String> getMatchingKeys(String key) {
Enumeration<String> keys = bundle.getKeys();
List<String> matchingKeys = new ArrayList<>();
while(keys.hasMoreElements()) {
String k = keys.nextElement();
if(k.startsWith(key)) {
matchingKeys.add(k);
}
}
Collections.sort(matchingKeys);
return matchingKeys;
}
public int getMaxArraySize(String key, List<String> matchingKeys) {
int maxArraySize = 0;
for (int i = 0; ; i++) {
boolean indexAvailable = false;
for (String matchingKey : matchingKeys) {
if(matchingKey.startsWith(key + "[" + i + "]")) {
indexAvailable = true;
break;
}
}
if(indexAvailable) {
maxArraySize++;
} else {
break;
}
}
return maxArraySize;
}
public String getStringOrNull(String key) {
try {
return bundle.getString(key);
} catch (MissingResourceException e) {
return null;
}
}
public List<String> getFields(Class<?> cls) {
final List<String> fields = new ArrayList<>();
for (Field field : cls.getDeclaredFields()) {
fields.add(field.getName());
}
return fields;
}
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle("com.example.application.resources.Resource");
ListResourceBundle applicationResourceBundle = new ListResourceBundle(bundle);
applicationResourceBundle.getProperties("property", ReportParam.class);
}
}
Resource:
property[0].name=A
property[0].value=1
property[1].name=B
property[1].value=2
property[2].name=C
property[2].value=3
Output:
result.toString() = [
ReportParam{name='A', value='1'},
ReportParam{name='B', value='2'},
ReportParam{name='C', value='3'}]
Process finished with exit code 0
I know it's bit late of an answer, but if I understand your problem statement correctly, you can use :
#ConfigurationProperties
to get your job done.
Here is my spring-boot example with a YAML file for the sake of convenience (same can be achieved through properties file as well).
application.yaml:
xyz:
xyzprops :
-
name: cbc
value: 441
-
name: obc
value: 443
XYZ class:
#Component
#ConfigurationProperties(prefix = "xyz")
public class XYZ{
private List<XYZProps> xyzprops;
public List<XYZProps> getXyzprops() {
return xyzprops;
}
public void setXyzprops(List<XYZProps> xyzprops) {
this.xyzprops = xyzprops;
}
public class XYZProps{
String name;
String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
And then #Autowire XYZ where you want to use it.
I would use JSON:
in your file:
property=[{"name":"A","value":"1"},{"name":"B","value":"2"},{"name":"C","value":"3"}]
and then deserialize it using com.google.gson.gson (or any other) library:
ArrayList<XYZ> propertiesList;
propertiesList = new gsonbuilder().create().fromjson(property, propertiesList.class);
NOTE: I haven't tested this code, and i'm not very familiar with java so i am sure there is a better,cleaner way to implement this.

read serializable custom object into file android

i am trying to record and reab back my list into file. It's working great until I restart my application. I am working with simulator (I don't have a real phone under Android)
Here is my function to record my class into a file :
public boolean writeRecordsToFile(String path, DummyContent object){
FileOutputStream fos;
ObjectOutputStream oos = null;
try {
fos = fileContext.openFileOutput(path, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.close();
Log.d("fileManager", "Records write successfully");
return true;
} catch (Exception e) {
Log.e("fileManager", "Cant save records : " + e.getMessage());
return false;
}
finally {
if (oos != null)
try {
oos.close();
} catch (Exception e) {
Log.e("fileManager", "Error while closing stream "+e.getMessage());
}
}
}
Here is my reading Function :
public boolean readRecordsFromFile(String path){
FileInputStream fin;
ObjectInputStream ois=null;
try {
fin = fileContext.openFileInput(path);
ois = new ObjectInputStream(fin);
DummyContent records = (DummyContent) ois.readObject();
records.addItem("test", "test", "test");
ois.close();
Log.d("fileManager", "Records read successfully :\n" + records.toString());
Log.d("fileManager", "nbArticle found : " + String.valueOf(records.ITEMS.size()));
Log.d("fileManager", "article 0 title :\n" + records.ITEMS.get(0).content);
Log.d("fileManager", "article 10 title :\n" + records.ITEMS.get(10).content);
return true;
} catch (Exception e) {
Log.e("fileManager", "Cant read saved records : "+e.getMessage());
return false;
}
finally {
if (ois != null)
try {
ois.close();
} catch (Exception e) {
Log.e("fileManager", "Error in closing stream while reading records : "+e.getMessage());
}
}
}
and here is my class :
public class DummyContent implements Serializable {
/**
* An array of sample (dummy) items.
*/
public static List<DummyItem> ITEMS = new ArrayList<DummyItem>();
/**
* A map of sample (dummy) items, by ID.
*/
public static Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();
public void addItem(String first, String second, String third) {
DummyItem dummyItem = new DummyItem(first, second, third, android.R.drawable.ic_input_add);
ITEMS.add(dummyItem);
ITEM_MAP.put(dummyItem.id, dummyItem);
}
public void deleteAll() {
ITEMS = new ArrayList<DummyItem>();
ITEM_MAP = new HashMap<String, DummyItem>();
}
public void changeURL(Long index, String newURL) {
ITEMS.get(index.intValue()).url = newURL;
}
public void changeContent(Long index, String newContent) {
ITEMS.get(index.intValue()).contenu = newContent;
}
/**
* A dummy item representing a piece of content.
*/
public static class DummyItem {
public final String id;
public final String content;
public final String details;
public final int imageResource;
public String url;
public String contenu;
public DummyItem(String id, String content, String details, int imageResource) {
this.id = id;
this.content = content;
this.details = details;
this.imageResource = imageResource;
this.url = "";
this.contenu = "";
}
#Override
public String toString() {
return content;
}
}
}
Finally I read my file at the onCreate of my MainActivity (first activity at the lunching app) :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fileManager = new FileManager(this.getApplicationContext());
Log.d("Main", String.valueOf(fileManager.fileExist("Article.art")));
fileManager.readRecordsFromFile("Article.art"); /* Bug here : size of my array is empty but file's size is the same */
}
Here is my console return :
D/fileManager: size = 102
D/fileManager: Records read successfully :
D/fileManager: nbArticle found : 1 (because i add an item at the read
function) E/fileManager: Cant read saved records : Index: 10, Size: 1
I know it is working because when I write and read directly after the writting, I got all my items and I can read several times and I still got all items (this bug semms to be only present when I restart my application)
Maybe can I got help ?
Thanks !
The reason is very easy: You have declared some field as static, which are not covered by standard serialization: So, the contents of these fields were never written nor read from the file. That's why they "dissapeared" after a JVM restart.
Any field you want to be serialized/deserialized, you must declare it as instance member (not static).
See documentation on Serializable.

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.

Can xstream deserialize a complicated array?

I study xstream these days.
But I found the xstream json tutorial which in its homepage is very simple.
I have an array as follows:
{
"mails":[
{
"uid":"ZC2027-mXOmcAtkfiztS0sEeJlkU25",
"relatedCardNums":"8299,0000,1531|8299,0000,1531",
"houseHolder":"",
"subject":"no-subject",
"receiveTime":"2012-05-27 00:00:00",
"bankName":"上海银行",
"cards":[]
}
],
"dealedNum":330,
"nextRequestDelay":"1",
"percent":"0",
"filterNum":410,
"resCode":"01",
"dealedBillNum":43,
"resMsg":"正在解析"
}
I want to convert this json string to a GetMailsDataResponseDto, but I dont know how to do?
Could you help me out?
package com.fund.etrading.ebankapp.base.credit.cardniu.ecardniu.dto;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fund.etrading.ebankapp.base.credit.utils.FileUtils;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
public class GetMailsDataResponseDto extends ResponseBaseDto{
protected int dealedNum;
protected String nextRequestDelay;
protected String percent;
protected int filterNum;
protected int dealedBillNum;
protected List mails = new ArrayList();
public List getMails() {
return mails;
}
public int getDealedNum() {
return dealedNum;
}
public String getNextRequestDelay() {
return nextRequestDelay;
}
public String getPercent() {
return percent;
}
public int getFilterNum() {
return filterNum;
}
public int getDealedBillNum() {
return dealedBillNum;
}
public void fromJson(String json){
try {
json = FileUtils.get_content("C:\\Documents and Settings\\Administrator\\workspace\\99fund_java\\src\\com\\fund\\etrading\\ebankapp\\base\\credit\\新建 文本文档 (2).txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json = "{\"root\":" + json + "}";
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias("root", this.getClass());
//xstream.addImplicitCollection(this.getClass(), "mails");
xstream.alias("mail", MailDto.class);
//xstream.aliasField("cards", MailDto.class, "cards");
//xstream.aliasField("currencyData", CardDto.class, "currencyData");
//xstream.aliasField("data", CurrencyDataDto.class, "data");
xstream.fromXML(json, this);
}
}
package com.fund.etrading.ebankapp.base.credit.cardniu.ecardniu.dto;
import java.util.ArrayList;
import java.util.List;
import com.fund.etrading.ebankapp.base.credit.BaseDto;
public class MailDto extends BaseDto{
protected String uid;
protected String relatedCardNums;
protected String houseHolder;
protected String subject;
protected String receiveTime;
protected String bankName;
protected List cards = new ArrayList();
public String getUid() {
return uid;
}
public String getRelatedCardNums() {
return relatedCardNums;
}
public String getHouseHolder() {
return houseHolder;
}
public String getSubject() {
return subject;
}
public String getReceiveTime() {
return receiveTime;
}
public String getBankName() {
return bankName;
}
public List getCards() {
return cards;
}
}
thanks in advance!
If you want to convert json string to your custom class(ex.GetMailsDataResponseDto), I recommend Google Gson.
If you use Gson, yon don't need fromJosn() method in GetMailsDataResponseDto class.
If you only use json parsing and have experiences of java script, I recommend Djson parser(java library).
"Djson Parse version 0.8a" -- http://blog.indf.net/category/Apps/djson
j1.txt - tip: "none BOM & UTF-8"
....
public void fromJson(String json){
//(real-code)--start
//Var var = Djson.parse(json);
//(real-code)--end
//--test-code--start
Var var = null;
try {
var = Djson.parse(new File("d:\\j1.txt"));
} catch (IOException e) {
e.printStackTrace();
}
//--test-code--end
this.dealedNum = var.get("dealedNum").toInt();
this.nextRequestDelay = var.get("nextRequestDelay").toString();
this.percent = var.get("percent").toString();
this.filterNum = var.get("filterNum").toInt();
this.dealedBillNum = var.get("dealedBillNum").toInt();
for(int i=0; i<var.get("mails").size(); i++) {
this.mails.add(var.get("mails").get(i).toObject()); // MAP type setting...
}
}

Categories