📄 agentimpl.java
字号:
/* $Id: AgentImpl.java,v 1.1 2004/02/05 23:02:22 giuli Exp $
* @(#)AgentImpl.java 02/2004
*
* The contents of this file are subject to the OAA Community Research
* License Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License
* at http://www.ai.sri.com/~oaa/. Software distributed under the License
* is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either
* express or implied. See the License for the specific language governing
* rights and limitations under the License. Portions of the software are
* Copyright (c) SRI International, 1999. All rights reserved.
* "OAA" is a registered trademark, and "Open Agent Architecture" is a
* trademark, of SRI International, a California nonprofit public benefit
* corporation.
*
*/
package com.sri.oaa2.agentlib;
import com.sri.oaa2.com.LibCom;
import com.sri.oaa2.com.LibComTcpProtocol;
import com.sri.oaa2.icl.IclList;
import com.sri.oaa2.icl.IclStruct;
import com.sri.oaa2.icl.IclTerm;
import com.sri.oaa2.icl.IclUtils;
import com.sri.oaa2.lib.LibOaa;
import com.sri.oaa2.lib.OAAEventListener;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import java.util.Arrays;
import java.util.Iterator;
/**
* Abstract base class for concrete Agent implementations.
*
* <h3>Usage</h3>
* Classes derived from this class must define the method
* <code>getAgentName</code>. If the agent has any capabilities (solvables)
* it must override the method <code>getAgentCapabilities</code> to declare
* those capabilities, and override the method
* <code>oaaDoEventCallback</code> as well to handle solve requests.
*
* @see Agent#getAgentName Agent.getAgentName()
* @see #getAgentCapabilities getAgentCapabilities()
* @see #oaaDoEventCallback oaaDoEventCallback()
* @see com.sri.oaa2.agentlib.example
*/
public abstract class AgentImpl implements Agent {
private LibOaa myOaa;
private Logger logger;
private static Logger defaultLogger;
private boolean blocking = true;
private boolean directConnect = false;
private String solvingAgent = null;
private IclTerm solvingAgentAddress = null;
// Initialize the library
static {LibOaa.libInit();}
// The connection ID must be "parent" for Java agents.
private static final String CONNECTION_ID = "parent";
protected AgentImpl() {
super();
logger = getDefaultLogger();
}
public void facilitatorConnect(String[] oaaArgs) throws AgentException {
logOaaArguments(oaaArgs);
myOaa = new LibOaa(new LibCom(new LibComTcpProtocol(), oaaArgs));
logger.info(getAgentName() + " Connecting");
if (!myOaa.oaaSetupCommunication(getAgentName())) {
String errorMsg = "Couldn't connect to facilitator";
logger.fatal(errorMsg);
throw new AgentException(errorMsg);
}
logger.info("Connection Made");
IclTerm icl = null;
// register the agent's info
try {
icl = IclTerm.fromString(true, getAgentCapabilities());
} catch (RuntimeException ex) {
String errorMsg = "Failed to parse ICL, error = " + ex.getMessage();
logger.fatal(errorMsg);
throw new AgentException(errorMsg);
}
logger.info("Registering " + getAgentName());
if (!myOaa.oaaRegister(CONNECTION_ID,
getAgentName(),
icl,
null)) {
String errorMsg = "Could not register";
logger.fatal(errorMsg);
throw new AgentException(errorMsg);
}
// register the call back method which the facilitator will call
myOaa.oaaRegisterCallback("oaa_AppDoEvent", new OAAEventListener() {
public boolean doOAAEvent(
IclTerm goal, IclList params, IclList answers) {
return oaaDoEventCallback(goal, params, answers);
}
});
}
private IclTerm findAddressForAgent(String agentName)
throws AgentException {
// We'll get into a infinite loop
// if we don't temporarily discard
// the solving agent's name while solving
// for the agent's name.
String realSolvingAgent = getSolvingAgent();
setSolvingAgent(null);
IclList result =
solve("agent_host(Addr,'" + agentName + "',Host)","[]");
setSolvingAgent(realSolvingAgent);
if (result.size() == 0) {
throw new AgentException(
"The agent name \""
+ agentName
+ "\" does not appear to be valid.");
}
IclTerm agentAddr = result.getTerm(0).getTerm(0);
return agentAddr;
}
public void facilitatorDisconnect() {
// Disconnect all connections
if (myOaa != null) {
myOaa.oaaDisconnect(iclEmptyList);
myOaa = null;
}
}
/**
* This implementation simply returns "[]" representing
* "no capabilities" or a "pure-client" Agent. Override
* this method in order to declare capabilities (solvables).
*
* @see Agent#getAgentCapabilities
*/
public String getAgentCapabilities() {
// no capabilities by default...a pure OAA client
return "[]";
}
public boolean getBlocking() {
return blocking;
}
/**
* The defaultLogger behaves like stdout
* with an INFO logging level.
*/
private Logger getDefaultLogger() {
if (defaultLogger == null) {
defaultLogger = Logger.getLogger(DEFAULT_AGENT_LOGGER);
defaultLogger.addAppender(
new ConsoleAppender(new PatternLayout("%m%n"), "System.out"));
defaultLogger.setLevel(Level.INFO);
// don't inherit any appenders...we just want a simple logger...
defaultLogger.setAdditivity(false);
}
return defaultLogger;
}
public Logger getLogger() {
return logger;
}
public LibOaa getLibOaa() {
return myOaa;
}
public String getSolvingAgent() {
return solvingAgent;
}
private IclTerm getSolvingAgentAddress() throws AgentException {
if (solvingAgentAddress == null) {
solvingAgentAddress = findAddressForAgent(solvingAgent);
}
return solvingAgentAddress;
}
public boolean getUseDirectConnect() {
return directConnect;
}
public IclList interpret(IclTerm toBeInterpreted, IclList localParams)
throws AgentException {
boolean blockAdded = false, dcAdded = false;
boolean useDirectConnect = false, addressAdded = false;
if (myOaa == null) {
throw new AgentException("Agent not connected to facilitator");
}
if ((toBeInterpreted.isStruct() && toBeInterpreted.
toIdentifyingString().equals("oaa_Solve"))) {
IclList params = (IclList)toBeInterpreted.getTerm(1);
if (IclUtils.getParamValue(BLOCK_PARAM_NAME, null, params) == null) {
blockAdded = true;
if (blocking) {
params.add(BLOCK_TRUE_PARAM);
} else {
params.add(BLOCK_FALSE_PARAM);
}
}
IclTerm dcParam = IclUtils.getParamValue(DC_PARAM_NAME, null, params);
if (dcParam == null) {
dcAdded = true;
if (directConnect) {
useDirectConnect = true;
params.add(DC_TRUE_PARAM);
} else {
params.add(DC_FALSE_PARAM);
}
} else {
useDirectConnect = dcParam.toIdentifyingString().equals("true");
}
if (useDirectConnect) {
// Request an out parameter which specifies whether or not
// direct_connect was actually used.
params.add(USED_DC_PARAM);
}
IclTerm addressParam
= IclUtils.getParamValue(ADDRESS_PARAM_NAME, null, params);
if (addressParam == null && solvingAgent != null) {
try {
params.add(getSolvingAgentAddress());
addressAdded = true;
}
catch (AgentException ae) {
getLogger().error(ae.getMessage());
}
}
}
IclList localSolutions = new IclList();
try {
if (!myOaa.oaaInterpret(toBeInterpreted, localParams, localSolutions)) {
throw new AgentException("Failed to interpret \"" +
toBeInterpreted + "\"");
}
// If direct_connect was requested but not actually used, throw
// an exception with the answers.
if (useDirectConnect) {
// Make sure direct_connect was actually used
IclList params = (IclList)toBeInterpreted.getTerm(1);
IclTerm get_direct_connect_used = IclUtils.getParamValue(
USED_DC_NAME, null, params);
if (get_direct_connect_used == null || get_direct_connect_used.
toIdentifyingString().equals("false")) {
throw new DirectConnectFailedException(
"Failed to use direct_connect", localSolutions);
}
}
} finally {
if (blockAdded) {
IclUtils.removeParamValue(BLOCK_PARAM_NAME,
(IclList)toBeInterpreted.getTerm(1));
}
if (dcAdded) {
IclUtils.removeParamValue(DC_PARAM_NAME,
(IclList)toBeInterpreted.getTerm(1));
}
if (useDirectConnect) {
IclUtils.removeParamValue(USED_DC_NAME,
(IclList)toBeInterpreted.getTerm(1));
}
if (addressAdded) {
IclUtils.removeParamValue(ADDRESS_PARAM_NAME,
(IclList)toBeInterpreted.getTerm(1));
}
}
return localSolutions;
}
private void logOaaArguments(String[] oaaArgs) {
if ((oaaArgs != null) && (oaaArgs.length > 0)) {
String oaaArgsString = "OAA Arguments = ";
Iterator it = Arrays.asList(oaaArgs).iterator();
while (it.hasNext()) {
oaaArgsString += it.next() + " ";
}
getLogger().info(oaaArgsString);
}
}
/**
* This default implementation is a "no-op" callback,
* appropriate only for "pure-client" Agents. This method must be
* overridden for all agents with solvables.
*/
public boolean oaaDoEventCallback(IclTerm goal,
IclList params,
IclList answers) {
// no capabilities by default
return false;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
public void setBlocking(boolean blocking) {
this.blocking = blocking;
}
public void setSolvingAgent(String agentName) {
solvingAgent = agentName;
}
public void setUseDirectConnect(boolean directConnect) {
this.directConnect = directConnect;
}
public IclList solve(String goal, String params) throws AgentException {
IclTerm iclGoal = null;
IclTerm iclParams = null;
try {
iclGoal = IclTerm.fromString(true, goal);
} catch (RuntimeException ex) {
throw new AgentException("Cannot interpret ICL: \"" +
goal + "\"");
}
try {
iclParams = IclTerm.fromString(true, params);
} catch (RuntimeException ex) {
throw new AgentException("Cannot interpret ICL: \"" +
params + "\"");
}
return solve(iclGoal, iclParams);
}
public IclList solve(IclTerm goal, IclTerm params) throws AgentException {
return interpret(new IclStruct("oaa_Solve", goal, params), new IclList());
}
public void start() {
logger.info("Starting " + getAgentName());
if (myOaa != null) {
myOaa.oaaReady(true);
} else {
logger.error("Agent not connected to facilitator. Agent not started.");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -