How to setup ArrayList<String> - java

I am trying to run this code and ArrayList data = handler.getnames(); is showing an error variable data is alredy defined in method main(String[]). I am guessing it wants me to combine it with ArrayList data = handler.getsetnums();. But how to i do it? or is there another way?
Ones the code works, and should be able to run it and get an output, now when i only have one Array working the code does what it needs to do.
expected outcome
<set-num>00-1</set-num>
<name>WEETABIX CASTLE</name>
Thank you.
---MAIN.java---
package assign6;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
*
* #author assign
*/
public class Assign6 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.print("Welcome to Benjamin Bolyard's Lego Sorter");
try {
XMLReader reader = XMLReaderFactory.createXMLReader();
MyHandler handler = new MyHandler();
reader.setContentHandler(handler);
reader.setErrorHandler(handler);
InputSource inputSource = new InputSource("legoSets.xml");
reader.parse(inputSource);
ArrayList<String> data = handler.getsetnums();
System.out.println("setnum List");
System.out.println("----------");
for (int i = 0; i < data.size(); i++) {
String setnum = data.get(i);
setnum = setnum.toUpperCase();
System.out.println((i + 1) + ": " + setnum);
}
ArrayList<String> data = handler.getnames();
System.out.println("name List");
System.out.println("----------");
for (int i = 0; i < data.size(); i++) {
String name = data.get(i);
name = name.toUpperCase();
System.out.println((i + 1) + ": " + name);
}
} catch (SAXException ex) {
Logger.getLogger(BolyardAssign6.class.getName())
.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BolyardAssign6.class.getName())
.log(Level.SEVERE, null, ex);
}
}
}
--HANDLER.java---
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bolyardassign6;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* #author bolya
*/
public class MyHandler extends DefaultHandler {
private boolean inlegosets;
private boolean inname;
private boolean insetnum;
private String nameBuffer;
private String setnumBuffer;
private ArrayList<String> setnums, names;
public ArrayList<String> getsetnums() {
return setnums;
}
public ArrayList<String> getnames() {
return names;
}
#Override
public void startDocument() throws SAXException {
// System.out.println("Start Document")
insetnum = false;
inname = false;
inlegosets = false;
nameBuffer = "";
names = new ArrayList<>();
}
#Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
if (localName.equals("lego-sets")) {
inlegosets = true;
} else if (inlegosets && localName.equals("setnum")) {
// System.out.println("Start element : " + localName);
insetnum = true;
setnumBuffer = "";
} else if (inlegosets && localName.equals("name")) {
// System.out.println("Start element : " + localName);
inname = true;
nameBuffer = "";
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
String data = new String(ch, start, length);
if (inlegosets && inname) {
// System.out.println("Characters : " + data);
nameBuffer = nameBuffer + data;
} else if (inlegosets && insetnum) {
// System.out.println("Characters : " + data);
setnumBuffer = setnumBuffer + data;
}
}
#Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
if (localName.equals("inlegosets")) {
inlegosets = false;
} else if (inlegosets && localName.equals("setnum")) {
// System.out.println("Title: " + titleBuffer);
// System.out.println("End element : " + localName);
// System.out.println();
setnums.add(setnumBuffer);
insetnum = false;
} else if (inlegosets && localName.equals("name")) {
// System.out.println("Title: " + titleBuffer);
// System.out.println("End element : " + localName);
// System.out.println();
names.add(nameBuffer);
inname = false;
}
}
#Override
public void endDocument() throws SAXException {
// System.out.println("End Document");
}
#Override
public void error(SAXParseException e) throws SAXException {
System.out.println("ERROR: Line number " + e.getLineNumber());
System.out.println("ERROR: " + e.getMessage());
}
#Override
public void fatalError(SAXParseException e) throws SAXException {
System.out.println("FATAL ERROR: Line number " + e.getLineNumber());
System.out.println("FATAL ERROR: " + e.getMessage());
}
}
---legoset.xml---
<lego-sets>
<set>
<set-num>00-1</set-num>
<name>WEETABIX CASTLE</name>
<year>1970</year>
<num-parts>471</num-parts>
</set>
<set>
<set-num>0011-2</set-num>
<name>TOWN MINI-FIGURES</name>
<year>1978</year>
<num-parts>12</num-parts>
</set>
<set>
<set-num>0011-3</set-num>
<name>CASTLE 2 FOR 1 BONUS OFFER</name>
<year>1987</year>
<num-parts>2</num-parts>
</set>
<set>
<set-num>0012-1</set-num>
<name>SPACE MINI-FIGURES</name>
<year>1979</year>
<num-parts>12</num-parts>
</set>
</lego-sets>

You have defined two variables with the name data. To fix this, change the name of one of them. Alternatively you can remove the declaration and just have the following on the second arraylist: data = handler.getnames();

I am trying to run this code and ArrayList data = handler.getnames(); is showing an error variable data is alredy defined in method main(String[]). I am guessing it wants me to combine it with ArrayList data = handler.getsetnums();. But how to i do it? or is there another way?
You have the right idea. The error is caused because you have two variable declarations withe same name:
ArrayList data = handler.getnames()
and
ArrayList data = handler.getsetnums();
Java doesn't allow this. However, you don't necessarily want to "combine them together" because these are two separate lists that seem to represent two different things.
I suggest changing the names of both variables to something more meaningful than data. For example:
ArrayList names = handler.getnames()
and
ArrayList setnums = handler.getsetnums();
Presumably, names and setnums represent something meaningful for what you are doing here.

Related

Move XML namespaces declarations to the root element

