i have coded a database update software which allows me to deploy a jade mobile agent in order to update the database. In order for it to run, i need to launch it using the AMS gui. I wanted to be able to launch it from gui. I have now done a nice swing gui and i only need to know the code which allows me to launch my mobile agent when the "Update" button is clicked. What is the code? Thanks in advance.
To launch an agent or do whatever related to JADE you need to write YOUR code using JADE libraries and API, irrespective of what Front End you have used (Swing in this case)
One suggestion would be, to keep the modularity, is create another file which does one of many such operations you want, and let your Swing GUI interact (say via sockets) to that file, triggering your operation.
That file, which would act as a server, would listen to the front end and do the respective work. But all commands are to be coded using JADE API. One such code is:
ContainerController cc = Runtime.instance().createAgentContainer(newProfileImpl());
Object arguments[] = new Object[1];``arguments[0]=new Object();
AgentController dummy = cc.createNewAgent("mob2","mobiletrial", arguments);
dummy.start();
This is a method I wrote for launching one agent from another.You'll have to edit it for multiple container use.
void launchAgent( final String AgentName, final String AgentType)
{
log(Level.FINER,"attempting to launch angent name: "+AgentName+" type: "+AgentType);
CreateAgent ca = new CreateAgent();
ca.setAgentName(AgentName);
ca.setClassName(AgentType);
ca.setContainer(new ContainerID(AgentContainer.MAIN_CONTAINER_NAME, null));
Action actExpr = new Action(this.getAMS(), ca);
ACLMessage request = new ACLMessage(ACLMessage.REQUEST);
request.addReceiver(this.getAMS());
request.setOntology(JADEManagementOntology.getInstance().getName());
request.setLanguage(FIPANames.ContentLanguage.FIPA_SL);
request.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
try {
getContentManager().fillContent(request, actExpr);
addBehaviour(new AchieveREInitiator(this, request) {
protected void handleInform(ACLMessage inform) {
log(Level.INFO,"Agent successfully created name:"+AgentName+" type: "+AgentType);
}
protected void handleFailure(ACLMessage failure) {
log(Level.SEVERE,"Agent launch failed name: "+AgentName+" type: "+AgentType);
}
} );
}
catch (Exception e) {
e.printStackTrace();
}
}
Related
I am making a personal planning program. I utilize XML documents to store user data and login data. This does not utilize a server and all accounts created in the program are localized to the computer it is stored on (in the XML documents.)
In the login XML document, I keep track of the users that are logged in so that one user can't have two windows at the same time to prevent any conflicts with data. This feature runs smoothly and I have no problem with it.
The only thing I want to know is if there is some way to catch an unexpected shut down of a program (such as a task-manager close or a forced close when shutting down the computer) so that I can "log" the user off of the XML document. Otherwise the user would never be able to get back on after an unexpected program close without going into the XML document and deleting the username from the logged in list.
It seems a shutdown hook does not work well with the event queue for a java GUI. much like this thread
I tried setting up my code exactly as shown and the shutdown hook doesn't work for me either. Are there any suggestions for ways of catching an unexpected shutdown without shutdown hooks?
this is my code:
import java.awt.EventQueue;
public class Gui {
private static Controller controller;
public static void main (String[] args) {
controller = new Controller();
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
controller.saveState();
controller.logUserOut();
}
});
EventQueue.invokeLater(
new Runnable() {
public void run() {
controller.start();
}
});
}
}
This is a closer look at my controller that logs the user out
public void logUserOut() {
loginDatabase.logUserOut(username);
saveLoginState();
}
All loginDatabase does is removes that username from the list of logged in users so that user is free to log in again
public void saveLoginState() {
XStream xStream = new XStream(new DomDriver());
OutputStream outFile;
try {
String filePath = "data" + File.separator + "loginDatabase.xml";
outFile = new BufferedOutputStream(new FileOutputStream(filePath));
xStream.toXML(loginDatabase, outFile); // This writes your state to the outputFile;
outFile.close(); //close the writer
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This is my process for writing on the login state xml file. I suspect it might be too long for a Shutdown Hook even if it were actually being called as I expect.
Any suggestions? I thought for a long time about possibly using simple variables to solve the problem but because I have the program set so that the user can be logged into multiple accounts, the use of variables is impossible.
Also, will the controller object contained in the scope of the shutdown hook be the same controller that is modified in the event queue scope?
The shutdown hook can be a solution here. For details see e.g. this answer: https://stackoverflow.com/a/2541618/2045440
[Off topic] However, if you're at risk that unexpected termination of your application can result in lost of important data, maybe it would be worth to consider the more persistent way of processing this data (autosaving, backup files etc).
I resolved the problem by checking the task manager of the operating system. It allowed me to see if the user the xml document said was logged in actually had a program open. If not then I knew there was a problem. This is a fix for my particular program but it might be a help for others as well.
The link to that thread is here.
I did this program that opens multiple link with default browser:
ArrayList<String> linkList = new ArrayList<>();
for (int i = 0; i < linkList.size(); i++) {
ClassRunnable_OpenLink obj = new ClassRunnable_OpenLink ( linkList.get(i) );
Thread thread = new Thread(obj);
thread.start();
}
private class ClassRunnable_OpenLink implements Runnable {
private URL link;
private String string;
public ClassRunnable_OpenLink (String string) {
this.string = string;
}
private void OpenWithBrowser () {
try {
link = new URL ( string );
edu.stanford.ejalbert.BrowserLauncher launcher = null;
try {
launcher = new BrowserLauncher(null);
} catch ( BrowserLaunchingInitializingException | UnsupportedOperatingSystemException ex) { }
launcher.openURLinBrowser( link );
} catch ( MalformedURLException ex | IOException | URISyntaxException ex) { }
}
#Override
public void run() {
OpenWithBrowser( );
}
}
This works great only if browser (say it's firefox) is already opened, but if it's not, my program only opens the first link and then I have a firefox message that tells me the the browser is still running so I need to close it first.
Same thing with chromium.
So I thought, if I had a way to check when the browser is closed I could use ProcessBuilder to open new firefox process, but I don't know if it's the best way to do this. Besides my java program allows user to select default browser so it could be complicated to use ProcessBuilder in that case.
So do you a have any idea to solve my problem? Maybe I could set a delay between each Thread in this way the system has the time to execute browser process first time, then opening first link and after the browser is running, opening other links, but how about the delay time in seconds? I'm not able to know the time that browser needs to open so it's not a good idea.
I hope you can help me. Thanks
Since java 6 you don't have to use 3rd party implementations to open a webpage with the standard browser. Try
java.awt.Desktop.getDesktop().browse(uri);
Since this maps to the underlying OS functions chances are high multiple calls will work as expected.
A workaround to this (without knowing your exact expectations), could be to do the following:
After first URL open, you could build a delay of for example 10 seconds.
Then in any consecutive URL openings, you can assume that the browser is now surely open, and start opening the next URL's fast after each other.
One note though: Always add some delay to opening URL's (not sure if your framework already does this), because else the browser might crash from the number of URL openings.
UPDATE: You say that Thread.sleep() causes your program to block, this should never happen.
You should always seperate long-during actions from the rest of your program (The (Graphical) User Interface).
So it would be better to write your 'URL opener facility' in another thread.
You can read more about that here: http://docs.oracle.com/javase/tutorial/essential/concurrency/
I'm executing a Perl script via "Runtime.getRuntime().exec("perl C:/script.pl")"
as part of a Jbutton action listener. I would like to be able to click the button twice and get two instances of the same Perl script running. The script is reading in a text file so it acts a little differently depending on the text file the second time it is started but in general the script does the same thing.
I've tried to combat this by wrapping the runtime command in a new thread and executing a ".run()" on it each time the button is pressed but this only seems to interrupt the first instance and start the new one. There seems to be no way to execute two of the same Perl script in parallel. Any ideas on how I can accomplish this?
ActionListener edit = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
class GetThread implements Runnable {
public void run() {
try {
Runtime.getRuntime().exec("C:/Perl/bin/perl5.16.3.exe C:/Perl/get.pl", null, new File("C:/Perl"));
} catch (IOException e1) {
exceptionLog(e1);
}
}
}
GetThread get = new GetThread();
get.run();
}
}
http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html says
Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.
It may be blocking on your call.
All,
I am creating a palette less eclipse plugin where am adding figures to the custom editor through the contextual menu, but am not finding a way to do it. Can anyone please guide me as to how to go about adding figures to editor dynamically through context menu i.e. adding actions/commands.
Since Eclipse GEF plugin development finds so less examples to look at, I am adding my solution so others find it useful. This code helps to render a node to the editor.
Source code for Action class to render figures to the editor:
public class AddNodeAction extends EditorPartAction
{
public static final String ADD_NODE = "ADDNODE";
public AddNodeAction(IEditorPart editor) {
super(editor);
setText("Add a Node");
setId(ADD_NODE); // Important to set ID
}
public void run()
{
<ParentModelClass> parent= (<ParentModelClass>)getEditorPart().getAdapter(<ParentModelClass>.class);
if (parent== null)
return;
CommandStack command = (CommandStack)getEditorPart().getAdapter(CommandStack.class);
if (command != null)
{
CompoundCommand totalCmd = new CompoundCommand();
<ChildModelToRenderFigureCommand>cmd = new <ChildModelToRenderFigureCommand>(parent);
cmd.setParent(parent);
<ChildModelClass> newNode = new <ChildModelClass>();
cmd.setNode(newNode);
cmd.setLocation(getLocation()); // Any location you wish to set to
totalCmd.add(cmd);
command.execute(totalCmd);
}
}
#Override
protected boolean calculateEnabled()
{
return true;
}
}
I think you need multiple different things here. Please remember that GEF would like you to have proper MVC pattern, where you have your own model, Figures as View and EditParts as controllers.
From the top of my head I would say that you need at least these things:
CreateCommand
contains all model level modifications that you need to
perform to add your new data to your
data model (undoable and transactional)
CreateAction
makes that CreateCommand instance, initializes it with current selection and executes that command in editdomain
ContextMenuProvider
Provides that CreateAction to context menu
If you happen to be using GMF the canonical mechanism will generate the editparts for you automatically when you make the model modifications inside a command, but if you are not using GMF, you must make sure that your own models and editparts are handling and refreshing the new item adding properly.
EDIT:
Ok, here is some code suggestion with playing around with requests.
public void run() {
// Fetch viewer from editor part (might not work, if not, try some other way)
EditPartViewer viewer = (EditPartViewer) part.getAdapter(EditPartViewer.class);
// get Target EditPart that is under the mouse
EditPart targetEditPart = viewer.findObjectAt(getLocation());
// If nothing under mouse, set root item as target (just playing safe)
if(targetEditPart == null)
targetEditPart = viewer.getContents();
// Make and initialize create request with proper information
CreateRequest createReq = new CreateRequest();
createReq.setLocation(getLocation());
createReq.setFactory(new OwnFactoryImplementation());
// Ask from target editpart command for this request
Command command = targetEditPart.getCommand(createReq);
// If command is ok, and it can be executed, go and execute it on commandstack
if(command != null && command.canExecute()) {
viewer.getEditDomain().getCommandStack().execute(command);
}
}
Now what happens is that editpart will be requested for creation, so the action itself doesn't know how the command works, what makes it objective agaist the command.
So to make things work, you need to install new EditPolicy to your EditPart. EditPolicies can be installed on EditParts createDefaultEditPolicies() function. This EditPolicy must react and return command when there is CreateRequest. This way any child can provide own kind of command for creating children for itself.
Here is a good image how it works (controller is EditPart):
Please ask if I can help you some more. I know that this looks bit more complex, but this makes your own life much more easier, and after you have done that, you actually understand Command-Request Pattern quite well, and it can be reused in many different places.
I developed one swing application but each time you run application new window is opened.
I want that if one window is already opened other not allow to open.
Here is an example of a Java Single Application Instance:
A single instance application is one that only allows for 1 of the application to run no matter how many times the user tries to launch.
See also: A shorter example that does not notify the running instance.
The application tries to open a Socket on a specific port. In case another instance of your application is already running, opening the Socket fails.
This should already be sufficient for you, so you would not have to use the part of the code used to register new applications to the first one started.
Using a Socket has one great advantage compared to writing some sort of flag to the filesystem/registry/whatever:
It is removed even if your application crashes.
It actually sounds like you only want one application open at a time. In which case why not take out a file lock or similar when the application runs, and check that on start up. The headache (of course) is clearing up that lock in the event that your program doesn't exit cleanly.
My preferred solution is, as Peter Lang linked to, to use Sockets. When your app starts you can start a server socket listening for incoming connections on localhost (plus port of your choice). Before this happens in your code though you can try and make a connection to the server socket and if it is successful you know there is another instance already open, so you can quit the current instance with an appropriate message.
In your server socket implementation you can also add functionality that on receiving an incoming connection you actually force the current instance of the app to the foreground.
Do you mean run the GUI like a Singleton?, I have done this in the past by making a Static private "view manager" such that it is null and not created or visible until the first time the gui is created, after that just as with a classic singleton, the GUI is set to visible when the app is run again... I have a couple of Frameworks that follow this design--In these frameworks the GUI is not "primary" there are also command line and the like interfaces so the GUI is summoned via the command line...
public class Samp {
JFrame f=new JFrame();
File ff=new File("D:\\a.txt");
FileWriter fw;
public Samp() {
f.setBounds(0, 0, 200, 200);
try {
Scanner sc=new Scanner(ff);
if(!sc.hasNext()) {
fw=new FileWriter(ff);
fw.write("Running");
fw.close();
} else {
System.exit(0);
}
} catch(Exception e) {
System.out.println(e.getMessage());
}
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
try {
Scanner sc = new Scanner(ff);
if(sc.hasNext()) {
fw=new FileWriter(ff);
fw.write("");
fw.close();
}
} catch (Exception ex) { }
}
};
f.setVisible(true);
f.addWindowListener(wndCloser);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]) {
new Samp();
}
}
Use Singletone Pattern as shown in the example!