How to create multiple containers with jade - agent

I want to create 2 containers but the agent of my second container shows a problem
ERROR: Agent robot10 died without being properly terminated !!!
when i delete the second container it works
Runtime Instance = Runtime.instance(); Instance.setCloseVM(true);
ProfileImpl Profile = new ProfileImpl(true);
Profile.setParameter(Profile.CONTAINER_NAME, "Pacman");
Profile.setParameter(Profile.MAIN_HOST, "localhost");
AgentContainer Conteneur = Instance.createAgentContainer(Profile);
for (int i = 1; i <= n; i++) {
AgentController Agent = Conteneur.createNewAgent("robot" + String.valueOf(i), "package1.robot", Parametres1);
Agent.start();
}
AgentContainer Conteneur1 = Instance.createAgentContainer(Profile);
AgentController Agent = Conteneur1.createNewAgent("robot10" , "package1.robot", new Object[] {});
Agent.start();

It is still showing errors
Here is the code
package package1;
import jade.Boot;
import jade.core.AID;
import jade.core.Agent;
import jade.core.Profile;
import static jade.core.Profile.PLATFORM_ID;
import jade.core.ProfileImpl;
import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAException;
import jade.lang.acl.ACLMessage;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;
import jade.wrapper.ContainerController;
import jade.wrapper.StaleProxyException;
import javax.swing.UIManager;
public class launch extends Agent {
static DFAgentDescription agentDescription;private static AID aid;
static ACLMessage message1, message2;
launch() throws FIPAException{
agentDescription = new DFAgentDescription();
agentDescription.setName(getAID());
DFService.register(this, agentDescription);
DFService.register(this, agentDescription);
}
public static void main(String[] args) throws StaleProxyException {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
}
try {
String[] arg = { "-gui","ClusteringAgent:multi.agent_clustering.ClusteringAgent" };
Boot.main(arg);
} catch (Exception e) {
e.printStackTrace();
}
jade.core.Runtime rt = jade.core.Runtime.instance(); rt.setCloseVM(true);
String containerName="Mycontainer1";
ProfileImpl pContainer = new ProfileImpl(true);
pContainer.setParameter(Profile.CONTAINER_NAME,containerName);
System.out.println("Launching container "+pContainer);
ContainerController containerRef = rt.createAgentContainer(pContainer);
AgentController Agent = containerRef.createNewAgent("robot" + String.valueOf(1), "package1.launch", new Object[] { 2});
Agent.start();
//create container2
containerName="Mycontainer2";
pContainer = new ProfileImpl( true);
pContainer.setParameter(Profile.CONTAINER_NAME,containerName);
System.out.println("Launching container "+pContainer);
containerRef = rt.createAgentContainer(pContainer);
AgentController Agent1 = containerRef.createNewAgent("robot" + String.valueOf(2), "package1.launch", new Object[] {2});
Agent.start();
}
}
the error showing is :
Exception in thread "main" jade.wrapper.StaleProxyException: Illegal access exception in createAgent() [nested java.lang.IllegalAccessException: Class jade.core.management.AgentManagementService$CommandTargetSink can not access a member of class package1.launch with modifiers ""]
at jade.wrapper.ContainerController.createNewAgent(Unknown Source)

There is an error in your code, you do not update the Profile of your containers and use the same Name for 2 different containers, which is wrong.
//create container1
String containerName="Mycontainer1";
ProfileImpl pContainer = new ProfileImpl(PLATFORM_IP, PLATFORM_PORT, PLATFORM_ID);
pContainer.setParameter(Profile.CONTAINER_NAME,containerName);
System.out.println("Launching container "+pContainer);
ContainerController containerRef = rt.createAgentContainer(pContainer);
//create container2
containerName="Mycontainer2";
pContainer = new ProfileImpl(PLATFORM_IP, PLATFORM_PORT, PLATFORM_ID);
pContainer.setParameter(Profile.CONTAINER_NAME,containerName);
System.out.println("Launching container "+pContainer);
containerRef = rt.createAgentContainer(pContainer);
For a running example with 3 containers, see : https://gitlab.com/startjade/startJade

