Unable To Save Java Object To XML File - java

I want to save my Object Mall into XML, however it doesn't seem to save when I open the XML file. Is it because there are too many objects within the Mall class to be saved therefore it can't be saved?
Below are my codes :
Mall Class
public class Mall implements ActionExecute,Serializable {
private static Mall singleton = null;
private ArrayList<Store> storeList = new ArrayList ();
private ArrayList<Customer> customerList = new ArrayList ();
public static Mall instance()
{
if(singleton == null)
{
singleton = new Mall();
}
return singleton;
}
public void createStore(String factory,String storeType,String storeName)
{
AbstractFactory Factory = FactoryProducer.getFactory(factory);
if(factory.equals("store"))
{
Store newstore = Factory.getStore(storeType,storeName);
storeList.add(newstore);
}
}
SaveFile Class
public class saveFile {
public static void write(Mall f) throws Exception{
try (XMLEncoder encoder = new XMLEncoder(
new BufferedOutputStream(
new FileOutputStream("designpattern.xml")))) {
encoder.writeObject(f);
}
}
}
XML file Result
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_25" class="java.beans.XMLDecoder">
<object class="designpattern.Mall"/>
</java>

Related

How can I access this list in another class?

I have created a list of items from a CSV file, but am not sure how to access this list in another class. I have created the instance of the list class in the new class, but have not been able to find a way to access the list.
public class ListClass {
public static void main(String[] args) throws IOException {
CSVReader csvReader = new CSVReader();
List list = csvReader.Read("csvFile.csv");
}
}
I have been able to print the list, and so I know that it's definitely working, but I'm just not sure how I'd access it in another class. The new class is currently empty, aside from the following;
ListClass listClass = new ListClass();
You should store the list as a private instance variable in your ListClass and create a getter for it:
public class ListClass {
private List list = null;
public static void main(String[] args) {
try {
new ListClass();
} catch(IOException ioEx){
// error handling
}
}
public ListClass() throws IOException {
CSVReader csvReader = new CSVReader();
list = csvReader.Read("csvFile.csv");
}
public List getList(){
return list;
}
}
Then you can access it from your other class:
try {
ListClass listClass = new ListClass();
List list = listClass.getList();
} catch(IOException ioEx){
// error handling
}
You need to make the list accessible to other classes by doing one of the following:
Delcare the list as a class level variable and make it public
class ListClass {
public List csvList;
...
}
Declare the list as a private class variable and have an accessor
class ListClass {
private List csvList;
public List getCsvList() {
return this.csvList;
}
...
}
There are a lot of other ways to access a class variable. The second one is a very common way of doing it.
1 )Add your list as a Field of ListClass and put your initialization inside the constructor.
public class ListClass {
public List list;
ListClass(){
try{
CSVReader csvReader = new CSVReader();
list = csvReader.Read("csvFile.csv");
}catch(IOException e){
//handle the exception
}
}
}
2) create an object of ListClass in OtherClass.
public class OtherClass{
public static void main(String[] args){
ListClass listClass = new ListClass();
List newList = listClass.list;// your list
}
}

Dropzone uploadMultiple with Java Struts, FileUploadInterceptor of File Name and Content Type not being called?

I am using dropzone with Java Struts2. Before adding uploadMultiple:true to dropzone, server side working properly, i.e. getter and setter of File, FileName, and ContentType will be called accordingly. However after adding uploadMultiple:true, only the getter and setter of File are being called by the Struts interceptor.
I tried to change the param name and following these two website to do that, but no luck.
https://struts.apache.org/core-developers/file-upload-interceptor.html
https://www.mkyong.com/struts2/struts-2-upload-multiple-files-example/
//My JS
$("form#addrBookDropzone").dropzone(
{
url: "uploadData",
maxFilesize: maxFileSize,
maxFiles: 10,
acceptedFiles: ".csv",
addRemoveLinks: true,
autoProcessQueue: false,
uploadMultiple:true,
parallelUploads: 10,
paramName:'csvFile',
init: function (e) {
abDropzone = this;
abDropzone.processQueue();
},
success: function(file, response){
retrieveCsvTransition();
}
}
);
//My Java
public class FileProcessor extends ActionSupport{
private static final long serialVersionUID = -234712913575630908L;
public static final Logger logger = Logger.getLogger(FileProcessor.class);
private String className = this.getClass().getSimpleName();
private List<File> csvFile = new ArrayList<File>();
private List<String> csvFileContentType = new ArrayList<String>();
private List<String> csvFileFileName = new ArrayList<String>();
private Set<TblCsvTransition> csvData = new HashSet<TblCsvTransition>(0);
private AbstractMap<String, File> fileMap = new HashMap<String, File>(0);
public List<File> getCsvFile() {
return csvFile;
}
public void setCsvFile(List<File> csvFile) {
this.csvFile = csvFile;
}
public List<String> getCsvFileContentType() {
return csvFileContentType;
}
public void setCsvFileContentType(List<String> csvFileContentType) {
this.csvFileContentType = csvFileContentType;
}
public List<String> getCsvFileFileName() {
return csvFileFileName;
}
public void setCsvFileFileName(List<String> csvFileFileName) {
this.csvFileFileName = csvFileFileName;
}
}
I couldn't figure why struts not passing file names, in the end I can only comment out parallelUploads and passing the file names as param

