How to restrict a java program to execute only N times - java

I want to make a java program that must run for a specific number of times only. e.g 2,5,10 etc. after that it must throw an Exception.
It is not allowed to use any FILE or Database for this. Someone gave me a hint of REGISTRY! But i don't know how to use it for this.
Please help me is this regard...

You can use java preferences (registry on windows) :
http://download.oracle.com/javase/6/docs/api/java/util/prefs/Preferences.html
You can find some sample usage here:
http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter10/Preferences.html

Whether this problem is solvable depends on what is meant by "any FILE or Database".
Depending on your point of view, the Windows Registry is a kind of file / database. Certainly, the only reason that values stay in the registry over a reboot is because registry changes are written to disc.
You can move state (such as a count of the number of times an application has been run) to some other service on the local machine. But once again, unless the service saves that state to disc (or some other stable storage medium) it will be lost is the local machine reboots.
You can move state to a service on a remote machine, but once again it may be lost if not saved to disc, etc. Moreover, you may not be able contact that remote service at the time you need the state; e.g. when starting the application.
You can copy the state to lots of remote services without discs, but a network failure (or the user unplugging from the network) will stop you accessing the state.
So to summarize, if you cannot write to disc (or nvram, tape, etc) locally, you cannot guarantee that the counter won't get reset, and that it will be available when needed. Therefore you cannot guarantee that the application won't be run more times than is allowed.
I imagine that you are trying to come up with some limited use scheme that users cannot subvert; e.g. by deleting stuff from the file / database / whatever that counter. Unfortunately, unless you physically control BOTH the hardware AND the operating system on which the application runs, you cannot prevent someone from subverting any counter stored on the machine itself. Anyone with "root" or full administrator rights, or with physical access, can ultimately change any data on the machine itself.
The best you can do is establish a secure connection to a remote server and use that to hold the usage counter. But even that is futile, because a motivated person can reverse engineer the critical part of your application and disable the code that checks the counter.

If the app. has a GUI, it can be launched using Java Web Start and use the PersistenceService. Here is a small demo. of the PersistenceService. The code is available for download.
Edit:
And the PersistenceService should work on any machine that has a JRE, as opposed to just Windows.

Even though this sounds like an attempt at copy protection, you may want to consider self-modifying code. There is an interesting discussion on this subject in Java here: Self modifying code in Java

Related

stop java execution if condition is met

So the idea is a kind of virtual classroom (a website) where students uploads uncompiled .java files, our server will compile it and execute it through C# or PHP, the language doesn't matter, creating a .bat file and get the feedback of the console if the program compiled correctly or not and if the execution was correct based on some pre-maded test, so far our tests did work but we have completely no control on what's inside the .java file so we want to stop the execution if some criterias did happen, i.e. an user input, infite loop, sockets instances, etc... I've digging on internet if there's a way to configure the java environment to avoid this but so far can't find anything, and we don't want our backend language to go through the file to check this things cause will be a completly mess up
Thanks for the help
You could configure a security manager, but it doesn't have a very good track record of stopping a determined attacker, and doesn't do resource limiting anyways.
You could load the untrusted code with a dedicated class loader that only sees white-listed classes.
Or you could use something like docker to isolate the process at the operating system level. This could also limit its cpu and memory consumption.
I'd probably combine these approaches, but some risk will remain in either case.
(Yes, I realize that is complex, but safely sandboxing arbitrary java code is a hard problem.)

Can I use a java policy file to safely run an un-trusted app with sudo

I'm running a J2SE application that is somewhat trusted (Minecraft) but will likely contain completely un-trusted (and likely even some hostile) plugins.
I'd like to create a plugin that can access the GPIO pins on the Raspberry PI.
Every solution I've seen requires that such an app be given sudo-superpowers because gpio is accessed through direct memory access.
It looks like the correct solution is to supply a command-line option like this:
-Djava.security.policy=java.policy
which seems to default you to no permissions (even access to files and high ports), then add the ones your app needs back in with the policy file.
In effect you seem to be giving Java "sudo" powers and then trusting java's security model to only give appropriate powers out to various classes. I'm guessing this makes the app safe to run with sudo--is this correct?
Funny that I've been using Java pretty much daily since 1.0 and never needed this before... You learn something new every day.
[Disclaimer: I'm not very convinced by the Java security model.]
The way I would solve this is to have the code that needs to access the hardware run as a separate privileged process, then have your Java application run as an unprivileged process and connect to the privileged process to have it perform certain actions on its behalf.
In the privileged process, you should check with maximum distrust each request whether it is safe to execute. If you are afraid that other unprivileged processes might connect to the daemon too and make it execute commands it shouldn't, you could make its socket owned by a special group and setgid() the Java application to that group by a tiny wrapper written in C before it is started.
Unix domain sockets are probably the best choice but if you want to chroot() the Java application, a TCP/IP socket might be needed.

Solution for system online or offline

The company that I work for has a web system, some modules will be used in the works, which do not always have connection to the internet.
What the best solution to deploy web modules of the system in construction?
The system cant read/write in the database.
You can have a local database that runs on your webserver. Every 15 min you check if there is a connection and transfer the changes from your local database onto your "real" database.
There is no perfect solution to this problem due to the CAP theorem. If there was, distributed systems would be a whole lot easier, though :)
The way I see it, you have a couple of options. All options require a copy of the data client-side so that the client can at least read the data while it's disconnected.
Don't allow inconsistent writes, just inconsistent reads.
Either the client or the server would take write-ownership of the data whenever the client is off the network. Whichever side owns the data is allowed to write, and the other side must read a potentially-stale local copy of the data (or it could generate errors if that's preferable, or at least tell the user that the data is stale). This is more difficult if you have multiple clients running at the same time.
A similar approach is to run all server-side write operations when you know no clients will be at work (i.e. run all your jobs at midnight). It's simple, but it works for many applications.
Allow inconsistencies and then deal with them later. When you have to be able to write to both sides of the disconnected network concurrently, this is the only way to go. There are a couple of ways to mitigate the inconsistency issues, however, depending on your design:
If you can make all transformations commutative (you can change the order of the transformations and the outcome will be the same), you could store the transformations performed on the client and the server and then apply any cached ones from the client when the it reconnects to the server. This makes dealing with inconsistencies very simple. This is what ATMs do when they are disconnected from the banking network - their commutative transformations are similar to, "Deduct $50 from acct #12345." Note that this can still cause invalid state - the user could deduct more than they had in their account by visiting multiple ATMs which are disconnected from the banking network. However, the bank makes up for this by charging overdraft fees when the ATMs reconnect to the network, and so they don't typically lose any money as a result.
If conflicts are rare, you could just tell a user of the client, "Hey, you wrote this while you were offline, but the value changed on the server - which copy should I keep?" This has the issue that you might have to ask it multiple times, since the user has to perform an atomic CAS operation on the value being changed and it's possible that multiple clients might be reconnecting at the same time. This approach can also suffer from the ABA problem if you're not careful (but that depends what you're doing).

Dumping a Java program into a file and restarting it

I was just wondering if it's possible to dump a running Java program into a file, and later on restart it (same machine)
It's sounds a bit weird, but who knows
--- update -------
Yes, this is the hibernate feature for a process instead of a full system. But google 'hibernate jvm process' and you'll understand my pain.
There is a question for linux on this subject (here). Quickly, it's possible to hibernate a process (far from 100% reliable) with CryoPID.
A similar question was raised in stackoverflow some years ago.
With a JVM my educated guess is that hibernating should be a lot easier, not always possible and not reliable at 100% (e.g. UI and files).
Serializing a persistent state of the application is an option but it is not an answer to the question.
This may me a bit overkill but one thing you can do is run something like VirtualBox and halt/save the machine.
There is also:
- JavaFlow from Apache that should do just that even though I haven't personally tried
it.
- Brakes that may be exactly what you're looking for
There are a lot restrictions any solution to your problem will have: all external connections might or might not survive your attempt to freeze and awake them. Think of timeouts on the other side, or even stopped communication partners - anything from a web server to a database or even local files.
You are asking for a generic solution, without any internal knowledge of your program, that you would like to hibernate. What you can always do, is serialize that part of the state of your program, that you need to restart your program. It is, or at least was common wisdom to implement restart point in long running computations (think of days or weeks). So, when you hit a bug in your program after it run for a week, you could fix the bug and save some computation days.
The state of a program could be surprisingly small, compared to the complete memory size used.
You asked "if it's possible to dump a running Java program into a file, and later on restart it." - Yes it is, but I would not suggest a generic and automatic solution that has to handle your program as a black box, but I suggest that you externalize the important part of your programs state and program restart points.
Hope that helps - even if it's more complicated than what you might have hoped for.
I believe what the OP is asking is what the Smalltalk guys have been doing for decades - store the whole programming/execution environment in an image file, and work on it.
AFAIK there is no way to do the same thing in Java.
There has been some research in "persisting" the execution state of the JVM and then move it to another JVM and start it again. Saw something demonstrated once but don't remember which one. Don't think it has been standardized in the JVM specs though...
Found the presentation/demo I was thinking about, it was at OOPSLA 2005 that they were talking about squawk
Good luck!
Other links of interest:
Merpati
Aglets
M-JavaMPI
How about using SpringBatch framework?
As far as I understood from your question you need some reliable and resumable java task, if so, I believe that Spring Batch will do the magic, because you can split your task (job) to several steps while each step (and also the entire job) has its own execution context persisted to a storage you choose to work with.
In case of crash you can recover by analyzing previous run of specific job and resume it from exact point where the failure occurred.
You can also pause and restart your job programmatically if the job was configured as restartable and the ExecutionContext for this job already exists.
Good luck!
I believe :
1- the only generic way is to implement serialization.
2- a good way to restore a running system is OS virtualization
3- now you are asking something like single process serialization.
The problem are IOs.
Says your process uses a temporary file which gets deleted by the system after
'hybernation', but your program does not know it. You will have an IOException
somewhere.
So word is , if the program is not designed to be interrupted at random , it won't work.
Thats a risky and unmaintable solution so i believe only 1,2 make sense.
I guess IDE supports debugging in such a way. It is not impossible, though i don't know how. May be you will get details if you contact some eclipse or netbeans contributer.
First off you need to design your app to use the Memento pattern or any other pattern that allows you to save state of your application. Observer pattern may also be a possibility. Once your code is structured in a way that saving state is possible, you can use Java serialization to actually write out all the objects etc to a file rather than putting it in a DB.
Just by 2 cents.
What you want is impossible from the very nature of computer architecture.
Every Java program gets compiled into Java intermediate code and this code is then interpreted into into native platform code (when run). The native code is quite different from what you see in Java files, because it depends on underlining platform and JVM version. Every platform has different instruction set, memory management, driver system, etc... So imagine that you hibernated your program on Windows and then run it on Linux, Mac or any other device with JRE, such as mobile phone, car, card reader, etc... All hell would break loose.
You solution is to serialize every important object into files and then close the program gracefully. When "unhibernating", you deserialize these instances from these files and your program can continue. The number of "important" instances can be quite small, you only need to save the "business data", everything else can be reconstructed from these data. You can use Hibernate or any other ORM framework to automatize this serialization on top of a SQL database.
Probably Terracotta can this: http://www.terracotta.org
I am not sure but they are supporting server failures. If all servers stop, the process should saved to disk and wait I think.
Otherwise you should refactor your application to hold state explicitly. For example, if you implement something like runnable and make it Serializable, you will be able to save it.

Are there any Java VMs which can save their state to a file and then reload that state?

Are there any Java VMs which can save their state to a file and then reload that state?
If so, which ones?
Another option, which may or may not be relevant in your case, is to run the JVM (any JVM) inside a virtual machine. Most virtual machines offer the option to store and resume state, so you should be able to restart your PC, fire up the VM when it comes back up and have the Java process pick up from where it was.
I use VMWare Player for testing on IE at work, and this works as noted above when I close and later reopen it. I don't generally do this when apps are doing anything of note in the VM, but as long as they aren't accessing any external resources (e.g. network sockets), I would expect it to work as if the VM was never shut down.
Continuations are probably be what you are looking for:
[...] first class continuations, which are constructs
that give a programming language the
ability to save the execution state at
any point and return to that point at
a later point in the program.
There are at least two continuation libraries for Java: RIFE continuations and javaflow. I know that javaflow at least allows serializing state to disk:
A Continuation can be serialized if
all objects it captured is also
serializable. In other words, all the
local variables (including all this
objects) need to be marked as
Serializable. In this example, you
need to mark the MyRunnable class as
Serializable . A serialized
continuation can be sent over to
another machine or used later. - Javaflow Tutorial
You should serialize relevant domain-specific objects which can be de-serialized by another JVM run-time.
I'm not aware of any tools persisting an entire JVM. The closest I got to doing this was creating a core dump from a running JVM process using gcore, then using jsadebugd, jmap or jstack to debug it.
For instance:
$ jps # get JVM process ID XXX
$ gcore -o core XXX
$ jsadebugd $JAVA_HOME/bin/java core.XXX
UPDATE
I don't think you're going to find a solution that's portable between architectures just yet.
It is worth noting that many objects cannot be serialized as they have state outside the java context.
e.g. Sockets, Threads, Open files, Database connections.
For this reason, it is difficult to to save the state of a useful application in a generic way.
I'm not aware of JVM's that can store state. Depending on your exact needs, you can maybe consider using Terracotta. Terracotta is essentially able to share heap state between JVM's, and store this state to disk.
This can be used to cluster applications, and/or make the heapstate persistent. In effect, you can use it to start the JVM up and pick up where you left off. For more information check out:
http://www.infoq.com/articles/open-terracotta-intro
Hope this helps.
I've worked on an embedded Java project which used this approach to start up quickly.
The JVM was from Wind River, running on top of VxWorks.
Sun has done some research on "orthogonal persistence", which provides "persistence for the full computational model that is definedby the Java Language Specification":
http://research.sun.com/forest/COM.Sun.Labs.Forest.doc.opjspec.abs.html
PJama is a prototype implementation:
http://research.sun.com/forest/opj.main.html
To my knowledge, there is nothing to capture JVM state and restore it, but people are trying to serialize/deserialize the Thread class to achieve something similar. The closest thing to a working implementation I found was brakes, but you may find more when you google for "thread serialization".
I take it you want to be able to resume from where the snapshot was stored, as if nothing thereafter had happened.
I wonder how many framework components and libraries such functionality would break. Suddenly, you are reviving a JVM state from storage; in the meantime, the clock has mysteriously skipped forward by 23 hours, network connections are no longer valid, GUI objects no longer have any underlying O/S handles... I'd say this is nontrivial, and impossible in the general case without modifying the framework extensively.
If you can get away with just storing the state of your in-memory objects, then something like Prevaylor might work for you. It uses a combination of journalling changes to business objects with a serialized snapshot to record the state of your objects, which you can then reload later.
However, it doesn't store the full JVM state (call stack, GC status etc). If you really need that level of detail, then a specialized JVM might be needed.
The answer at this time is no, there are no JVMs that can 'hibernate' like your operating system can or like VMWare et al can.
You could get half-way there, depending on the complexity of your app, by just serializing state out when the program closes and serializing it back in, but that won't do stuff like pause executing some business logic when you close and then continue when you open it again.

Categories