I have a XML string/object:
<?xml version="1.0"?>
<ns0:top xmlns:ns0="someUrl1">
<ns1:child xmlns:ns1="someUrl2">
Value
</ns1:child>
</ns0:top>
How can I transform in to "normalized" namespaces XML form like this:
<?xml version="1.0"?>
<ns0:top xmlns:ns0="someUrl1" xmlns:ns1="someUrl2">
<ns1:child>
Value
</ns1:child>
</ns0:top>
This might be a bad idea for a few reasons (it's going to be hard to cover lots of edge cases), but (for fun and for very simple cases like the one you posed) here's an implementation using SAXParser that does this:
/* package whatever; // don't place package name! */
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone extends DefaultHandler
{
StringBuilder sb;
private Hashtable namespaces;
private int nsIdx;
boolean rootDone;
String rootNodeName;
String rootNS;
public void startDocument() throws SAXException {
namespaces = new Hashtable();
nsIdx = 0;
sb = new StringBuilder();
rootDone = false;
}
public void endDocument() throws SAXException {
Set<String> keys = namespaces.keySet();
StringBuilder rootEl = new StringBuilder();
rootEl.append("<" + namespaces.get(rootNS) + ":" + rootNodeName);
for(String key: keys){
rootEl.append(" xmlns:" + namespaces.get(key) + "='" + key + "'");
}
rootEl.append(">");
sb.insert(0, rootEl.toString());
System.out.println(sb.toString());
}
public void characters(char[] ch, int start, int length) throws SAXException {
for (int i = start; i < start + length; i++)
{
sb.append(ch[i]);
}
}
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
if (!namespaces.containsKey(namespaceURI))
{
nsIdx++;
namespaces.put(namespaceURI, "ns" + nsIdx);
}
boolean printEl = rootDone;
if (!rootDone)
{
rootNodeName = localName;
rootNS = namespaceURI;
rootDone = true;
}
else
{
sb.append("<" + namespaces.get(namespaceURI) + ":" + localName);
}
for (int i = 0; i < atts.getLength(); i++)
{
if (!namespaces.containsKey(atts.getURI(i)))
{
nsIdx++;
namespaces.put(atts.getURI(i),"ns" + nsIdx);
}
if (atts.getLocalName(i) == atts.getQName(i))
{
sb.append(" " + atts.getLocalName(i) + "='" + atts.getValue(i) + "'");
}
else
{
sb.append(" " + namespaces.get(atts.getURI(i)) + ":" + atts.getLocalName(i) + "='" + atts.getValue(i) + "'");
}
}
if (printEl)
{
sb.append(">");
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
sb.append("</" + namespaces.get(uri) + ":" + localName + ">");
}
public static void main (String[] args) throws java.lang.Exception
{
String xml = "<?xml version=\"1.0\"?><ns0:top xmlns:ns0=\"someUrl1\"><ns1:child xmlns:ns1=\"someUrl2\" ns0:testNS=\"tstNS\" test=\"tst\">Value</ns1:child><child2></child2><child3/></ns0:top>";
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(new Ideone());
xmlReader.parse(new InputSource(new StringReader(xml)));
}
}
(ideone: http://ideone.com/E4LIac)
Note that this will do the following things that may not be desireable:
Make nodes that were self closing be empty (e.g. <child3 /> becomes <child3></child3>)
Create prefixes for unprefixed nodes (e.g. xmlns:ns3='')
Probably doesn't properly handle some other edge cases
Probably doesn't follow the best Java conventions, I'm a bit rusty there
Also note that it just prints the final result out to System.out - you'd likely want to return it or save it or something else. And I have no idea if or how this would work in groovy.

wanted to get the return Type and parameter types from all the methods presents in the class

In my code i am getting the method names present in a class.
i wanted to get return types and Parameter types of all the methods present in all the class.I tried it using substring as well reflection.but not getting proper output.
For type-1,its giving the output only for one method properly, for rest its giving public only.
For type-2, the out put is like this:
The Method Found is: public int java.lang.String.hashCode()
METHOD FOUND:public int java.lang.String.hashCode()
Return Type: int
PArams: int
PArams: int
Which not the expected output.
My class contains follwing method:
public int test(int a, intb)
public static String Add(String str)
public static void main(String args[])
The expected output should be:
Method Found: public int test(int a, intb)
Return Type: int
Parameter Type: inta intb
same for rest two also.
Any help is appreciable.Thanks in advance.
In the code i have commented out as //type-1 and //type-2
Here is my code:
package com.sify.ABCD;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/** Class to Recursively searching the folders, and files and
* the comments inside the files
* #param <Data>
*
*/
public class ABCDTool {
String projectCode="027505";
public static void main(String[] args) throws NoSuchMethodException {
String parentFolder="D:/TestFileProgram";
ABCDTool abcdTool = new ABCDTool();
abcdTool.execute(parentFolder);
}
public void execute(String fileName) throws NoSuchMethodException {
File file = new File(fileName);
if(file.isFile()){
if(file.getName().contains(".java")){
readFile(file);
}
}
else if (file.isDirectory()){
System.out.println("Analysing Directory: "+file);
String[] list = file.list();
for (String innerFile : list) {
execute(file+"/"+innerFile);
}
}
}
public void readFile(File file) throws NoSuchMethodException {
String className=null;
String packageName=null;
String methodName=null;
String methodReturn=null;
String[] methodParams=null;
boolean packageFound=false;
boolean classFound=false;
boolean methodLineFound=false;
Method method = null;
Class classObject = null;
try {
System.out.println("Reading file: "+file);
List<FixDetails> fileNameList = new ArrayList<FixDetails>();
BufferedReader bufferReader = new BufferedReader(new FileReader(file.getPath()));
String line="";
while ((line = bufferReader.readLine()) != null) {
int packageLength = "package ".length();
int classLength ="class ".length();
int indexOfPackage = line.indexOf("package ");
int indexOfClass = line.indexOf("class ");
int indexOfMethod = line.indexOf("public ");
int indexOfSemicolon= line.indexOf(";");
int indexOfOpenBrace = line.indexOf("(");
int indexOfCloseBrace = line.indexOf(")");
int indexOfMethodName = line.indexOf("methodName ");
//Finds Package Name
if((!packageFound) && indexOfPackage > -1) {
packageName = line.substring(indexOfPackage + packageLength, indexOfSemicolon);
System.out.println("Package Name: " + packageName + " ");
packageFound=true;
}
//Finds Class Name
if((!classFound) && indexOfClass > -1){
String modified = line.substring(indexOfClass + classLength);
String st[] = modified.split(" ");
className = st[0].trim();
System.out.println("Class Name: " + className + " ");
/*Method m[] = className.getClass().getDeclaredMethods();
System.out.println("The Method Found is: " + m[1]);
for (Method method2 : m)
{
System.out.println("METHOD FOUND:"+method);
System.out.println(method2.getReturnType());
Class pr[] = method2.getParameterTypes();
for (Class class1 : pr)
{
System.out.println(class1);
}
}*/
/*String pathName = packageName+"."+ className;
System.out.println("The path name is "+ pathName);
classObject = Class.forName(pathName);
Method m[] = classObject.getDeclaredMethods();
System.out.println("The methods present are" + m);
System.out.println("ClassObject:"+ classObject);*/
classFound = true;
}
//Finds Method Name
**if(indexOfMethod >-1 && indexOfOpenBrace >-1){
String modified = line.substring(indexOfMethod, indexOfOpenBrace);
String st[] = modified.split(" ");
methodName = st[st.length-1];
System.out.println("methodName="+methodName);
System.out.println("method line="+line);**
//Get method returnType and Params
if ((line !=null)) {
//Type-1
String str=line;
System.out.println("tested:"+str);
String[] temp = str.split(" ");
for (String st1 : temp){
if(st1.equalsIgnoreCase("private")||st1.equalsIgnoreCase("protected")||
st1.equalsIgnoreCase("static")||st1.equalsIgnoreCase("public")||st1.equalsIgnoreCase("synchronized"))
{
}
else {
System.out.println("Return Type should be:"+st1);
break;
}
}
/*for (int i =0; i < temp.length ; i++)
System.out.println("Splitted Return Type string:" +temp[i]);*/
//Type-2
Method m[] = className.getClass().getDeclaredMethods();
System.out.println("The Method Found is: " + m[0]);
for (Method method2 : m)
{
System.out.println("METHOD FOUND:"+method);
System.out.println("Return Type: "+method2.getReturnType());
Class pr[] = method2.getParameterTypes();
for (Class class1 : pr)
{
System.out.println("PArams: "+class1);
}
}
String paramList=line.substring(indexOfOpenBrace+1, indexOfCloseBrace);
System.out.println("Present Params are:" + paramList);
methodParams=paramList.split(",");
for (int i =0; i < methodParams.length ; i++)
System.out.println("Splitted Paramstring:" +methodParams[i]);
/*
String returnTypeStore[] = str.split(" ");
methodReturn = returnTypeStore[returnTypeStore.length-1];
System.out.println("Method Return Type:" + methodReturn);*/
}
else System.out.println("Methodname not found");
methodLineFound=true;
}
if(line.contains(this.projectCode)){
System.out.println("Found:"+line);
//System.out.println("methodName="+methodName);
if(classFound){
// create FixDetails object.
FixDetails fixDetails = new FixDetails(packageName, className, methodName);
// set all required params.
/*fixDetails.setPackageName(packageName);
fixDetails.setClassName(className);
fixDetails.setMethodName(methodName);*/
System.out.println("fixDetails:" + fixDetails);
}else{System.out.println("Class not found yet.");}
}
}
bufferReader.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} /*catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
public Method getMethod(Class classObject, String line, String methodName) throws SecurityException, NoSuchMethodException {
// TODO Auto-generated method stub
System.out.println("Trying to search "+methodName +" in class "+classObject);
System.out.println("line="+line);
/*Class[] cArg = new Class[1];
cArg[0] = int.class;
Method m1= classObject.getClass().getDeclaredMethod(methodName, cArg );
return m1;*/ return null;
}
}
You can use .class.getMethods() to get all the methods of the class (also returns methods from extended classes)
Method[] methods = ABCTool.class.getMethods();
Note the .getName() (methodname) .getReturnType() and .getParameterTypes() you can call on Method
Example
public class ABCDTool {
public String method1(String param) {
return "Working";
}
public static void main(String[] args) {
Method[] methods = ABCDTool.class.getMethods();
for(Method method : methods){
System.out.println("Method Found: " + method.getName());
System.out.println("Return type: " + method.getReturnType().getName());
Object[] params = method.getParameterTypes();
for(Object param : params) {
System.out.println("Parameter Type: " + param);
}
System.out.println();
}
}
}
Note that if you dont want the "wait", "notify" and "notifyall" methods from Object, you need to add some logic to exclude them (.getName().equals("wait"))

wrapper class is it a design pattern

i'm new to design pattern , and now i'm working on an open ware code : so i'm trying to understand the architecture of the code : layers , used design pattern ...
So i found the a package containing classes named EntityWrapper.java here's an example :
The wrapper class :
package org.objectweb.salome_tmf.api.data;
/**
* #author marchemi
*/
public class ActionWrapper extends DataWrapper{
String awaitedResult;
int orderIndex;
int idTest;
/**
* #return Returns the orderIndex.
*/
public int getOrderIndex() {
return orderIndex;
}
/**
* #param orderIndex The orderIndex to set.
*/
public void setOrderIndex(int orderIndex) {
this.orderIndex = orderIndex;
}
/**
* #return Returns the waitedResult.
*/
public String getAwaitedResult() {
return awaitedResult;
}
/**
* #param waitedResult The waitedResult to set.
*/
public void setAwaitedResult(String awaitedResult) {
this.awaitedResult = awaitedResult;
}
/**
* #return Returns the idTest.
*/
public int getIdTest() {
return idTest;
}
/**
* #param idTest The idTest to set.
*/
public void setIdTest(int idTest) {
this.idTest = idTest;
}
}
The entity class:
package org.objectweb.salome_tmf.data;
import java.io.File;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import org.objectweb.salome_tmf.api.Api;
import org.objectweb.salome_tmf.api.ApiConstants;
import org.objectweb.salome_tmf.api.Util;
import org.objectweb.salome_tmf.api.data.ActionWrapper;
import org.objectweb.salome_tmf.api.data.FileAttachementWrapper;
import org.objectweb.salome_tmf.api.data.ParameterWrapper;
import org.objectweb.salome_tmf.api.data.SalomeFileWrapper;
import org.objectweb.salome_tmf.api.data.UrlAttachementWrapper;
import org.objectweb.salome_tmf.api.sql.ISQLAction;
public class Action extends WithAttachment {
static ISQLAction pISQLAction = null;
private String awaitedResult;
public String getAwaitedResult() {
return awaitedResult;
}
public void setAwaitedResult(String awaitedResult) {
this.awaitedResult = awaitedResult;
}
private int orderIndex;
private Hashtable parameterHashTable;
private Test pTest = null;
public Action(Test pTest, String name, String description) {
super(name, description);
awaitedResult = "";
orderIndex = 0;
parameterHashTable = new Hashtable();
this.pTest = pTest;
if (pISQLAction == null){
pISQLAction = Api.getISQLObjectFactory().getISQLAction();
}
}
public Action(ActionWrapper pAction, Test pTest) {
this(pTest, pAction.getName(), pAction.getDescription());
awaitedResult = pAction.getAwaitedResult();
orderIndex = pAction.getOrderIndex();
idBdd = pAction.getIdBDD();
}
public Action(Action pAction, Test pTest) {
this(pTest, pAction.getNameFromModel(), pAction.getDescriptionFromModel());
awaitedResult = pAction.getAwaitedResultFromModel();
} // Fin du constructeur Action/1
protected void reloadBaseFromDB() throws Exception {
if (isInBase()) {
throw new Exception("Action " + name + " is already in BDD");
}
ActionWrapper pActionWrapper = pISQLAction.getActionWrapper(idBdd);
awaitedResult = pActionWrapper.getAwaitedResult();
orderIndex = pActionWrapper.getOrderIndex();
name = pActionWrapper.getName();
description = pActionWrapper.getDescription();
}
public void reloadFromDB(boolean base, Hashtable paramsInModel, boolean attach)
throws Exception {
int transNuber = -1;
try {
transNuber = Api.beginTransaction(101, ApiConstants.LOADING);
if (base){
reloadBaseFromDB();
}
reloadUsedParameterFromDB(paramsInModel);
if (attach){
reloadAttachmentDataFromDB(false);
}
Api.commitTrans(transNuber);
} catch (Exception e){
Api.forceRollBackTrans(transNuber);
throw e;
}
}
public void clearCache() {
/* TODO ClearAttachement */
}
/******************************************************************************/
/** ACCESSEURS ET
MUTATEURS ***/
/******************************************************************************/
public String getAwaitedResultFromModel() {
return awaitedResult;
}
public void setAwaitedResultInModel(String string) {
awaitedResult = string;
}
public int getOrderIndexFromModel() {
return orderIndex;
}
public void setOrderIndex(int i) {
orderIndex = i;
}
public Test getTest(){
return pTest;
}
/////////////////////////////// Basic Operation /////////////////////////
/* Used by Manuel Test */
void addInDB(Test pTest) throws Exception {
//boolean needUpdate = false;
if (isInBase()) {
throw new Exception("Action " + name + " is already in BDD");
}
if (!pTest.isInBase()){
throw new Exception("Test " + pTest.getNameFromModel() + " is not in BDD");
}
int id = pISQLAction.insert(pTest.getIdBdd(), name, description, awaitedResult);
setIdBdd(id);
orderIndex = pISQLAction.getActionWrapper(id).getOrder();
/*if (orderIndex != rowCount){
needUpdate = true;
}
return needUpdate;*/
Project.pCurrentProject.notifyChanged( ApiConstants.INSERT_ACTION ,this);
}
/* Used by Manuel Test */
void addInModel(Test pTest){
this.pTest = pTest;
}
/* Used by Manuel Test */
void addInDBAndModel(Test pTest)throws Exception {
//boolean res;
addInDB(pTest);
addInModel(pTest);
//return res;
}
public void updateInDB(String newActionName, String newActionDesc, String newActionResAttendu) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.update(idBdd, newActionName, newActionDesc, newActionResAttendu );
Project.pCurrentProject.notifyChanged( ApiConstants.UPDATE_ACTION ,this, new String(name), newActionName);
}
public void updateInModel(String newActionName, String newActionDesc, String newActionResAttendu) {
setNameInModel(newActionName);
updateDescriptionInModel(newActionDesc);
setAwaitedResultInModel(newActionResAttendu);
}
public void updateInDBAndModel(String newActionName, String newActionDesc, String newActionResAttendu) throws Exception {
updateInDB(newActionName, newActionDesc, newActionResAttendu);
updateInModel(newActionName, newActionDesc, newActionResAttendu);
}
public void updateInDBAndModel(String newName, String newDesc) throws Exception {
updateInDB(newName, newDesc, awaitedResult);
updateInModel(newName, newDesc, awaitedResult);
}
public void updateOrderInDBAndModel(boolean inc) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
orderIndex = pISQLAction.updateOrder(idBdd, inc);
}
/* Used by Manuel Test */
void deleteInDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.delete(idBdd);
Project.pCurrentProject.notifyChanged( ApiConstants.DELETE_ACTION ,this);
}
/* Used by Manuel Test */
void deleteInModel(){
pTest=null;
parameterHashTable.clear();
clearAttachInModel();
}
/* Used by Manuel Test */
void deleteInDBAndModel() throws Exception {
deleteInDB();
deleteInModel();
}
//////////////// PARAMETERS ////////////////////////
public void setParameterHashSetInModel(HashSet set) {
parameterHashTable.clear();
for (Iterator iter = set.iterator(); iter.hasNext();) {
Parameter param = (Parameter)iter.next();
parameterHashTable.put(param.getNameFromModel(), param);
}
}
public void setParameterHashtableInModel(Hashtable table) {
parameterHashTable.clear();
parameterHashTable = table;
}
public Hashtable getCopyOfParameterHashTableFromModel(){
Hashtable copyParameter = new Hashtable();
Enumeration enumKey = parameterHashTable.keys();
while (enumKey.hasMoreElements()){
Object key = enumKey.nextElement();
copyParameter.put(key, parameterHashTable.get(key));
}
return copyParameter;
}
public void reloadUsedParameterFromDB(Hashtable parametersInModel) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] paramActionArray = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < paramActionArray.length; i++) {
Parameter param = null;
ParameterWrapper pParameterWrapper = paramActionArray[i];
if (parametersInModel != null){
param = (Parameter)parametersInModel.get(pParameterWrapper.getName());
if (param == null){
param = new Parameter(pParameterWrapper);
}
}
setUseParamInModel(param);
}
}
public void setUseParamInModel(Parameter pParam) {
parameterHashTable.put(pParam.getNameFromModel(), pParam);
if (pTest != null) {
if (pTest.getUsedParameterFromModel(pParam.getNameFromModel()) == null){
pTest.setUseParamInModel(pParam);
}
}
}
public void setUseParamInDB(int paramId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.addUseParam(idBdd,paramId);
}
public void setUseParamInDBAndModel(Parameter pParam) throws Exception {
//DB
setUseParamInDB(pParam.getIdBdd());
//model
setUseParamInModel(pParam);
}
public void deleteUseParamInDB(int paramId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.deleteParamUse(idBdd, paramId);
}
public void deleteUseParamInDBAndModel(Parameter pParam) throws Exception {
deleteUseParamInDB(pParam.getIdBdd());
deleteUseParamInModel(pParam);
}
public void deleteUseParamInModel(Parameter pParam) {
// Clean Action
String newDesc = null ;
if (getDescriptionFromModel()!=null)
newDesc = clearStringOfParameter(getDescriptionFromModel(), pParam);
String newResult = null;
if (getAwaitedResultFromModel()!=null)
newResult = clearStringOfParameter(getAwaitedResultFromModel(), pParam);
description = newDesc;
awaitedResult = newResult;
Object o= parameterHashTable.remove(pParam.getNameFromModel());
Util.log("[Action->deleteUseParamInModel] Delete Use Parameter " + pParam + ", in Action " + name + " res is " +o);
}
public Parameter getParameterFromModel(String name) {
Enumeration paramList = parameterHashTable.elements();
while (paramList.hasMoreElements()){
Parameter param = (Parameter)paramList.nextElement();
if (param.getNameFromModel().equals(name)) {
return param;
}
}
return null;
}
public Parameter getParameterFromDB(String name) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
HashSet result = getParameterHashSetFromDB();
for (Iterator iter = result.iterator(); iter.hasNext(); ) {
Parameter param = (Parameter)iter.next();
if (param.getNameFromModel().equals(name)) {
return param;
}
}
return null;
}
public HashSet getParameterHashSetFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
HashSet result = new HashSet();
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] listParamWrapper = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < listParamWrapper.length; i++){
result.add(new Parameter(listParamWrapper[i]));
}
return result;
}
public Vector getParameterVectorFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
Vector result = new Vector();
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] listParamWrapper = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < listParamWrapper.length; i++){
result.add(new Parameter(listParamWrapper[i]));
}
return result;
}
public Hashtable getParameterHashSetFromModel() {
return parameterHashTable;
}
////////////// ATTACHEMENT ///////////////////////
public void addAttachementInDB (Attachment attach )throws Exception {
if (attach instanceof FileAttachment) {
addAttachFileInDB((FileAttachment) attach);
} else {
addAttachUrlInDB((UrlAttachment) attach);
}
}
void addAttachFileInDB(FileAttachment file) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
File f = file.getLocalFile();
int id = pISQLAction.addFileAttach(idBdd,new SalomeFileWrapper(f),file.getDescriptionFromModel());
file.setIdBdd(id);
}
void addAttachUrlInDB(UrlAttachment url) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
int id = pISQLAction.addUrlAttach(idBdd, url.getNameFromModel(),url.getDescriptionFromModel());
url.setIdBdd(id);
}
public void deleteAttachementInDB(int attachId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.deleteAttachment(idBdd, attachId);
}
public void deleteAttachementInDBAndModel(Attachment attach)throws Exception {
deleteAttachementInDB(attach.getIdBdd());
deleteAttachmentInModel(attach);
}
public Vector getAttachFilesFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
FileAttachementWrapper[] fawArray = pISQLAction.getAllAttachFile(idBdd);
Vector result = new Vector();
for(int i = 0; i < fawArray.length; i++) {
result.add(fawArray[i]);
}
return result;
}
public Vector getAttachUrlsFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
UrlAttachementWrapper[] uawArray = pISQLAction.getAllAttachUrl(idBdd);
Vector result = new Vector();
for(int i = 0; i < uawArray.length; i++) {
result.add(uawArray[i]);
}
return result;
}
//////// PROTECTED //////////////
protected String clearStringOfParameter(String prtString, Parameter pParam) {
String result = prtString;
result = result.replaceAll("[$]" + pParam.getNameFromModel() + "[$]", "");
return result;
}
public static boolean isInBase(Test pTest, String actionName) {
try {
int id = pISQLAction.getID(pTest.getIdBdd(), actionName);
if (id > 0){
return true;
}
return false;
} catch (Exception e) {
}
return false;
} // Fin de la methode isInBase/1
public boolean existeInBase() throws Exception {
if (!isInBase()) {
return false;
}
return pISQLAction.getID(pTest.getIdBdd(), name) == idBdd;
}
}
So what is the utility of the wrapper class , is it a kind of design pattern ?
I can not see, what ActionWrapper wraps, for me is just implementation of DataWrapper interface.
There 3 "kinds" of wrappers design patterns:
Facade design pattern = take a lot of classes/interfaces, do some logic inside and get out small interface. For example "Car start" encapsulate inside: open car, put key, set DVD, correct chair, ignition.
Decorator design pattern = take some class with behavior and make ability to add behaviors in run time. for example, instead of do class CarWithLCDWithDVDWithTurbo you can do: new LCDDecorator(new DVDDecorator(TurboDecorator(new car)));
Adapter design pattern = take some new interface and adapt it to some known interface.
The fact that something ends with the Wrapper word doesn´t make it a wrapper. To be a wrapper it has to wrap something. This is, it has to encapsulate one or more components, probably a whole third-party API.
There are different types of wrappers as #zzfima says. And yes, proxy could be a wrapper in some cases and also bridges could be.
Your code doesn´t encapsulate any other component and then, it is not a wrapper (at least for me)
call something "wrapper" doesn't make it a wrapper. Basically it needs to encapsulate something or wrap something, whatever you call it

