Visualizzazione dei risultati da 1 a 9 su 9

Discussione: Web monitor JAVA

  1. #1

    Web monitor JAVA

    salve a tutti... per un esame all'università devo fare un webmonitor... il prof naturalmente mi ha detto di non farlo da 0 ma di trovare una base e poi implementarlo come vuole lui. Queste sono le specifiche che mi ha dato:

    Si tratterebbe sostanzialmente di un programma che gira da solo (senza intervento dell'operatore), prende in input un elenco di URL e periodicamente verifica che la risorsa puntata dall'URL sia stata aggioranata, producendo una segnalazione per ogni aggiornamento. Occorre specificare: la frequenza di visita (ad es. personalizzata per ogmni URL); come verificare l'aggiornamento (che richiesta fare, preferibilmente HEAD, che header cercare: Last-Modified, Etag; che fare se mancano header...); come escludere URL dinamici (la cosa ha senso solo per pagine statiche, si potrebbe ad es. cercare header di controllo cache).

    e questo è il codice che ho trovato ed iniziato a modificare

    codice:
    package jwebmonitor;      /**   * Imports   */  import java.util.*;  import java.io.*;  import javax.xml.parsers.*;  import org.w3c.dom.*;  import java.net.*;  import mailer.Mailer;      /**   *     */  // Monitor and Notify	  public class JWebMonitor  {  	static ArrayList	sitelist = new ArrayList();  	static String		emailmethod = new String();  	static String 		emailfrom = new String();  	static ArrayList	emailto = new ArrayList();  	static ArrayList	emailcc = new ArrayList();  	static String		emailsubject = new String();  	static String		emailmessage = new String();  	static String		emailserver = new String();  	static String		emailsmtpport = new String();  	static String		emailsmtpssl = new String();  	static String		emailsmtpauth = new String();  	static String		emailuser = new String();  	static String		emailpw = new String();  	          // Creates a new instance of JWebMonitor          public JWebMonitor()          {          }  		  	// Open connections to above websites and report if down  	public static void main(String[] args)          {  		System.out.println("" +  			"=====================================================\n" +  			"=== Java Web Monitor (JWebMonitor)\n" +  			"====================================================="  		);                    File file;    		// Get values from the config file  		try{                      file = new File(args[0]);                   }                  catch(Exception e){                      System.out.println("!!! Unable to find config.xml.  Please specify the config.xml location as a parameter.");                      return;                  }                                       // Get data from XML  		try {  			DocumentBuilder builder = DocumentBuilderFactory  			.newInstance()  			.newDocumentBuilder();  			Document doc = builder.parse(file);    			// site info  			System.out.println("\n[Adding Sites...]");  			sitelist =        createArray(doc,"data","site");					// get list of websites    			// Type of notification  			System.out.println("\n[Adding email data...]");  			emailmethod =     createString(doc,"data", "emailmethod");  			emailsmtpauth =   createString(doc,"data", "emailsmtpauth");  			  			// email info  			emailfrom =       createString(doc,"data","emailfrom");				// Get emailfrom addresses  			emailto =         createArray(doc,"data","emailto");				// Get emailto addresses  			emailcc =         createArray(doc,"data","emailcc");				// Get emailcc addresses  			emailsubject =    createString(doc,"data","emailsubject");			// Get emailsubject addresses  			emailmessage =    createString(doc,"data","emailmsg");				// Get emailmsg addresses  			  			// email server info  			if (emailsmtpauth.equals("false")){  				emailserver = createString(doc,"data","emailsmtpserver");		// Get sendmail server  			}else{  				emailserver = createString(doc,"data","emailsmtpserver");		// Get smtp server  				emailuser =   createString(doc,"data","emailsmtpuser");			// Get stmp user  				emailpw =     createString(doc,"data","emailsmtppw");			// Get smtp pw  			}  			  			emailsmtpport =   createString(doc,"data","emailsmtpport");			// Get smtp port  			emailsmtpssl =   createString(doc,"data","emailsmtpssl");			// Get smtp use ssl?  		}  		catch (Exception e) {  			System.out.println("!!! Problem Reading XML !!! - " + e);  		}    		// Quit app if no websites listed  		if (sitelist.isEmpty()){  			System.out.println("!!! There are no websites to scan.  Please add a site element to config.xml!!!");  			return;  		}    		// connect to website and if problem (exception) then run notifier else do nothing  		System.out.println("\n[Testing websites...]");  		for (int i=0; i<sitelist.size(); i++){  			try	{  				URL url = new URL(sitelist.get(i).toString());  				  				System.out.println("*** Testing " + url);  				long begin = System.currentTimeMillis();			// Record start time  				URLConnection uc = url.openConnection();			// Open connection to website  				InputStream ic = uc.getInputStream();				// Get input stream to try and cause exception  				long end = System.currentTimeMillis();				// Record end time  				float timeToLoad = (((float)(end - begin))/1000);	// Convert to floating number    				System.out.println(">>> " + url + " is OK! Time: " + timeToLoad + " seconds.\n");  			}  			catch (Exception e) {  				String emailmsg = emailmessage + " " + sitelist.get(i) + "\n\nDetected Problem:\n" + e;  				String theError = "" + e;  				  				Mailer.sendMessage(emailmethod, emailsmtpauth, emailserver, emailsmtpport, emailsmtpssl, emailuser, emailpw, emailfrom, emailto, emailcc, emailsubject, emailmsg, theError);  			}  		}  	}      	  	  	  	  	  	  	  	// return the string of the requested child  	public static String createString(Document doc, String roottag, String childsection)          {  		String thestring = new String();		  		NodeList nodes = doc.getElementsByTagName(roottag);  		  		for (int i = 0; i < nodes.getLength(); i++) {  			Element element = (Element) nodes.item(i);    			// Process the lines  			NodeList lines = element.getElementsByTagName(childsection);    			Element line = (Element) lines.item(0);  			  			// Collect the text from the <Line> element  			StringBuffer sb = new StringBuffer();  			Node child = line.getFirstChild();  			if (child instanceof CharacterData && child != null) {  				CharacterData cd = (CharacterData) child;  				sb.append(cd.getData());  			}    			String text = sb.toString().trim();  			thestring = text;  			System.out.println(">>> Added " + childsection + ": " + text);  		}  		return thestring;  	}// End createString method    	  	  	// return an array of similar child nodes  	public static ArrayList createArray(Document doc, String roottag, String childsection)          {  		ArrayList thearray = new ArrayList();		  		NodeList nodes = doc.getElementsByTagName(roottag);  		  		for (int i = 0; i < nodes.getLength(); i++) {  			Element element = (Element) nodes.item(i);    			// Process the lines  			NodeList lines = element.getElementsByTagName(childsection);    			for (int j = 0; j < lines.getLength(); j++) {  				Element line = (Element) lines.item(j);    				// Collect the text from the <Line> element  				StringBuffer sb = new StringBuffer();  				for (Node child = line.getFirstChild(); child != null; child = child.getNextSibling()){  					if (child instanceof CharacterData) {  						CharacterData cd = (CharacterData) child;  						sb.append(cd.getData());  					}  				}    				String text = sb.toString().trim();  				thearray.add(text);  				System.out.println(">>> Added " + childsection + ": " + text);  			}  		}  		return thearray;  	}// End createArray method    } // End JWebMonitor class
    qualunque aiuto è più che gradito anche perché non sono un gran programmatore specialmente java.

  2. #2
    Utente di HTML.it L'avatar di desa
    Registrato dal
    Oct 2008
    Messaggi
    569
    Ho dato solo un'occhiata veloce al codice (oltretutto non sono al mio computer, e qui dispongo solo di un notepad e di un Internet Explorer che - non so se per colpa sua - mi visualizza tutto su un'unica riga...) ma non ho capito bene a cosa ti servono tutte quelle informazioni relative a e-mail e smtp.

    Relativamente al progetto, ho intenzione anche io di fare una cosa del genere un giorno o l'altro (se non altro per poter verificare l'aggiornamento anche di siti privi di newsletters/RSS)... qualche idea ce l'ho, in base a quello che svilupperai potrei darti qualche suggerimento.

    Credo che per ogni sito che vuoi verificare dovresti prevedere un thread distinto (così da poter modellare anche i tempi di "polling" personalizzati). Puoi provare a scaricarti un software per gli RSS (io uso FeedReader) e vedere che tipo di opzioni ti consente.
    La scrittura del codice per la connessione è abbastanza elementare: HTTP è un protocollo molto semplice.
    La parte un po' più complessa è gestire la valutazione dell'avvenuto aggiornamento: ok se c'è un header Last-Modified... ma se non c'è? Per questo ti suggerisco di parlarne con il tuo professore e di definire che tipo di aggiornamenti devi monitorare (ad esempio, che succede se fra due "polling" di uno stesso URL cambia esclusivamente il riferimento di un banner pubblicitario?)

  3. #3
    innanzitutto ti ringrazio per l'interesse... comunque io vado a parma all'università e il professore sta a milano... ha detto di contattarlo con le email... ma tramite mail non è facile gestire dei rapporti... così sono un po' così nei casini...

  4. #4
    Utente di HTML.it L'avatar di desa
    Registrato dal
    Oct 2008
    Messaggi
    569
    Capisco... però poichè è il tuo professore che decide se il progetto va bene oppure no (così come pure il voto d'esame) devi per forza tenerti - almeno ogni tanto - in contatto con lui e farti "validare" le scelte progettuali che deciderai. Non puoi rischiare di presentarti il giorno dell'esame e scoprire se quello che hai fatto andava bene oppure no.

    Lunedì dall'ufficio provo a dare un'occhiata al codice che hai postato, ok?

  5. #5
    Ovviamente hai gia' guardato la libreria HTTPClient di Apache vero?

    L'esempio per il metodo HEAD che c'e' nella documentazione mi pare esattamente quello che devi fare tu, in 3 righe di codice ...

    http://hc.apache.org/httpclient-3.x/methods/head.html
    max

    Silence is better than bullshit.
    @mmarcon
    jHERE, Maps made easy

  6. #6
    ragazzi intanto vi ringrazio tantissimo per l'attenzione... al professore manderò un po' di codice ogni tanto per farglielo vedere e naturalmente approvare... io adesso starò in vacanza per una settimana... aspetto ancora i vostri aiuti... perché ho paura che senza non potrei farcela
    vi ringrazio e quando torno vi faccio sapere se e come ho capito quello che mi avete spiegato!

  7. #7
    ciao sono tornato... avete qualche novità?

  8. #8
    Originariamente inviato da azidoiam
    ciao sono tornato... avete qualche novità?
    Come ho gia' detto, quello che ho postato io dovrebbe fare esattamente quello che ti serve.

    E poi cosa ti aspettavi, che tu vai in vacanza e noi ti facciamo il progetto scusa??
    max

    Silence is better than bullshit.
    @mmarcon
    jHERE, Maps made easy

  9. #9
    :P:P:P no certo che no... però mi avevan detto anche gli altri utenti che ci davano un'occhiata e allora volevo dire che ero tornato e che ero qua per discuterne ancora

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.