Related

Cisco JTAPI phone register/unregister status

I am using the below code to check the phone status(if phone is up or down). When phone is down sends an alarm. However this doesn't show when 8800 series phones are down. Is there any other method to check the Phone register/unregister status?
#Override public void terminalChangedEvent(TermEv[] eventList) {
if ( eventList != null ) {
for (TermEv eventList1 : eventList) {
if (eventList1 instanceof CiscoTermInServiceEv){
if(terminalInService.test()==true){
LogSQL.removeLog(terminal.getName());
}
System.out.println(terminal.getName());
terminalInService.set();
return;
} else if (eventList1 instanceof CiscoTermOutOfServiceEv &&
terminalInService.test()==true) {
offline();
}
}
}
}
Second Question, I was not able to find the methods or documentation about "com.cisco.cti.util.Condition" class. What does Condition.set() and Condition.test() methods do?
Looks like you have the right general idea - JTAPI should work fine for 88xx models, assuming you have the correct device->user association, and user permissions (Standard CTI Enabled, and Standard CTI Allow Control of Phones supporting Connected Xfer and conf needed for 88xx).
Here is my version working on CUCM 11.5:
package com.mycompany.app;
import com.cisco.jtapi.extensions.*;
import java.util.*;
import javax.telephony.*;
import javax.telephony.events.*;
import javax.telephony.callcontrol.*;
import javax.telephony.callcontrol.events.*;
import com.cisco.cti.util.Condition;
public class DataTerm implements ProviderObserver, TerminalObserver {
public static final int OUT_OF_SERVICE = 0;
public static final int IN_SERVICE = 1;
private Address destAddress;
private CiscoTerminal observedTerminal;
private boolean addressInService;
private boolean terminalInService;
protected int state = OUT_OF_SERVICE;
Condition conditionInService = new Condition();
Provider provider;
public DataTerm(String[] args) {
try {
System.out.println("Initializing Jtapi");
String providerName = "ds-ucm115-1.cisco.com";
String login = "dstaudt";
String passwd = "password";
String dest = "2999";
JtapiPeer peer = JtapiPeerFactory.getJtapiPeer(null);
String providerString = providerName + ";login=" + login + ";passwd=" + passwd;
System.out.println("Opening " + providerString + "...\n");
provider = peer.getProvider(providerString);
provider.addObserver(this);
conditionInService.waitTrue();
this.destAddress = provider.getAddress(dest);
this.observedTerminal = (CiscoTerminal) destAddress.getTerminals()[0];
try {
if (destAddress != null) {
System.out.println("Adding Terminal Observer to Terminal" + observedTerminal.getName());
observedTerminal.addObserver(this);
}
} catch (Exception e) {
}
} catch (Exception e) {
System.out.println("Caught exception " + e);
}
}
public void terminalChangedEvent(TermEv[] events) {
for (int i = 0; i < events.length; i++) {
Terminal terminal = events[i].getTerminal();
switch (events[i].getID()) {
case CiscoTermInServiceEv.ID:
System.out.println("Received " + events[i] + "for " + terminal.getName());
terminalInService = true;
break;
case CiscoTermOutOfServiceEv.ID:
System.out.println("Received " + events[i] + "for " + terminal.getName());
terminalInService = false;
if (state != OUT_OF_SERVICE) { // you only want to notify when you had notified earlier that you are IN_SERVICE
state = OUT_OF_SERVICE;
}
break;
}
}
}
public void providerChangedEvent(ProvEv[] eventList) {
if (eventList != null) {
for (int i = 0; i < eventList.length; i++) {
if (eventList[i] instanceof ProvInServiceEv) {
conditionInService.set();
}
}
}
}
}
The "com.cisco.cti.util.Condition" seems to be based on this pattern:
public interface Condition
Condition factors out the Object monitor methods (wait, notify and notifyAll) into distinct objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary Lock implementations. Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods.
Conditions (also known as condition queues or condition variables) provide a means for one thread to suspend execution (to "wait") until notified by another thread that some state condition may now be true. Because access to this shared state information occurs in different threads, it must be protected, so a lock of some form is associated with the condition. The key property that waiting for a condition provides is that it atomically releases the associated lock and suspends the current thread, just like Object.wait.
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html

