begin process at 2010 02 10 15:04:11
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Reseaux et Internet

 > BLOGREADER

BLOGREADER


 Information sur la source

 Description

Comme la plupart d'entre vous j'ai un blog, eh oui :) .
Le seul problème c'est que j'en voulais gratuit et sans pubs, j'ai trouvé pour cela un bon hébergeur sur http://www.zeblog.com.
Malheureusement la gratuité à un prix: le peu de fonctionnalités. Notamment une qui me désespérait jusqu'à ce que j'écrive ce programme: être avertit lorsque que j'ai de nouveaux  commentaires afin de répondre à mes lecteurs le plus rapidement possible.
Comme vous l'avez donc deviné, j'ai écris un programme java qui se connecte à mon blog toutes les 15 minutes et me dit qui affiche une boite de dialogue si j'ai de nouveaux commentaires ;-) .
Enjoy!

Source

  • import javax.swing.*;
  • import java.net.*;
  • import java.io.*;
  • import java.util.*;
  • import java.text.*;
  • public class BlogReader extends Thread{
  • private String fileName;
  • private String blogUrl;
  • private String lastCount;
  • private String currentCount;
  • private BufferedInputStream fileIn;
  • private int sleepTimeMs;
  • public BlogReader(String fileName, String blogUrl, int sleepTimeMin){
  • this.fileName = fileName;
  • this.blogUrl = blogUrl;
  • this.sleepTimeMs = sleepTimeMin*60*1000;
  • }
  • private boolean fileInRead(){
  • // Saved count
  • int car;
  • StringBuffer buffer = new StringBuffer();
  • try{
  • fileIn = new BufferedInputStream(new FileInputStream(fileName));
  • while((car = fileIn.read()) != -1){
  • buffer.append((char)car);
  • }
  • lastCount = new String(buffer.toString());
  • if(car == -1)
  • fileIn.close();
  • return true;
  • }catch (FileNotFoundException ex){
  • JOptionPane.showMessageDialog(null, "Error BlogReader: you have to create and initialize the file "+fileName+" manually !");
  • System.exit(0);
  • return false;
  • }catch (IOException ex){
  • System.out.println("Error BlogReader!");
  • ex.printStackTrace();
  • return false;
  • }
  • }
  • private boolean saveNewInformations(String newCount){
  • // Save new information
  • OutputStream fileOut;
  • byte [] bytes= newCount.getBytes();
  • try{
  • fileOut = new BufferedOutputStream(new FileOutputStream(fileName));
  • for(int i = 0; i < newCount.length(); i++ )
  • fileOut.write(bytes[i]);
  • fileOut.flush();
  • fileOut.close();
  • return true;
  • }catch (FileNotFoundException ex){
  • JOptionPane.showMessageDialog(null, "Error BlogReader: cannot open the file "+fileName+" for writing !");
  • return false;
  • }catch (IOException ex){
  • System.out.println("Error BlogReader!");
  • ex.printStackTrace();
  • return false;
  • }
  • }
  • private void search (){
  • if(!fileInRead())
  • System.exit(0);
  • System.out.println( DateFormat.getTimeInstance().format(new Date()));
  • System.out.println("Last count was : "+lastCount+" comments");
  • StringBuffer buffer = new StringBuffer();
  • int car;
  • // String
  • String strToSearch = new String("commentaires</li>");
  • String page = new String();
  • try{
  • // Connection
  • URL myBlog = new URL(blogUrl);
  • URLConnection connection = myBlog.openConnection();
  • System.out.println("Connection...");
  • // read the URL
  • InputStream is = connection.getInputStream();
  • while( (car = is.read()) != -1){
  • //System.out.print((char)car);
  • buffer.append((char)car);
  • }
  • page = buffer.toString();
  • // Parse HTML
  • if(page.contains(strToSearch)){
  • int firstOccurrence = buffer.indexOf(strToSearch);
  • buffer.delete(0, firstOccurrence-(lastCount.length()+1)); // +1 for the space
  • firstOccurrence = buffer.indexOf(strToSearch);
  • buffer.delete(strToSearch.length()+(lastCount.length()+1)-5, buffer.length());
  • currentCount = new String(buffer.substring(0, buffer.indexOf(" ")));
  • System.out.println("Current count is : "+currentCount+" comments");
  • if(lastCount.compareTo(currentCount) != 0){
  • System.out.println("You have new comment(s) on your blog !");
  • JOptionPane.showMessageDialog(null, "BlogReader: you have new comment(s) on your blog!");
  • saveNewInformations(currentCount);
  • connection = null;
  • }else{
  • System.out.println("No new comment...");
  • }
  • }else{
  • JOptionPane.showMessageDialog(null, "Error BlogReader: the doesn't contain strToSearch !");
  • }
  • }catch (MalformedURLException ex){
  • JOptionPane.showMessageDialog(null, "Error BlogReader: Malformed URL!");
  • }catch (IOException ex){
  • System.out.println("Error BlogReader!");
  • ex.printStackTrace();
  • }
  • }
  • // run methode
  • public void run() {
  • while(true){
  • search();
  • try{
  • sleep(sleepTimeMs);
  • }catch (Exception e){
  • e.printStackTrace();
  • }
  • }
  • }
  • // main
  • static public void main(String [] arg){
  • System.out.println("-----[BlogReader by psyphi]-----");
  • System.out.println("--> http://psyphi.zeblog.com <--");
  • System.out.println("--------------------------------");
  • BlogReader br = new BlogReader("last_count", "http://psyphi.zeblog.com", 15);
  • br.start();
  • }
  • }
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.text.*;

public class BlogReader extends Thread{
	private String fileName;
	private String blogUrl;
	private String lastCount;
	private String currentCount;
	private BufferedInputStream fileIn;
	private int sleepTimeMs;
	
	public BlogReader(String fileName, String blogUrl, int sleepTimeMin){
		this.fileName	= fileName;
		this.blogUrl	= blogUrl;
		this.sleepTimeMs	= sleepTimeMin*60*1000;
	}
	
	private boolean fileInRead(){
		// Saved count
		int car;
		StringBuffer buffer = new StringBuffer();
		try{
			fileIn = new BufferedInputStream(new FileInputStream(fileName));

			while((car = fileIn.read()) != -1){
				buffer.append((char)car);
			}
			
			lastCount = new String(buffer.toString());
			
			if(car == -1)
				fileIn.close();
			
			return true;
		}catch (FileNotFoundException ex){
			JOptionPane.showMessageDialog(null, "Error BlogReader: you have to create and initialize the file "+fileName+" manually !");
			System.exit(0);
			return false;
		}catch (IOException ex){
			System.out.println("Error BlogReader!");
			ex.printStackTrace();
			return false;
		}
	}
	
	private boolean saveNewInformations(String newCount){
		// Save new information
		OutputStream fileOut;
		byte [] bytes= newCount.getBytes();
		try{
			fileOut = new BufferedOutputStream(new FileOutputStream(fileName));
			for(int i = 0; i < newCount.length(); i++ )
				fileOut.write(bytes[i]);
			fileOut.flush();
			fileOut.close();
			return true;
		
		}catch (FileNotFoundException ex){
			JOptionPane.showMessageDialog(null, "Error BlogReader: cannot open the file "+fileName+" for writing !");
			return false;
		}catch (IOException ex){
			System.out.println("Error BlogReader!");
			ex.printStackTrace();
			
			return false;
		}
	}
		
	private void search (){
			if(!fileInRead())
				System.exit(0);
			
			System.out.println( DateFormat.getTimeInstance().format(new Date()));
			System.out.println("Last count was : "+lastCount+" comments");
		
			StringBuffer buffer = new StringBuffer();
			int car;
					
			// String
			String strToSearch = new String("commentaires</li>");
			String page = new String();
					
			try{
				// Connection
				URL myBlog = new URL(blogUrl);
				URLConnection connection = myBlog.openConnection();
				System.out.println("Connection...");
				// 	read the URL
				InputStream is = connection.getInputStream();
						
				while( (car = is.read()) != -1){
					//System.out.print((char)car);
					buffer.append((char)car);
				}
				page = buffer.toString();
				// Parse HTML
				if(page.contains(strToSearch)){
					int firstOccurrence = buffer.indexOf(strToSearch);
					buffer.delete(0, firstOccurrence-(lastCount.length()+1)); // +1 for the space
					firstOccurrence = buffer.indexOf(strToSearch);
					buffer.delete(strToSearch.length()+(lastCount.length()+1)-5, buffer.length());
					
					currentCount = new String(buffer.substring(0, buffer.indexOf(" ")));
					System.out.println("Current count is : "+currentCount+" comments");
					if(lastCount.compareTo(currentCount) != 0){
						System.out.println("You have new comment(s) on your blog !");
						JOptionPane.showMessageDialog(null, "BlogReader: you have new comment(s) on your blog!");
						saveNewInformations(currentCount);
						connection = null;
					}else{
						System.out.println("No new comment...");
					}
				}else{
					JOptionPane.showMessageDialog(null, "Error BlogReader: the doesn't contain strToSearch !");
				}
			}catch (MalformedURLException ex){
				JOptionPane.showMessageDialog(null, "Error BlogReader: Malformed URL!");
			}catch (IOException ex){
				System.out.println("Error BlogReader!");
				ex.printStackTrace();
			}
		}
	
