-
[Problems] ArrayList
Hello to all, well i'm a new user and i have a problem with ArrayList.
Well i need to get some information from a log in xml and save it in a DB; i create
a method wich will return a ArrayList of the type message; but for some reason the final ArrayList that i get is just the last element wich is repeating a lot of times.
Well the code is:
Code:
//Obtem os dados do log
public ArrayList<Message> getDados(File arquivo) throws ParserConfigurationException, SAXException,IOException, XPathExpressionException
{
Message message = new Message();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(arquivo);
NodeList bodys = doc.getElementsByTagName("body");
ArrayList<Message> messages = new ArrayList<Message>();
for (int i = 0; i < bodys.getLength(); i++)
{
Node nodeBody = bodys.item(i);
//Extrai o texto do no Body
/*if (nodeBody.hasChildNodes())
{
message.setMessage(nodeBody.getFirstChild().getTextContent().toString());
}
else
{*/
message.setMessage(nodeBody.getTextContent().toString());
//}
//Extrai os atributos do "message" pai do no body corrente
Attr attr;
Node nodeMessage = nodeBody.getParentNode();
for (int j=0; j < nodeMessage.getAttributes().getLength();j++)
{
attr = (Attr)nodeMessage.getAttributes().item(j);
if (attr.getName()=="to")
{
message.setTo(attr.getValue());
}
else if (attr.getName()=="from")
{
message.setFrom(attr.getValue());
}
else if (attr.getName()=="type")
{
message.setType(attr.getValue());
}
else if (attr.getName()=="id")
{
message.setId(attr.getValue());
}
}
//Extrai os atributos do "packet" avo do no body corrente
Node nodePacket = nodeMessage.getParentNode();
for (int j=0; j < nodePacket.getAttributes().getLength();j++)
{
attr = (Attr)nodePacket.getAttributes().item(j);
if (attr.getName()=="timestamp")
{
message.setTimeStamp(attr.getValue());
}
}
messages.add(message);
}
return messages;
}
Code:
public static void main(String[] args) throws Exception
{
Connection connection = null;//gerencia conexão
PreparedStatement stmt = null;//instrução de consulta
//O diretorio dos logs
String urlDiretorio = "C:/Java/log xml/conversas";
File diretorio = new File(urlDiretorio);
//Arquivos no diretorio
String arquivos[] = diretorio.list();
File arquivoXml;
Xml xml = new Xml();
//conecta-se ao banco de dados e o consulta
try
{
Class.forName( JDBC_DRIVER );//carrega a classe de driver do banco de dados
//estabelece conexão com o banco de dados
connection = DriverManager.getConnection (DATABASE_URL, "ADMINLOG","ADMIN");
//cria Statement para consultar banco de dados
//statement = connection.createStatement();
//cria um preparedStatement
stmt = connection.prepareStatement("INSERT INTO LOG (\"ID\",\"TO\",\"FROM\",\"MESSAGE\",\"TYPE\") VALUES (?,?,?,?,?)");
for (int i=0; i < arquivos.length; i++)
{
arquivoXml = new File(urlDiretorio+"/"+arquivos[i]);
if (arquivoXml.isFile())
{
String conteudoArquivo = xml.retArq(arquivoXml = new File(urlDiretorio+"/"+arquivos[i]));
conteudoArquivo =conteudoArquivo.substring(conteudoArquivo.length()-7);
String jive = "</jive>";
if (!conteudoArquivo.equalsIgnoreCase(jive))
xml.fechaXml(urlDiretorio+"/"+arquivos[i]);
ArrayList<Message> messages = new ArrayList<Message>();
messages = xml.getDados(arquivoXml = new File(urlDiretorio+"/"+arquivos[i]));
for (int j=0;j<messages.size();j++)
{
System.out.println("Mensagem: "+messages.get(j).getMessage());
System.out.println("Id: "+messages.get(j).getId());
System.out.println("From: "+messages.get(j).getFrom());
System.out.println("To: "+messages.get(j).getTo());
System.out.println("Type: "+messages.get(j).getType());
System.out.println(messages.get(j).getTimeStamp());
// preenche os valores
stmt.setString(1, messages.get(j).getId());
stmt.setString(2, messages.get(j).getTo());
stmt.setString(3, messages.get(j).getFrom());
stmt.setString(4, messages.get(j).getMessage());
stmt.setString(5, messages.get(j).getType());
//executa
//stmt.execute();
}
System.out.println("Gravado!");
File destino = new File (urlDiretorio+"/backups/"+arquivos[i]);
//arquivoXml.renameTo(destino);
}
}
}
catch ( SQLException sqlException)
{
sqlException.printStackTrace();
System.exit(1);
}//fim do catch
catch (ClassNotFoundException classNotFound)
{
classNotFound.printStackTrace();
System.exit(1);
}//fim do catch
finally//asegura que a instrução e a conexão são fechadas adequadamente
{
try
{
stmt.close();
connection.close();
}//fim do try
catch ( Exception exception )
{
exception.printStackTrace();
System.exit(1);
}//fim do catch
}//fim do finally
}//fim de main
Sorry for the horrivell english, i will be improving it slowly.
I know of the method "getAttribute" but for some reason it doesn't work here.
If some one can give me an advice for improving my code it will be usefull to, because it's my first java project.
-
When you store an Object in ana ArrayList, it does not create a copy of that Object and store that, rather it simply stores a copy of the reference value, which will point to the same object as the reference value that was used to store the object. So, when you create one object, store it, then modify it's values, and store it again, you have simply stored the same Object twice. Create a new message object in each iteration rather than simply modifying the values.
I.E.
Code:
// bad
ArrayList<MyObject> a = new ArrayList<MyObject>();
MyObject b = new MyObject();
b.setID = 1;
a.store(b);
b.setID = 2; // This reference is the same one as already stored, so it's value changes to, because it is the same object.
a.store(b); // now you have simply stored the same object reference, again.
//good
ArrayList<MyObject> a = new ArrayList<MyObject>();
MyObject b = new MyObject();
b.setID = 1;
a.store(b);
b = new MyObject(); // now b has a new reference and no longer references the same object as the one already stored in the ArrayList
b.setID = 2;
a.store(b);