How to get list of Named range,sheet name and referance formuls using XSSF and SAX (Event API) for large excel file

I'm tring to to read large excel file (size~10MB,.xlsx) .
I'm using below code
Workbook xmlworkbook =WorkbookFactory.create(OPCPackage.openOrCreate(root_path_name_file));
But it's showing Heap memory issue.
I have also seen other solution on StackOverflow some of them given to increase the JVM but i dont want to increase jvm.
Issue 1) We can't use SXSSF (Streaming Usermodel API) because this is only for writing or creating new workbook.
My sole objective to get the number of NamedRange of sheet, Total number of sheet and their sheet name for large excel file.
If the requirement is only to get the named ranges and sheet names, then only the /xl/workbook.xml from the *.xlsx ZIPPackage must be parsed since those informations are all stored there.
This is possible by getting the appropriate PackagePart and parsing the XML from this. For parsing XML my favorite is using StAX.
Example code which gets all sheet names and defined named ranges:
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.XMLEvent;
import javax.xml.namespace.QName;
import java.io.File;
import java.util.regex.Pattern;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class StaxReadOPCPackageParts {
public static void main(String[] args) {
try {
File file = new File("file.xlsx");
OPCPackage opcpackage = OPCPackage.open(file);
//get the workbook package part
PackagePart workbookpart = opcpackage.getPartsByName(Pattern.compile("/xl/workbook.xml")).get(0);
//create reader for package part
XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(workbookpart.getInputStream());
List<String> sheetNames = new ArrayList<>();
Map<String, String> definedNames = new HashMap<>();
boolean isInDefinedName = false;
String sheetName = "";
String definedNameName = "";
StringBuffer definedNameFormula = new StringBuffer();
while(reader.hasNext()){ //loop over all XML in workbook.xml
XMLEvent event = (XMLEvent)reader.next();
if(event.isStartElement()) {
StartElement startElement = (StartElement)event;
QName startElementName = startElement.getName();
if(startElementName.getLocalPart().equalsIgnoreCase("sheet")) { //start element of sheet definition
Attribute attribute = startElement.getAttributeByName(new QName("name"));
sheetName = attribute.getValue();
sheetNames.add(sheetName);
} else if (startElementName.getLocalPart().equalsIgnoreCase("definedName")) { //start element of definedName
Attribute attribute = startElement.getAttributeByName(new QName("name"));
definedNameName = attribute.getValue();
isInDefinedName = true;
}
} else if(event.isCharacters() && isInDefinedName) { //character content of definedName == the formula
definedNameFormula.append(((Characters)event).getData());
} else if(event.isEndElement()) {
EndElement endElement = (EndElement)event;
QName endElementName = endElement.getName();
if(endElementName.getLocalPart().equalsIgnoreCase("definedName")) { //end element of definedName
definedNames.put(definedNameName, definedNameFormula.toString());
definedNameFormula = new StringBuffer();
isInDefinedName = false;
}
}
}
opcpackage.close();
System.out.println("Sheet names:");
for (String shName : sheetNames) {
System.out.println("Sheet name: " + shName);
}
System.out.println("Named ranges:");
for (String defName : definedNames.keySet()) {
System.out.println("Name: " + defName + ", Formula: " + definedNames.get(defName));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Updating UI from a background thread in ScalaFX

Here is the code:
import javafx.event
import javafx.event.EventHandler
import scalafx.application.{Platform, JFXApp}
import scalafx.application.JFXApp.PrimaryStage
import scalafx.event.ActionEvent
import scalafx.scene.Scene
import scalafx.scene.control.{Button, Label}
import scalafx.Includes._
import scalafx.scene.layout.{VBox, HBox}
object Blocking extends JFXApp {
val statusLbl = new Label("Not started...")
val startBtn = new Button("Start") {
onAction = (e: ActionEvent) => startTask
}
val exitBtn = new Button("Exit") {
onAction = (e: ActionEvent) => stage.close()
}
val buttonBox = new HBox(5, startBtn, exitBtn)
val vBox = new VBox(10, statusLbl, buttonBox)
def startTask = {
val backgroundThread = new Thread {
setDaemon(true)
override def run = {
runTask
}
}
backgroundThread.start()
}
def runTask = {
for(i <- 1 to 10) {
try {
val status = "Processing " + i + " of " + 10
Platform.runLater(() => {
statusLbl.text = status
})
println(status)
Thread.sleep(1000)
} catch {
case e: InterruptedException => e.printStackTrace()
}
}
}
stage = new PrimaryStage {
title = "Blocking"
scene = new Scene {
root = vBox
}
}
}
When the "start" button is pressed, the status label should be updated 10 times, but it is not. From the console you can see the background thread is actually updating the status, but these are not reflected in the UI. Why?
The problem is with the invocation of Platform.runLater. To make it work change it to:
Platform.runLater {
statusLbl.text = status
}
runLater[R](op: => R) takes as an argument a code block that returns a value of type R. You were passing a code block defining an anonymous function. runLater was creating a function, not executing it.

Apache Thrift RejectedExecutionException

My application consists of PHP client and Java backend wired by Apache Thrift, and I faced with problem with Thrift thread pool.
In case I run PHP tests which send requests via Thrift to backend I get an exception
TSocket: timed out reading 4 bytes from localhost:34567
And at the same time I see the following in logs on Java side:
java.util.concurrent.RejectedExecutionException: Task org.apache.thrift.server.TThreadPoolServer$WorkerProcess#17a0d6f rejected from java.util.concurrent.ThreadPoolExecutor#80080[Running, pool size = 50, active threads = 50, queued tasks = 0, completed tasks = 0]
So from my point of view it means that single-threaded synchronous PHP application uses all the configured threads (50), and it's strange.
I use Apache Thrift 0.9.0, PHP 5.4.13 and Java 1.7.0_45
Java server code:
public class ThriftServer implements TransportServer {
private static Logger logger = LoggerFactory.getLogger(ThriftServer.class);
private final TServer server;
private final SprootService service;
private final int port;
public ThriftServer(Integer thriftPort) throws IOException, ThriftException, ConfigurationException, ConfigValidationException {
this.service = new SprootService();
this.port = thriftPort;
try {
TProcessor processor = new TSprootService.Processor<SprootService>(service);
TServerSocket socket = new TServerSocket(port);
TBinaryProtocol.Factory protocolFactory = new TBinaryProtocol.Factory(true, true);
ThreadPoolServerArgs targs = new ThreadPoolServerArgs(socket, processor, protocolFactory, 5, 50);
this.server = new TThreadPoolServer(targs);
} catch (TTransportException tte) {
throw new ThriftException("Exception has occured during attempt to create Thrift server on port " + port, tte);
}
}
public void start() {
logger.info("Thrift server is started on port " + port);
System.out.println("Thrift server is started on port " + port);
server.serve();
}
}
PHP client code:
class SprootClient {
private $thriftClient = null;
private $mappersRegistry = null;
private $tSocket = null;
public function __construct($host, $port) {
$this->thriftClient = $this->initThriftClient($host, $port);
$this->mappersRegistry = new MappersRegistry();
}
public function __destruct() {
$this->tSocket->close();
}
private function initThriftClient($host, $port) {
settype($port, 'integer');
$this->tSocket = new TSocket($host, $port);
$this->tSocket->setRecvTimeout(3000);
try {
$this->tSocket -> open();
$protocol = new TBinaryProtocol($this->tSocket);
return new TSprootServiceClient($protocol);
} catch (Exception $e) {
throw new SprootClientException($e->getMessage()." ".$e->getTraceAsString());
}
}
private function getThriftClient() {
return $this->thriftClient;
}
public function put($cacheName, $key, $domainObject) {
if ($domainObject == null || $key == null) {
throw new SprootClientException("Both key and value cannot be null or empty");
}
try {
$mapper = $this->mappersRegistry->getDomainMapper($cacheName);
$dataObject = $mapper->toTDataObject($domainObject);
$this->getThriftClient()->put($cacheName, $key, $dataObject);
} catch (Exception $e) {
throw new SprootClientException($e->getMessage()." ".$e->getTraceAsString());
}
}

how reading nutch generated content data on the segment folder using java

I am trying to read the content data inside the segment folder. I think the content data file is written in a custom format
I experimented with nutch's Content class, but it does not recognize the format.
import java.io.IOException;
import org.apache.commons.cli.Options;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.util.NutchConfiguration;
public class ContentReader {
public static void main(String[] args) throws IOException {
// Setup the parser
Configuration conf = NutchConfiguration.create();
Options opts = new Options();
GenericOptionsParser parser = new GenericOptionsParser(conf, opts, args);
String[] remainingArgs = parser.getRemainingArgs();
FileSystem fs = FileSystem.get(conf);
String segment = remainingArgs[0];
Path file = new Path(segment, Content.DIR_NAME + "/part-00000/data");
SequenceFile.Reader reader = new SequenceFile.Reader(fs, file, conf);
Text key = new Text();
Content content = new Content();
// Loop through sequence files
while (reader.next(key, content)) {
try {
System.out.write(content.getContent(), 0,
content.getContent().length);
} catch (Exception e) {
}
}
}
}
org.apache.nutch.segment.SegmentReader
has a map reduce implementation that reads content data in the segment directory.
spark/scala code to read data from the segments content folder.
How I read from the content folder in my project.
I have created a case class page which holds data read from the content folder
case class Page(var url: String, var title: String = null
,var contentType: String = null, var rawHtml: String = null,var language: String = null
,var metadata: Map[String,String])
Code to read from content folder
import org.apache.commons.lang3.StringUtils
import org.apache.hadoop.io.{Text, Writable}
import org.apache.nutch.crawl.{CrawlDatum, Inlinks}
import org.apache.nutch.parse.ParseText
import org.apache.nutch.protocol.Content
val contentDF = spark.sparkContext.sequenceFile(path.contentLocation, classOf[Text], classOf[Writable])
.map { case (x, y) => (x.toString, extract(y.asInstanceOf[Content])) }
/** converts Content object to Page **/
def extract(content: Content): Page = {
try {
val parsed = Page(content.getUrl)
var charset: String = getCharsetFromContentType(content.getContentType)
if (StringUtils.isBlank(charset)) {
charset = "UTF-8"
}
parsed.rawHtml = Try(new String(content.getContent, charset)).getOrElse(new String(content.getContent, "UTF-8"))
parsed.contentType = Try(content.getMetadata.get("Content-Type")).getOrElse("text/html")
// parsed.isHomePage = Boolean.valueOf(content.getMetadata.get("isHomePage"))
parsed.metadata = content.getMetadata.names().map(name => (name,content.getMetadata.get(name))).toMap
Try {
if (StringUtils.isNotBlank(content.getMetadata.get("Content-Language")))
parsed.language = content.getMetadata.get("Content-Language")
else if (StringUtils.isNotBlank(content.getMetadata.get("language")))
parsed.language = content.getMetadata.get("language")
else parsed.language = content.getMetadata.get("lang")
}
parsed
} catch {
case e: Exception =>
LOG.error("ERROR while extracting data from Content ", e)
null
}
}
/**Get Html ContentType **/
def getCharsetFromContentType(contentType: String): String = {
var result: String = "UTF-8"
Try {
if (StringUtils.isNotBlank(contentType)) {
val m = charsetPattern.matcher(contentType)
result = if (m.find) m.group(1).trim.toUpperCase else "UTF-8"
}
}
result
}

Resources