ciao a tutti
avrei bisogno di un altro vostro aiuto
in pratica io avevo creato un file .xml ke mi conteneva tutti gli item ke ho aggiunto ora io voglio copiarlo in un altro file .xml cambiando la radice del file e aggiungervi un altro attributo al content
vi posto il mio codice
codice:
/**
*
*/
package projectservlet;
/**
* @(#)Recommendations.java
*
*
* @author Raffaella
* @version 1.00 2007/4/24
*/
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.io.File;
import java.util.*;
import java.text.*;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import java.util.Iterator;
import java.util.List;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.lang.String;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Recommendations extends HttpServlet {
Document documento = null;
Document itemDocumento = null;
Element elementoRate = null;
Element itemElemento = null;
String rating_inviato;
//metodo che permette di aggiungere un item copiandolo dal file Item.xml
public void aggiungiRatedItem(){
Calendar calendar = new GregorianCalendar();
//CONTROLLO SE ESISTE GIA' UN FILE .XML CHE SI CHIAMA REGISTRATED
String itemPath = new String ("C:/Programmi/Apache Software Foundation/Tomcat 6.0/webapps/ITemRecommender/xml/Item.xml");
File itemFile = new File(itemPath);
//SE IL FILE NON ESISTE LO CREO E GLI AGGIUNGO L'ELEMENTO RADICE IL PRIMO REGISTRATO
if (itemFile.exists()){
//SE IL FILE ESISTE LO CARICO IN MEMORIA
SAXBuilder saxBuilder = new SAXBuilder();
try{
itemDocumento = saxBuilder.build(new File(itemPath));
}
catch (JDOMException ex){
System.err.println(ex);
}
catch (IOException ex){
System.err.println(ex);
}
try{
//verifica che l'id scelto per essere valutato sia contenuto nel file Item.xml
//String tempIDPath = new String("C:/Programmi/Apache Software Foundation/Tomcat 6.0/webapps/ITemRecommender/temp/IDItem - " + calendar.get(Calendar.DAY_OF_MONTH) + "/" + calendar.get(Calendar.MONTH) + "/" + calendar.get(Calendar.YEAR) + ".txt");
String tempIDPath = new String("C:/Programmi/Apache Software Foundation/Tomcat 6.0/webapps/ITemRecommender/temp/IDItem.txt");
File tempIDFile = new File(tempIDPath);
BufferedReader readTempID = new BufferedReader( new FileReader(tempIDFile));String line;
String tmp = "";
//Leggo tutto il file e lo butto in una variabile temporanea
while ((line = readTempID.readLine()) != null){
tmp += line;
}
readTempID.close();
Element elementoTempID = itemDocumento.getRootElement();
List lista_TempID = elementoTempID.getChildren();
// ottengo un iteratore alla lista chiamando il metodo iterator() di Collection (essendo una list una collection)
Iterator iteratoreTempID = lista_TempID.iterator();
while (iteratoreTempID.hasNext())
{
// ottengo l'elemento corrente chiamando next() sull'iteratore
Element tempID_corrente = (Element)iteratoreTempID.next();
String tempID = tempID_corrente.getAttributeValue("id");
if (tmp.equals(tempID)){
//POI UNA VOLTA CARICATO CONTROLLO CHE NON CI SIA GIA' UN REGISTRATO CON TALE LOGIN E SE NON C'è INSERISCO IL NUOVO
//REGISTRATO ALTRIMENTI DICO DI CAMBIARE LOGIN
itemElemento = itemDocumento.getRootElement();
List item_lista = itemElemento.getChildren();
// ottengo un iteratore alla lista chiamando il metodo iterator() di Collection (essendo una list una collection)
Iterator itemIteratore = item_lista.iterator();
while (itemIteratore.hasNext())
{
// ottengo l'elemento corrente chiamando next() sull'iteratore
Element item_corrente = (Element)itemIteratore.next();
String id = item_corrente.getAttributeValue("id");
//copia il content corrente, impostando i nuovi attributi, in un altro file xml
Element rated = new Element("ratedItem");
rated.addContent(item_corrente);
rated.setAttribute("id", id);
rated.setAttribute("rate", rating_inviato);
elementoRate.addContent(rated);
}
}
}
}
catch (FileNotFoundException ex){
System.err.println(ex);
}
catch (NumberFormatException ex){
System.err.println(ex);
}
catch (IOException ex){
System.err.println(ex);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
Calendar calendar = new GregorianCalendar();
StringBuffer buf = new StringBuffer();
response.setContentType("text/html");
PrintWriter responseOutput = response.getWriter();
buf.append("<html><head></head><body><table border=\"1\" width=\"40%\" align=\"center\"><tbody><tr>");
//preleva dal file ItemCount.txt il totale degli item da votare
//String tempIDPath = new String("C:/Programmi/Apache Software Foundation/Tomcat 6.0/webapps/ITemRecommender/temp/IDItem - " + calendar.get(Calendar.DAY_OF_MONTH) + "/" + calendar.get(Calendar.MONTH) + "/" + calendar.get(Calendar.YEAR) + ".txt");
String tempIDPath = new String("C:/Programmi/Apache Software Foundation/Tomcat 6.0/webapps/ITemRecommender/temp/IDItem.txt");
File tempIDFile = new File(tempIDPath);
BufferedReader readTempID = new BufferedReader( new FileReader(tempIDFile));
String line2;
int countLine = 0;
//Leggo tutto il file e lo butto in una variabile temporanea
while ((line2 = readTempID.readLine()) != null){
countLine += 1;
}
readTempID.close();
for (int i = 1; i <= countLine; i++){
//RECUPERO LE INFORMAZIONI INVIATE DAL FORM
rating_inviato = request.getParameter("rated" + countLine);
if (rating_inviato != ""){
HttpSession session = request.getSession(true);
//String username = (String)session.getAttribute("Username");
//CONTROLLO SE ESISTE GIA' UN FILE .XML CHE SI CHIAMA REGISTRATI
String path = new String ("C:/Programmi/Apache Software Foundation/Tomcat 6.0/webapps/ITemRecommender/xml/Recommendations.xml");
File file = new File(path);
//SE IL FILE NON ESISTE LO CREO E GLI AGGIUNGO L'ELEMENTO RADICE IL PRIMO ITEM CON RATING
if (!file.exists()){
file.createNewFile();
elementoRate = new Element("recommendations");
//AGGIUNGO IL RATING CHE RISULTA IL PRIMO DATO CHE IL FILE RECOMMENDATIONS.XML NON ESISTEVA
aggiungiRatedItem();
//SCRIVO IL DOCUMENT NEL FILE
documento = new Document(elementoRate);
XMLOutputter xmlOutputter = new XMLOutputter();
try{
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
xmlOutputter.output(documento, fileOutputStream);
}
catch (FileNotFoundException ex){
System.err.println(ex);
}
catch (IOException ex){
System.err.println(ex);
}
}
else{
//SE IL FILE ESISTE LO CARICO IN MEMORIA
SAXBuilder saxBuilder = new SAXBuilder();
try{
documento = saxBuilder.build(new File(path));
}
catch (JDOMException ex){
System.err.println(ex);
}
catch (IOException ex){
System.err.println(ex);
}
//RISCRIVO L'INTERO DOCUMENTO NEL FILE XML DOPO AVER AGGIUNTO IL RATING
aggiungiRatedItem();
XMLOutputter xmlOutputter = new XMLOutputter();
//IL METODO SEGUENTE Format.getPrettyFormat() SERVE PER SCRIVERE SUL FILE XML IN MODO BEN FORMATTATO
//CON GLI A CAPO E LE INDENTAZIONI PER OGNI ELEMENTO, ma non lo accetta
//xmlOutputter.setFormat(Format.getPrettyFormat());
try{
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
xmlOutputter.output(documento, fileOutputStream);
buf.append("<td align=\"center\">
Items Rated.
<a href=\"index.htm\">Proceed
</a></p>
</td>");
}
catch (FileNotFoundException ex){
System.err.println(ex);
}
catch (IOException ex){
System.err.println(ex);
}
}
}
else{
buf.append("<td align=\"center\">
Missing informations, try again
<a href=\"RecommendedItem.htm\">Go Back
</a></p>
</td>");
}
}
buf.append("</tr></tbody></table></body></html>");
responseOutput.println(buf.toString());
responseOutput.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
però quando faccio send dalla pagina web(dove ho dato un rate ad un item il quale me lo deve inserire nel nuovo file .xml recuperando le informazioni dal primo file .xml aggiungendovi un altro attributo relativo al rate dato) tomcat mi da questo errore
codice:
HTTP Status 500 -
--------------------------------------------------------------------------------
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.jdom.IllegalAddException: The Content already has an existing parent "itemAdded"
org.jdom.ContentList.add(ContentList.java:218)
org.jdom.ContentList.add(ContentList.java:140)
java.util.AbstractList.add(Unknown Source)
org.jdom.Element.addContent(Element.java:809)
projectservlet.Recommendations.aggiungiRatedItem(Recommendations.java:107)
projectservlet.Recommendations.doPost(Recommendations.java:172)
javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.13 logs.
--------------------------------------------------------------------------------
Apache Tomcat/6.0.13
ho sbagliato a copiare i content giusto? come posso rimediare?
grazie mille