Resolver o Problema do Temperature Server do Deitel

2 respostas
E

Alguém pode me ajudar a resolver esse problema , não consigo executar.
Mesmo indo a pagina do Deitel.

// Fig. 20.1: TemperatureServer.java
// Definição da interface TemperatureServer
import java.rmi.*;

public interface TemperatureServer extends Remote {

public WeatherInfo[] getWeatherInfo()

throws RemoteException;

}
// Fig. 20.2: TemperatureServer.java

// Definição de TemperatureServerImpl

import java.rmi.<em>;

import java.rmi.server.</em>;

import java.util.<em>;

import <a href="http://java.io">java.io</a>.</em>;

import <a href="http://java.net">java.net</a>.*;

public class TemperatureServerImpl extends UnicastRemoteObject implements TemperatureServer {

private WeatherInfo weatherInformation[];

public TemperatureServerImpl() throws RemoteException
 {
 super();
 updateWeatherConditions();
 }

// obtém as informações de clima a partir de NWS
@SuppressWarnings("empty-statement")
private void updateWeatherConditions()
     throws RemoteException
 {
     try {
            System.err.println( "Updating weather information..." );

         // Página da Web Traveler Forecast
            URL url = new URL(
            "http://iwin.nws.noaa.gov/iwin/us/traveler.html" );

            BufferedReader in =
                 new BufferedReader(
                    new InputStreamReader( url.openStream() ) );

            String separator = "</PRE><HR> <BR><PRE>"; //  original
            //  String separator = "";                     //alteração

            // localiza a primeira linha horizontal na página da Web
            while ( !in.readLine().startsWith( separator ) );
            // não faz nada

            // s1 é o formato diurno e s2 é o formato noturno
            String s1 = "CITY WEA HI/LO WEA HI/LO";
            String s2 = "CITY WEA LO/HI WEA LO/HI";
            String inputLine = "";

             // localiza cabeçalho que inicia as informações de clima
            do {
                 inputLine = in.readLine();
            } while ( !inputLine.equals( s1 ) && !inputLine.equals( s2 ) );

            Vector cityVector = new Vector();

            inputLine = in.readLine(); // obtém info da 1a. cidade

            // while ( inputLine.length ()> 28) (
            while ( !inputLine.equals( "" ) ) {
                // cria objeto WeatherInfo para cidade
                 WeatherInfo w = new WeatherInfo(
                    inputLine.substring( 0, 16 ),
                    inputLine.substring( 16, 22 ),
                    inputLine.substring( 23, 29 ) );

                 cityVector.addElement( w ); // adiciona ao Vetor
                 inputLine = in.readLine(); // obtém informações
             } // da próxima cidade

            // cria array para retornar para o cliente
            weatherInformation =
             new WeatherInfo[ cityVector.size() ];

             for ( int i = 0; i < weatherInformation.length; i++ )
                weatherInformation[ i ] =
                    ( WeatherInfo ) cityVector.elementAt( i );

             System.err.println( "Finished Processing Data." );
             in.close(); // fecha conexão com servidor de NWS
         }
         catch( java.net.ConnectException ce ) {
            System.err.println( "Connection failed." );
            System.exit( 1 );
         }
         catch( Exception e ) { e.printStackTrace();
            System.exit( 1 );
         }
    } // Fim throws RemoteException


// implementação para o método de interface TemperatureServer
 public WeatherInfo[] getWeatherInfo()
 {
 return weatherInformation;
 }

 public static void main( String args[] ) throws Exception
 {
  System.err.println( "Initializing server: please wait." );

  // cria objeto servidor
  TemperatureServerImpl temp = new TemperatureServerImpl();

  // vincula objeto TemperatureServerImpl com o rmiregistry
  String serverObjectName = "//localhost/TempServer";
  Naming.rebind( serverObjectName, temp );
  System.err.println(
  "The Temperature Server is up and running." );
}

} //Fim Class TemperatureServerImpl

// Fig. 20.3: WeatherInfo.java

// Definição da classe WeatherInfo

import java.rmi.*;

import java.io.Serializable;
public class WeatherInfo implements Serializable {

private String cityName;

private String temperature;

private String description;
public WeatherInfo( String city, String desc, String temp )

{

cityName = city;

temperature = temp;

description = desc;

}

public String getCityName() { return cityName; }

public String getTemperature() { return temperature; }

public String getDescription() { return description; }
}

// Fig. 20.4: TemperatureClient.java

// Definição de TemperatureClient

import java.awt.<em>;

import java.awt.event.</em>;

import javax.swing.<em>;

import java.rmi.</em>;

public class TemperatureClient extends JFrame {

public TemperatureClient( String ip )  {

    super( "RMI TemperatureClient..." );
    getRemoteTemp( ip );

    setSize( 625, 567 );
    setResizable( false );
    show();

}

// obtém as informações de clima do objeto remoto

// TemperatureServerImpl
private void getRemoteTemp( String ip ) {

try {
    // nome do obj. servidor remoto vinculado ao registro rmi
     String serverObjectName = "//" + ip + "/TempServer";

    // pesquisa objeto remoto TemperatureServerImpl
    // em rmiregistry
     TemperatureServer mytemp = ( TemperatureServer )
     Naming.lookup( serverObjectName );

    // obtém as informações de clima do servidor
     WeatherInfo weatherInfo[] = mytemp.getWeatherInfo();
     WeatherItem w[] =
     new WeatherItem[ weatherInfo.length ];
     ImageIcon headerImage =
     new ImageIcon( "images/header.jpg" );

     JPanel p = new JPanel();

    // determina número de linhas para o GridLayout;
    // adiciona 3 para acomodar os dois JLabels de cabeçalho
    // e equilibrar as colunas
    p.setLayout(
    new GridLayout( ( w.length + 3 ) / 2, 2 ) );
    p.add( new JLabel( headerImage ) ); // cabeçalho 1
    p.add( new JLabel( headerImage ) ); // cabeçalho 2

    for ( int i = 0; i < w.length; i++ ) {
    w[ i ] = new WeatherItem( weatherInfo[ i ] );
    p.add( w[ i ] );
     }

     getContentPane().add( new JScrollPane( p ),
     BorderLayout.CENTER );
     }
     catch ( java.rmi.ConnectException ce ) {
            System.err.println( "Connection to server failed. " +
            "Server may be temporarily unavailable." );
            }
     catch ( Exception e ) {
            e.printStackTrace();
            System.exit( 1 );
            }

} // fim getRemoteTemp

public static void main( String args[] ) {

TemperatureClient gt = null;
// se nenhum end. IP de servidor ou nome de host especificado,

// usa “localhost”; caso contrário utiliza o host especificado

if ( args.length == 0 )

gt = new TemperatureClient( localhost );

else

gt = new TemperatureClient( args[ 0 ] );
gt.addWindowListener(

         new WindowAdapter() {

            public void windowClosing( WindowEvent e )  {

                System.exit( 0 );
              }

        } //fim windowClosing
                   
 );   // fim addWindowListener


 }

}

// Fig. 20.5: WeatherItem.java

// Definição de WeatherItem

import java.awt.<em>;

import javax.swing.</em>;
public class WeatherItem extends JLabel {

private static ImageIcon weatherImages[], backgroundImage;

private final static String weatherConditions[] =

{ SUNNY, PTCLDY, CLOUDY, MOCLDY, TSTRMS,

RAIN, SNOW, VRYHOT, FAIR, RNSNOW,

SHWRS, WINDY, NOINFO, MISG };

private final static String weatherImageNames[] =

{ sunny, pcloudy, mcloudy, mcloudy, rain,

rain, snow, vryhot, fair, rnsnow,

showers, windy, noinfo, noinfo };
// bloco inicializador static para carregar as imagens de clima

static {

backgroundImage = new ImageIcon( images/back.jpg );

weatherImages =

new ImageIcon[ weatherImageNames.length ];
for ( int i = 0; i < weatherImageNames.length; ++i )

weatherImages[ i ] = new ImageIcon(images/ + weatherImageNames[ i ] + “.jpg );

}
// variáveis de instância

private ImageIcon weather;

private WeatherInfo weatherInfo;
public WeatherItem( WeatherInfo w )

{

weather = null;

weatherInfo = w;
// localiza imagem da condição de clima da cidade

for ( int i = 0; i < weatherConditions.length; ++i )

if ( weatherConditions[ i ].equals(

weatherInfo.getDescription().trim() ) ) {

weather = weatherImages[ i ];

break;

}
// seleciona a imagem “no info” se não houver

// informações de clima ou nenhuma imagem das

// condições atuais do clima

if ( weather == null ) {

weather = weatherImages[ weatherImages.length - 1 ];

System.err.println( "No info for: " +

weatherInfo.getDescription() );

}

}
public void paintComponent( Graphics g )

{

super.paintComponent( g );

backgroundImage.paintIcon( this, g, 0, 0 );

Font f = new Font( SansSerif, Font.BOLD, 12 );

g.setFont( f );

g.setColor( Color.white );

g.drawString( weatherInfo.getCityName(), 10, 19 );

g.drawString( weatherInfo.getTemperature(), 130, 19 );

weather.paintIcon( this, g, 253, 1 );
}

// transforma o tamanho preferido do WeatherItem

// na largura e altura da imagem de fundo

public Dimension getPreferredSize()

{

return new Dimension( backgroundImage.getIconWidth(),

backgroundImage.getIconHeight() );

}

}

2 Respostas

M

Antes de mais nada, sempre coloque seu código entre as tags code, desse jeito:

// seu código aqui
E

marcobiscaro2112:
Antes de mais nada, sempre coloque seu código entre as tags code, desse jeito:

// seu código aqui

Beleza, valeu , eu não sabia disso.

Criado 14 de fevereiro de 2010
Ultima resposta 15 de fev. de 2010
Respostas 2
Participantes 2