How do intelligent Agents work with data base? - java

I am working with JADE framework and I want to know is there any way for intelligent agents to work with some kind of data base, where they can read from it and write some information?..
I tried to make a connection between excel (using jxl) and my project but there is a problem: below is the code for writing in excel file:
public static void write(String[] args) throws Exception {
// TODO code application logic here
File f = new File("C:\\Users\\Mastisa\\Desktop\\Master.xls");
WritableWorkbook Master = Workbook.createWorkbook(f);
WritableSheet History_Table = Master.createSheet("History_Table", 0);
Label L00 = new Label (0,0,"RUN#");
History_Table.addCell(L00);
Master.write();
System.out.println("finished...");
Master.close();
}
}
but I want agents to do something like this:
Database D;
D.add(myAgent.getLocalName);
but it is not possible as jxl doesn't provide functions for working with agents. and it looks like that everything must be written in that excel file manually.... but it is not what I want.. I want agents comfortably read and write...
Is there any other way?

Yes basically when you create a JADE agent, you can add behaviors to those Agents,
There are several types of behaviors, you should be choosing them based on your requirement. You can find the list of behaviors here
For an Example,
public class MyAgent extends Agent
{
#Override
protected void setup()
{
addBehaviour( new InformBehaviour() );
}
private class InformBehaviour extends CyclicBehaviour
{
//dostuff
}
}
So basic idea is you need to do all these inside a behavior of a agent.
Make sure you choose right behaviour which suites your requirement.

Related

How to make google datastore persistent in java

It's very slow to test datastore api in cloud in my country, I hope a way to test datastore code in local. so I found following code:
package ro.gae
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig
import com.google.appengine.tools.development.testing.LocalServiceTestHelper
/**
* Created by roroco on 8/23/15.
*/
trait LcDatastore {
LocalServiceTestHelper h = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
def iiLcDs() {
h.setUp()
}
def closeLcDs() {
h.tearDown()
}
}
But above code only save records in memory, and these records will disappear after code finish. I hope a way to save records in my disk to simplify my code
update
I hope the way don't need to start dev_server since dev_server need a long startup in java
did you try something like this?
public class MyTestClass {
LocalServiceTestHelper localServiceTestHelper;
#BeforeClass
public void beforeClass(){
LocalDatastoreServiceTestConfig localDatastoreServiceTestConfig = new LocalDatastoreServiceTestConfig();
localDatastoreServiceTestConfig.setBackingStoreLocation("storagefilelocation");
localDatastoreServiceTestConfig.setNoStorage(false);
localServiceTestHelper = new LocalServiceTestHelper(localDatastoreServiceTestConfig);
}
#Test
public void testSomething(){
}
}
edit: By the way, I aggree with #Igor Artamonov that this is very likely a bad idea. It should work though. I can also think of a few things that this could help with; like importing huge datasets into the dev local storage by running a unit test (or any external application).

Creating Annotations in Java like Mockito's before

In processing I have several functions that change the properties of applet to draw stuff, for instance:
public void resetBackground(PApplet pApplet){
pApplet.fill(175);
pApplet.noStroke();
pApplet.rect(0,0,100,100);
}
But I want these functions to preserve the state of the pApplet after the function call, for that I have something like:
public void resetBackground(PApplet pApplet){
SaveAndRestoreDefaults saveAndRestoreDefaults = new SaveAndRestoreDefaults(pApplet);
// Code that changes state.
saveAndRestoreDefaults.restoreOriginals();
}
Now this works for me but I would like this not to clutter my code here but rather be annotation driven, something like:
#PreserveState
public void resetBackground(){
// code that changes state.
}
I have done a little research on it but it seems to be not an easy task. The googling took me to AOP and I don't want to spend time to learn that. Is there an easier way to achieve the same?
Thanks :)
I'd strongly recommend staying in Processing, instead of reaching into the underlying virtual machine API (just because you run it in java, doesn't mean every implementation of Processing has a JVM. Processing.js comes to mind).
Just make a state class and keep track that way:
class SketchState {
color background_color, stroke_color, fill_color;
SketchState(color bg, color st, color fl) {
sketch = s; background_color = bg; stroke_color = st; fill_color = fl;
}
}
ArrayList<SketchState> stateCache = new ArrayList<SketchState>();
void cacheState() {
stateCache.add(new SketchState(...));
}
void restoreState() {
SketchState rest = stateCache.remove(stateCache.size()-1);
background(rest.background_color);
stroke(rest.stroke_color);
fill(rest.fill_color);
}
and add whatever other state aspects you want saved to that class.

I'm new to java from a javascript background: how do they manage event listeners properly and not tighting classes together?

I've been trying to do some "simple thing" in java that in javascript would look like:
// Main class
var model = new Model();
this.callback = function(e){/* do something */}
model.addListener("change", callback);
Well in java what I found so far is making the Main class deriving from java.util.Observer and Model from java.util.Observable; Then when the model will dispatch the event it will call the update method on the Main class. I found really ugly and not elegant at all. I can't even think of how I could work with this;
Is there any cleaner and flexible ways, maybe some libs to help me out here, because I have not found any acceptable tutorial about how to do it like this?
thanks a lot
Well what I've managed so far, and I quite I like it a lot more than creating "empty" classes just for simple events (but still not good, at least for me):
private ArrayList __items;
public void addListener(Method method, Object object){
this.__listeners.add(new Object[] {method, object});
}
public void dispatch(){
int i = this.__listeners.size();
Method method;
Object context;
while(i>0){
i--;
method = (Method)(this.__listeners.get(i))[0];
context = (Object)(this.__listeners.get(i))[1];
try{
method.invoke(context);
}catch(java.lang.reflect.InvocationTargetException e){
}catch(java.lang.IllegalAccessException e){
}
}
}
Then I use like this:
Gifts gifts = prendastotty.PrendasTotty.getMain().getLoggedUserGifts();
Class[] parameterTypes = new Class[0];
try{
Method m = Home.class.getMethod("__updateTable", parameterTypes);
gifts.addListener(m, this);
}catch(NoSuchMethodException e){
}
It this leaky/anti-pattern/buggy?
I must say that I had a bit of trouble keeping up with your code because in my head some of the stuff didn't make sense (from a Java way of thinking, or at least my Java way of thinking). So I hope I understood you correctly and can help you out.
Let's first take your simple example:
var model = new Model();
this.callback = function(e){/* do something */}
model.addListener("change", callback);
In Java a good approach,for example, would be:
public interface ModelListener {
public void execute(Model context);
}
public class Model {
private List<ModelListener> listeners;
public Model() {
this.listeners = new ArrayList<ModelListener>();
}
public void addListener(ModelListener listener) {
this.listeners.add(listener);
}
public void dispatch() {
for (ModelListener listener: listeners) {
listener.execute(this);
}
}
}
With this sort of design you can now do one of two things:
Use anonymous classes
In Java the most common case is that all your classes have a name, although there are cases when you can create anonymous classes, these are basically classes that
are implemented inline. Since they are implemented inline, they're usually only
used when they're small and it's known they won't be re-usable.
Example:
Model model = new Model();
model.add(new ModelListener() {
public void execute(Model model) { /* do something here */ }
});
Notice how the new ModelListener object is created (which is an interface) and the execute implementation is provided inline. That is the anonymous class.
Interface Implementations
You can create classes that implement your interface and use them instead of anonymous classes. This approach is often use when you want your listeners to be re-usable, have names that give semantic meaning to the code and/or they're logic isn't just a few lines of code.
Example:
public class LogListener implements ModelListener {
public void execute(Model model) {
// Do my logging here
}
}
Model model = new Model();
model.addListener(new LogListener());
Side note
As a side note, I saw that the method you were trying to bind as a listener was called __updateTable are you by any chance trying to detect object's changes so you can commit them to the database? If so I strongly suggest you to look at some ORM frameworks such as Hibernate or JPA they'll keep all that hassle from you, keeping track of changes and committing them to the database.
Hope it helps, regards from a fellow portuguese StackOverflow user ;)
You will find it a bit difficult to try to directly map javascript ideology into java. Their underlying philosophies are different. Without more definite code and expectations it is difficult to give you a clearer answer. Here is a sample of code in GWT(written in java) that attaches a click handler to a button.
Hope this helps you get started.
myButton.addSelectionListener(new SelectionListener<ComponentEvent>(){
#Override
public void componentSelected(ComponentEvent ce) {
// do your processing here
}
});
In Java, a function can't exist outside of a class as it can in Javascript. So when you need to provide a function implementation at runtime, you have to wrap that function inside a class and pass an instance of the class, unfortunately.
The solution you have using reflection will work (I assume), but it is not the preferred way to do it in Java since what used to be compile-time errors will now be runtime errors.

Serialize JavaFX components

I'm trying to develop a little drag & drop application under Java FX. User will drop JFX components like Buttons, Menus, Labels on certain positions. When done, he will save this layout and later on he will reopen the layout and he will use it again.
Its important to store the information about all objects that are dropped on some position.
I decided to use serialization for this purpose. But I'm not able to serialize JavaFX components. I tried to serialize Buttons, Scenes, Stages, JFXPane but nothing seemed to work (I obtained NotSerializableException).
Any suggestions how to save all the components and then retrieve them ?
P.S.: I was trying to find out some method with FXML but I did not succeed.
Thank you very much for your answers :)
You are correct, JavaFX (as of 2.1) does not support serialization of components using the Java Serializable interface - so you cannot use that mechanism.
JavaFX can deserialize from an FXML document using the FXMLLoader.load() method.
The trick though, is how to write your existing components and states out to FXML?
Currently, there is nothing public from the platform which performs FXML serialization. Apparently, creating a generic scenegraph => FXML serializer is quite a complex task (and there is no public 3rd party API for this that I know of). It wouldn't be too difficult to iterate over the scenegraph and write out FXML for a limited set of components and attributes.
If the main goal of saving user components on the servers side - is to have a possibility to show the same interface to the user - why not to save all descriptive information you need about users components, and when it is needed - just rebuild user interface again, using stored descriptive information? Here is primitive example:
/* That is the class for storing information, which you need from your components*/
public class DropedComponentsCoordinates implements Serializable{
private String componentID;
private String x_coord;
private String y_coord;
//and so on, whatever you need to get from yor serializable objects;
//getters and setters are assumed but not typed here.
}
/* I assume a variant with using FXML. If you don't - the main idea does not change*/
public class YourController implements Initializable {
List<DropedComponentsCoordinates> dropedComponentsCoordinates;
#Override
public void initialize(URL url, ResourceBundle rb) {
dropedComponentsCoordinates = new ArrayList();
}
//This function will be fired, every time
//a user has dropped a component on the place he/she wants
public void OnDropFired(ActionEvent event) {
try {
//getting the info we need from components
String componentID = getComponentID(event);
String component_xCoord = getComponent_xCoord(event);
String component_yCoord = getComponent_yCoord(event);
//putting this info to the list
DropedComponentsCoordinates dcc = new DropedComponentsCoordinates();
dcc.setX_Coord(component_xCoord);
dcc.setY_Coord(component_yCoord);
dcc.setComponentID(componentID);
} catch (Exception e) {
e.printStackTrace();
}
}
private String getComponentID(ActionEvent event){
String componentID;
/*getting cpmponentID*/
return componentID;
}
private String getComponent_xCoord(ActionEvent event){
String component_xCoord;
/*getting component_xCoord*/
return component_xCoord;
}
private String getComponent_yCoord(ActionEvent event){
String component_yCoord;
/*getting component_yCoord*/
return component_yCoord;
}
}

How to make a link betweeen the name a function and the actual function in java

I am building a user interface in netBeans (coding by hand, more flexible) with multiple toolbars.
What I am trying to do is create an actionListener for each button. I am retrieving names of the functions from XML and parse them to string. I will write implementations for those functions in a separate class, but my problem is the following:
How do I make the link between the function name and the string containing it's name?
Example: String is Open(), function will be Open(someParameter) and in the definitions class there will be static void Open(param).
First of all, consider my comment about your idea of dynamic button behavior resolved from strings being a wrong approach. However if you still need exactly what you asked, what you need is Reflection API.
Here's an example:
Class c = SomeClassWithMethods.class;
Method m = c.getMethod("someMethodName", String.class, Integer.class, Integer.TYPE);
m.invoke(baseObjectFromWhichToCallTheMethod, "stringParam", 10, 5);
Added:
Another option, which is a little bit prettier than reflection, but still a messy design, would be to use a map to link those Strings to methods. The code is a bit longer, but from the Java perspective it is much better than using reflection for your task (unless you have some specific requirement of which I'm not aware). This is how it would work:
//Interface whose instances will bind strings to methods
interface ButtonClickHandler {
void onClick();
}
class SomeClassYouNeed {
//One of the methods that will be bound to "onButtonOneClick()"
public void onButtonOneClick() {
log.info("ButtonOneClick method is called");
}
public void onButtonTwoClick() {
log.info("ButtonTwoClick method is called");
}
//Map that will hold your links
private static Map<String, ButtonClickHandler> buttonActionMap;
//Static constructor to initialize the map
static {
buttonActionMap = new Map<String, ButtonClickHandler>();
buttonActionMap.put("onButtonOneClick()",new ButtonClickHandler() {
#Override
public void onClick() {
onButtonOneClick();
}
});
buttonActionMap.put("onButtonTwoClick()",new ButtonClickHandler() {
#Override
public void onClick() {
onButtonTwoClick();
}
});
}
public void callByName(String methodName) {
final ButtonClickHandler handler = buttonActionMap.get(methodName);
if (handler == null) {
throw new IllegalArgumentException("No handler found by name: "+methodName);
}
handler.onClick();
}
}
After you call callByName("onButtonTwoClick()") it will fetch the respective instance of ButtonClickHandler which will use the static method onButtonTwoClick() to process the click of the button.
It seems to me that you are looking for the equivalent of JS "eval" function in Java. This might help. Nevertheless it is generally not a good idea as #Max stated, you might want to rethink your design.
If i have understood your question correctly you are trying to generate your code files based on some strings taken from a XML file. I can suggest you this library to generate your codes.
For tutorials you can visit this link.
You may even use the Java Reflection API. Here is a link for the tutorial.
Its upto you, that which of the above two you use.

Categories