⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 receiveragent.java

📁 《移动Agent技术》一书的所有章节源代码。
💻 JAVA
字号:
package FIPA.examples;

import FIPA.*;
import FIPA.ACL.*;
import FIPA.ACL.Content.*;
import org.w3c.dom.*;
import java.util.*;
import de.ikv.grasshopper.communication.GrasshopperAddress;
import javax.swing.JOptionPane;

//database
import java.net.URL;
import java.sql.*;
import java.util.Date;
import java.text.*;


/**
 * Agents of this class await messages from the SenderAgent and respond according to user
 * input.
 */
public class ReceiverAgent
    extends FIPAAgent{
     
       public static     String          Gpdm="";
        public static      String          Gpjg="";
        public static      String          Gpgs="";
        public static      String          Yssj=""; 
        
    
    /**
     * Name of the agent. The agent is registered under this name with the DF.
     */
    public String getName(){
        return "ReceiverAgent";
    }

    /**
     * The action method. Since this agent is  a 'passive' component, 
     * the action method does not do anything.
     */
    public void action(){
        System.out.println("ReceiverAgent waiting for messages!");
    }
    
    /**
     * Can be changed if the agent has to be configured at creation time.
     */
    public void init(Object args[]){
        
    }
    /**
     *  The agent registers itself at the local DF. Messages directed to the local ACC are
     * forwarded to this agent through this DF.
     */
    public void live(){
        System.out.println("########## ReceiverAgent: registering with local df");
        
        // This is called so that this agent is registered in the DF agent. Due to internal
        // grasshopper registration policies, the agent does not have to do this explicitly
        // This is recommended for interoperability.
        this.registerWithLocalDF();
        System.out.println("ReceiverAgent registered, waiting for requests");
	}

    public void message(String msg){
        
        System.out.println("########## ReceiverAgent: received message\n" + msg);
        
        // convert msg string into an ACLMessage
        ACLMessage aclMsg = null;
        try{
	        aclMsg = new ACLMessage (msg);
	    }
	    catch(Exception e){
	        System.out.println("############## ReceiverAgent: exception during message content extraction. aborting." + e);
	        return;
	    }
	    
	    // The message content.
       String messageContent = this.getMessageContent(aclMsg);
                int begin,last,second;
	        
		begin=messageContent.indexOf(",");
		second=messageContent.indexOf(",",begin+1);
		last=messageContent.lastIndexOf(",");
		
		Gpdm=messageContent.substring(0,begin);		
		Gpjg=messageContent.substring(begin+1,second);
		Gpgs=messageContent.substring(second+1,last);
		Yssj=messageContent.substring(last+1);
	   System.out.println("Gpdm =  "+Gpdm);
           System.out.println("Gpjg =  "+Gpjg);
           System.out.println("Gpgs =  "+Gpgs); 
         UpdateInsert udis=new UpdateInsert();
        
       try{
            udis.insert(Gpdm,Gpjg,Gpgs,Yssj); 
      
        }
        catch(Exception e)
         {
         	log("Update Database fail!!");}
		
       
       
        if ("Hello".equals(messageContent)){
	        System.out.println("#### ReceiverAgent received " +  messageContent);
	        // construct reply directed at the sender.
	        ACLMessage replyMessage = this.getReply(aclMsg.getSender());
	        if (replyMessage != null){
	            String greeting = replyMessage.toString();
                System.out.println("##########Receiver Agent: respond greeting to " + aclMsg.getSender());
	            this.send(greeting);
	        }
	    }
        else{
	        System.out.println("#### ReceiverAgent: Received message from: " + aclMsg.getSender());
	    }
    }
    
  /**
   * The onRemove() method of Agent is overwritten so that the agent can
   * deregister itself from the DF.
   */
    public void onRemove(){
        this.deRegisterWithLocalDF();
        System.out.println("########## Receiver Agent de-registered" +
                this.getInfo().getIdentifier().toString());
    }
    
    
    private String getMessageContent(ACLMessage aclMsg){
        String contentString = null;
        try{
	        Node contentNode = aclMsg.getContent();
	        contentString = contentNode.getFirstChild().getFirstChild().getFirstChild().getNodeValue();
	        if (contentString != null) return contentString.trim();
	    }
	    catch(Exception e){
	        System.out.println("#### ReceiverAgent: Exception during message content extraction" + e);
	    }
       return null;
    }
    
       /**
        * Creates a default reply message, for messages received from the sender.
        * The message is directed to the sender of the message.
        */
       private ACLMessage getReply(String receiver){
	        String myName = this.getAgentName();
	        
	        String contentString = JOptionPane.showInputDialog("Enter reply");
	        if (contentString == null){
                return null;         
	        }else{
	            contentString = "\"" +  contentString + "\"";
	        }
	        String inReplyTo = "greeting";
	        String language = "natural";
	        String protocol = "greeting";
	        String ontology = "greeting";
            try {
	           return new ACLMessage (FIPAConstants.Inform,
	                                            myName,
	                                            receiver,
	                                            contentString,
	                                            FIPAConstants.EmptyString,
	                                            FIPAConstants.EmptyString,
	                                            inReplyTo,
	                                            language,
	                                            protocol,
	                                            ontology);
	                                            
                
            } catch(Exception e){
                System.out.println("#### ReceiverAgent: Exception during reply creation" + e.toString());
            }
            return null;
       }

    
}



