Help in JavaSpaces Calculator

Tatiana Pereira Filgueiras <[email protected]> Mon, 25 Sep 2006 14:18:11 -0600
Newsgroups gmane.comp.java.sun.javaspaces
Message-ID <LISTSERV%[email protected]>
Hi!
I'm new on JavaSpaces Tecnology and I'm trying to make a Calculator.
But I don't understand why errors below... anybody can help me? Anybody have
a Calculator Code example? (in this structure: client --- javaspace --
calculator server)
thx
Tatiana

My errors:(the same is for Cliente.java)

C:\Documents and Settings\Tati\Desktop\Pesquisas\pratica\Tentativa2>java -classp
ath .\;"C:\Arquivos de programas\jini2_1\lib\jini-ext.jar";"C:\Documents and Set
tings\Tati\Desktop\Pesquisas\pratica\pac.jar";"C:\Arquivos de programas\jini2_1\
lib\reggie.jar";"C:\Arquivos de programas\jini2_1\lib\outrigger.jar";"C:\Arquivo
s de programas\jini2_1\lib\jini-core.jar" Servidor

Localizando JavaSpace...

JavaSpace localizado.

Registrying object notify...

Error!

java.rmi.ServerException: RemoteException in server thread; nested exception is:

        java.rmi.UnmarshalException: unmarshalling method/arguments; nested exce
ption is:
        java.lang.ClassNotFoundException: Servidor
        at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispa
tcher.java:644)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java
:597)
        at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:
103)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(Objec
tTable.java:595)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(Obje
ctTable.java:212)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java
:568)
        at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvi
der.java:527)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(Object
Table.java:565)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(Object
Table.java:540)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTabl
e.java:778)
        at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(
ServerConnectionManager.java:148)
        at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244)
        at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvi
der.java:513)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241)
        at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136)
        at java.lang.Thread.run(Thread.java:595)
        at com.sun.jini.jeri.internal.runtime.Util.__________EXCEPTION_RECEIVED_
FROM_SERVER__________(Util.java:108)
        at com.sun.jini.jeri.internal.runtime.Util.exceptionReceivedFromServer(U
til.java:101)
        at net.jini.jeri.BasicInvocationHandler.unmarshalThrow(BasicInvocationHa
ndler.java:1303)
        at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethodOnce(BasicInvo
cationHandler.java:832)
        at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethod(BasicInvocati
onHandler.java:659)
        at net.jini.jeri.BasicInvocationHandler.invoke(BasicInvocationHandler.ja
va:528)
        at com.sun.jini.outrigger.$Proxy1.notify(Unknown Source)
        at com.sun.jini.outrigger.SpaceProxy2.notify(SpaceProxy2.java:507)
        at Servidor.main(Servidor.java:34)
Caused by: java.rmi.UnmarshalException: unmarshalling method/arguments; nested e
xception is:
        java.lang.ClassNotFoundException: Servidor
        at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispa
tcher.java:619)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java
:597)
        at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:
103)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(Objec
tTable.java:595)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(Obje
ctTable.java:212)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java
:568)
        at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvi
der.java:527)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(Object
Table.java:565)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(Object
Table.java:540)
        at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTabl
e.java:778)
        at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(
ServerConnectionManager.java:148)
        at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244)
        at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvi
der.java:513)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241)
        at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136)
        at java.lang.Thread.run(Thread.java:595)
Caused by: java.lang.ClassNotFoundException: Servidor
        at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at net.jini.loader.pref.PreferredClassLoader.loadClass(PreferredClassLoa
der.java:922)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:242)
        at net.jini.loader.pref.PreferredClassProvider.loadClass(PreferredClassP
rovider.java:613)
        at java.rmi.server.RMIClassLoader.loadClass(RMIClassLoader.java:247)
        at net.jini.loader.ClassLoading.loadClass(ClassLoading.java:138)
        at net.jini.io.MarshalInputStream.resolveClass(MarshalInputStream.java:2
96)
        at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:154
4)
        at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1466)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1
