Get MS-Windows Installed Applications from Java - java

Is it possible to get a list of installed applications (like the list from the un-install programs) from a windows vista computer with java?

If you mean installed applications I don't think it's possible by directly using Java SDK (also because it's not a cross platform requirement).. what I think you can do is to use an external native API to interact with windows registry (like jRegistryKey) and retrieve the information you need..
Instead if you want to get all the running applications from a Java program you could parse tasklist.exe output as explained here.

Not a Solution but a workaround!!
Getting windows native information using java SDK is not possible without support of external APIs. Instead of using external APIs (which is mostly LGPL licensed and not completely open), we can use the shell commands to get the same.
For getting the installed softwares list, use ProcessBuilder or Runtime.exec to run one of the following PowerShell commands:
Get-WmiObject -class Win32_Product | Select-Object -Property Name - This is bit slower! It uses Win32_Product class.
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate - This is faster and can give additional details. This uses PS registry provider.
You can stream the output of these and process it.
This is just a workaround and it is as per my analysis. As java is completely platform independent, fetching native information becomes difficult and the use of platform native tools (like command shell,, power shell etc.,) is a must.

package Vishal;
import com.sun.jna.platform.win32.Advapi32Util;
import static com.sun.jna.platform.win32.WinReg.HKEY_LOCAL_MACHINE;
import java.util.ArrayList;
import java.util.TreeMap;
public class GenerateInstalledApplicationList
{
ArrayList<String> getlist()
{
ArrayList<String> arr = new ArrayList();
String [] keys = Advapi32Util.registryGetKeys(HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
String temp;
for (String key : keys)
{
temp = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall" + "\\" +key;
TreeMap<String, Object> tr = Advapi32Util.registryGetValues(HKEY_LOCAL_MACHINE,temp);
if(tr.isEmpty())
{
if(!key.contains("Update"))//all the instances of update are not actually installed applications
{
arr.add(key);
}
}
else
{
if(tr.containsKey("DisplayName"))
{
String str = (String) tr.get("DisplayName");
if(!str.contains("Update"))
{
arr.add(str);
}
}
}
}
return arr;
}}
Just Copy and paste this code it will return all the installed applications
only thing you will need is the jna api.

Related

Access parameters from custom URI scheme in Java application on OS X

I've successfully added a custom URI scheme in info.plist on OS X so my Java 1.7 based application (written in Netbeans) is launched whenever the user enters "myApp:SomeParameter" in their browser:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>My App</string>
<key>CFBundleURLSchemes</key>
<array>
<string>myApp</string>
</array>
</dict>
</array>
I have also successfully added the corresponding registry entry for the application if installed on a Windows machine. The problem is that on the Windows platform I can easily pass on parameters (in the above case I want "SomeParameter" from the entered uri "myApp:SomeParameter"). It is simply passed on to the application main method as regular parameters, but this is not the case on OS X. I have done some research and tried this solution but it requires some Cocoa libraries and causes issues when compiled and run on Windows.
EDIT: I have tried to track down a version of AppleJavaExtensions that contains the com.apple.eawt.Application.setOpenURIHandler() but I've only found version 1.4 where it's missing. Any idea why?
Is there another way to pass parameters from a custom URI scheme to a cross platform Java application running on Mac / OS X?
EDIT 2: Please see accepted answer below, but as a side note: we successfully experimented with a possible workaround using AppleScript as a middle-tier. The script in this article can be simplified to receive the full URL with parameters, and then invoke your Java based application with the query string as normal command line parameters.
It looks like you're on the right track. Your Info.plist looks correct. You don't need to create any custom native Cocoa code, just use setOpenURIHandler(). For example:
public class AppleMenus implements com.apple.eawt.OpenURIHandler {
private MyApp myApp;
public AppleMenus(MyApp myApp) {
this.myApp = myApp;
final com.apple.eawt.Application app = com.apple.eawt.Application.getApplication();
app.setOpenURIHandler(this);
}
#Override
public void openURI(final com.apple.eawt.AppEvent.OpenURIEvent oue) {
myApp.openCustomURL(oue.getURI());
}
}
The only reason you would need AppleJavaExtensions is if you are trying to compile this code on a non-Apple environment, such as Windows. Windows won't know what OpenURIHandler is, so you will get a compile error there. AppleJavaExtensions just provides that necessary API without implementation, just for the purposes of being able to compile in these other environments.
Here, is the official latest (and probably last) version: https://developer.apple.com/legacy/library/samplecode/AppleJavaExtensions/Introduction/Intro.html
Note that your URI handler will be called in the currently running instance of you app or will first create a new instance of your app then get called. The OpenURIEvent will contain the entire URI message you send.
The following (for Java 9) will work cross platform (Windows and macOS has been tested):
import java.awt.*;
import java.awt.desktop.OpenURIEvent;
import java.awt.desktop.OpenURIHandler;
import java.net.URI;
import java.net.URISyntaxException;
public class UriLaunchedApp {
public static void main(String[] args) throws URISyntaxException {
try {
Desktop.getDesktop().setOpenURIHandler(new OpenURIHandler() {
#Override
public void openURI(OpenURIEvent e) {
System.out.println("We are maybe on macOS...");
processUri(e.getURI());
}
});
} catch (UnsupportedOperationException e) {
System.out.println("We are maybe on Windows...");
processUri(new URI(args[0]));
}
}
private static void processUri(URI uri) {
System.out.println("Do something with " + uri);
}
}
See too https://docs.oracle.com/javase/9/docs/api/java/awt/Desktop.html#setOpenURIHandler-java.awt.desktop.OpenURIHandler-.

Can Eclipse for Java and Eclipse for WEBMethods be on the same hard drive?

I am new to WEBMethods. I have been working on a Java service for a project. I really need to be able to write some code in regular Java for some quick testing of reading in a simple text expression with some regular expressions. Nothing at all that fancy with the Java part. But eclipse currently is set up for WEBMethods and I need to be in a regular Java mode for Eclipse (If there is such a thing). At home I have the standard eclipse version and have no trouble writting code. But at work I have WEBMethods installed in the Eclipse (Software AG Designer). I think that if I can write the code in regular Java then I can just copy and paste it into the WEBMethods Java services and set up the INPUT and OUTPUT variables and it should work. But currently I cannot find a way to just write Java code like I do from my home computer.
Question: How can I write just a regular Java program (classes, packages, ...etc...) with a machine with WEBMethods installed? Do I have to install another session of Eclipse on my hard drive? (I tried this a while back and there was an issue with having more than one session of Eclipse on the machine).
Java Web Services Code:
package DssAccessBackup.services.flow;
import com.wm.data.*;
import com.wm.util.Values;
import com.wm.app.b2b.server.Service;
import com.wm.app.b2b.server.ServiceException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public final class new_javaService_SVC
{
/**
* The primary method for the Java service
*
* #param pipeline
* The IData pipeline
* #throws ServiceException
*/
public static final void new_javaService(IData pipeline)
throws ServiceException {
// pipeline
IDataCursor pipelineCursor = pipeline.getCursor();
String inputFileName = IDataUtil.getString( pipelineCursor, "inputFileName" );
pipelineCursor.destroy();
// pipeline
IDataCursor pipelineCursor_1 = pipeline.getCursor();
IDataUtil.put( pipelineCursor_1, "fileName", "fileName" );
// outDoc
IData outDoc = IDataFactory.create();
IDataUtil.put( pipelineCursor_1, "outDoc", outDoc );
pipelineCursor_1.destroy();
String fileName = new String();
fileName = null;
try {
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\itpr13266\\Desktop\\TestFile.txt"));
String line = null;
//Will read through the file until EOF
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Try-Catch Message - " + e.getMessage());
e.printStackTrace();
}
}
// --- <<IS-BEGIN-SHARED-SOURCE-AREA>> ---
// --- <<IS-END-SHARED-SOURCE-AREA>> ---
}
You don't need to install another Eclipse for Java development. WebMethods Designer (v9) comes with Java tooling. Just open the Java perspective and use it.
Besides that you should use the Service Development perspective, when developing WebMethods Java Services, because WM Designer handles Java services in a special way, which could make importing standard Java files difficult.
There is no problem running multiple instances of Eclipse at the same time as long as they point to different workspaces.
Normally you get a dialog to choose the workspace when Eclipse starts up. If not, check this answer on how to enable that dialog: https://stackoverflow.com/a/8616216/1599890
So if you download, unzip and set up Eclipse for Java development and point it to another workspace than Software AG Designer uses you should be good to go.

Lotus Domino 8.5.2 Java Agent , write Metadata to extracted attachments?

I'm using Lotus Domino server 8.5.2. Using Java scheduled agents, I can extract the attachments of several Lotus Domino Documents in to the file system (win 32). The Idea is that after extraction I need add some metadata to the files and upload the files to another system.
Does someone knows, or can give me a few tips (preferably using Java) of how I can write some metadata to the extracted files? I need add some keywords, change the author, and so on. I understand Lotus Domino 8.5.2 supports Java 6
thank you!
Alex.
According to this answer, Java 7 has a native ability to manipulate Windows metadata but Java 6 does not.
It does say that you can use Java Native Access (JNA) to make calls to native DLLs, which means you should be able to use dsofile.dll to manipulate the metadata. Example from here of using JNA to access the "puts" function from msvcrt.dll (couldn't find any examples specific to dsofile.dll):
Interface
package CInterface;
import com.sun.jna.Library;
public interface CInterface extends Library
{
public int puts(String str);
}
Sample class
// JNA Demo. Scriptol.com
package CInterface;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class hello
{
public static void main(String[] args)
{
String mytext = "Hello World!";
if (args.length != 1)
{
System.err.println("You can enter your own text between quotes...");
System.err.println("Syntax: java -jar /jna/dist/demo.jar \"myowntext\"");
}
else
mytext = args[0];
// Library is c for unix and msvcrt for windows
String libName = "c";
if (System.getProperty("os.name").contains("Windows"))
{
libName = "msvcrt";
}
// Loading dynamically the library
CInterface demo = (CInterface) Native.loadLibrary(libName, CInterface.class);
demo.puts(mytext);
}
}

Running a Java program from Adobe AIR's native process

I've use Adobe native process to run java program from my air app. Here the code and it works fine. But i should write absolute path to java runtime for that:
/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java.
If user installed java runtime in diff folder, or have diff version then this code would not work. How i can detect where java were installed or maybe there is another right way to run java applications from air applications? If i run java library from terminal command line then i could just write "java -jar pdfbox-app-1.6.0.jar" etc. and it runs fine.
private function convertPdf2Txt():void{
var arg:Vector.<String> = new Vector.<String>;
arg.push("-jar");
arg.push(File.applicationDirectory.resolvePath("pdfbox-app-1.6.0.jar").nativePath);
arg.push("ExtractText");
arg.push("-force");
arg.push(File.applicationStorageDirectory.resolvePath("Data/1.pdf").nativePath);
arg.push(File.applicationStorageDirectory.resolvePath("Data/1.txt").nativePath);
var fjava:File = new File("/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java");
if (fjava.exists==false){
Alert.show("Can't find Java Runtime in default folder.","Idea Rover",mx.controls.Alert.OK, null,null,imgInfo);
return;
}
var npInfo:NativeProcessStartupInfo;
npInfo = new NativeProcessStartupInfo();
npInfo.executable = fjava;
npInfo.arguments = arg;
var nativeProcess:NativeProcess;
nativeProcess = new NativeProcess();
nativeProcess.addEventListener(NativeProcessExitEvent.EXIT,onNativeProcessExit);
nativeProcess.start(npInfo);
}
Absolute path is:
Mac OS: /usr/bin/java
Win OS: (default)
64bit : C:\Program Files\Java
32bit : C:\Program Files (x86)\Java
rather than popping up an Alert, you could open a file selection dialog, using File.browseForOpen(). then, the File you want is contained in the event passed by the Event.SELECT handler. this flow seems standard for applications i've used that need to access other applications, but aren't sure where to find their executables.
var npInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
// setup npInfo, nativeProcess...
var fjava:File = new File("/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java");
if (!fjava.exists) {
fjava.addEventListener(Event.SELECT, onFileSelected);
fjava.browseForOpen("Where is Java located?");
}
private function onFileSelected (evt:Event) :void {
npInfo.executable = evt.target;
nativeProcess.start(npInfo);
fjava.removeEventListener(Event.SELECT, onFileSelected);
}
of course, you can use the same logic to find the file java needs to launch as well.
You may be able to determine where the Java binaries are by looking at the JAVA_HOME environment variable. I'd like to do the same thing as you're doing, so I'll post more after I do more research.

Is *this* really the best way to start a second JVM from Java code?

This is a followup to my own previous question and I'm kind of embarassed to ask this... But anyway: how would you start a second JVM from a standalone Java program in a system-independent way? And without relying on for instance an env variable like JAVA_HOME as that might point to a different JRE than the one that is currently running. I came up with the following code which actually works but feels just a little awkward:
public static void startSecondJVM() throws Exception {
String separator = System.getProperty("file.separator");
String classpath = System.getProperty("java.class.path");
String path = System.getProperty("java.home")
+ separator + "bin" + separator + "java";
ProcessBuilder processBuilder =
new ProcessBuilder(path, "-cp",
classpath,
AnotherClassWithMainMethod.class.getName());
Process process = processBuilder.start();
process.waitFor();
}
Also, the currently running JVM might have been started with some other parameters (-D, -X..., ...) that the second JVM would not know about.
I think that the answer is "Yes". This probably as good as you can do in Java using system independent code. But be aware that even this is only relatively system independent. For example, in some systems:
the JAVA_HOME variable may not have been set,
the command name used to launch a JVM might be different (e.g. if it is not a Sun JVM), or
the command line options might be different (e.g. if it is not a Sun JVM).
If I was aiming for maximum portability in launching a (second) JVM, I think I would do it using wrapper scripts.
It's not clear to me that you would always want to use exactly the same parameters, classpath or whatever (especially -X kind of stuff - for example, why would the child need the same heap settings as its parents) when starting a secondary process.
I would prefer to use an external configuration of some sort to define these properties for the children. It's a bit more work, but I think in the end you will need the flexibility.
To see the extent of possible configuration settings you might look at thye "Run Configurations" settings in Eclipse. Quite a few tabs worth of configuration there.
To find the java executable that your code is currently running under (i.e. the 'path' variable in your question's sample code) there is a utility method within apache ant that can help you. You don't have to build your code with ant - just use it as a library, for this one method.
It is:
org.apache.tools.ant.util.JavaEnvUtils.getJreExecutable("java")
It takes care of the sort of special cases with different JVM vendors that others have mentioned. (And looking at the source code for it, there are more special cases than I would have imagined.)
It's in ant.jar. ant is distributed under the Apache license so hopefully you can use it how you want without hassle.
Here's a way that determines the java executable which runs the current JVM using ProcessHandle.current().info().command().
The ProcessHandle API also should allow to get the arguments. This code uses them for the new JVM if available, only replacing the current class name with another sample class. (Finding the current main class inside the arguments gets harder if you don't know its name, but in this demo it's simply "this" class. And maybe you want to reuse the same JVM options or some of them, but not the program arguments.)
However, for me (openjdk version 11.0.2, Windows 10), the ProcessInfo.arguments() is empty, so the fallback else path gets executed.
package test;
import java.lang.ProcessBuilder.Redirect;
import java.lang.management.ManagementFactory;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TestStartJvm {
public static void main(String[] args) throws Exception {
ProcessHandle.Info currentProcessInfo = ProcessHandle.current().info();
List<String> newProcessCommandLine = new LinkedList<>();
newProcessCommandLine.add(currentProcessInfo.command().get());
Optional<String[]> currentProcessArgs = currentProcessInfo.arguments();
if (currentProcessArgs.isPresent()) { // I know about orElse, but sometimes isPresent + get is handy
for (String arg: currentProcessArgs.get()) {
newProcessCommandLine.add(TestStartJvm.class.getName().equals(arg) ? TargetMain.class.getName() : arg);
}
} else {
System.err.println("don't know all process arguments, falling back to passed args array");
newProcessCommandLine.add("-classpath");
newProcessCommandLine.add(ManagementFactory.getRuntimeMXBean().getClassPath());
newProcessCommandLine.add(TargetMain.class.getName());
newProcessCommandLine.addAll(List.of(args));
}
ProcessBuilder newProcessBuilder = new ProcessBuilder(newProcessCommandLine).redirectOutput(Redirect.INHERIT)
.redirectError(Redirect.INHERIT);
Process newProcess = newProcessBuilder.start();
System.out.format("%s: process %s started%n", TestStartJvm.class.getName(), newProcessBuilder.command());
System.out.format("process exited with status %s%n", newProcess.waitFor());
}
static class TargetMain {
public static void main(String[] args) {
System.out.format("in %s: PID %s, args: %s%n", TargetMain.class.getName(), ProcessHandle.current().pid(),
Stream.of(args).collect(Collectors.joining(", ")));
}
}
}
Before ProcessHandle was added in Java 9, I did something like this to query the current JVM's command-line:
Let the user pass or configure a "PID to command-line" command template; under Windows, this could be wmic process where 'processid=%s' get commandline /format:list.
Determine PID using java.lang.management.ManagementFactory.getRuntimeMXBean().getPid().
Expand command template; execute; parse its output.

Categories