Trouble with a small library-management program

I'm having major trouble piecing this together. I have basic read and write functionality. What I need is for the input from file 'Books.txt' to be checked so that:
ISBN is valid
CopyNumber, Year and Statistics should be numeric
Title, Author and Publisher must contain values
BorrowDate must be a valid date
ReturnDate if available must be a valid date
LibraryCardNumber if available must be numeric.
If a book is not borrowed the two last fields are nonexistent.
2 sample rows from 'Books.txt':
9780140455168#2#The Twelve Caesars#Suetonius#Penguin Classics#2007#3#101009#101030#5478
9780141188607#1#Claudius the God#Robert Graves#Penguin Classics#2006#2#080123
Error lines should be written to 'ErrorLines.txt' with an error-message, e.g. Wrong ISBN. Error-free books should be written to 'NewBooks.txt' sorted by name of author.
Here's what I've got so far. I'm not looking for a complete solution, because I obviously have a looong way to go, but if someone would be so kind as to give me some pointers, I'd be extremely grateful! And yes, it's homework :D
Do I need to make a try loop to validate the input...?
The Library class:
import java.util.ArrayList;
import java.util.*;
import java.io.*;
import java.io.IOException;
public class Library {
public void readFromFile (String filename) throws IOException {
String inLine;
File inFile;
inFile = new File("Books.txt");
BufferedReader fIn = new BufferedReader(new FileReader(inFile));
inLine = fIn.readLine();
while (inLine != null) {
inLine = fIn.readLine();
aBookList.add(inLine + "\n");
}
fIn.close();
}
public void writeToFile (String fileName) throws IOException {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(fileName));
bw.write("???"); //Dont know what to put here...
bw.newLine();
} catch (IOException e) {
System.out.println("Error writing file.");
} finally {
bw.close();
}
}
public static boolean isISBN13Valid(isbn) {
int check = 0;
for (int i = 0; i < 12; i += 2) {
check += Integer.valueOf(isbn.substring(i, i + 1));
}
for (int i = 1; i < 12; i += 2) {
check += Integer.valueOf(isbn.substring(i, i + 1)) * 3;
}
check += Integer.valueOf(isbn.substring(12));
return check % 10 == 0;
}
}
And here's the Book class:
import java.util.*;
import java.io.*;
public class Book {
Book b = new Book();
private static ArrayList<String> aBookList = new ArrayList<String>();
private String Isbn;
private int CopyNumber;
private String Title;
private String Author;
private String Publisher;
private int Year;
private int Statistics;
private String BorrowDate;
private String ReturnDate;
private int LibraryCardNumber;
public void bookInfo (String nIsbn, int nCopyNumber, String nTitle, String nAuthor, String nPublisher, int nYear,
int nStatistics, String nBorrowDate, String nReturnDate, int nLibraryCardNumber) {
Isbn = nIsbn;
CopyNumber = nCopyNumber;
Title = nTitle;
Author = nAuthor;
Publisher = nPublisher;
Year = nYear;
Statistics = nStatistics;
BorrowDate = nBorrowDate;
ReturnDate = nReturnDate;
LibraryCardNumber = nLibraryCardNumber;
}
public void bookInfo (String Row) {
StringTokenizer sT = new StringTokenizer(Row);
Isbn = sT.nextToken("#");
CopyNumber = Integer.parseInt(sT.nextToken("#") );
Title = sT.nextToken("#");
Author = sT.nextToken("#");
Publisher = sT.nextToken("#");
Year = Integer.parseInt(sT.nextToken("#") );
Statistics = Integer.parseInt(sT.nextToken("#") );
BorrowDate = sT.nextToken("#");
ReturnDate = sT.nextToken("#");
LibraryCardNumber = Integer.parseInt(sT.nextToken("#") );
}
public void setIsbn(String nIsbn) {
Isbn = nIsbn;
}
public void setCopynumber(int nCopyNumber) {
CopyNumber = nCopyNumber;
}
public void setTitle(String nTitle) {
Title = nTitle;
}
public void setAuthor(String nAuthor) {
Author = nAuthor;
}
public void setPublisher(String nPublisher) {
Publisher = nPublisher;
}
public void setYear(int nYear) {
Year = nYear;
}
public void setStatistics(int nStatistics) {
Statistics = nStatistics;
}
public void setBorrowDate(String nBorrowDate) {
BorrowDate = nBorrowDate;
}
public void setReturnDate(String nReturnDate) {
ReturnDate = nReturnDate;
}
public void setLibraryCardNumber(int nLibraryCardNumber) {
LibraryCardNumber = nLibraryCardNumber;
}
public String getAll () {
String s = " ";
return (Isbn + s + CopyNumber + s + Title + s + Author + s + Publisher + s +
Year + s + Statistics + s + BorrowDate + s + ReturnDate + s +
LibraryCardNumber);
}
public void showAll () {
String t = "\t";
System.out.println(Isbn + t + CopyNumber + t + Title + t + Author + t +
Publisher + t + Year + t + Statistics + t +
BorrowDate + t + ReturnDate + t + LibraryCardNumber);
}
}
And finally there's the Main class with main method:
public class Main<aBookList> implements Comparable<aBookList> {
public static void main(String [] args) throws Exception {
new Library().readFromFile("Books.txt");
new Library().writeToFile("NewBooks.txt");
new Library().writeToFile("ErrorLines.txt");
}
#Override
public int compareTo(aBookList o) {
return 0;
}
}
as it is homework, i will point you direction, not give you code
1) you have lot of mess here, ie i'm not sure why you have compare in your main class? instead of creating getAll method in bookInfo(which is named against java nameing convention) just override toString method
2) why do you have list of strings? read a line, convert this into book, if book is valid add it to your list, otherwise report an error
3) move your isISBN13Valid method to book
4) write to file -> loop through your list, and save each element into file by bw.write(book.toString()),
5) create second method createErrorFile, then each error what you will have add into your error list, and after you call that method, you will sace each element into given file, it is not perfetc solution, better will be if you add error to file each time when it occur.
6) create one instance of library in your main method, and just call on it all your method, and avoid using static fields in your project(sometimes you must, but if you don;t need, just avoid them)
7) names for method import/ export i think sounds nicer than read from file read from file

