servlets count in program - java

I want to count the number of times my servlet program ran in the application.
I have used count variable in doPost method of the servlet. Every time I run the application the count will increase. But if close the editor (eclipse/netbeans) or if I close the project then my count will be reset to zero.because my servlet container will also stop running.
One way is to save my count value in data base. Is there any other way apart from database where I can store my count value even after closing the editor or project. Can I store my count value in file?

In general you can store the count value whenever you want, file, database of any kind and so on.
However I would like to mention that servlets in general are designed to run in environments where many users can access the servlet simultaneously, so you always have to think about the synchronization.
Multiple instances of the serlvet class can exist (it's up to you web container when to create them).
In general what you need to do is:
Get the current value
Increase the value by 1
Store the value
Now this thing has to be carefully implemented.
Depending on the underlying layer you might want to consider using Transactions:For example for postgesql
Another example is using a NoSQL store like Redis:
Read Pattern counter section
The best way to implement a distributed counter really depends on the underlying storage so its hard to advice on anything more specific, the choice is yours.
Another aspect I would like to mention is a distributed nature of web application.
If its a real world application, eventually you might want to run it on multiple service and 'scale it out' (at least its a trend in a modern server side software in my opinion).
From this perspective, the application can't really use local file and, say, windows registry because the file system is not a distributes thing (unless you use a distributed file system).
Hope, this helps

Related

How to open a file in Java that does not prevent external "Safe Save"?

We want to open a file in Java and read its contents.
This file may be updated by an external application using Safe Save. That means the file will be externally read and its updated contents will be stored to a new file. Eventually the original file is deleted and the new file is renamed to match the original file's name.
Unfortunately the external process fails during rename (last part of the Safe Save) when our Java Application is reading the original file at the same time.
We played with different kind of open modes but could not get a solution that does not fail the external reader.
Is there some way to open a file that does not interfere with external processes accessing the same file? Ideally, whenever an external process moves or deletes the file we would like to get an exception in our Java application. And only there.
Do you have any ideas on how to achieve that?
EDIT:
Just some clarification regarding the use case:
This an indexer like scenario. We want to index contents of a potentially very large filesystem where 3rd party independent processes can concurrently read from or write to as well. We have no control over the 3rd party processes.
Copying the original file seems like a big overhead and we are not sure if that helps with the original problem as it will probably fail the external reader on a Safe Save as well.
Last but not least: This should work on Windows and Linux. But we are experiencing this problems on Windows.
On Windows, whether a file can be renamed or deleted while it's open is controlled by the FILE_SHARE_DELETE sharing mode flag. This flag should be passed in when the file is opened with the low level CreateFile function.
Unfortunately, Java API does not give you control over low level Windows-specific flags. There is an open bug report to have FILE_SHARE_DELETE added by default, but it's unlikely it will be done because of backwards compatibility (some applications may depend on this behavior). the A comment in the report suggests a workaround: instead of new FileInputStream(file) use the java.nio API.
InputStream in = Files.newInputStream(file.toPath());
I don't have access to Windows right now to verify that this workaround uses the right sharing mode.
Make a copy of the original file an use this within your Java program, and at the same time keep track of the original file.
Here, this might help you out:
The java.nio.file package provides a file change notification API, called the Watch Service API. This API enables you to register a directory (or directories) with the watch service. When registering, you tell the service which types of events you are interested in: file creation, file deletion, or file modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When an event comes in, it is handled as needed. Official docs
You cannot achieve this only with files, at least not without making additional assumptions. If the processes are not synchronized you will get either (a) errors (b) corrupted data or (c) both. Furthermore, such system will be unstable, prone to race conditions and implementation-specific details. This means that even if it looks like it's working it will not work correctly always and in each case.
Depending on your circumstances you might try to use a combination of scehduling (i.e. process A runs every even minute, process B every odd minute), exclusive/shared open flags, range locks, copying files, file change notifiers, retrying on failure etc. If you can somehow ensure that your assumptions are never broken you might end up with something which is "good enough". But all in all, this is a bad engineering practice and should be avoided.
For a proper solution, you need to make both processes aware that they are talking to each other. What you have is really a textbook use case for a database. Besides using a database there are plenty of other ways to synchronize access to data - messaging, streams, locks, shared memory etc. Each way has its own benefits and downsides and without knowing more about your specific situation it is impossible to say which would be better.

How to "hide" sensitive system properties like passwords set by Java applications?

I am maintaining an existing Java product (which has a HUGE code-base). I discovered that it is setting (and getting) two of its internal passwords as Java system properties, at no less than 4-5 different places (methods). Now, the problem is, the passwords are being stored as plain text in the Java system properties, and so, the same is visible to external entities, as the application is not using any Java Security Manager. For example, if the application (process) is running on port number 1234, we can run the Java command:
jinfo -sysprops 1234
to view both the passwords as values of the corresponding Java system properties. I wish to ask if there is any remedy to this without changing the existing code-base too much? The desired effect would be to "hide" the two Java system properties (denoting the two passwords) from all external entities.
It may be noted that introducing a Java Security Manager into the application may not be a solution, as if we revoke read permissions from the said two Java system properties using the Java Security Manager, the application codes which read those properties would crash. Same is applicable for storing the passwords in encrypted form, as that would crash all codes within the application which are expecting to read the passwords in clear text form.
Since you said:
...at no less than 4-5 different places...
and you really don't want to do major code changes, I would:
Supply the password in an encrypted form.
Go through those 4-5 places (it's not so much!), and call a wrapper method that you have to write separately: MyPassUtil.getXYZPassword() which internally calls the System.getProperty() to get the encrypted password, decrypt it, and return the plain text version to whoever is calling it.
Keep in mind though, that this way, the decryption key and algorithm is stored within the application, and a good Java decompiler (JD-GUI or CFR) will still return this information. In other words, anyone with the access to the JAR file, can still get the information with some minor effort, something which I presume, since one can call jinfo, they can also get the JAR file.
The best is to use some form of keystore, which again, you can easily implement once you do the wrapper method mentioned in step 2, without affecting whoever is using it.
Also, some security tips:
If it's an SSH / SFTP connection, set up SSH keys between the two machines, and eliminate use of passwords.
If it's a database connection, at least configure the DBMS to allow connections only from this particular machine's IP address. If the connection is over the internet and you are behind an NAT, set-up a VPN first, and channel the traffic between the hosts through it.
For other setups, try and see whether there are some other tips you can do similar to these two points, to improve the security around these passwords.

Call Unix Shell commands from Servlet/JSP

I need to call some Unix commands from my Servlet.
I have some Perl script, but I want to "translate" them into Java.
Here is something that I want to do on Java, but that I've made in Perl:
system("myfolder/myscript.sh > /myfolder/logs/myscript.log");
Is it possible to do this on a Servlet?
Yes, but note that redirect is part of the shell you will want:
ProcessBuilder pb =
new ProcessBuilder("/bin/sh", "-c", "myfolder/myscript.sh > /myfolder/logs/myscript.log");
pb.start();
Short answer:
it's possible but it's bad design, and can pose a security risk.
better to flag somehow that the script needs to run and check the flag via script
Long answer (following the commments):
Servlets are usually used to provide a user interface (or api) to something, for example accessing data or in your case triggering an action. As such, they imply the possibility of access from a remote resource such as a remote computer. In some (actually most) cases, that remote computer may even be out of the network, for example somebody's home.
Every server which is exposed to the outside world has the potential of being hacked or attacked in some way, with the risk being directly related to the level of interest this resource poses.
For example, if you work for a big company (which is then noticeable by hackers), and this servlet is used to trigger a build in your local repository, and you decide that developers will be able to work from home and need to login in order to trigger a build or check their build status, it means that anyone with the right credentials can potentially access the servlet, from anywhere in the world. Now lets assume that your perl script needs to access your CI server for some data, and your source repository for another data (maybe it even copies the sources instead of letting the CI server do it). In this case, you just created a direct link between someone sitting somewhere in the world, to the company's source code. It also means that even if it's too hard to penetrate your incredibly secure service because you spent a vast amount of time closing all potential gaps, they may still be able to trigger many unnecessary builds, and if you work in Continuous Deployment even make those builds go to production (maybe causing a DOS attack or service disruption). If at some point someone decides that the script also needs to get a parameter from the servlet, you've even made the hacker's life easier and could eventually give him access to your system.
All I described in the previous paragraph may be completely irrelevant to your case, you might be developing a service which will run on your home computer and won't interest anyone but yourself, but this does not change the fact that this is bad design (which might be ok for home use by the way).
What I said in the short answer is that it's better to have servlets flag the system that an action is needed, for example set a flag in DB or even in a file, in this case a hacker's life would be much more difficult, as there's no direct link. This also makes the servlet respond immediately, possibly automatically updating on status, instead of waiting for the perl script to finish running.
Did u try Jsch.It can do ssh and execute shell commands.

Stopping the manipulation of variables used for data collection?

I am working on a project in java and I was hoping to be able to collect statistics from the client and a possible problem that I fear will occur is the manipulation of the variables used for collection which will lead to illegitimate statistics. Is it in any way possible to prevent the manipulation of variables or is it always possible?
For example: I want to log the actions made per hour from the client. The variable acting as a counter for the amount of actions performed is manipulated and a much larger amount is added to the counter. This data is then uploaded to the server (Of course using a multi-tier architecture to prevent even more possible problems) and considered 'legit.'
Is there any way to prevent this?
Depending on how the data is uploaded, there are various ways to secure the information.
If you are uploading some kind of text or data file, using basic encryption, even a ZIP with a password, should be sufficient to stop casual users from changing the information.
Your application could also simply use RMI or a web service to upload the information, never giving the user the change to manipulate the data.
All of this of course assumes that the application itself gathers the information - if users have the opportunity to enter the data, there's no real way of preventing them from giving you bogus information.
Without knowing if this is a desktop or web application, I'm going to suggest you encrypt your upload files somehow. It doesn't have to be complicated, just enough so someone can't edit it in a text editor.
Just remember that if something runs on the client machine, it can be manipulated. Java is not a secure language, nothing is, for that matter, and while you can do many things to secure applications, there's always someone just a little smarter out there that can crack it.
If I was doing this, I'd do the accumulation of the statistics on a secured machine. Have the primary data gathering code send "event" message to the accumulator, and have the accumulator keep a log of the raw events and their arrival timestamps. This won't prevent people manipulating the stats, but it could make it easier to detect suspicious patterns after the fact.
Building on that idea, you could arrange that event generator application (on the user's computer) uses some kind of handshaking involving a shared secret or public/private key encryption. I don't think you can fully secure this, but security-by-obscurity could be enough to deal with attempts to cheat by people without the skills to reverse engineer the code.
But like Ewald says, any algorithmic process can be reverse engineered by someone who has sufficient control of the hardware it runs on. If the process needs to use a "secret" to operate, then that secret can be revealed.

Serving Java Applets from a Queue?

I'm looking for a elegant way to create a queue for serving up batch compiled applets.
I have hacked together a SQL and PHP script to handle this but it chokes under mild loads.
is there an existing system that can handle taking a list in SQL and serve the applets in descending order each time it is requested. I'm also trying to handle this all server side as well.
The trick would be getting file001, then file002 ++ ect. to get served each time a web page is loaded. I'm batch creating applets that has a slightly modified background and I'm trying to serve a never been used applet waiting in the queue to load each time the a page is requested.
Is there a applet server I can tweak or does look like something that needs to be built?
No, I have never heard of a "batch compile applet server".
Could you maybe explain in more detail why you feel this is necessary?
Why don't you just use the same class and pass parameters to it?
That said, you can do compilation on demand quite well with e.g. ant and / or CruiseControl. You could put the pre-compiled applets into a directory. Then your PHP frontend just needs to keep track of what applet it delivered last, and fetch the next one the next time.
Still, this sounds rather complicated to me; so maybe you could explain your motivation.
In particular, why do you want a new applet on every reload? Would that not be rather confusing? Why not offer a link for each variant, so the user can choose?

Categories