I'm working on java application which perform some Runtime sub-process on files, for some files I got error cause the Send error report to Microsoft window to appear ,I need to handle this error programmatically, without showing this window to user. Please can anyone help ?
To Suppress windows error reporting the .exe that is being invoked should not terminate with an unhandled exception. This only works if you have access to the source of the application.
Based on the WER Reference - you should use the Win32 API call WerAddExcludedApplication to add the specific .exe files that you are intending to ignore to the per-user ignore list - you could create a simple stub-application that allows you to add applications by name to the ignore list. Then when you invoke the application it does not trigger the error.
Similarly you could create another application to remove them using the WerRemoveExcludedApplication.
Alternatives are to use JNI/JNA to make a class to encapsulate this functionality rather than using Runtime.exec
Here is a simple example using Java Native Access (JNA), which is a simpler version of JNI (no C++ needed for the most part). Download the jna.jar and make it part of your project.
import com.sun.jna.Native;
import com.sun.jna.WString;
import com.sun.jna.win32.StdCallLibrary;
public class JNATest {
public interface CLibrary extends StdCallLibrary {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary("wer.dll",
CLibrary.class);
int WerAddExcludedApplication(WString name, boolean global);
int WerRemoveExcludedApplication(WString name, boolean global);
}
public static void main(String[] args) {
CLibrary.INSTANCE.WerAddExcludedApplication(new WString("C:\\foo.exe"), false);
CLibrary.INSTANCE.WerRemoveExcludedApplication(new WString("C:\\foo.exe"), false);
}
}
Basically, replace the new WString(...) value with the name of the application that you are intending to ignore. It should be ignored for the purposes of windows error reporting at that point.
Bear in mind that the wer.dll is only on Windows Vista and newer, so if this is a problem, then you may need to edit the registry entries manually.
You can always use try-catch-finally statement:
try
{
some code here (the code that is causing the error);
}
catch (Exception x)
{
handle exception here;
}
It works for me...
EDIT Here is the link that can help you a little bit more:
http://www.exampledepot.com/egs/Java%20Language/TryCatch.html
Related
Is there a way to check if a specific program is installed on Windows using Java?
I'm trying to develop a Java program that automatically creates zip archives by using the code line command from 7-Zip.
So, I would like to check in Java if on my windows OS '7-Zip' is already installed. No check for running apps or if OS is Windows or Linux. I want to get a bool (true/false) if '7-Zip' is installed on Windows.
The library Apache Commons has a class called SystemUtils - full documentation is available at https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SystemUtils.html.
In this library you have the following static boolean properties at your disposal:
SystemUtils.IS_OS_LINUX
SystemUtils.IS_OS_WINDOWS
The unix-like solution would be to simply try to run the program with --version flag (on windows probably the /? or - like in the 7zip case - without any at all) and check whether it fails, or what the return code will be.
Something like:
public boolean is7zipInstalled() {
try {
Process process = Runtime.getRuntime().exec("7zip.exe");
int code = process.waitFor();
return code == 0;
} catch (Exception e) {
return false;
}
}
I assume that you're talking about Windows. As Java is intended to be a platform-independent language and the way how to determine it differs per platform, there's no standard Java API to check that. You can however do it with help of JNI calls on a DLL which crawls the Windows registry. You can then just check if the registry key associated with the software is present in the registry. There's a 3rd party Java API with which you can crawl the Windows registry: jRegistryKey.
Here's an SSCCE with help of jRegistryKey:
package com.stackoverflow.q2439984;
import java.io.File;
import java.util.Iterator;
import ca.beq.util.win32.registry.RegistryKey;
import ca.beq.util.win32.registry.RootKey;
public class Test {
public static void main(String... args) throws Exception {
RegistryKey.initialize(Test.class.getResource("jRegistryKey.dll").getFile());
RegistryKey key = new RegistryKey(RootKey.HKLM, "Software\\Mozilla");
for (Iterator<RegistryKey> subkeys = key.subkeys(); subkeys.hasNext();) {
RegistryKey subkey = subkeys.next();
System.out.println(subkey.getName()); // You need to check here if there's anything which matches "Mozilla FireFox".
}
}
}
If you however intend to have a platformindependent application, then you'll also have to take into account the Linux/UNIX/Mac/Solaris/etc. (in other words: anywhere where Java is able to run) ways to detect whether FF is installed. Else you'll have to distribute it as a Windows-only application and do a System#exit() along with a warning whenever System.getProperty("os.name") is not Windows.
Sorry, I don't know how to detect in other platforms whether FF is installed or not, so don't expect an answer from me for that ;)
I want to create a GUI app in java for signing j2me app which is done by JadTool.jar but it is a Command Line Interface Apps. So I just want to use it as library and pass the parameters in program. How it can be done?
Check out Runtime. It will allow you to execute a command. You can use this to start your command line interface library.
Edit:
Ah, I didn't read care carefully earlier. If you're using a Java library starting a separate process is not the best solution.
Just reference the JadTool jar from your project. If the functionality you need isn't accessible in the library, edit the source and recompile. Make sure JadTool's license allows this.
If you're against editing the source (or not allowed) try using reflection to invoke the private run method you need.
A jar is just a library of classes, the fact that it can be run from the command line is caused by the presence of a main method in a class. As jadtool's source is available it's easy to see its very simple main:
public static void main(String[] args) {
int exitStatus = -1;
try {
new JadTool().run(args);
exitStatus = 0;
} catch (Exception e) {
System.err.println("\n" + e.getMessage() + "\n");
}
System.exit(exitStatus);
}
Unfortunately, that run() method is private, so calling it directly from another class won't work, leading to a reduced set of options:
#WilliamMorrison 's solution of going via Runtime - not really a library call, but it would work.
see Any way to Invoke a private method?
I use Eclipse Java 32Bit JDK. I am trying to import a 32-Bit DLL, which i got very few documentation for. I am using com.sun.jna.
The documentation tells me to call the method InitImagerIPC without any parameters.
As in this example i created an interface:
public interface ImagerIPC extends com.sun.jna.win32.StdCallLibrary{
HRESULT InitImagerIPC ();
}
When I try to import the DLL no error occurs.
ImagerIPC lib = (ImagerIPC) Native.loadLibrary ("ImagerIPC", ImagerIPC.class);
But I receive an UnsatisfiedLinkError if I mistype my DLL name. So I guess it's loaded correctly?
But when I try to call
lib.InitImagerIPC();
I get the UnsatisfiedLinkError. :(
Where's the mistake?
BTW: The DLL Export Viewer pulls out this info for the wanted method:
_InitImagerIPC#0 0x10001fc0 0x00001fc0 45 (0x2d)
ImagerIPC.dll J:\<my Path>\ImagerIPC.dll Exported Function
I am not sure about the naming. Do I also have to add the _?
Your DLL uses the stdcall calling convention, which typically has the compiler mangle function names to include the arguments' stack size. You need to use a StdCallFunctionMapper passed in as the Library.OPTION_FUNCTION_MAPPER option when you load your library (or recompile your library to use undecorated names).
Library.loadLibrary("myLib", myLib.class, new HashMap() { { put(Library.OPTION_FUNCTION_MAPPER, new StdCallFunctionMapper()); } });
I am trying to grab filesystem events on OS / Kernel level on OS X.
There are 2 requirements i have to follow. The first one is to do this in java as the whole project im developing for is written in java. The second one is that i have to find out when a document is opened.
For Linux I used inotify-java, but I can't find a good equivalent on OS X. Also the JNA doesn't provide a helpful binding. Currently I'm avoiding catching events by frequently calling the lsof program. This, however, is a bad solution.
Thanks for the help.
You can use dtrace on OSX, but since it needs root privileges it's not something you'd want to put into a runtime of a system.
In any case, you won't be able to do this in pure Java (any Java API would be a wrapper around some lower level C introspection, and if you're doing it kernel-wide, would need to be done as root).
If you just want to track when your program is opening files (as opposed to other files on the same system) then you can install your own Security Manager and implement the checkRead() family of methods, which should give you an idea of when accesses are happening.
import java.io.*;
public class Demo {
public static void main(String args[]) throws Exception {
System.setSecurityManager(new Sniffer());
File f = new File("/tmp/file");
new FileInputStream(f);
}
}
class Sniffer extends SecurityManager {
public void checkRead(String name) {
System.out.println("Opening " + name);
}
}
How do i call a Java command from a stand alone java program.
I understand that Runtime.getRuntime().exec("cmd c/ javac <>.java"); would work. However, this would be platform specific.
Any other APIs available that could make it work in j2sdk1.4 ?
If you can run everything in the same JVM, you could do something like this:
public class Launcher {
...
public static void main(String[] args) throws Exception {
launch(Class.forName(args[0]), programArgs(args, 1));
}
protected static void launch(Class program, String[] args) throws Exception {
Method main = program.getMethod("main", new Class[]{String[].class});
main.invoke(null, new Object[]{args});
}
protected static String[] programArgs(String[] sourceArgs, int n) {
String[] destArgs = new String[sourceArgs.length - n];
System.arraycopy(sourceArgs, n, destArgs, 0, destArgs.length);
return destArgs;
}
And run it with a command line like this:
java Launcher OtherClassWithMainMethod %CMD_LINE_ARGS%
Calling Runtime.getRuntime().exec() is not only platform specific, it is extremely inefficient. It will result in spawning a brand new shell and an entire jvm which could potentially be very expensive depending on the dependencies of this application (no pun intended).
The best way to execute "external" Java code would be to place it in your CLASSPATH. If you must call an application's main method you can simply import and call the method directly. This could be done like so:
import my.externals.SomeMain
// call as if we are running from console
SomeMain.main(new String[] {"some", "console", "arguments"})
Of course, the best case scenario would be to simply use this as an external library and access the code you need without having to call SomeMain.main(). Adhering to best practices and writing proper encapsulated modular objects allows for much greater portability and ease of use when being used by other applications.
When you leave the JVM and move to system commands, then you have to deal with the platform specific commands yourself. The JVM offers a good way for abstraction, so why move away?
If you want to execute java specific binaries, check out the ant libraries of java. You can execute ant scripts from java which execute platform depending commands.
Java programming from quercus php on GAE:
import com.newatlanta.commons.vfs.provider.gae.GaeVFS;
import org.apache.commons.io.IOUtils;
import java.lang.Long;
import java.lang.Boolean;
GaeVFS::setRootPath(quercus_servlet_request()->getSession(true)->getServletContext()->getRealPath('/'));
define('VFSM', GaeVFS::getManager());
//VFSM->resolveFile('gae://gaevfs')->createFolder();
$file=VFSM->resolveFile('gae://gaevfs/tmp1');
//$file->createFile();
$text='pp';
$method=$file->getClass()->getDeclaredMethod('updateContentSize', array(Long::TYPE, Boolean::TYPE));
$method->setAccessible(true);
$method->invoke($file, strlen($text), true);
$out=$file->getContent()->getOutputStream();
IOUtils::write($text, $out, 'UTF8');
$out->close();
$in=$file->getContent()->getInputStream();
$method=$file->getClass()->getDeclaredMethod('doGetContentSize',array());
$method->setAccessible(true);
$len=$method->invoke($file);
$whole=IOUtils::toString($in, 'UTF8').':'.$len."<br>";
$in->close();
echo $whole;
GaeVFS::clearFilesCache();
GaeVFS::close();