How to get first level super class in freemarker template by java reflection?

suppose that i have a these below classes:
public abstract class A<T> implements Serializable {
}
public class B extends A<Long> {
}
public class C extends B {
}
public class D {
public C c;
}
then, i want to generate code using these below codes and template:
private static void generateJavaCode(Class clazz) {
try {
Configuration cfg = new Configuration();
FileTemplateLoader ftl1 = new FileTemplateLoader(new File("E:/templates/code/"));
cfg.setTemplateLoader(ftl1);
Template template = cfg.getTemplate(tmpl);
Map<String, Object> data = new HashMap<String, Object>();
String modelPackage = clazz.getPackage().getName();
data.put("fields", clazz.getDeclaredFields());
File f = new File(filePath);
String absolutePath = f.getAbsolutePath();
String ffilePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
new File(ffilePath).mkdirs();
Writer file = new FileWriter(f);
template.process(data, file);
file.flush();
file.close();
}
catch (Exception e) {
}
}
and this is the content of .ftl file:
<#list fields as field>
<#attempt>
field.superclass.superclass
<#recover>
field.superclass
</#attempt>
</#list>
but field.superclass.superclass doesn't work, how can i solve this problem?
Supposing your "clazz" variable is a instance of the "D" class you declared. With:
data.put("fields", clazz.getDeclaredFields());
you assign to "fields" the Field[] object (returned from Class.getDeclaredFields()), not a Class[]. As the Field class does not have a 'superclass' getter, your code in .ftl causes an exception:
${field.superclass} // it does not work
but Field class has a method getDeclaringClass(), which gives a Class reference. then you can call it from your freemarker as follow:
${field.declaringClass // return: C
${field.declaringClass.superclass} // return: B
${field.declaringClass.superclass.superclass} // return: A

How to deserialize using XStream?

<PlayListSettings>
<PlayList>
<id>PlayList1</Name>
<File class="string">/mnt/sdcard/Video1</File>
</PlayList>
</PlayListSettings>
This is my Serialized xml,where File is an arrayList of strings. I could remove the class="string" using xstream.aliasSystemAttribute(null, "class");
and the output is
<PlayListSettings>
<PlayList>
<id>PlayList1</Name>
<File>/mnt/sdcard/Video1</File>
</PlayList>
</PlayListSettings>
How do i deserialize using XStream?
You can use the #XStreamImplicit annotation for it. Here is a fully working example:
#XStreamAlias("PlayList")
public final class PlayList {
#XStreamImplicit(itemFieldName = "File")
private final List<String> files = new ArrayList<>();
public void addFile(final String file) {
checkFile(file);
files.add(file);
}
public void removeFile(final String file) {
checkFile(file);
files.remove(file);
}
public List<String> getFiles() {
return Collections.unmodifiableList(files);
}
private void checkFile(final String file) {
if (file == null) {
throw new NullPointerException();
} else if (file.isEmpty()) {
throw new IllegalArgumentException("is empty");
}
}
public static void main(String[] args) {
final PlayList playList = new PlayList();
playList.addFile("Foo");
playList.addFile("Bar");
// Serialize
final XStream xstream = new XStream();
xstream.autodetectAnnotations(true);
final String xml = xstream.toXML(playList);
System.out.println(xml);
// Deserialize
final PlayList playList2 = (PlayList) xstream.fromXML(xml);
for (final String file : playList.getFiles()) {
System.out.println(file);
}
}
}
The output looks like:
<PlayList>
<File>Foo</File>
<File>Bar</File>
</PlayList>

BeanWriter Disable outputting empty lists

I have the following bean:
public class ContractBean {
private List<String> listNd;
private String nd;
public List<String> getListNd() {
return listNd;
}
public void setListNd(final List<String> listNd) {
this.listNd = listNd;
}
public String getNd() {
return nd;
}
public void setNd(final String nd) {
this.nd= nd;
}
}
I use apache Betwixt to output XML from my bean.
final BeanWriter beanWriter = new BeanWriter(outputWriter);
beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
beanWriter.getBindingConfiguration().setMapIDs(false);
beanWriter.enablePrettyPrint();
beanWriter.setWriteEmptyElements(false);
beanWriter.getBindingConfiguration().setObjectStringConverter(new CustomObjectStringConverter());
beanWriter.write(obj);
The listND attribute of my bean is null, but i still get:
<contract>
<listNd/>
<nd>22222</nd>
</contract>
How can I remove empty lists from the output XML ?

Categories

Resources