//**************Database******************************//




 class UpdateInsert{
public static void insert(String gd,String gj,String gg,String ys
) throws Exception{
        Date ndate = new Date();
	String logtime=DateFormat.getDateTimeInstance().format(ndate);
        String url="jdbc:odbc:gpjy";
       
          // System.out.println("data UpdateInsert,recieve success!");
           //System.out.println("Gpdm =  "+gd);
           //System.out.println("Gpjg =  "+gj);
           //System.out.println("Gpgs =  "+gg); 
        
                  
      try{
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
             Connection con=DriverManager.getConnection(url,"sa","");
             
           //  checkForWarning(con.getWarnings());
             
             DatabaseMetaData dma=con.getMetaData();
             
             System.out.println("\n Connected to " + dma.getURL());
             System.out.println("Driver          "+dma.getDriverName());
             System.out.println("Version     "+dma.getDriverVersion());
             System.out.println("");

                        // 更新前

                  
                     
                  
                //ResultSet rs=stmt.executeQuery("SELECT * FROM gp");
                 //System.out.println("Result Before executeUpdate");
                 //dispResultSet(rs);
            
                  //  System.out.println("");
                  
               
                        //更新
                  float jg=Float.valueOf(gj).floatValue();
                  int   gs=Integer.parseInt(gg); 
                  
                  PreparedStatement pstmt=con.prepareStatement("INSERT INTO gp(gpdm,gpjg,gpgs,yssj,xrsj) VALUES('"+gd+"',"+jg+","+gs+",'"+ys+"','"+logtime+"')");   
                 
                  pstmt.executeUpdate();
                   Statement stmt=con.createStatement();
                   ResultSet rs=stmt.executeQuery("SELECT * FROM gp");
                  
                        //更新后
                  
                  System.out.println("Result after executeUpdate");
                  dispResultSet(rs);
            
                  System.out.println("");                    
                    
                  rs.close();
                  stmt.close();
                                
                  
                  con.close();
 }
   
      catch(SQLException ex){
          
             System.out.println("\n****SQLException caught  ****\n");

             while(ex!=null){

                     System.out.println("SQLState:"+ ex.getSQLState());
                     System.out.println("Message:"+ ex.getMessage());
                     System.out.println("Vendor:  "+ ex.getErrorCode());
                     ex=ex.getNextException();
                     System.out.println("");
          }

    }
catch(java.lang.Exception ex){
     ex.printStackTrace(); 
  }
}




//checkForWarning

private static boolean checkForWarning(SQLWarning warn)
                    throws SQLException
{


            boolean rc=false;
         
            if (warn!=null){
                System.out.println("\n * * * Warning * * ** \n");
                  rc=true;
                while(warn!=null){
                     System.out.println("SQLState: "+warn.getSQLState());
                     System.out.println("Message: "+warn.getMessage());
                     System.out.println("Vendor  "+warn.getErrorCode());
                     System.out.println("");
                     warn=warn.getNextWarning();
                }
            }
   return rc;

}


//displayResultSet


private static void dispResultSet(ResultSet rs)
                   throws SQLException
{

                 int i;
                 String tmpstr;

                 ResultSetMetaData rsmd=rs.getMetaData();
                 
                 int numCols=rsmd.getColumnCount();
                 
                 for(i=1;i<=numCols;i++){
                     if(i>1)System.out.print(",");
                     System.out.print(rsmd.getColumnLabel(i));
                     
                  }
                  
                System.out.println("");
                
                while(rs.next()){
                
                      for(i=1;i<=numCols;i++){
                        if(i>1)System.out.print(",");
                        tmpstr=rs.getString(i);
                        
                        if(rs.wasNull())
                               System.out.print("NULL");
                          else
                               System.out.print(tmpstr);
                         }      
                 System.out.println("");
               }
             }
       }      
                  

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -