I wrote program in java which is using some kind of win lib and now I want to write one more program to simulate other one. I mean, it should be going like that :
first program asking lib for some simple data ( just true false)
and other program in this same time by using function from this lib setting some variable in this lib which might be return to first program...
both programs are independent first (lets say "getter") in java and second ("setter") in c++... I have already set all variables in lib as static but it didn't solved problem.
Is this kind of solution even possible? or I have to use maybe some kind of socket or else
thanks for replay
I've been working with this kind of stuff (Java + dll + another programs) and I can tell that the libraries executed from another program and Java doesn't share the static variables, so I think you won't be able to do it that way.
The example that I have uses a window, whose size is 0, to exchange messages between the two programs (Java and VB 6.0), the first call between the two programs share the window handler, but I think this isn't the best way to do it, and, in addition, it has some limitations.
I expose the ways I think that could match your problem:
Shared file: pretty easy, just must take care with the encoding.
Memory area: You can use in the dll a memory area for data exchange, this is a truly "static" context
Socket: Maybe is the most flexible since it will work with any program/system.
The last one would be the one that I'll use if I must implement something like that, but that depends on you.
Related
I'm following the Integrating AnyLogic Models with External Java Applications module and while I am able to change parameters before I run the exported java application, it seems the values become immutable once the model runs. Is there a way to dynamically modify parameter values at runtime?
Below is a snippet of my Java code:
final Simulation s = new Simulation();
IExperimentHost host = new ExperimentHost(s);
s.parameter1 = 50;
s.setup(host);
host.launch();
s.runTheModel();
s.parameter1 = 100;
The result is that parameter1 never changes from 50 to 100. Is there a way to circumvent this?
Try set_parameter. The help menu talks about this a little bit.
Edit:
Your original question was not directly linked to running as an external java application, but I think this could really simplify things. When you export your java application, look at the .bat file. You will see what the command line would look like to run the model. What we do when we are running from an external application is just have the external application call this command line, as opposed to what AnyLogic discusses in the help menu. A significant advantage of this is that you can easily mimic in the development environment what is going on in the exported model.
Ask your self why you are changing these parameters at runtime. Is it because of a read statement and you just don't have the data prior to the model run? If so, think about the order you instantiate your objects and don't start them until after you have the variables set that you want to use. This can be done by passing in parameters to main, setting database values, or having the main agent do various read statements.
Is it that you just want items to change over time? If so, consider variables, instead of parameters. Consider other objects that may allow you to more easily change flow. For example, does a valve before a pipeline or other sequence give you the level of control that you want?
At this point, would probably need more detailed information about what you are trying to accomplish / the system you are modeling, in order to provide any more specific advice.
Is there a way to make a collection of class files/objects and then have them used in an interactive main file? So let's say I want to make a program to store information interactively where different classes are designed to hold different information. Then I would have an interactive main file where I made instances of these classes which would collectively hold the information I want stored. And then any changes or anything I do in this interactive main file is then saved.
I understand that this might be a very odd inquiry and maybe some other program might be useful for this. If so, feel free to point me in the right direction.
Here are two solutions that are good for the purpose you mentioned in your comment.
The first one is called Serialization. This let's you save your java object to your hard drive, and retrieve it later.
The second, (and in this case, more preferable option in my opinion), is using a Database.
A database is a compliment to your program, that stores data. You can then use "Queries" to access this data, and update it. Almost every database software is compatible with java.
I would look into MySQL
The reason I think a database would be better for your purpose is that they are already highly optimized, and are designed to have multiple people accessing and writing to them at once. If you wanted just want one person to use this program at a time however, serialization might be easier to implement.
Absolutely! Your main class would use the standard input (perhaps Scanner input = new Scanner(System.in);) and output (System.out.println()). To interact with your other classes, most simply, just put them in the same folder (if you are interested take a look at Java packages). If you have a Dog class in the same folder as your main class, you can freely create Dog objects in your main class. I hope this helps!
As a side note, because you mentioned storing information with different classes, you might be interested in the Java Collections Framework.
I am looking for a way to find the name of the program (in my code) that will launch when an operating system tries to open a given file. I will not be launching the application I'm just looking for its name. Ideally the routine I'm looking for/building would take a filename and return a string. I am programming in Java 8 on Eclipse and need my jar file to stay cross platform.
Simplest solution I can find is to use SWT's class 'Program'. Although this assumes that I can correctly identify filetype which is another big can of worms I'm not going to into here.
String ext = extractFileType(filename);
Program p2 = Program.findProgram(ext);
if (p2 != null) programName = p2.toString();
But for a number of reasons I DON'T WANT TO USE the SWT library if at all possible. I'm using Swing and and I really don't want my clients to need to download a different application (jar) dependent on their operating system. I'm well aware that the underlying code is operating system/Window Manager dependent.
Anyone know of any other package besides SWT that already does this? I can't find one. Or similar enough I can strip the results to get what I want? Even if it's only for one platform? I'm experimenting with Apache Tika but I don't see anything helpful there.
Any hints on where to look to start write this myself? I know this entails reading the registry on Windows. I need this code to work on the most recent versions of Windows, and OS X. And eventually Linux but Linux windowing systems are not a priority.
Is there a way to link/load SWT in Eclipse to make the cross-dependent part of using SWT this code a little more lightweight and invisible to the end user? I'm not new to coding but am to using Eclipse.
Here is a quick description of my solution. I did a fair amount of hunting around and I deciding on simply using the JNA library. https://github.com/java-native-access/jna and writing my own native library on a Macintosh to get it to work.
Windows: Fairly straight forward usage of JNA. I'm calling FindExecutable & PathFindExtension from JNA.
public interface MyShell32 extends Shell32 {
MyShell32 INSTANCE = (MyShell32) Native.loadLibrary("shell32", MyShell32.class, W32APIOptions.DEFAULT_OPTIONS);
WinDef.HINSTANCE FindExecutable(String lpFile, String lpDirectory, char[] lpResult);
}
{
...
char[] returnBuffer = new char[WinDef.MAX_PATH];
shell.FindExecutable(filename, null, returnBuffer);
app = Native.toString(returnBuffer);
...
}
PathFindExtention() call is similar but returns a pointer so it's more straight forward.
Macintosh: I tried all sorts of things and finally decided to write my own tiny native library to call in objective C
rtnValue = [[NSWorkspace sharedWorkspace] getInfoForFile:filenameNS
application:&AStr
type:&TStr];
This library is tiny (but I may add to it if I need other native calls) but I need to write a C/C++ shell as well as the Objective C to get it to work. I then call this library JNA. Not that different from writing straight JNI but I found it easier to code.
public interface NSWWraper extends Library {
/** The instance **/
NSWWraper INSTANCE = (NSWWraper) Native.loadLibrary("NSWWraper", NSWWraper.class);
// CP_NSWWraper
Pointer FindFileInfo(String filename);
void FreeMem(Pointer memory);
}
I honestly haven't tested this calling this a large number of files so I don't know how much it slows down my code. JNA calls are supposed to be expensive. It's interesting timing on someone asking for my solution as I'd had to put this on back burner and only got it working on Windows yesterday. I was going to incorporate this into the rest of my project today.
Edited to add. I didn't use JINI because I found it's not being very well supported on a Macintosh anymore and JNA was the better solution for Windows and I had to use it anyway.
I have a Java project in eclipse which is divided in two parts; two different main classes that run two different Threads basically.
One contains loading, initialization and debug-showing procedures that are quite slow. While, the other manipulates the initialized data. In order to retrieve the information in the second part, the first one "saves" all the references inside a static map which contains instances of classes.
Does exist a way to run the first part only once, and then compile and run the second part more times? I tried with just set two different console and pressing the run button in different times but the static field of the first class looks not existing when the second runs.
I am working now only in the second part, so I need to test and start it many times. I really appreciate an help to save a lot of time wasted in always initialize the same thing.
ps : Everything works fine if I run both parts together.
thanks in advance
Luca
thanks to the replay (Multithreader, Stephen C) I am trying to make the question more clear and to ask how to solve it since my solution does not look the best one.....
EDIT 1 : The "first part" initializes the program and then runs an easy GUI which is periodically update. So as long as it shows up we shouldn’t care about how to manage input and output from the user
EDIT 2 : the "second part" reads information from the previous and send back strings to the GUI for debug purposes.
EDIT 3 : I do not have specific constrains in the shape of the project, so I can change the structure if there are better solutions. As well as for the way to run it.
FARTHER QUESTION 1 : there is a possibility to compile only one part of the project in eclipse while it runs all together? I mean, if two threads are running, can I stop one, re-compile it and run it again in a way that it can see the instances created from the first thread which never stops? Basically I need to refer at the same static variable loaded in memory, if it exists.
FARTHER QUESTION 2 : or more luckily does exist a way to store and load in a file instances of Java classes avoiding to write from sketch a mapping mechanism from/into txt files?
It is not entirely clear what you are asking here, but I'm assuming that you are talking about running the "first part" and the "second part" in the same JVM ...
Yes, it is possible. But it is not straightforward.
Basically, you need to refactor your code so that there is some kind of "control box" that the user can interact with from the outside. For instance, this might just be a simple command loop that reads commands from standard input and runs them. (Alternatively you could turn your application into a "service" that accepts requests over a network socket, via RMI, via HTTP, etcetera.)
Then you wire things up so that there is a "command" to run the "second part" of your application in response to the user's request.
That's the basics. The other thing you want to do is to "compile and run the second part [many] times". That implies that you need to set up your "control box" so that it can load a fresh copy of the code for the "second part" after you have modified and recompiled it. To achieve this, you will need to create a new ClassLoader object (each time) and use that to load the classes that make up the "second part". This is possible, but a bit tricky. The problems you are going to need to address include:
Splitting the "first part" and the "second part" into separate JAR files (or directory trees). The "first part" needs to be self-contained ... no dependencies on classes in the "second part".
Make sure that there are no runtime references from the "first part" data structures to instances of objects / enums in the "second part".
If you don't get the above right, you are likely to experience "permgen" storage leaks and mysterious type cast errors.
All in all, there's a lot that needs to be done to make this work. Unless you already understand all of the technologies involved, I'm doubtful that it will save you time overall. A better idea might be to figure out how to speed up the initialization of the "first part"; e.g. by doing lazy initialization, or caching the data structures using some fast / light-weight persistence mechanism.
I think it is better to change your design unless there is a requirement for it to stay the same.
Although I do not have the requirements or what you are actually trying to accomplish, I suggest you the following design:
1. App_1 does the calculations and then writes the results into file
2. App_2 reads checks for the file, if NOT exists display error message; otherwise read the file and keep going...
I guess I found a tricky solution. It is dirty but it works natively in the eclipse debugger.
I am running in debugging mode a main method which create a thread that works as a caller. This runs the first part of the project and wait until the initialization is complete (note that the first part doesn't end here, it remains looping to show debugging information based on a static class which evolves with the second part of the program). Then it starts with an infinite loop where it just calls the second part that I want to test and change: here there are also a breakpoint.
Well, now I can coding in the second parts while the eclipse debugger is waiting in the breakpoint than save it and hit F8. The debugger resumes, the algorithms runs and then it stops again in the breakpoint. Just check if works, eventually change something then save and hit F8 again without wait to re-initialize the first part of the project.
Probably this method has to be restarted after a while but still, it better then restart every time :)
many thanks to all your help.
If somebody has more elegant way to do that they are welcome!!
I've always wanted to write a simple world in Java, but which I could then run the 'world' and then add new objects (that didn't exist at the time the world started running) at a later date (to simulate/observe different behaviours between future objects).
The problem is that I don't want to ever stop or restart the world once it's started, I want it to run for a week without having to recompile it, but have the ability to drop in objects and redo/rewrite/delete/create/mutate them over time.
The world could be as simple as a 10 x 10 array of x/y 'locations' (think chessboard), but I guess would need some kind of ticktimer process to monitor objects and give each one (if any) a chance to 'act' (if they want to).
Example: I code up World.java on Monday and leave it running. Then on Tuesday I write a new class called Rock.java (that doesn't move). I then drop it (somehow) into this already running world (which just drops it someplace random in the 10x10 array and never moves).
Then on Wednesday I create a new class called Cat.java and drop that into the world, again placed randomly, but this new object can move around the world (over some unit of time), then on Thursday i write a class called Dog.java which also moves around but can 'act' on another object if it's in the neighbour location and vice versa.
Here's the thing. I don't know what kinda of structure/design I would need to code the actual world class to know how to detect/load/track future objects.
So, any ideas on how you would do something like this?
I don't know if there is a pattern/strategy for a problem like this, but this is how I would approach it:
I would have all of these different classes that you are planning to make would have to be objectsof some common class(maybe a WorldObject class) and then put their differentiating features in a separate configuration files.
Creation
When your program is running, it would routinely check that configuration folder for new items. If it sees that a new config file exists (say Cat.config), then it would create a new WorldObject object and give it features that it reads from the Cat.config file and drops that new object into the world.
Mutation
If your program detects that one of these item's configuration file has changed, then it find that object in the World, edit its features and then redisplay it.
Deletion
When the program looks in the folder and sees that the config file does not exist anymore, then it deletes the object from the World and checks how that affects all the other objects.
I wouldn't bet too much on the JVM itself running forever. There are too many ways this could fail (computer trouble, unexepected out-of-memory, permgen problems due to repeated classloading).
Instead I'd design a system that can reliably persist the state of each object involved (simplest approach: make each object serializable, but that would not really solve versioning problems).
So as the first step, I'd simply implement some nice classloader-magic to allow jars to be "dropped" into the world simulation which will be loaded dynamically. But once you reach a point where that no longer works (because you need to modify the World itself, or need to do incompatible changes to some object), then you could persist the state, switch out the libraries for new versions and reload the state.
Being able to persist the state also allows you to easily produce test scenarios or replay scenarios with different parameters.
Have a look at OSGi - this framework allows installing and removing packages at runtime.
The framework is a container for so called bundles, java libraries with some extra configuration data in the jars manifest file.
You could install a "world" bundle and keep it running. Then, after a while, install a bundle that contributes rocks or sand to the world. If you don't like it anymore, disable it. If you need other rocks, install an updated version of the very same bundle and activate it.
And with OSGi, you can keep the world spinning and moving around the sun.
The reference implementation is equinox
BTW: "I don't know what kinda of structure/design" - at least you need to define an interface for a "geolocatable object", otherwise you won't be able to place and display it. But for the "world", it really maybe enough to know, that "there is something at coordinates x/y/z" and for the world viewer, that this "something" has a method to "display itself".
If you only care about adding classes (and not modifying) here is what I'd do:
there is an interface Entity with all business methods you need (insertIntoWorld(), isMovable(), getName(), getIcon() etc)
there is a specific package where entities reside
there is a scheduled job in your application which every 30 seconds lists the class files of the package
keep track of the classes and for any new class attempt to load class and cast to Entity
for any newlly loaded Entity create a new instance and call it's insertIntoWorld().
You could also skip the scheduler and automatic discovery thing and have a UI control in the World where from you could specify the classname to be loaded.
Some problems:
you cannot easily update an Entity. You'll most probably need to do some classloader magic
you cannot extend the Entity interface to add new business bethod, so you are bound to the contract you initially started your application with
Too long explanation for too simple problem.
By other words you just want to perform dynamic class loading.
First if you somehow know the class name you can load it using Class.forName(). This is the way to get class itself. Then you can instantiate it using Class.newInstance(). If you class has public default constructor it is enough. For more details read about reflection API.
But how to pass the name of new class to program that is already running?
I'd suggest 2 ways.
Program may perform polling of predefined file. When you wish to deploy new class you have to register it, i.e. write its name into this file. Additionally this class has to be available in classpath of your application.
application may perform polling of (for example) special directory that contains jar files. Once it detects new jar file it may read its content (see JarInputStream), then call instantiate new class using ClaasLoader.defineClass(), then call newInstane() etc.
What you're basically creating here is called an application container. Fortunately there's no need to reinvent the wheel, there are already great pieces of software out there that are designed to stay running for long periods of time executing code that can change over time. My advice would be to pick your IDE first, and that will lead you someways to what app container you should use (some are better integrated than others).
You will need a persistence layer, the JVM is reliable but eventually someone will trip over the power cord and wipe your world out. Again with JPA et al. there's no need to reinvent the wheel here either. Hibernate is probably the 'standard', but with your requirements I'd try for something a little more fancy with one of the graph based NoSQL solutions.
what you probably want to have a look at, is the "dynamic object model" pattern/approach. I implemented it some time ago. With it you can create/modify objecttypes at runtime that are kind of templates for objects. Here is a paper that describes the idea:
http://hillside.net/plop/plop2k/proceedings/Riehle/Riehle.pdf
There are more papers but I was not able to post them, because this is my first answer and I dont have enough reputation. But Google is your friend :-)