699)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
        at com.sun.jini.jeri.internal.runtime.Util.unmarshalValue(Util.java:221)

        at net.jini.jeri.BasicInvocationDispatcher.unmarshalArguments(BasicInvoc
ationDispatcher.java:1049)
        at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispa
tcher.java:599)
        ... 17 more
Pressione qualquer tecla para continuar. . .


This is my codes:

Cliente.java

import Calculadora2App.*;

import java.io.Serializable;
import java.util.Scanner;
import net.jini.space.JavaSpace;
import net.jini.core.lease.Lease;
import net.jini.core.event.RemoteEvent;
import net.jini.core.event.RemoteEventListener;
import java.lang.*;

public class Cliente implements RemoteEventListener,Serializable{

 private JavaSpace space;

 public Cliente(){}

 public Cliente(JavaSpace space){
  this.space = space;
  }

 public static void main(String[] args){

 try {
  // ************* Fazendo Lookup para achar o espaço ***********************

  Utilidades conexao = new Utilidades();
  JavaSpace space = conexao.conecta();
  Cliente setar = new Cliente(space);
  // ************** Registrando cliente para receber notificação de
resultado **************

  Cliente usuario = new Cliente();
  Resultado template = new Resultado();
  space.notify(template, null,usuario, Lease.FOREVER, null);

  //
***************************************************************************************

  Scanner sc = new Scanner(System.in);
        CalcEntry msg = new CalcEntry(); // Entry de requisição de calculos


   System.out.println("************************************************\n");
   System.out.println("Digite o numero da operacao desejada:\n");
   System.out.println("1. Adicao\n");
   System.out.println("2. Subtracao:\n");
   System.out.println("3. Multiplicacao\n");
   System.out.println("4. Divisao\n");
   System.out.println("************************************************\n");


//****************************************************************************************


  msg.operacao = new Integer(sc.nextInt());
  System.out.println("Digite o primeiro numero: ");
  msg.op1 = new Integer(sc.nextInt());
  System.out.println("\nDigite o segundo numero:");
  msg.op2 = new Integer(sc.nextInt());

  //****************************** Usando write para escrever no espaço
*********************
  conexao.escreve(msg,space);

    }
    catch (Exception e){
         e.printStackTrace();
         }
 }
// ************************************** Usar take para retirar do espaço
**************************

 public void notify(RemoteEvent evento){

  System.out.println("Evento recebido. Tentando retirar do espaco........\n");

  Resultado resulEntry = new Resultado();

  //loop para tirar todas as entrys do espaço
  while(resulEntry == null){
   try{
   resulEntry = (Resultado)space.take(resulEntry,null,Long.MAX_VALUE);
   System.out.println("\nResultado da operacao:
"+resulEntry.resultado.intValue());
   }
  catch(Exception e){
   System.err.println("Erro ao retirar do espaço\n");
   e.printStackTrace();
  }
 }
 }
 //
**************************************************************************************************
}


Servidor.java

import Calculadora2App.*;

import java.io.Serializable;
import java.util.Scanner;
import net.jini.space.JavaSpace;
import net.jini.core.lease.Lease;
import net.jini.core.event.RemoteEvent;
import net.jini.core.event.RemoteEventListener;
import java.lang.*;

public class Servidor implements RemoteEventListener,Serializable{

 private JavaSpace space;

 public Servidor(){}

 public Servidor(JavaSpace space){
  this.space = space;
  }

 public static void main(String[] args){

 try {
  // ************* Fazendo Lookup para achar o espaço ***********************

  Utilidades conexao = new Utilidades();
  JavaSpace space = conexao.conecta();
  Servidor setar = new Servidor(space);

  // ************** Registrando servidor para receber solicitações
**************
  System.out.println("Registrando objeto notify...\n");
  Servidor calculadora = new Servidor();
  CalcEntry solicitacao = new CalcEntry();
  space.notify(solicitacao, null,calculadora, Lease.FOREVER, null);
  System.out.println("Objeto Notify Registrado!\n");
  }
  catch(Exception e){
   System.err.println("Erro no Servidor\n");
   e.printStackTrace();
  }
 }

// ************************************** Usar take para retirar do espaço
**************************

