HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"Creating Newsfeeds Using Java Applets"
Volume: 4 Issue: 10, p. 22

	

Listing 1:  newsfeed.java

//newsfeed.java a class for creating a newsfeed

//includes
import java.awt.*;
import java.util.Vector;
import java.util.StringTokenizer;
import java.net.*;
import java.io.*;
import java.util.Date;


//class that implements a simple newsfeed
public class newsfeed extends java.applet.Applet
                              implements Runnable
  {
  int speed=2000, iHeight=0, iTimesThrough=11,
      iCurrentPosition;
  Thread newsthread;
  Image image;
  String strCurrentURL,  strCurrentString;
  boolean bCalledFromRun=false;
  Vector veInformation;


  //called from paint when needed, don't want to
  //call from init, because we need a graphics
  //object for this
  private void initialize(Graphics g)
    {
    String strType=getParameter("type");
    if(strType==null)
      strType="ls";


    //a date is used to prevent caching
    Date date=new Date();
    long lUnique=date.getTime();


    iHeight=g.getFontMetrics().getHeight()+2;


    g.setColor(Color.black);
    g.drawString("Getting current news...", 45,
                  iHeight);


    strCurrentURL=".";
    iCurrentPosition=0;
    //first one for use on your own system, with
    //appletviewer, second third, fourth, or fifth
    //for use on the Web, depending on if you use
    //a flat file in a directory called news, or a
    //script in a cgi-local or cgi-bin directory, and
    //how the script parses the query string
    String str="news.txt";
    //String str="http://"+getCodeBase().getHost()+
    //           "/news/news.txt?"+lUnique;
    //String str="http://"+getCodeBase().getHost()+
    //           "/cgi-local/newsfeed.pl?"+
    //           strType+iUnique;
    //String str="http://"+getCodeBase().getHost()+
    //           "/cgi-bin/newsfeed.pl?"+
    //           strType+lUnique;
    //String str="http://"+getCodeBase().getHost()+
    //          "/cgi-bin/newsfeed.pl?type="+
    //           strType+"&time="+lUnique+
    //           "&docbase="+getDocbase();


    //a url object is created, then a stream is created
    //to retrieve the content of the url
    URL url=null;
    String strContent="";
    try
      {
      //first one for use on your own system, with
      //AppletViewer, second for use on the Web
      url=new URL(getCodeBase(), str);
      //url=new URL(str);
      }
    catch(MalformedURLException m){return;}
    try
      {
      StringBuffer sb=new String-
      Buffer("");
      InputStream is=url.openStream();
      DataInputStream dis=new DataIn-
      putStream(is);
      while (true)
        {
        try{sb.append((char)dis.read-
        Byte());}
        catch(EOFException f){break;}
        }
      strContent=sb.toString();
      }
    catch(IOException e){return;}


    //after the contents of the url are
    //retrieved, they are parsed to
    //create a Vector which contains
    //the information
    veInformation=vectorize(strContent, "");


    //get the background image, then
    //remove it
    String strImage=(String)veInforma-
    tion.elementAt(0);
    veInformation.removeElementAt(0);


    //load the image, if there is one
    if(strImage.compareTo(".")!=0)
      image=getImage(getCodeBase(),
      strImage);


    iTimesThrough=0;
    }


  //parses the returned information
  //based on <CR>
  private Vector vectorize(String strIn,
                      String strParse)
    {
    //if it ends with our parse charac-
    ter, pull it off the end
if(strIn.endsWith("\r")||strIn.endsWith("")||strIn.endsWith(strParse))
      strIn=strIn.substring(0,
      strIn.length()-1);    if(strIn.endsWith("\r")||strIn.endsWith("\n")
      strIn=strIn.substring(0,
      strIn.length()-1);


    Vector ve=new Vector(1);


    //get ready to tokenize the string
       StringTokenizer t = new StringTo-
      kenizer(strIn, strParse);
    int iLines = t.countTokens();


    if(strParse.compareTo("\n")==0)
      {
      for(int i=0; i<iLines; i++)
        {
        String str=t.nextToken();
        if(str.indexOf("\n")!=-1)
          str=str.substring(0,
          str.length()-1);
        if(str.indexOf("\n")!=-1)
          str=str.substring(0,
          str.length()-1);
        ve.addElement(str);
        }
      }
    else
      {
      for(int 1=0; i<iLines; i++)
        ve.addElement(t.nextToken());
      }


    ve.trimToSize();
    return ve;
    }



  public void paint(Graphics g)
    {
    Dimension d=this.size();


    //the first time through, and each
    //ten thereafter, get the news
    if(iTimesThrough>10)
      {
      //clear this
      g.setColor(Color.white);
      g.fillRect(0, 0, d.width, d.height);


      initialize(g);
      }


    //clear
    g.setColor(Color.white);
    g.fillRect(0, 0, d.width, d.height);


    //draw the background image
    if(image!=null)
      g.drawImage(image, 0, 0, this);


    //get the current text and url,
    //then draw the text
    String strTemp=(String)veInforma-
    tion.elementAt(iCurrentPosition);
    strCurrentURL=strTemp.substring(0,
    strTemp.indexOf(" "));
    strCurrentString=strTemp.sub-
    string(strTemp.indexOf(" ")+1);
    g.setColor(Color.blue);
    g.drawString(strCurrentString, 45,
    iHeight);


    //only advance if called from run
    if(bCalledFromRun)
      iCurrentPosition++;
    bCalledFromRun=false;


    if(iCurrentPosition>=veInfor-
    mation.size())
      {
      iCurrentPosition=0;
      iTimesThrough++;
      }
    }


  //overide update for smoother graphics
  public void update(Graphics g)
    {
    paint(g);
    }


  //If there is a mousedown go to the url
  //associated with this news event.  A
  //"." is used if there is no url
  //associated with the news item
  public boolean mouseDown(Event e, int
  x, int y)
    {
    if(strCurrentURL.compareTo(".")!=0)
      {
      URL url;
      try{url=new URL(strCurrentURL);}
      catch(MalformedURLException
      m){return true;}
      this.getAppletContext().showDocu-
      ment(url);
      }
    return true;
    }


  //if the mouse enters the applet,
  //repaint the text red and stop run-
  //ning. Set the status to the url
  //associated with the news item
  public boolean mouseEnter(Event e,
  int x, int y)
    {
    Graphics g=this.getGraphics();


    //clear
    Dimension d=this.size();
    g.setColor(Color.white);
    g.fillRect(0, 0, d.width,
    d.height);


    //draw the background image
    if(image!=null)
      g.drawImage(image, 0, 0, this);


    g.setColor(Color.red);


    g.drawString(strCurrentString, 45,
    iHeight);
    if(strCurrentURL.compareTo(".")!=0)
      showStatus(strCurrentURL);
    else
      showStatus("No Link");
    this.stop();
    return true;
    }


  //if the mouse exits the applet,
  //repaint the text blue and start
  //running again. Clear the status
  public boolean mouseExit(Event e, int
  x, int y)
    {
    Graphics g=this.getGraphics();
    g.setColor(Color.blue);
    g.drawString(strCurrentString, 45,
    iHeight);
    this.start();
    showStatus("");
    return true;
    }



  //start stop and run are required to
  //implement the Runnable interface.
  //Speed can be adjusted to present
  //information faster or slower.
  public void start()
    {
         newsthread = new Thread(this);
         newsthread.start();
    }


  public void stop()
    {
         newsthread.stop();
    }


  public void run()
    {
         while (true)
      {
      bCalledFromRun=true;
         try {Thread.currentThread()
        .sleep (speed);}
      catch (InterruptedException e){}
           repaint();
      }
    }
}


Listing 2:  news.txt

lithic.gif
tmtm.gif
lshttp://www.lithic.com/java/PersonalChatware.html Have a look at the
plugin API in lpc
lshttp://www.lithic.com/java/calculator.html See Lithic Software's newest
applet
lshttp://www.lithic.com/onlinesystems/index.html Check out LSC Online
Systems
tmhttp://www.toastmasters.org/ Toastmasters main page is more useful than
ever
tmhttp://www.lithic.com/tm/tm.html Grand Junction Clubs now have a page



<HTML>
<HEAD>
<title>Lithic Newsfeed</title>

<!newsfeed.java a page with the newsfeed.class embedded>

</HEAD>

<BODY BGCOLOR=White>

<CENTER>
<APPLET CODE="newsfeed.class" width=300 height=20>
<PARAM NAME=type VALUE="1S">
</APPLET>
</CENTER>

<BODY>
</HTML>







Listing 4:  newsfeed.pl

#!/usr/bin/perl
# newsfeed.pl


#newsfeed.pl a script for sending out news
MAIN:
  {
  $file="cginews.txt";
  $querystring=$ENV{"QUERY_STRING"} ;
  print("Content-type: text/html");
  if($querystring)
    {
    $query=substr($querystring, 0, 2);
    &PrintNews($file, $query);
    }
  }


#prints out all the lines that begin with the
#appropriate letters the letter is the token
#sent in the query string
sub PrintNews
  {
  local($file, $control)[email protected]_;
  local($guardian);


  $guardian="";


  open(TIMES, $file);
  while(<TIMES>)
    {
    $type=substr($_, 0, 2);
    if($type=~/$control/)
      {
      $content=substr($_, 2);
      print($content);
      $guardian="t";
      }
    }
  close(TIMES);


  #if nothing was found, just print out
  that no news is currently available
  if(!$guardian)
    {
    print("");
    print(" no news currently available");
    }
  }


Listing 5:  cginews.txt

lslithic.gif
tmtm.gif
lshttp://www.lithic.com/java/PersonalChatware.html Have a look at the
plugin API in lpc
lshttp://www.lithic.com/java/calculator.html See Lithic Software's newest
applet
lshttp://www.lithic.com/onlinesystems/index.html Check out LSC Online
Systems
tmhttp://www.toastmasters.org/ Toastmasters main page is more useful than
ever
tmhttp://www.lithic.com/tm/tm.html Grand Junction Clubs now have a page



      
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.