/********************************************************************** * Copyright (c) 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * $Id: AgentImpl.java,v 1.19 2006/01/14 00:31:59 vnaikawadi Exp $ * * Contributors: * Vishnu K Naikawadi, Intel - Initial API and implementation **********************************************************************/ package org.eclipse.tptp.platform.execution.client.agent.impl; import java.util.Hashtable; import java.util.Vector; import java.util.Enumeration; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import org.eclipse.tptp.platform.execution.client.agent.*; import org.eclipse.tptp.platform.execution.client.core.*; import org.eclipse.tptp.platform.execution.client.core.impl.*; import org.eclipse.tptp.platform.execution.client.core.impl.commands.rac.*; import org.eclipse.tptp.platform.execution.exceptions.*; import org.eclipse.tptp.platform.execution.util.*; import org.eclipse.tptp.platform.execution.util.impl.CommandFragment; import org.eclipse.tptp.platform.execution.util.impl.Constants; import org.eclipse.tptp.platform.execution.util.impl.TPTPXMLParse; import org.eclipse.tptp.platform.execution.util.impl.DimeHeader; public class AgentImpl implements IAgent, IProcessListener, IConnectionListener { // Bug 59316 protected String _name=null; protected String _type=null; protected String _uuid=null; protected String _version = null; private IAgentController _ac = null; protected boolean _autoAttach=false; protected boolean _isMonitored=false; protected boolean _isActive=true; protected boolean _isAttached=false; protected String _profileFile=null; protected IProcess _process = null; protected String agentMetadata = null; protected TPTPAgentAccess agentMode = null; private int _agentID = -1; private int _tokenID = -1; private int _dataConnectionID = -1; private boolean dataPathEstablished = false; private boolean addEventRespReceived = false; protected Vector _listeners=new Vector(10); private Object _lock = new Object(); public AgentImpl() {} public AgentImpl(String name) { _name = name; } public AgentImpl(String name, String type) { _name = name; _type = type; } public IAgentController getAgentController() { return _ac; } public void setAgentController(IAgentController ac) { _ac = ac; } /** * @see Agent#addAgentListener(AgentListener) */ public void addAgentListener(IAgentListener listener) { synchronized(_listeners) { if(!_listeners.contains(listener)) { _listeners.add(listener); } } } /** * @see Agent#removeAgentListener(AgentListener) */ public void removeAgentListener(IAgentListener listener) { synchronized(_listeners) { if(_listeners.contains(listener)) { _listeners.remove(listener); } } } /** * Change the type of the agent * @param type value of the new type */ public void setType(String type) { _type = type; } /** * Change the name of the agent * @param name the new agent's name */ public void setName(String name) { _name = name; } /** * Retrieve the instance id of this agent. * @return the id of the agent if it is known, negative if it is not assigned yet */ public int getAgentInstanceId() { return _agentID; } /** * Change the agent instance's id * @param uuid the new uuid's value */ public void setAgentInstanceId(int id) { _agentID = id; } /** * Retrieve the instance id of this agent. * @return the id of the agent if it is known, negative if it is not assigned yet */ public int getAgentTokenId() { return _tokenID; } /** * Change the agent instance's id * @param uuid the new uuid's value */ public void setAgentTokenId(int id) { _tokenID = id; } /** * Retrieve the version of this agent. * @return the version */ public String getVersion() { return _version; } /** * Set the Agent version * @param version the new version number */ public void setVersion(String version) { _version = version; } /** * Set the Process associated with Agent * @param version the new version number */ public void setProcess(IProcess process) { _process = process; } /** * Get the Process assocites with Agent * @param version the new version number */ public IProcess getProcess() { return _process; } /** * Add a listener for agent events * @param listener to handle the event notification */ public long addEventListener(String interfaceID, ICommandHandler listener) { StringBuffer AddEventListenerCommand = new StringBuffer(""); long listenerID = -1; try { listenerID = _ac.getNextContextId(); //System.out.println("Sending addEventListener() command"); AddEventListenerCommand.append(""); AddEventListenerCommand.append(interfaceID); AddEventListenerCommand.append(""); AddEventListenerCommand.append(listenerID); AddEventListenerCommand.append(""); //System.out.print("The Add Event Listener Command is - " + AddEventListenerCommand.toString()); IConnection conn = ((AgentController)_ac).getConnection(); ((ConnectionImpl)conn).addContext(listenerID, listener); sendCommand(AddEventListenerCommand.toString(), new ICommandHandler() { public void incomingCommand(INode node, ICommandElement command) { String commandStr = new String(((CommandFragment)command).getCommandData()); System.out.println("The command is - " + commandStr); //handleAgentCommand(command); TPTPXMLParse ParseObj = new TPTPXMLParse(); ParseObj.setParser(commandStr); Hashtable CommandHash = ParseObj.getHashTable(); if (CommandHash.containsKey("listenerAccepted")) { System.out.println("The listenerAccepted command is received"); addEventRespReceived = true; } } }); if (!addEventRespReceived) { Thread.sleep(Constants.THREAD_SLEEP); } addEventRespReceived = false; } catch(Exception exp) { exp.printStackTrace(); } return listenerID; } /** * Remove a listener for agent events * @param listener to handle the event notification */ public void removeEventListener(String interfaceID, long listenerID) { StringBuffer RemoveEventListenerCommand = new StringBuffer(""); try { //Send the releaseAgent command //System.out.println("Sending removeEventListener() command"); RemoveEventListenerCommand.append(""); RemoveEventListenerCommand.append(interfaceID); RemoveEventListenerCommand.append(""); RemoveEventListenerCommand.append(listenerID); RemoveEventListenerCommand.append(""); sendCommand(RemoveEventListenerCommand.toString(), new ICommandHandler() { public void incomingCommand(INode node, ICommandElement command) { handleAgentCommand(command); } }); } catch(Exception exp) { exp.printStackTrace(); } } /** * Send the command * @param outCommand the command to send out * @param handler processing the response of the command */ public void sendCommand(ICommandElement outCommand, ICommandHandler respHandler) throws InactiveAgentException { if(!_isActive) { throw new InactiveAgentException(); } ControlMessage message=new ControlMessage(); outCommand.setContext(getAgentController().getNextContextId()); message.appendCommand(outCommand); try { //command.setProcessId(Long.parseLong(_process.getProcessId())); ((AgentController)getAgentController()).sendMessage(message, new ICommandHandler() { public void incomingCommand(INode node, ICommandElement element) { handleAgentCommand(element); } }); } // catch(InactiveProcessException e) { // throw new InactiveAgentException(); // } catch(IOException e) { /* We need to handle this */ e.printStackTrace(); } } /** * Send the command * @param outCommand the command to send out * @param handler processing the response of the command */ public void sendCommand(String outCommand, ICommandHandler respHandler) throws InactiveAgentException { if(!_isActive) { throw new InactiveAgentException(); } try { if (respHandler == null) { ((AgentController)getAgentController()).sendCommand(outCommand, _agentID, new ICommandHandler() { public void incomingCommand(INode node, ICommandElement element) { handleAgentCommand(element); } }); } else { ((AgentController)getAgentController()).sendCommand(outCommand, _agentID, respHandler); } } // catch(InactiveProcessException e) { // throw new InactiveAgentException(); // } catch(IOException e) { /* We need to handle this */ e.printStackTrace(); } } /** * @see Agent#isAutoAttach(boolean) */ public boolean isAutoAttach() { return _autoAttach; } /** * @see Agent#getType() */ public String getType() { return _type; } /** * @see Agent#getName() */ public String getName() { return _name; } /** * @see Agent#getUUID() */ public String getUUID() { return _uuid; } /** * @see Agent#isActive() */ public boolean isActive() { return _isActive; } /** * @see Agent#isMonitored() */ public boolean isMonitored() { return _isMonitored; } public int addDataListener(IDataProcessor dataProcessor) { return ((AgentController)getAgentController()).addDataListener(_dataConnectionID, dataProcessor); //startMonitoring(dataConnID); } public void startMonitoring(TPTPDataPath direction) { StringBuffer tempbuf = new StringBuffer(""); long agentDataPathDirection = -1; try { if (dataPathEstablished) return; if (_dataConnectionID == -1) { _dataConnectionID = ((AgentController)getAgentController()).createDataConnection(direction.getValue()); } if (direction.getValue() == Constants.DATA_PATH_SEND) { agentDataPathDirection = Constants.DATA_PATH_RECEIVE; } else if (direction.getValue() == Constants.DATA_PATH_RECEIVE) { agentDataPathDirection = Constants.DATA_PATH_SEND; } else if (direction.getValue() == Constants.DATA_PATH_TWO_WAY) { agentDataPathDirection = Constants.DATA_PATH_TWO_WAY; } //Send the establishDataPath command if(Constants.TPTP_DEBUG)System.out.println("Sending establishDataPath() command"); tempbuf.append(""); tempbuf.append(_dataConnectionID); tempbuf.append(""); tempbuf.append(agentDataPathDirection); tempbuf.append(""); sendCommand(tempbuf.toString(), new ICommandHandler() { public void incomingCommand(INode node, ICommandElement command) { handleAgentCommand(command); } }); while(!dataPathEstablished) { Thread.sleep(1000); } _isMonitored=true; } catch(Exception exp) { exp.printStackTrace(); } } /** * @see Agent#startMonitoring() */ public void startMonitoring(TPTPDataPath direction, IDataProcessor processor) throws InactiveAgentException { startMonitoring(direction); addDataListener(processor); _isMonitored=true; } /** * @see Agent#startMonitoring() */ public void startMonitoring(IDataProcessor processor) throws InactiveAgentException { startMonitoring(TPTPDataPath.DATA_PATH_RECEIVE); addDataListener(processor); _isMonitored=true; } /** * @see Agent#startMonitoring() */ public void stopMonitoring(IDataProcessor processor) throws InactiveAgentException { //TODO Destroy the data path _isMonitored=false; } /** * @see Agent#stopMonitoring() */ public void stopMonitoring() throws InactiveAgentException { //TODO destroy the data path _isMonitored=false; } public void sendData(byte[] buffer, int bufferLength) throws DataChannelConnectionException { byte[] buf = DimeHeader.shipIt(buffer, bufferLength); if(buf != null) { ((AgentController)this._ac).sendData(this._dataConnectionID, buf, buf.length); } } public void sendData(byte[] buffer) throws DataChannelConnectionException { this.sendData(buffer, buffer.length /*Length*/); } public void releaseAccess() { try { ((AgentController)getAgentController()).releaseAgent(this._agentID); this.setAgentMode(null); } catch(Exception exp) { exp.printStackTrace(); } } public boolean requestControl() { boolean reqgrant = false; try { reqgrant = ((AgentController)getAgentController()).requestAgentControl(this._agentID, TPTPAgentAccess.TPTP_CONTROLLER_ACCESS.getValue()); if(reqgrant){this.setAgentMode(TPTPAgentAccess.TPTP_CONTROLLER_ACCESS);} } catch(Exception e){e.printStackTrace();} return reqgrant; } public void releaseControl() { try { ((AgentController)getAgentController()).releaseAgentControl(this._agentID); this.setAgentMode(TPTPAgentAccess.TPTP_OBSERVER_ACCESS); } catch(Exception e){e.printStackTrace();} } public void setUUID(String uuid) { _uuid=uuid; } /** * This is the local handler for */ public void handleAgentCommand(final ICommandElement command) { String commandStr = new String(((CommandFragment)command).getCommandData()); TPTPXMLParse ParseObj = new TPTPXMLParse(); ParseObj.setParser(commandStr); Hashtable CommandHash = ParseObj.getHashTable(); if (CommandHash.containsKey("dataPathEstablished")) { dataPathEstablished = true; if(Constants.TPTP_DEBUG)System.out.println("Data Path Established"); } } /** * @see ProcessListener#processLaunched */ public void processLaunched(IProcess process) { } /** * @see ProcessListener#processExited */ public void processExited(IProcess process) { } // Bug 59316 begins public void connectionClosed(IConnection connection) { synchronized(_listeners) { _isActive = false; Enumeration elements = _listeners.elements(); while(elements.hasMoreElements()) { ((IAgentListener)elements.nextElement()).agentInactive(this); } } } public AgentConfiguration getConfiguration() { throw new NotSupportedException(); } public void setConfiguration(AgentConfiguration config) { throw new NotSupportedException(); } public void publishConfiguration() { throw new NotSupportedException(); } /** * @see Agent#attach() */ public void attach() throws InactiveAgentException, InactiveProcessException{ throw new NotSupportedException(); } /** * @see Agent#detach() */ public void detach() throws InactiveAgentException, InactiveProcessException { throw new NotSupportedException(); } /** * @see Agent#isAttached() */ public boolean isAttached() { throw new NotSupportedException(); } /** * @see Agent#isAttached() */ public boolean isAttached(boolean remote) { throw new NotSupportedException(); } public int receiveData(char[] buffer) throws InactiveAgentException, NotConnectedException { int response = 0; return response; } public String[] getSupportedInterfaces() { //TODO:Get the supported interfaces return new String[10]; } public String getAgentMetaData() throws NotConnectedException { if(this.getName() == null) { new Exception("Agent Name required for querying meta data"); } try { agentMetadata = ((AgentController)this.getAgentController()).getAgentMetadata(this.getName()); return agentMetadata; } catch(NotConnectedException e) { throw new NotConnectedException(); } } public int getAgentMode() { return agentMode.getValue(); } /** * Get the Agent reference mode - Observer or Controller * @return int - TPTPAgentAccess */ public void setAgentMode(TPTPAgentAccess agentMode) { this.agentMode = agentMode; } public boolean requestAccess(org.eclipse.tptp.platform.execution.util.TPTPAgentAccess accessMode) { return true; } }