 public void notify(RemoteEvent evento){

  System.out.println("Evento recebido. Tentando retirar do espaco........\n");

  CalcEntry solicitacao = new CalcEntry();

  //loop para tirar todas as entrys do espaço
  while(solicitacao == null){
   try{
   solicitacao = (CalcEntry)space.take(solicitacao,null,Long.MAX_VALUE);

opera(solicitacao.operacao.intValue(),solicitacao.op1.intValue(),solicitacao.op2.intValue());
   }
  catch(Exception e){
   System.err.println("Erro ao retirar do espaço\n");
   e.printStackTrace();
  }
 }
 }
 //
**************************************************************************************************

 public void opera(int operacao, int n1, int n2){

     try{
     switch(operacao){
      case 1: space.write(Soma(n1,n2),null, Lease.FOREVER);break;
      case 2: space.write(Subtrai(n1,n2), null, Lease.FOREVER);break;
      case 3: space.write(Multiplica(n1,n2),null, Lease.FOREVER);break;
      case 4: space.write(Divide(n1,n2),null, Lease.FOREVER);break;
      default: System.err.println("Operacao invalida!\n");break;
     }
    }
  catch(Exception e){
   System.err.println("Erro ao escrever no espaço\n");
   e.printStackTrace();
  }
 }

 public Resultado Soma(int n1, int n2){
  Resultado resul = new Resultado();
  resul.resultado = new Integer(n1+n2);
  return resul;
 }

 public Resultado Subtrai(int n1, int n2){
  Resultado resul = new Resultado();
  resul.resultado = new Integer(n1-n2);
  return resul;
 }

 public Resultado Multiplica(int n1, int n2){
  Resultado resul = new Resultado();
  resul.resultado = new Integer(n1*n2);
  return resul;
 }

 public Resultado Divide(int n1, int n2){
  Resultado resul = new Resultado();
  resul.resultado = new Integer(n1/n2);
  return resul;
 }

}

Resultado.java

package Calculadora2App;
import net.jini.core.entry.*;

public class Resultado implements Entry {
 public Integer resultado;

 public Resultado(){}
}

CalcEntry.java

package Calculadora2App;
import net.jini.core.entry.*;

public class CalcEntry implements Entry {
 public Integer operacao;
 public Integer op1;
 public Integer op2;

 public CalcEntry(){}
}

Utilidades.java

package Calculadora2App;

import java.util.Scanner;
import net.jini.space.JavaSpace;
import net.jini.core.lease.Lease;

public class Utilidades{

 private JavaSpace space;
 private boolean continua = true;

 public Utilidades(){}

 public void escreve(CalcEntry msg,JavaSpace space){
  System.out.println("\nEscrevendo mensagem no espaco...\n");
  try{
  space.write(msg, null, Lease.FOREVER); //escreve a mensagem no espaço
  System.out.println("\nMensagem escrita!\n");
  }
  catch (Exception e) {
    System.err.println("Erro na escrita!\n");
    e.printStackTrace();
   }
 }


 public JavaSpace conecta(){
    // Encontra o espaço
  try{
   System.out.println("Localizando JavaSpace...\n");
          Lookup finder = new Lookup(JavaSpace.class);
           this.space = (JavaSpace) finder.getService();
           System.out.println("JavaSpace localizado.\n");

   } catch (Exception e) {
    System.err.println("Erro no espaco!\n");
    e.printStackTrace();
    System.exit(1);
   }
  return this.space;
 }

 public boolean continuar(){
  return this.continua;
 }

 public void setFalse(){
  this.continua = false;
 }

