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

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-.

Related

CodenameOne Java String.Format "error: cannot find symbol" on Hello World example

A super-simple String.format("this is a test %d",5) doesn't work in my HelloWorld CodenameOne project: I get "error: cannot find symbol".
It doesn't seem to matter what format I used, I always get the same error. This seems to be an import problem, though I'm not importing any special packages outside of the defaults.
Here is the java source:
package com.test.test;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.io.NetworkEvent;
/**
* This file was generated by Codename One for the purpose
* of building native mobile applications using Java.
*/
public class MyApplication {
private Form current;
private Resources theme;
public void init(Object context) {
// use two network threads instead of one
updateNetworkThreadCount(2);
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
// Pro only feature
Log.bindCrashProtection(true);
/*
Updating property file: C:\Users\admin\Desktop\test2\build\built-jar.properties
Compile is forcing compliance to the supported API's/features for maximum device compatibility. This allows smaller
code size and wider device support
Compiling 1 source file to C:\Users\admin\Desktop\test2\build\tmp
C:\Users\admin\Desktop\test2\src\com\test\test\MyApplication.java:39: error: cannot find symbol
s = String.format("this is a test %d",5);
symbol: method format(String,int)
location: class String
1 error
C:\Users\admin\Desktop\test2\build.xml:62: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 0 seconds)
*/
String s;
s = String.format("this is a test %d",5);
addNetworkErrorListener(err -> {
// prevent the event from propagating
err.consume();
if(err.getError() != null) {
Log.e(err.getError());
}
Log.sendLogAsync();
Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
});
}
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("Hi World", BoxLayout.y());
hi.add(new Label("Hi World"));
hi.show();
}
public void stop() {
current = getCurrentForm();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = getCurrentForm();
}
}
public void destroy() {
}
}
CodenameOne compiles your source code using its own subset of the Java SE API, which is missing some features that the standard Java API includes.
Quoting their FAQ:
What features of Java are supported? What features of Java aren't supported?
The most obvious thing missing is reflections. The main problem is that when we package the VM into devices that don’t have Java, we would have to include EVERYTHING. If reflections were included, they wouldn’t work anyway since we obfuscate the code for the platforms where reflections do work (e.g. Android). On top of that reflection code is generally slow and a bad idea on a mobile device to begin with. As an alternative some developers were successful with bytecode manipulation which is something that is completely seamless to the server and as performant/efficient as handcoding.
Many of the desktop API’s such as java.net, java.io.File etc. aren’t very appropriate for mobile devices and just didn’t make it. We provide our own alternatives which are more portable and better suited for mobile settings.
Of the other missing things, if you run into a missing method or ability, there are cases where that functionality can be added.
Specifically, its version of java.lang.String does not include the format method.
In this case, it can be rewritten using simple string concatenation:
String s = "this is a test " + 5;

Could not load JIntellitype.dll from local file system or from inside JAR

I am trying to use JIntellitype to listen to global hotkeys but I get this error:
Exception in thread "main"
com.melloware.jintellitype.JIntellitypeException: Could not load
JIntellitype.dll from local file system or from inside JAR at
com.melloware.jintellitype.JIntellitype.(JIntellitype.java:114)
at
com.melloware.jintellitype.JIntellitype.getInstance(JIntellitype.java:177)
at utils.HotKey.(HotKey.java:19) at
ui.Main.Catch_Hotkeys(Main.java:78) at ui.Main.(Main.java:20)
at ui.Main.main(Main.java:15) Caused by: java.io.IOException:
FromJarToFileSystem could not load DLL:
com/melloware/jintellitype/JIntellitype.dll at
com.melloware.jintellitype.JIntellitype.fromJarToFs(JIntellitype.java:150)
at
com.melloware.jintellitype.JIntellitype.(JIntellitype.java:105)
... 5 more Caused by: java.lang.NullPointerException at
com.melloware.jintellitype.JIntellitype.fromJarToFs(JIntellitype.java:146)
... 6 more
I have loaded the jar file and I also pointed to the folder where the dlls are located through Referenced Libraries.
Here is the code I am trying to run:
import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.IntellitypeListener;
import com.melloware.jintellitype.JIntellitype;
public class HotKey extends Thread implements HotkeyListener, IntellitypeListener {
private final int CTRL_C_SHIFT = 10;
public HotKey()
{
JIntellitype.getInstance().unregisterHotKey(CTRL_C_SHIFT);
JIntellitype.getInstance().registerHotKey(CTRL_C_SHIFT, JIntellitype.MOD_CONTROL + (int)'C', JIntellitype.MOD_SHIFT);
if (!JIntellitype.isJIntellitypeSupported())
{
System.exit(1);
}
}
#Override
public void onIntellitype(int arg0)
{
}
#Override
public void onHotKey(int key)
{
if (key == CTRL_C_SHIFT)
{
System.out.println("smg");
}
}
}
Any idea how to fix this?
Your problem will occur because of a version problem between that OS version and the JRE version.
You should check:
Whether an appropriate dll file is installed in your OS system folder.
JIntellitype package has two dll files, one is for 32bit OSs and the other is for 64bit OSs, they have different names.
Check your Java Platform version in the properties of the projects.
You can try to change the Java Platform, if there are more than one types of JDKs.
Make sure about which one is for 64bit or 32bit version.
Have good luck!
I recommend you do something like this:
try
{
JIntellitype.getInstance().unregisterHotKey(CTRL_C_SHIFT);
MyHotKeyListener hotKeyListener = new MyHotKeyListener();
hotKeyListener.addObserver(new MyEventListener());
JIntellitype.getInstance().addHotKeyListener(hotKeyListener);
JIntellitype.getInstance().registerHotKey(CTRL_C_SHIFT, JIntellitype.MOD_CONTROL + (int)'C', JIntellitype.MOD_SHIFT);
}
catch (JIntellitypeException je)
{
logger.warn("JIntellitype initialization failed.");
// DO WHATEVER (NOTIFY USERS?)
}
I can point to other threads, including one where the creator of this library himself denies problems with the library. However, many users such as myself encounter these sort of problems from time to time where JIntellitype fails to initialize and the only solution is to reboot the computer. Because of this, you should catch the JIntellitype exception (the only exception thrown by the library) and warn users (via dialog window) that the hotkey failed to register. You should give them the option to continue without them, or to reboot the computer and trying again.
Trust me.... unless this is a constant problem (which means you configured it incorrectly), it is your best alternative. This WILL happen from time to time at random.