Android: How Can I display all XML values of same tag name

I have the ff. XML from a URL:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<Phonebook>
<PhonebookEntry>
<firstname>Michael</firstname>
<lastname>De Leon</lastname>
<Address>5, Cat Street</Address>
</PhonebookEntry>
<PhonebookEntry>
<firstname>John</firstname>
<lastname>Smith</lastname>
<Address>6, Dog Street</Address>
</PhonebookEntry>
</Phonebook>
I want to display both PhonebookEntry values (firstname,lastname,Address). Currently, my code displays only the PhonebookEntry of John Smith (the last entry). Here's my code.
ParsingXML.java
package com.example.parsingxml;
import java.net.Proxy;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class ParsingXML extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* Create a new TextView to display the parsingresult later. */
TextView tv = new TextView(this);
try {
/* Create a URL we want to load some xml-data from. */
URL url = new URL("http://somedomain.com/jm/sampleXML.xml");
URLConnection ucon = url.openConnection();
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
/* Create a new ContentHandler and apply it to the XML-Reader*/
ExampleHandler myExampleHandler = new ExampleHandler();
xr.setContentHandler(myExampleHandler);
/* Parse the xml-data from our URL. */
xr.parse(new InputSource(url.openStream()));
/* Parsing has finished. */
/* Our ExampleHandler now provides the parsed data to us. */
ParsedExampleDataSet parsedExampleDataSet =
myExampleHandler.getParsedData();
/* Set the result to be displayed in our GUI. */
tv.setText(parsedExampleDataSet.toString());
} catch (Exception e) {
/* Display any Error to the GUI. */
tv.setText("Error: " + e.getMessage());
}
/* Display the TextView. */
this.setContentView(tv);
}
}
ExampleHandler.java
package com.example.parsingxml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ExampleHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private boolean in_outertag = false;
private boolean in_innertag = false;
private boolean in_firstname = false;
private boolean in_lastname= false;
private boolean in_Address=false;
private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
// ===========================================================
// Getter & Setter
// ===========================================================
public ParsedExampleDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new ParsedExampleDataSet();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
#Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equals("PhoneBook")) {
this.in_outertag = true;
}else if (localName.equals("PhonebookEntry")) {
this.in_innertag = true;
}else if (localName.equals("firstname")) {
this.in_firstname = true;
}else if (localName.equals("lastname")) {
this.in_lastname= true;
}else if(localName.equals("Address")) {
this.in_Address= true;
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("Phonebook")) {
this.in_outertag = false;
}else if (localName.equals("PhonebookEntry")) {
this.in_innertag = false;
}else if (localName.equals("firstname")) {
this.in_firstname = false;
}else if (localName.equals("lastname")) {
this.in_lastname= false;
}else if(localName.equals("Address")) {
this.in_Address= false;
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(this.in_firstname){
myParsedExampleDataSet.setfirstname(new String(ch, start, length));
}
if(this.in_lastname){
myParsedExampleDataSet.setlastname(new String(ch, start, length));
}
if(this.in_Address){
myParsedExampleDataSet.setAddress(new String(ch, start, length));
}
}
}
ParsedExampleDataSet.java
package com.example.parsingxml;
public class ParsedExampleDataSet {
private String firstname = null;
private String lastname=null;
private String Address=null;
//Firstname
public String getfirstname() {
return firstname;
}
public void setfirstname(String firstname) {
this.firstname = firstname;
}
//Lastname
public String getlastname(){
return lastname;
}
public void setlastname(String lastname){
this.lastname=lastname;
}
//Address
public String getAddress(){
return Address;
}
public void setAddress(String Address){
this.Address=Address;
}
public String toString(){
return "Firstname: " + this.firstname + "\n" + "Lastname: " + this.lastname + "\n" + "Address: " + this.Address;
}
}
I'm new to java and android dev, many thanks in advance for any help! :)
The other responses have already pointed out that you require a list to store all the ParsedExampleDataSet objects gotten from the XML.
But I want to point your attention to another thing about XML handlers which may bite you only later (and randomly). The characters method is not a good place to assign the values found between tags in you XML, because the characters method is not guaranteed to return all the characters in an element at once. It may be called multiple times within the same element to report characters found so far. With your implementation as it is right now, you will end up with missing data and wonder what is going on.
That said, what I would do it use a StringBuilder to accumulate your characters and then assign them in an endElement(...) call. Like so:
public class ExampleHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private StringBuilder mStringBuilder = new StringBuilder();
private ParsedExampleDataSet mParsedExampleDataSet = new ParsedExampleDataSet();
private List<ParsedExampleDataSet> mParsedDataSetList = new ArrayList<ParsedExampleDataSet>();
// ===========================================================
// Getter & Setter
// ===========================================================
public List<ParsedExampleDataSet> getParsedData() {
return this.mParsedDataSetList;
}
// ===========================================================
// Methods
// ===========================================================
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
#Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equals("PhonebookEntry")) {
this.mParsedExampleDataSet = new ParsedExampleDataSet();
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("PhonebookEntry")) {
this.mParsedDataSetList.add(mParsedExampleDataSet);
}else if (localName.equals("firstname")) {
mParsedExampleDataSet.setfirstname(mStringBuilder.toString().trim());
}else if (localName.equals("lastname")) {
mParsedExampleDataSet.setlastname(mStringBuilder.toString().trim());
}else if(localName.equals("Address")) {
mParsedExampleDataSet.setAddress(mStringBuilder.toString().trim());
}
mStringBuilder.setLength(0);
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
mStringBuilder.append(ch, start, length);
}
}
You can then retrieve the list of ParsedExampleDataSets in your activity and either display in multiple text views or only in one. Your Activity.onCreate(...) method may look like:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* Create a new TextView to display the parsingresult later. */
TextView tv = new TextView(this);
try {
/* Create a URL we want to load some xml-data from. */
URL url = new URL("http://somedomain.com/jm/sampleXML.xml");
URLConnection ucon = url.openConnection();
/* Create a new ContentHandler and apply it to the XML-Reader*/
ExampleHandler myExampleHandler = new ExampleHandler();
//remember to import android.util.Xml
Xml.parse(url.openStream(), Xml.Encoding.UTF_8, myExampleHandler);
/* Our ExampleHandler now provides the parsed data to us. */
List<ParsedExampleDataSet> parsedExampleDataSetList =
myExampleHandler.getParsedData();
/* Set the result to be displayed in our GUI. */
for(ParsedExampleDataSet parsedExampleDataSet : parsedExampleDataSetList){
tv.append(parsedExampleDataSet.toString());
}
} catch (Exception e) {
/* Display any Error to the GUI. */
tv.setText("Error: " + e.getMessage());
}
/* Display the TextView. */
this.setContentView(tv);
}
You only have one ParsedExampleDataSet object in your handler, so there's only room to store one entry. Change ExampleHandler to have an ArrayList<ParsedExampleDataSet> results and also a ParsedExampleDataSet currentSet. Inside startElement, when you see the PhoneBook tag, set currentSet to a new instance of ParsedExampleDataSet and add it to results. After parsing, results should contain everything you want.
You were close. Since you have many PhoneBookeEntrys you need to store them somewhere:
public class ExampleHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private boolean in_outertag = false;
private boolean in_innertag = false;
private boolean in_firstname = false;
private boolean in_lastname= false;
private boolean in_Address=false;
private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
private List<ParsedExampleDataSet> allSets = new ArrayList<ParsedExampleDataSet>();
// ===========================================================
// Getter & Setter
// ===========================================================
public ParsedExampleDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
// ===========================================================
// Methods
// ===========================================================
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
#Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equals("PhoneBook")) {
this.in_outertag = true;
}else if (localName.equals("PhonebookEntry")) {
this.in_innertag = true;
this.myParsedExampleDataSet = new ParsedExampleDataSet();
}else if (localName.equals("firstname")) {
this.in_firstname = true;
}else if (localName.equals("lastname")) {
this.in_lastname= true;
}else if(localName.equals("Address")) {
this.in_Address= true;
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("Phonebook")) {
this.in_outertag = false;
}else if (localName.equals("PhonebookEntry")) {
this.in_innertag = false;
allSets.add(myParsedExampleDataSet);
}else if (localName.equals("firstname")) {
this.in_firstname = false;
}else if (localName.equals("lastname")) {
this.in_lastname= false;
}else if(localName.equals("Address")) {
this.in_Address= false;
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(this.in_firstname){
myParsedExampleDataSet.setfirstname(new String(ch, start, length));
}
if(this.in_lastname){
myParsedExampleDataSet.setlastname(new String(ch, start, length));
}
if(this.in_Address){
myParsedExampleDataSet.setAddress(new String(ch, start, length));
}
}
}
I found an XML tutorial online here and editied it to work with your XML file. Below is the code. For the sake of testing it on my machine, I've sourced the XML file from a local file rather than online, but it shouldn't be too hard to work out.
This should hopefully point you in the right direction.
package phonebook;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class program {
public static void main(String argv[]) {
try {
File file = new File("phonebook.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("PhonebookEntry");
System.out.println("Information of all entries");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fstElmnt = (Element) fstNode;
// Firstname
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println("First Name : " + ((Node) fstNm.item(0)).getNodeValue());
// Lastname
NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
System.out.println("Last Name : " + ((Node) lstNm.item(0)).getNodeValue());
// Address
NodeList addrNmElmntLst = fstElmnt.getElementsByTagName("Address");
Element addrNmElmnt = (Element) addrNmElmntLst.item(0);
NodeList addrNm = addrNmElmnt.getChildNodes();
System.out.println("Address : " + ((Node) addrNm.item(0)).getNodeValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Categories

Resources