 public void setTrue(){
  this.continua = true;
 }
}

Lookup.java

package Calculadora2App;

import java.io.IOException;

import java.rmi.RemoteException;

import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceTemplate;

import net.jini.discovery.LookupDiscovery;
import net.jini.discovery.DiscoveryListener;
import net.jini.discovery.DiscoveryEvent;

/**
   A class which supports a simple JINI multicast lookup.  It doesn't register
   with any ServiceRegistrars it simply interrogates each one that's
   discovered for a ServiceItem associated with the passed interface class.
   i.e. The service needs to already have registered because we won't notice
   new arrivals. [ServiceRegistrar is the interface implemented by JINI
   lookup services].

   @todo Be more dynamic in our lookups - see above

   @author  Dan Creswell ([email protected])
   @version 1.00, 7/9/2003
 */
public class Lookup implements DiscoveryListener {
    private ServiceTemplate theTemplate;
    private LookupDiscovery theDiscoverer;

    private Object theProxy;

    /**
       @param aServiceInterface the class of the type of service you are
       looking for.  Class is usually an interface class.
     */
    public Lookup(Class aServiceInterface) {
        Class[] myServiceTypes = new Class[] {aServiceInterface};
        theTemplate = new ServiceTemplate(null, myServiceTypes, null);
    }

    /**
       Having created a Lookup (which means it now knows what type of service
       you require), invoke this method to attempt to locate a service
       of that type.  The result should be cast to the interface of the
       service you originally specified to the constructor.

       @return proxy for the service type you requested - could be an rmi
       stub or an intelligent proxy.
     */
    public Object getService() {
        synchronized(this) {
            if (theDiscoverer == null) {

                try {
                    theDiscoverer =
                        new LookupDiscovery(LookupDiscovery.ALL_GROUPS);
                    theDiscoverer.addDiscoveryListener(this);
                } catch (IOException anIOE) {
                    System.err.println("Failed to init lookup");
                    anIOE.printStackTrace(System.err);
                }
            }
        }

        return waitForProxy();
    }

    /**
       Location of a service causes the creation of some threads.  Call this
       method to shut those threads down either before exiting or after a
       proxy has been returned from getService().
     */
    public void terminate() {
        synchronized(this) {
            if (theDiscoverer != null)
                theDiscoverer.terminate();
        }
    }

    /**
       Caller of getService ends up here, blocked until we find a proxy.

       @return the newly downloaded proxy
     */
    private Object waitForProxy() {
        synchronized(this) {
            while (theProxy == null) {

                try {
                    wait();
                } catch (InterruptedException anIE) {
                }
            }

            return theProxy;
        }
    }

    /**
       Invoked to inform a blocked client waiting in waitForProxy that
       one is now available.

       @param aProxy the newly downloaded proxy
     */
    private void signalGotProxy(Object aProxy) {
        synchronized(this) {
            if (theProxy == null) {
                theProxy = aProxy;
                notify();
            }
        }
    }

    /**
       Everytime a new ServiceRegistrar is found, we will be called back on
       this interface with a reference to it.  We then ask it for a service
       instance of the type specified in our constructor.
     */
    public void discovered(DiscoveryEvent anEvent) {
        synchronized(this) {
            if (theProxy != null)
                return;
        }

        ServiceRegistrar[] myRegs = anEvent.getRegistrars();

        for (int i = 0; i < myRegs.length; i++) {
            ServiceRegistrar myReg = myRegs[i];

            Object myProxy = null;

            try {
                myProxy = myReg.lookup(theTemplate);

                if (myProxy != null) {
                    signalGotProxy(myProxy);
                    break;
                }
            } catch (RemoteException anRE) {
                System.err.println("ServiceRegistrar barfed");
                anRE.printStackTrace(System.err);
            }
        }
    }

    /**
       When a ServiceRegistrar "disappears" due to network partition etc.
       we will be advised via a call to this method - as we only care about
       new ServiceRegistrars, we do nothing here.
     */
    public void discarded(DiscoveryEvent anEvent) {
    }
}

===========================================================================
To unsubscribe, send email to [email protected] and include in the body
of the message "signoff JAVASPACES-USERS".  For general help, send email to
[email protected] and include in the body of the message "help".

To view past JAVASPACES-USERS postings, please see:
http://archives.java.sun.com/archives/javaspaces-users.html