/* $Id$ */
/* Copyright 2010 Sebastian Haufe
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
[url]http://www.apache.org/licenses/LICENSE-2.0[/url]
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package com.ebenius;
import java.io.*;
import java.net.*;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
public class SingleInstanceAppTest {
public static void main(String[] args)
throws IOException, InterruptedException, BackingStoreException {
if (args.length == 0) {
System.out.println("Nothing to do.");
System.exit(0);
}
final Preferences node =
Preferences.userNodeForPackage(SingleInstanceAppTest.class);
int port = node.getInt("SingleInstanceApp.listenPort", -1);
boolean running = false;
if (port != -1) {
try {
// App läuft schon
final Socket socket = new Socket(InetAddress.getLocalHost(), port);
final OutputStreamWriter w =
new OutputStreamWriter(socket.getOutputStream());
w.write(args[0]);
w.flush();
w.close();
socket.close();
running = true;
} catch (ConnectException ex) {
System.out.printf("Cannot connect to port %d.%n", port);
}
}
if (!running) {
port = createTCPListener();
node.putInt("SingleInstanceApp.listenPort", port);
node.flush();
handleCommand(args[0]);
// just for my test app: wait for infinity
final Object obj = new Object();
synchronized (obj) {
obj.wait();
}
}
}
private static int createTCPListener() throws IOException {
final ServerSocket serverSock = new ServerSocket();
serverSock.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
final Thread listenerThread = new Thread(new Runnable() {
public void run() {
try {
while (true) {
final Socket socket = serverSock.accept();
final InputStream is = socket.getInputStream();
final InputStreamReader r = new InputStreamReader(is);
final StringBuilder sb = new StringBuilder();
int c;
while ((c = r.read()) != -1) {
sb.append((char) c);
}
handleCommand(sb.toString());
socket.close();
}
} catch (IOException ex) {} finally {
applicationExit();
}
}
});
listenerThread.setName("SingleInstanceApp.tcpListener");
listenerThread.setDaemon(true);
listenerThread.setPriority(Thread.MIN_PRIORITY);
listenerThread.start();
System.out.println("Now listening to port: " + serverSock.getLocalPort());
return serverSock.getLocalPort();
}
static void handleCommand(String cmd) {
System.out.println("Now Playing: " + cmd);
}
static void applicationExit() {
// remove config when application ends
final Preferences node =
Preferences.userNodeForPackage(SingleInstanceAppTest.class);
node.remove("SingleInstanceApp.listenPort");
}
}