samples/deadlock/src/org/apidesign/deadlock/startuplock/CLIHandlerBlocking.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:58:11 +0200
changeset 154 0fd5e9c500b9
parent 153 b5cbb797ec0a
permissions -rw-r--r--
Merge: Geertjan's changs up to 2000
jtulach@106
     1
package org.apidesign.deadlock.startuplock;
jtulach@106
     2
jtulach@106
     3
import java.io.DataOutputStream;
jtulach@106
     4
import java.io.File;
jtulach@106
     5
import java.io.FileOutputStream;
jtulach@106
     6
import java.io.IOException;
jtulach@106
     7
import java.net.ServerSocket;
jtulach@106
     8
import java.util.logging.Level;
jtulach@106
     9
import java.util.logging.Logger;
jtulach@106
    10
jtulach@106
    11
public final class CLIHandlerBlocking {
jtulach@106
    12
    // BEGIN: cli.real
jtulach@106
    13
    public static int start(File lockFile) throws IOException {
jtulach@106
    14
        enterState(10);
jtulach@106
    15
        if (lockFile.exists ()) {
jtulach@106
    16
            // read the port number and connect to it
jtulach@106
    17
            enterState(11);
jtulach@106
    18
            int alive = readPortNumber(lockFile);
jtulach@106
    19
            if (alive != -1) {
jtulach@106
    20
                // exit
jtulach@106
    21
                return alive;
jtulach@106
    22
            }
jtulach@106
    23
        }
jtulach@106
    24
        // otherwise try to create the file yourself
jtulach@106
    25
        enterState(20);
jtulach@106
    26
        lockFile.createNewFile();
jtulach@154
    27
        DataOutputStream os = new DataOutputStream(
jtulach@154
    28
            new FileOutputStream(lockFile)
jtulach@154
    29
        );
jtulach@106
    30
        ServerSocket server = new ServerSocket();
jtulach@106
    31
        enterState(21);
jtulach@106
    32
        int p = server.getLocalPort();
jtulach@106
    33
        enterState(22);
jtulach@106
    34
        os.writeInt(p);
jtulach@106
    35
        enterState(23);
jtulach@106
    36
        
jtulach@106
    37
        return p;
jtulach@106
    38
    }
jtulach@106
    39
    // END: cli.real
jtulach@106
    40
jtulach@106
    41
    private static Logger LOG = Logger.getLogger(CLIHandlerBlocking.class.getName());
jtulach@106
    42
    private static void enterState(int state) {
jtulach@106
    43
        LOG.log(Level.FINEST, "enterState {0}", state);
jtulach@106
    44
    }
jtulach@106
    45
jtulach@106
    46
    private static int readPortNumber(File lockFile) throws IOException {
jtulach@106
    47
        return -1;
jtulach@106
    48
    }
jtulach@106
    49
}