Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 20
  1. #1

    [Servlet]Copiare i content con i relativi attributi in un altro file .xml

    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

  2. #2
    nessuno proprio più aiutarmi?? vi prego è urgente

  3. #3
    Utente di HTML.it
    Registrato dal
    Apr 2007
    Messaggi
    906
    Prova cosi'.
    codice:
    // 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");
    item_corrente.detach();
    rated.addContent(item_corrente);
    rated.setAttribute("id", id);
    rated.setAttribute("rate", rating_inviato);
    rated.detach(); //Questa linea credo non serva perche' l'element rated non ha parent
    elementoRate.addContent(rated);
    P.s. La prossima volta quando hai un codice cosi' lungo, se puoi evidenzia le linee che ti sollevano l'eccezione, sono indicate nello stacktrace dell'eccezione stessa altrimenti ci vuole molto a trovare il frammento di codice che origina il problema.

  4. #4
    ciao
    scusami farò come mi hai detto
    ti ringrazio per avermi risposto solo che ho provato e non mi da nessun errore solo ke da lo stesso risultato al codice ke ho fatto io... ovvero nella pagina reccomendation.xml mi esce scritto questo

    codice:
    <?xml version="1.0" encoding="UTF-8"?>
    <recommendations />
    e non ho capito cosa sbaglio allora posto tutto il 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;	
    	int countLine;
    	String id, author, description;
    	
    	//metodo che permette di aggiungere un item	copiandolo dal file Item.xml
    	public void aggiungiRatedItem(){
    		
    		Calendar calendar = new GregorianCalendar();
    		String controllo = new String("ok");
    		
    		//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);
    	
    		//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);
    			
    			
     		try{
     			
     			//SE IL FILE ESISTE LO CARICO IN MEMORIA
     			SAXBuilder saxBuilderItem = new SAXBuilder();
    			try{
       				itemDocumento = saxBuilderItem.build(new File(itemPath)); 
     			}
     			catch (JDOMException ex){
       				System.err.println(ex);
    			}
    	 		catch (IOException ex){
       				System.err.println(ex);
     			}
     				
     			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)){
    					
      					controllo = new String("ok");
    					break;
    				}
    	 		}
    	 		
      			if (controllo.equals("ok"))
      			{
      				//provvedo a copiare ogni elemento			
    				while (iteratoreTempID.hasNext())
    	 			{  				
    	 				
    	 				
    	   				// ottengo l'elemento corrente chiamando next() sull'iteratore 
    	   				Element item_corrente = (Element)iteratoreTempID.next();
    	   				if ((item_corrente.getName()).equals("item"))
    	   					{id = item_corrente.getAttributeValue("id");}
    	   				if ((item_corrente.getName()).equals("author"))
    	   					{author = item_corrente.getText();}
    	   				if ((item_corrente.getName()).equals("description"))
    	   					{description = item_corrente.getText();}
    	   				
    	   				
    	   								
    					//copia il content corrente, impostando i nuovi attributi, in un altro file xml
    					Element rated = new Element("ratedItem");
    					Element element_id = new Element("id");
    					Element element_rate = new Element("rate");
    					Element element_author = new Element("author");
    					Element element_description = new Element("description");
    					
    					element_author.setText(author);
    					element_description.setText(description);
    		
    					
    		
    					rated.addContent(element_author);
    					rated.addContent(element_description);
    		
    					
    					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");
    		
    			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);
       						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{
    					//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);
        }
    }
    ho sostituito il mio pezzo di codice in grassetto ovvero
    codice:
    	 				
    	   				// ottengo l'elemento corrente chiamando next() sull'iteratore 
    	   				Element item_corrente = (Element)iteratoreTempID.next();
    	   				if ((item_corrente.getName()).equals("item"))
    	   					{id = item_corrente.getAttributeValue("id");}
    	   				if ((item_corrente.getName()).equals("author"))
    	   					{author = item_corrente.getText();}
    	   				if ((item_corrente.getName()).equals("description"))
    	   					{description = item_corrente.getText();}
    	   				
    	   				
    	   								
    					//copia il content corrente, impostando i nuovi attributi, in un altro file xml
    					Element rated = new Element("ratedItem");
    					Element element_id = new Element("id");
    					Element element_rate = new Element("rate");
    					Element element_author = new Element("author");
    					Element element_description = new Element("description");
    					
    					element_author.setText(author);
    					element_description.setText(description);
    		
    					
    		
    					rated.addContent(element_author);
    					rated.addContent(element_description);
    		
    					
    					rated.setAttribute("id", id);
    					rated.setAttribute("rate", rating_inviato);
    					
    					elementoRate.addContent(rated);
    col tuo postato cioè
    codice:
    // 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");
    item_corrente.detach();
    rated.addContent(item_corrente);
    rated.setAttribute("id", id);
    rated.setAttribute("rate", rating_inviato);
    rated.detach(); //Questa linea credo non serva perche' l'element rated non ha parent
    elementoRate.addContent(rated);
    entrambi i codici danno lo stesso risultato ke ho scritto prima nel file .xml
    perkè?
    help please

  5. #5
    Utente di HTML.it
    Registrato dal
    Apr 2007
    Messaggi
    906
    Mmmh... La linea che ti da errore qual'e' di preciso?
    P.s. Trovi il numero della linea nello stacktrace dell'eccezione. Ad esempio
    codice:
    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)

  6. #6
    il problema è che non mi da nessun errore è questo il bello
    non riesco a capire dove è sbagliato perkè effettivamente mi crea il nuovo file xml mi da come risposta item rated procedee solo ke il contenuto del file xml è quello ke ti ho mostrato e non capisco il motivo
    hai qualke idea? magari c'è qualke pezzo di codice ke ostacola? provo a commentare tutto ciò ke viene fatto con tempID magari è quello

  7. #7
    ci sono riuscita grazie mille

  8. #8
    un ultima cosa..
    poikè io ho creato le webpage dinamiche nasce un piccolo problema
    in pratica nel file .htm ci dovrebbero essere tante select il cui nome è dato da una stringa più un contatore ke si DOVREBBE incrementare di uno
    ora quando io nella servlet prendo il paramentro io l'ho implementato come un array dove la lunghezza la so perkè mi sono creato un file .txt in cui mi sono contenuti il numero di item da dare un rate e questo sarà la dimensione dell'array
    solo ke quando provo a avviarlo mi fa il difetto di prima cioè mi da nel nuovo file .xml quelle scritte ke ho postato prima e ho notato ke questo difetto lo fa quando voglio leggere un file .txt ed utilizzare il valore contenuto all'interno..

    ora posto il codice del do post magari c'è qualke errore
    codice:
    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 tempCountPath = new String("C:/Programmi/Apache Software Foundation/Tomcat 6.0/webapps/ITemRecommender/temp/IDCount.txt");
    		File tempCountFile = new File(tempCountPath);
    		BufferedReader readTempCount = new BufferedReader( new FileReader(tempCountFile));
     		
     		String line2;
     		String countLine = "";
       		//Leggo tutto il file e lo butto in una variabile temporanea
       		while ((line2 = readTempCount.readLine()) != null){
         		countLine += line2;
      		}
      		readTempCount.close();
    	
    	int count = Integer.valueOf(countLine).intValue();
    	rating_inviato = new String[count];	
    	for (i = 0; i < rating_inviato.length; i++) {
    	
    		//RECUPERO LE INFORMAZIONI INVIATE DAL FORM
    		rating_inviato[i] = request.getParameter("rated" + i);
    		
    			if (rating_inviato[i] != ""){	
    				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);
       						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{
    					//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();
        }
    il codice in grassetto è la parte ke ho aggiunto considerando un array di stringhe per contenere i valori dei parametri ottenuti da un combobox presente nella relativa pagina web
    il fatto è ke non mi da nessun errore ma se levo la lettura del .txt e non utilizzo il valore in esso contenuto nel resto del codice va perkè?

  9. #9
    help pleaze

  10. #10
    Utente di HTML.it
    Registrato dal
    Apr 2007
    Messaggi
    906
    E' possibile che non ti entri in qualche parte del metodo aggiungiRatedItem() e questi non metta il content all'elemento di <recommendations> (che resta cosi' vuoto e si spiegherebbe il <recommendations />)?
    Prova a mettere delle stampe di controllo dentro il metodo aggiungiRatedItem e guarda se ti fa tutto come desiderato.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.