public List removePendingMessages(MessageTemplate template) { synchronized (pendingCommands) { List messages = new ArrayList(); List commands = new ArrayList(); Enumeration e = pendingCommands.elements(); while (e.hasMoreElements()) { PostponedCommand pc = (PostponedCommand) e.nextElement(); Command c = pc.getCommand(); if (c.getCode() == FrontEndSkel.MESSAGE_IN) { ACLMessage msg = (ACLMessage) c.getParamAt(0); if (template.match(msg)) { Object[] oo = new Object[] {msg, c.getParamAt(1)}; messages.add(oo); commands.add(c); } } } // Remove all the commands carrying matching messages Iterator it = commands.iterator(); while (it.hasNext()) { pendingCommands.remove(it.next()); } // Return the list of matching messages return messages; } }
void initMandatoryServices(List services) throws ServiceException { ServiceDescriptor dsc = startService("jade.core.management.BEAgentManagementService", false); dsc.setMandatory(true); services.add(dsc); dsc = startService("jade.core.messaging.MessagingService", false); dsc.setMandatory(true); services.add(dsc); }
private pikater.ontology.messages.Option convertOption(MyWekaOption _weka_opt) { pikater.ontology.messages.Option opt = new pikater.ontology.messages.Option(); Interval interval = null; opt.setMutable(_weka_opt.mutable); interval = new Interval(); interval.setMin(_weka_opt.lower); interval.setMax(_weka_opt.upper); opt.setRange(interval); if (_weka_opt.set != null) { // copy array to List List set = new ArrayList(); for (int i = 0; i < _weka_opt.set.length; i++) { set.add(_weka_opt.set[i]); } opt.setSet(set); } opt.setIs_a_set(_weka_opt.isASet); interval = new Interval(); interval.setMin(_weka_opt.numArgsMin); interval.setMax(_weka_opt.numArgsMax); opt.setNumber_of_args(interval); opt.setData_type(_weka_opt.type.toString()); opt.setDescription(_weka_opt.description); opt.setName(_weka_opt.name); opt.setSynopsis(_weka_opt.synopsis); opt.setDefault_value(_weka_opt.default_value); opt.setValue(_weka_opt.default_value); return opt; }
public void doNotSniff(String agentName) { String realName = checkString(agentName); agent = new Agent(realName); noSniffedAgents.add(agent); mainPanel.panelcan.canvAgent.removeAgent(agent.agentName); mainPanel.panelcan.canvAgent.repaintNoSniffedAgent(agent); mySniffer.sniffMsg(noSniffedAgents, Sniffer.SNIFF_OFF); // Sniff the Agents noSniffedAgents.clear(); }
/** returns the results of an action requested. */ public List getResult() throws FIPAException, NotYetReady { if (notYetReady) throw new NotYetReady(); if (lastMsg.getPerformative() != ACLMessage.INFORM) throw new FIPAException(lastMsg); Result r = AppletRequestProto.extractContent(lastMsg.getContent(), (SLCodec) c, o); Iterator i = r.getItems().iterator(); // this is the set of DFAgentDescription List l = new ArrayList(); while (i.hasNext()) l.add(i.next()); return l; }
private String[] parseAddressList(String toParse) { StringTokenizer lexer = new StringTokenizer(toParse, ADDR_LIST_DELIMITERS); List addresses = new ArrayList(); while (lexer.hasMoreTokens()) { String tok = lexer.nextToken(); addresses.add(tok); } Object[] objs = addresses.toArray(); String[] result = new String[objs.length]; for (int i = 0; i < result.length; i++) { result[i] = (String) objs[i]; } return result; }
Object processInformation(Information info) { // ------------------------------------------- Account acc = (Account) accounts.get(info.getAccountId()); if (acc == null) return newProblem(ACCOUNT_NOT_FOUND); java.util.Date date = new java.util.Date(); Operation op = new Operation(); // <-- Apply admin charge op.setType(ADMIN); op.setAmount(info.getType() == BALANCE ? BAL_CHARGE : OPER_CHARGE); acc.setBalance(acc.getBalance() - op.getAmount()); op.setBalance(acc.getBalance()); op.setAccountId(acc.getId()); op.setDate(date); List l = (List) operations.get(acc.getId()); l.add(op); operations.put(acc.getId(), l); if (info.getType() == BALANCE) return acc; if (info.getType() == OPERATIONS) return l; return null; }
Object processOperation(MakeOperation mo) { // ------------------------------------------- Account acc = (Account) accounts.get(mo.getAccountId()); if (acc == null) return newProblem(ACCOUNT_NOT_FOUND); if (mo.getAmount() <= 0) return newProblem(ILLEGAL_OPERATION); if (mo.getType() != DEPOSIT && mo.getType() != WITHDRAWAL) return null; if (mo.getType() == DEPOSIT) acc.setBalance(acc.getBalance() + mo.getAmount()); else if (mo.getType() == WITHDRAWAL) { if (mo.getAmount() > acc.getBalance()) return newProblem(NOT_ENOUGH_MONEY); acc.setBalance(acc.getBalance() - mo.getAmount()); } Operation op = new Operation(); op.setType(mo.getType()); op.setAmount(mo.getAmount()); op.setAccountId(acc.getId()); op.setDate(new java.util.Date()); List l = (List) operations.get(acc.getId()); l.add(op); operations.put(acc.getId(), l); return acc; }
public void fillWekaInstances(weka.core.Instances winsts) { // set name setName(winsts.relationName()); // set attributes List onto_attrs = new ArrayList(); for (int i = 0; i < winsts.numAttributes(); i++) { Attribute a = new Attribute(); a.fillWekaAttribute(winsts.attribute(i)); onto_attrs.add(a); } setAttributes(onto_attrs); // set instances List onto_insts = new ArrayList(); for (int i = 0; i < winsts.numInstances(); i++) { Instance inst = new Instance(); weka.core.Instance winst = winsts.instance(i); List instvalues = new ArrayList(); List instmis = new ArrayList(); for (int j = 0; j < winst.numValues(); j++) { if (winst.isMissing(j)) { instvalues.add(new Double(0.0)); instmis.add(new Boolean(true)); } else { instvalues.add(new Double(winst.value(j))); instmis.add(new Boolean(false)); } } inst.setValues(instvalues); inst.setMissing(instmis); onto_insts.add(inst); } setInstances(onto_insts); setClass_index(winsts.classIndex()); }
public void addWeightedDescriptors(WeightedDescriptor elem) { weightedDescriptors.add(elem); pcs.firePropertyChange("weightedDescriptors", oldList, this.weightedDescriptors); }
/** * Add a content language name to the <code>languages</code> slot collection of this object. * * @param l The content language name to add to the collection. */ public void addLanguages(String l) { language.add(l); }
public void addDescribedBy(Object elem) { describedBy.add(elem); }
@Override protected Agent chooseBestAgent(Data data) { Metadata metadata = data.getMetadata(); GetAllMetadata gm = new GetAllMetadata(); gm.setResults_required(true); // 1. choose the nearest training data List allMetadata = DataManagerService.getAllMetadata(this, gm); // set the min, max instances and attributes first Iterator itr = allMetadata.iterator(); while (itr.hasNext()) { Metadata next_md = (Metadata) itr.next(); int na = next_md.getNumber_of_attributes(); minAttributes = Math.min(minAttributes, na); maxAttributes = Math.max(maxAttributes, na); int ni = next_md.getNumber_of_instances(); minInstances = Math.min(ni, minInstances); maxInstances = Math.max(ni, maxInstances); } ArrayList<MetadataDistancePair> distances = new ArrayList<MetadataDistancePair>(); itr = allMetadata.iterator(); while (itr.hasNext()) { Metadata next_md = (Metadata) itr.next(); double dNew = distance(metadata, next_md); distances.add(new MetadataDistancePair(next_md, dNew)); } Collections.sort(distances); List agents = new LinkedList(); for (int i = 0; i < M; i++) { log(distances.get(i).m.getExternal_name() + ": " + distances.get(i).d); List ag = DataManagerService.getTheBestAgents(this, distances.get(i).m.getInternal_name(), N); Iterator it = ag.iterator(); while (it.hasNext()) { agents.add(it.next()); } } HashMap<String, Integer> counts = new HashMap<String, Integer>(); Iterator it = agents.iterator(); while (it.hasNext()) { Agent a = (Agent) it.next(); if (counts.containsKey(a.getType())) { counts.put(a.getType(), counts.get(a.getType()) + 1); } else { counts.put(a.getType(), 1); } } int maxCount = 0; String bestAgentType = null; for (String s : counts.keySet()) { log(s + ": " + counts.get(s)); if (counts.get(s) > maxCount) { maxCount = counts.get(s); bestAgentType = s; } } log("Best agent: " + bestAgentType); ArrayList<Agent> bestAgentOptions = new ArrayList<Agent>(); it = agents.iterator(); while (it.hasNext()) { Agent a = (Agent) it.next(); if (a.getType().equals(bestAgentType)) { bestAgentOptions.add(a); } } List optionSamples = getAgentOptions(bestAgentType); List options = new LinkedList(); it = optionSamples.iterator(); while (it.hasNext()) { Option o = (Option) it.next(); Option newOpt = o.copyOption(); // ignore boolean and set options for now, set their value to the one of the best agent on // closest file if (o.getData_type().equals("BOOLEAN") || o.getData_type().equals("MIXED")) { if (bestAgentOptions.get(0).getOptionByName(o.getName()) == null) { continue; } newOpt.setValue(bestAgentOptions.get(0).getOptionByName(o.getName()).getValue()); } else { double sum = 0; int count = 0; String optionName = o.getName(); for (Agent a : bestAgentOptions) { if (a.getOptionByName(optionName) != null) { sum += Double.parseDouble(a.getOptionByName(optionName).getValue()); } count++; } double avg = sum / count; double stdDev = 0; for (Agent a : bestAgentOptions) { if (a.getOptionByName(optionName) != null) { stdDev += Math.pow(Double.parseDouble(a.getOptionByName(optionName).getValue()) - avg, 2); } } stdDev = Math.sqrt(stdDev / count); if (stdDev > 0) { newOpt.setValue("?"); newOpt.setUser_value("?"); newOpt.setMutable(true); Interval range = new Interval(); range.setMin((float) Math.max(avg - 2 * stdDev, o.getRange().getMin())); range.setMax((float) Math.min(avg + 2 * stdDev, o.getRange().getMax())); newOpt.setRange(range); } else { if (o.getData_type().equals("FLOAT")) { newOpt.setValue(Double.toString(avg)); } if (o.getData_type().equals("INT")) { newOpt.setValue(Integer.toString((int) avg)); } } } options.add(newOpt); } Agent agent = new Agent(); agent.setName(null); agent.setType(bestAgentType); agent.setOptions(options); return agent; }
/** * @param out * @param parser * @param sender the sender of the message * @param receiver the receiver of the message * @param actionName the action requested * @param parentDF the df to wich request an action (used for federate action) */ JADEAppletRequestProto( DFAppletCommunicator communicator, AID receiver, String actionName, Object description, Object parentDF, SearchConstraints constraints) throws FIPAException { super(communicator.getStream(), communicator.getParser(), new ACLMessage(ACLMessage.REQUEST)); this.gui = communicator.getGUI(); this.dfApplet = communicator; ACLMessage request = new ACLMessage(ACLMessage.REQUEST); // request.setSender(sender); request.addReceiver(receiver); request.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST); request.setLanguage(FIPANames.ContentLanguage.FIPA_SL); request.setOntology(DFAppletOntology.NAME); request.setReplyWith("rw" + (new Date()).getTime()); request.setConversationId("conv" + (new Date()).getTime()); this.reqMsg = (ACLMessage) request.clone(); this.action = actionName; this.receiver = receiver; this.parent = (AID) parentDF; Action act = new Action(); act.setActor(receiver); if (actionName.equalsIgnoreCase(DFAppletVocabulary.FEDERATE)) { Federate action = new Federate(); action.setDf((AID) parentDF); action.setDescription((DFAgentDescription) description); act.setAction(action); } else if (actionName.equalsIgnoreCase(DFAppletVocabulary.GETDESCRIPTION)) act.setAction(new GetDescription()); else if (actionName.equalsIgnoreCase(DFAppletVocabulary.GETPARENTS)) act.setAction(new GetParents()); else if (actionName.equalsIgnoreCase(DFAppletVocabulary.GETDESCRIPTIONUSED)) { GetDescriptionUsed action = new GetDescriptionUsed(); action.setParentDF((AID) parentDF); act.setAction(action); } else if (actionName.equalsIgnoreCase(DFAppletVocabulary.DEREGISTERFROM)) { DeregisterFrom action = new DeregisterFrom(); action.setDf((AID) parentDF); action.setDescription((DFAgentDescription) description); act.setAction(action); } else if (actionName.equalsIgnoreCase(DFAppletVocabulary.REGISTERWITH)) { RegisterWith action = new RegisterWith(); action.setDf((AID) parentDF); action.setDescription((DFAgentDescription) description); act.setAction(action); } else if (actionName.equalsIgnoreCase(DFAppletVocabulary.SEARCHON)) { SearchOn action = new SearchOn(); action.setDf((AID) parentDF); action.setDescription((DFAgentDescription) description); action.setConstraints(constraints); act.setAction(action); } else if (actionName.equalsIgnoreCase(DFAppletVocabulary.MODIFYON)) { ModifyOn action = new ModifyOn(); action.setDf((AID) parentDF); action.setDescription((DFAgentDescription) description); act.setAction(action); } else throw new UnsupportedFunction(); // initialize SL0 Codec and FIPAAgentManagementOntology // FIXME for applet I have not the agent c = sender.lookupLanguage(SL0Codec.NAME); // if (c == null) c = new SLCodec(); // Write the action in the :content slot of the request List content = new ArrayList(); content.add(act); try { String s = ((SLCodec) c).encode(o, (AbsContentElement) o.fromObject(act)); this.reqMsg.setContent(s); } catch (OntologyException oe) { oe.printStackTrace(); throw new FIPAException("Ontology error: " + oe.getMessage()); } catch (Exception e) { e.printStackTrace(); } }
@Override protected void getParameters() { // fills the global Options vector System.out.println(getLocalName() + ": The options are: "); String optPath = System.getProperty("user.dir") + getOptFileName(); agent_options = new pikater.ontology.messages.Agent(); agent_options.setName(getLocalName()); agent_options.setType(getAgentType()); // read options from file try { /* Sets up a file reader to read the options file */ FileReader input = new FileReader(optPath); /* * Filter FileReader through a Buffered read to read a line at a * time */ BufferedReader bufRead = new BufferedReader(input); String line; // String that holds current file line int count = 0; // Line number of count // Read first line line = bufRead.readLine(); count++; // list of ontology.messages.Option List _options = new ArrayList(); // Read through file one line at time. Print line # and line while (line != null) { System.out.println(" " + count + ": " + line); // parse the line String delims = "[ ]+"; String[] params = line.split(delims, 7); if (params[0].equals("$")) { MyWekaOption.dataType dt = MyWekaOption.dataType.BOOLEAN; if (params[2].equals("boolean")) { dt = MyWekaOption.dataType.BOOLEAN; } if (params[2].equals("float")) { dt = MyWekaOption.dataType.FLOAT; } if (params[2].equals("int")) { dt = MyWekaOption.dataType.INT; } if (params[2].equals("mixed")) { dt = MyWekaOption.dataType.MIXED; } String[] default_options = ((Classifier) getModelObject()).getOptions(); Enumeration en = ((Classifier) getModelObject()).listOptions(); while (en.hasMoreElements()) { Option next = (weka.core.Option) en.nextElement(); String default_value = "False"; for (int i = 0; i < default_options.length; i++) { if (default_options[i].equals("-" + next.name())) { if (default_options[i].startsWith("-")) { // if the next array element is again an // option name, // (or it is the last element) // => it's a boolean parameter if (i == default_options.length - 1) { default_value = "True"; } else { // if // (default_options[i+1].startsWith("-")){ if (default_options[i + 1].matches("\\-[A-Z]")) { default_value = "True"; } else { default_value = default_options[i + 1]; } } } } } if ((next.name()).equals(params[1])) { MyWekaOption o; if (params.length > 4) { o = new MyWekaOption( next.description(), next.name(), next.numArguments(), next.synopsis(), dt, new Integer(params[3]).intValue(), new Integer(params[4]).intValue(), params[5], default_value, params[6]); } else { o = new MyWekaOption( next.description(), next.name(), next.numArguments(), next.synopsis(), dt, 0, 0, "", default_value, ""); } // convert&save o to options vector _options.add(convertOption(o)); } } } line = bufRead.readLine(); count++; } agent_options.setOptions(_options); bufRead.close(); } catch (ArrayIndexOutOfBoundsException e) { /* * If no file was passed on the command line, this exception is * generated. A message indicating how to the class should be called * is displayed */ System.out.println("Usage: java ReadFile filename\n"); } catch (Exception e) { e.printStackTrace(); System.err.println(getLocalName() + ": Reading options from .opt file failed."); } // Save the agent's options /* * Enumeration en = cls.listOptions(); * * while(en.hasMoreElements()){ Option next = * (weka.core.Option)en.nextElement(); * System.out.println(" "+next.description()+ ", " +next.name()+ ", " * +next.numArguments()+ ", " +next.synopsis() ); System.out.println(); * } */ /* * System.out.println("MyWekaOptions: "); for (Enumeration e = * Options.elements() ; e.hasMoreElements() ;) { MyWekaOption next = * (MyWekaOption)e.nextElement(); System.out.print(next.name+" "); * System.out.print(next.lower+" "); System.out.print(next.upper+" "); * System.out.print(next.type+" "); * System.out.print(next.numArgsMin+" "); * System.out.print(next.numArgsMax+" "); System.out.println(next.set); * System.out.println("------------"); } */ } // end getParameters
public void addScore(Object elem) { score.add(elem); pcs.firePropertyChange("score", oldList, this.score); }
public void addScore(Object elem) { score.add(elem); }
// remove this method when the bug with opts parsing is removed List readOptionsFromFile(String agentName) { String optPath = System.getProperty("user.dir") + System.getProperty("file.separator") + "options" + System.getProperty("file.separator") + agentName + ".opt"; // read options from file try { /* Sets up a file reader to read the options file */ FileReader input = new FileReader(optPath); /* * Filter FileReader through a Buffered read to read a line at a * time */ BufferedReader bufRead = new BufferedReader(input); String line; // String that holds current file line int count = 0; // Line number of count // Read first line line = bufRead.readLine(); count++; // list of ontology.messages.Option List _options = new jade.util.leap.ArrayList(); // Read through file one line at time. Print line # and line while (line != null) { // parse the line String delims = "[ ]+"; String[] params = line.split(delims, 11); for (int i = 0; i < params.length; i++) { if (params[i].equals("MAXINT")) { params[i] = Integer.toString(Integer.MAX_VALUE); } } if (params[0].equals("$")) { String dt = null; if (params[2].equals("boolean")) { dt = "BOOLEAN"; } if (params[2].equals("float")) { dt = "FLOAT"; } if (params[2].equals("int")) { dt = "INT"; } if (params[2].equals("mixed")) { dt = "MIXED"; } float numArgsMin; float numArgsMax; float rangeMin = 0; float rangeMax = 0; String range; List set = null; if (dt.equals("BOOLEAN")) { numArgsMin = 1; numArgsMax = 1; range = null; } else { numArgsMin = Float.parseFloat(params[3]); numArgsMax = Float.parseFloat(params[4]); range = params[5]; if (range.equals("r")) { rangeMin = Float.parseFloat(params[6]); rangeMax = Float.parseFloat(params[7]); } if (range.equals("s")) { set = new jade.util.leap.ArrayList(); String[] s = params[6].split("[ ]+"); for (int i = 0; i < s.length; i++) { set.add(s[i]); } } } Option o = new Option( params[1], dt, numArgsMin, numArgsMax, range, rangeMin, rangeMax, set, params[params.length - 3], params[params.length - 2], params[params.length - 1]); _options.add(o); } line = bufRead.readLine(); count++; } bufRead.close(); return _options; } catch (IOException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } return null; }
/** * Add a service description to the <code>service</code> slot collection of this object. * * @param a The service description to add to the collection. */ public void addServices(ServiceDescription a) { services.add(a); }
public void addApliesTo(Object elem) { apliesTo.add(elem); }
/** Add a sub behaviour to this <code>SequentialBehaviour</code> */ public void addSubBehaviour(Behaviour b) { subBehaviours.add(b); b.setParent(this); b.setAgent(myAgent); }
/** * Add a protocol name to the <code>protocols</code> slot collection of this object. * * @param ip The protocol name to add to the collection. */ public void addProtocols(String ip) { interactionProtocols.add(ip); }
// For persistence service private void setSubBehaviours(Behaviour[] behaviours) { subBehaviours.clear(); for (int i = 0; i < behaviours.length; i++) { subBehaviours.add(behaviours[i]); } }
private void postponeAfterFrontEndSynch(ACLMessage msg, String sender) { // No need for synchronization since this is called within a synchronized block fronEndSynchBuffer.add(new MessageSenderPair(msg, sender)); }
/** * Add an ontology name to the <code>ontologies</code> slot collection of this object. * * @param o The ontology name to add to the collection. */ public void addOntologies(String o) { ontology.add(o); }