Put a program icon depending on the platform

I've realized that my code has a problem with setting a program icon (instead of the java one) in different platforms. I had written this code for windows and mac:
private void putIcon() {
URL url = ClassLoader.getSystemResource("resources/icon.png");
String name = System.getProperty("os.name");
if (name.startsWith("Win")) {
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
this.setIconImage(img);
} else {
Application.getApplication().setDockIconImage(new ImageIcon(url).getImage());
}
}
While I was testing it in mac there was not problem, but when I tried it windows I realized that won't work because that class isn't in windows:
import com.apple.eawt.Application;
What could I do to solve this issue? For what I've researched it's not possible to have some kind of "if" in the import section of the code, and if that class is there in windows it won't compile.
Check if the specified class Application can be found by using
Class.forName("com.apple.eawt.Application");
If this method does not throw a ClassNotFoundException, invoke the methods you want by using reflection only. Seems a bit hacky but it should work.
Also make sure that you are not importing the class.

java.lang.UnsatisfiedLinkError: jssc.SerialNativeInterface.getSerialPortNames()

I'm doing a processing based project with eclipse and Procliping. When I'm testing the project with "Run" command inside the IDE, everything works fine. But if I export it into a runable-jar, when I run the jar it'll give this error on the line String[] li=Serial.list();. Any idea what's going wrong?
Java source attachment is "processing-2.2.1/modes/java/libraries/serial/src"
And here is a sample code:
package abcd;
import processing.core.PApplet;
import processing.serial.Serial;
public class TestUI extends PApplet {
Serial port;
public void setup(){
System.out.println(Serial.list());
}
public void draw(){
}
public static void main(String _args[]) {
PApplet.main(new String[] { abcd.TestUI.class.getName() });
}
}
My approach of solving it:
Download the latest version of java-simple-serial-connector(Which is the base library used for Processing's serial library), replace jssc.jar in the lib folder, and the error will be gone, and my application runs smoothly.
However the base library is 4 times bigger than the modified version used in Processing, so there may be some unnecessary features involved.
Seems like in their latest alpha version, Processing solved the same problem for exporting apps(at least in windows) by adding more look-up paths, while keeping their Serial library intact. I'm not familiar with their development environment, so I didn't look further into it. There may be a simpler solution.

Java: CaptureDeviceManager#getDeviceList() is empty?

I am trying to print out all of the capture devices that are supported using the #getDeviceList() method in the CaptureDeviceManager class and the returned Vector has a size of 0.
Why is that? I have a webcam that works - so there should be at least one. I am running Mac OS X Lion - using JMF 2.1.1e.
Thanks!
CaptureDeviceManager.getDeviceList(Format format) does not detect devices. Instead it reads from the JMF registry which is the jmf.properties file. It searches for the jmf.properties file in the classpath.
If your JMF install has succeeded, then the classpath would have been configured to include all the relevant JMF jars and directories. The JMF install comes with a jmf.properties file included in the 'lib' folder under the JMF installation directory. This means the jmf.properties would be located by JMStudio and you would usually see the JMStudio application executing correctly. (If your JMF install is under 'C:\Program Files', then run as administrator to get around UAC)
When you create your own application to detect the devices, the problem you described above might occur. I have seen a few questions related to the same problem. This is because your application's classpath might be different and might not include the environment classpath. Check out your IDE's properties here. The problem is that CaptureDeviceManager cannot find the jmf.properties file because it is not there.
As you have found out correctly, you can copy the jmf.properties file from the JMF installation folder. It would contain the correct device list since JMF detects it during the install (Check it out just to make sure anyway).
If you want do device detection yourself, then create an empty jmf.properties file and put it somewhere in your classpath (it might throw a java.io.EOFException initially during execution but that's properly handled by the JMF classes). Then use the following code for detecting webcams...
import javax.media.*;
import java.util.*;
public static void main(String[] args) {
VFWAuto vfwObj = new VFWAuto();
Vector devices = CaptureDeviceManager.getDeviceList(null);
Enumeration deviceEnum = devices.elements();
System.out.println("Device count : " + devices.size());
while (deviceEnum.hasMoreElements()) {
CaptureDeviceInfo cdi = (CaptureDeviceInfo) deviceEnum.nextElement();
System.out.println("Device : " + cdi.getName());
}
}
The code for the VFWAuto class is given below. This is part of the JMStudio source code. You can get a good idea on how the devices are detected and recorded in the registry. Put both classes in the same package when you test. Disregard the main method in the VFWAuto class.
import com.sun.media.protocol.vfw.VFWCapture;
import java.util.*;
import javax.media.*;
public class VFWAuto {
public VFWAuto() {
Vector devices = (Vector) CaptureDeviceManager.getDeviceList(null).clone();
Enumeration enum = devices.elements();
while (enum.hasMoreElements()) {
CaptureDeviceInfo cdi = (CaptureDeviceInfo) enum.nextElement();
String name = cdi.getName();
if (name.startsWith("vfw:"))
CaptureDeviceManager.removeDevice(cdi);
}
int nDevices = 0;
for (int i = 0; i < 10; i++) {
String name = VFWCapture.capGetDriverDescriptionName(i);
if (name != null && name.length() > 1) {
System.err.println("Found device " + name);
System.err.println("Querying device. Please wait...");
com.sun.media.protocol.vfw.VFWSourceStream.autoDetect(i);
nDevices++;
}
}
}
public static void main(String [] args) {
VFWAuto a = new VFWAuto();
System.exit(0);
}
}
Assuming you are on a Windows platform and you have a working web-cam, then this code should detect the device and populate the jmf.properties file. On the next run you can also comment out the VFWAuto section and it's object references and you can see that CaptureDeviceManager reads from the jmf.properties file.
The VFWAuto class is part of jmf.jar. You can also see the DirectSoundAuto and JavaSoundAuto classes for detecting audio devices in the JMStudio sample source code. Try it out the same way as you did for VFWAuto.
My configuration was Windows 7 64 bit + JMF 2.1.1e windows performance pack + a web-cam.
I had the same issue and I solved by invoking flush() on my ObjectInputStream object.
According to the API documentation for ObjectInputStream's constructor:
The stream header containing the magic number and version number are read from the stream and verified. This method will block until the corresponding ObjectOutputStream has written and flushed the header.
This is a very important point to be aware of when trying to send objects in both directions over a socket because opening the streams in the wrong order will cause deadlock.
Consider for example what would happen if both client and server tried to construct an ObjectInputStream from a socket's input stream, prior to either constructing the corresponding ObjectOutputStream. The ObjectInputStream constructor on the client would block, waiting for the magic number and version number to arrive over the connection, while at the same time the ObjectInputStream constructor on the server side would also block for the same reason. Hence, deadlock.
Because of this, you should always make it a practice in your code to open the ObjectOutputStream and flush it first, before you open the ObjectInputStream. The ObjectOutputStream constructor will not block, and invoking flush() will force the magic number and version number to travel over the wire. If you follow this practice in both your client and server, you shouldn't have a problem with deadlock.
Credit goes to Tim Rohaly and his explanation here.
Before calling CaptureDeviceManager.getDeviceList(), the available devices must be loaded into the memory first.
You can do it manually by running JMFRegistry after installing JMF.
or do it programmatically with the help of the extension library FMJ (Free Media in Java). Here is the code:
import java.lang.reflect.Field;
import java.util.Vector;
import javax.media.*;
import javax.media.format.RGBFormat;
import net.sf.fmj.media.cdp.GlobalCaptureDevicePlugger;
public class FMJSandbox {
static {
System.setProperty("java.library.path", "D:/fmj-sf/native/win32-x86/");
try {
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
GlobalCaptureDevicePlugger.addCaptureDevices();
Vector deviceInfo = CaptureDeviceManager.getDeviceList(new RGBFormat());
System.out.println(deviceInfo.size());
for (Object obj : deviceInfo ) {
System.out.println(obj);
}
}
}
Here is the output:
USB2.0 Camera : civil:\\?\usb#vid_5986&pid_02d3&mi_00#7&584a19f&0&0000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global
RGB, -1-bit, Masks=-1:-1:-1, PixelStride=-1, LineStride=-1

Categories