	// run methode
	public void run() {
		while(true){
			search();
			try{
				sleep(sleepTimeMs);
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		
	}
	
	// main
	static public void main(String [] arg){
		System.out.println("-----[BlogReader by psyphi]-----");
		System.out.println("--> http://psyphi.zeblog.com <--");
		System.out.println("--------------------------------");
		BlogReader br = new BlogReader("last_count", "http://psyphi.zeblog.com", 15);
		br.start();
	}
}



 Sources du même auteur

BASIC JDBC

 Sources de la même categorie

Source avec Zip SERVEUR GENERIQUE par pacifikateur
Source avec Zip Source avec une capture JOMESSENGER : APPLICATION CLIENT/SERVER par numurique
Source avec Zip MINI SERVEUR HTTP par yvesyves
Source avec Zip Source avec une capture TCHAT EN DEUX PARTIES: CLIENT ET SERVEUR par benads
Source avec Zip CONNEXION SERVEUR VIA PROXY EN JAVA par moumou95

 Sources en rapport avec celle ci

Source avec Zip CONNEXION SERVEUR VIA PROXY EN JAVA par moumou95
Source avec Zip SERVEUR TCP/IP SOUS JAVA par MrEske
TELECHARGER UN FICHIER A PARTIR D'UNE URL par jaoued zahraoui
Source avec une capture TÉLÉCHARGEMENT D'IMAGES (POCHETTES CD, DVD, LIVRES...) SUR I... par dufour137
Source avec Zip WEBSOURCEASPIRO - ASPIRATEUR DE CODE SOURCE DE PAGE INTERNET par Mikonyx

Commentaires et avis

Commentaire de Twinuts le 22/12/2006 15:35:29 administrateur CS

Salut,

le code pourrait être optimisé (je reviendrai dessus plus tard)

sinon pour l'idée je la trouve simplement originale est ça devait être dit ;)

Commentaire de psyphi le 22/12/2006 20:22:03

Merci de ton soutient :).
Si tu as des optimisations je suis preneur ;) .

Commentaire de pukanvrou le 30/03/2007 16:49:11

Sympa ce code: j'en ai dérivé un outil pour récupérer différentes infos sur des sites web ;-)

Merci !

Commentaire de phm le 07/08/2007 17:27:13

super interessant ! Merci !
sur mon blog chaque article a un lien <a href....>x commentaires</a>
donc je boucle (tag = "commentaires</a>")


pos = page.indexOf(tag);
if(pos > 0)
{
while (pos > 0)
{

str = page.substring(pos-7,pos-1);

pos2 = str.indexOf(">");
if (pos2 > 0)
{
str = str.substring(pos2+1,str.length());
nbtags=nbtags+(Integer.parseInt(str.trim()));
}
pos = page.indexOf(tag,(pos+1));
}
page = Integer.toString(nbtags);
page = "Resultat : " + page;
}

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

download d'un fichier zip sur un site internet [ par yann.jaunin ] Hello,j'essaye de télécharger un fichier zip qui se trouve sur un site internet. Je suis débutant donc soyez indulgent :-)voici l'erreur que j'aie :un je cherche comment creer un blog sur mon site mais un systeme de blog ou les gens peuvent s incrire et faire leur page perso [ par marsupiot67 ] je cherche a faire sur mon site un blog meme genre sue skyblog ou ircblog ou en faite les gens peuven faire leur blog perso apres inscription et ou le mettre sur mon site internet un chat video tout pret (executable en .jar) [ par luckyman300 ] salut a tous je suis debutant et je voudrais savoir comment integrer un chat video en java client qui utilise le jmf framework&nbsp;(executable en .ja Indicateur de statut téléphone sur site Internet [ par myauxc ] Bonjour A tous,Je voudrai pouvoir fair figurer sur un site des indicateur de statut téléphonique "en tps reele"LIBRE / OCCUPER / INDISPONIBLEMeme genr Parcourir un site internet [ par badkrist ] Bonjour,j'ai besoin de creer sous forme d'arbre, une representation d'un site internet quelconque. Sur un site simple (sans identification) tout se pa Help [ par yvon_bizimana ] Bonjour, je suis entrain de créer un site internet avec java/j2ee et jsp sous eclipse. pour l'instant je ne suis qu'au jsp et j'ai un probleme. Je vou Ping site Internet [ par leviz ] Bonjour tout le monde!!J'aurais besoin d'être aiguillé!!Voilà mon problème : je cherche à faire un servlet qui ira tester si mes sites web sont UP en lien internet [ par juliox24 ] Bonjour,J'aimerai créer un bouton dant un JFrame sur lequel je pourrait me diriger sur un site comme : http://www.google.frEst-ce possible avec un "ja Détecter url d'un site avant son affichage [ par Profite ] Bonjour,J'aimerai savoir s'il est possible dans un application Java de détecter l'url d'un site qui va s'afficher dans un webbrowser ?Si oui, pouvez-v Message d'erreur lors de l'ouverture d'un site web [ par metalkev64 ] Salut,Dans mon application je dois ouvrir une page web dans le navigateur par défaut. Pour ce faire j'utilise j'utilise ce code qui a été cité d'innom


Nos sponsors


Sondage...

Comparez les prix


HTC Magic

Entre 429€ et 429€

CalendriCode

Février 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 1,264 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales