Example usage for java.net InetAddress getByName

List of usage examples for java.net InetAddress getByName

Introduction

In this page you can find the example usage for java.net InetAddress getByName.

Prototype

public static InetAddress getByName(String host) throws UnknownHostException 

Source Link

Document

Determines the IP address of a host, given the host's name.

Usage

From source file:Logi.GSeries.Service.LogiGSKService.java

/**
 * @param args the command line arguments
 *//*from   ww w  .j av a  2 s . com*/
public static void main(String[] args) {
    SystemTray.DEBUG = false;

    Settings settings;
    if (IOOperations.currentSettingsExist()) {
        settings = IOOperations.loadCurrentSettingsObjectFromFile();
    } else {
        settings = new Settings();
    }

    LogiGSKService l = new LogiGSKService();
    if (settings.getShowSystemTray()) {
        l.showSystemTray();
    } else {
        l.hideSystemTray();
    }
    l.begin();
    try {
        String dataFolderPath = IOOperations.getLocalDataDirectoryPath();
        File dataFolder = new File(dataFolderPath);
        if (!dataFolder.exists()) {
            dataFolder.mkdir();
        }
        String logFolderPath = IOOperations.getLogDirectoryPath();
        File logFolder = new File(logFolderPath);
        if (!logFolder.exists()) {
            logFolder.mkdir();
        }
        FileHandler fileHandler = new FileHandler(logFolderPath + "LogiGSK.log", FILE_SIZE, 3);
        fileHandler.setLevel(Level.ALL);
        logger.setLevel(Level.ALL);
        logger.addHandler(fileHandler);
    } catch (IOException | SecurityException ex) {
        Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
    }
    int clientNumber = 0;
    ServerSocket listener = null;
    PropertyConfigurator.configure(LogiGSKService.class.getResource("/Logi/GSeries/Service/log4j.properties"));
    reloading = true;
    boolean firstTime = true;
    while (reloading) {
        listener = null;
        if (reloading && !firstTime) {
            if (IOOperations.currentSettingsExist()) {
                settings = IOOperations.loadCurrentSettingsObjectFromFile();
            } else {
                settings = new Settings();
            }
        }
        firstTime = false;
        reloading = false;
        running = true;
        try {
            listener = new ServerSocket(settings.getPort(), 0, InetAddress.getByName(null));
            while (running) {
                new Manager(listener.accept(), clientNumber++, logger).start();
            }
        } catch (IOException ex) {
            Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (listener != null) {
                try {
                    listener.close();
                } catch (IOException ex) {
                    Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

From source file:com.entertailion.java.caster.Main.java

/**
 * @param args//from w ww . ja v  a 2s . com
 */
public static void main(String[] args) {
    // http://commons.apache.org/proper/commons-cli/usage.html
    Option help = new Option("h", "help", false, "Print this help message");
    Option version = new Option("V", "version", false, "Print version information");
    Option list = new Option("l", "list", false, "List ChromeCast devices");
    Option verbose = new Option("v", "verbose", false, "Verbose debug logging");
    Option transcode = new Option("t", "transcode", false, "Transcode media; -f also required");
    Option rest = new Option("r", "rest", false, "REST API server");

    Option url = OptionBuilder.withLongOpt("stream").hasArg().withValueSeparator()
            .withDescription("HTTP URL for streaming content; -d also required").create("s");

    Option server = OptionBuilder.withLongOpt("device").hasArg().withValueSeparator()
            .withDescription("ChromeCast device IP address").create("d");

    Option id = OptionBuilder.withLongOpt("app-id").hasArg().withValueSeparator()
            .withDescription("App ID for whitelisted device").create("id");

    Option mediaFile = OptionBuilder.withLongOpt("file").hasArg().withValueSeparator()
            .withDescription("Local media file; -d also required").create("f");

    Option transcodingParameters = OptionBuilder.withLongOpt("transcode-parameters").hasArg()
            .withValueSeparator().withDescription("Transcode parameters; -t also required").create("tp");

    Option restPort = OptionBuilder.withLongOpt("rest-port").hasArg().withValueSeparator()
            .withDescription("REST API port; default 8080").create("rp");

    Options options = new Options();
    options.addOption(help);
    options.addOption(version);
    options.addOption(list);
    options.addOption(verbose);
    options.addOption(url);
    options.addOption(server);
    options.addOption(id);
    options.addOption(mediaFile);
    options.addOption(transcode);
    options.addOption(transcodingParameters);
    options.addOption(rest);
    options.addOption(restPort);
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    //String[] arguments = new String[] { "-vr" };

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        Option[] lineOptions = line.getOptions();
        if (lineOptions.length == 0) {
            System.out.println("caster: try 'java -jar caster.jar -h' for more information");
            System.exit(0);
        }

        Log.setVerbose(line.hasOption("v"));

        // Custom app-id
        if (line.hasOption("id")) {
            Log.d(LOG_TAG, line.getOptionValue("id"));
            appId = line.getOptionValue("id");
        }

        // Print version
        if (line.hasOption("V")) {
            System.out.println("Caster version " + VERSION);
        }

        // List ChromeCast devices
        if (line.hasOption("l")) {
            final DeviceFinder deviceFinder = new DeviceFinder(new DeviceFinderListener() {

                @Override
                public void discoveringDevices(DeviceFinder deviceFinder) {
                    Log.d(LOG_TAG, "discoveringDevices");
                }

                @Override
                public void discoveredDevices(DeviceFinder deviceFinder) {
                    Log.d(LOG_TAG, "discoveredDevices");
                    TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers();
                    for (DialServer dialServer : trackedDialServers) {
                        System.out.println(dialServer.toString()); // keep system for output
                    }
                }

            });
            deviceFinder.discoverDevices();
        }

        // Stream media from internet
        if (line.hasOption("s") && line.hasOption("d")) {
            Log.d(LOG_TAG, line.getOptionValue("d"));
            Log.d(LOG_TAG, line.getOptionValue("s"));
            try {
                Playback playback = new Playback(platform, appId,
                        new DialServer(InetAddress.getByName(line.getOptionValue("d"))),
                        new PlaybackListener() {
                            private int time;
                            private int duration;
                            private int state;

                            @Override
                            public void updateTime(Playback playback, int time) {
                                Log.d(LOG_TAG, "updateTime: " + time);
                                this.time = time;
                            }

                            @Override
                            public void updateDuration(Playback playback, int duration) {
                                Log.d(LOG_TAG, "updateDuration: " + duration);
                                this.duration = duration;
                            }

                            @Override
                            public void updateState(Playback playback, int state) {
                                Log.d(LOG_TAG, "updateState: " + state);
                                // Stop the app if the video reaches the end
                                if (time > 0 && time == duration && state == 0) {
                                    playback.doStop();
                                    System.exit(0);
                                }
                            }

                            public int getTime() {
                                return time;
                            }

                            public int getDuration() {
                                return duration;
                            }

                            public int getState() {
                                return state;
                            }

                        });
                playback.stream(line.getOptionValue("s"));
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        // Play local media file
        if (line.hasOption("f") && line.hasOption("d")) {
            Log.d(LOG_TAG, line.getOptionValue("d"));
            Log.d(LOG_TAG, line.getOptionValue("f"));

            final String file = line.getOptionValue("f");
            String device = line.getOptionValue("d");

            try {
                Playback playback = new Playback(platform, appId, new DialServer(InetAddress.getByName(device)),
                        new PlaybackListener() {
                            private int time;
                            private int duration;
                            private int state;

                            @Override
                            public void updateTime(Playback playback, int time) {
                                Log.d(LOG_TAG, "updateTime: " + time);
                                this.time = time;
                            }

                            @Override
                            public void updateDuration(Playback playback, int duration) {
                                Log.d(LOG_TAG, "updateDuration: " + duration);
                                this.duration = duration;
                            }

                            @Override
                            public void updateState(Playback playback, int state) {
                                Log.d(LOG_TAG, "updateState: " + state);
                                // Stop the app if the video reaches the end
                                if (time > 0 && time == duration && state == 0) {
                                    playback.doStop();
                                    System.exit(0);
                                }
                            }

                            public int getTime() {
                                return time;
                            }

                            public int getDuration() {
                                return duration;
                            }

                            public int getState() {
                                return state;
                            }

                        });
                if (line.hasOption("t") && line.hasOption("tp")) {
                    playback.setTranscodingParameters(line.getOptionValue("tp"));
                }
                playback.play(file, line.hasOption("t"));
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        // REST API server
        if (line.hasOption("r")) {
            final DeviceFinder deviceFinder = new DeviceFinder(new DeviceFinderListener() {

                @Override
                public void discoveringDevices(DeviceFinder deviceFinder) {
                    Log.d(LOG_TAG, "discoveringDevices");
                }

                @Override
                public void discoveredDevices(DeviceFinder deviceFinder) {
                    Log.d(LOG_TAG, "discoveredDevices");
                    TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers();
                    for (DialServer dialServer : trackedDialServers) {
                        Log.d(LOG_TAG, dialServer.toString());
                    }
                }

            });
            deviceFinder.discoverDevices();

            int port = 0;
            if (line.hasOption("rp")) {
                try {
                    port = Integer.parseInt(line.getOptionValue("rp"));
                } catch (NumberFormatException e) {
                    Log.e(LOG_TAG, "invalid rest port", e);
                }
            }

            Playback.startWebserver(port, new WebListener() {
                String[] prefixes = { "/playback", "/devices" };
                HashMap<String, Playback> playbackMap = new HashMap<String, Playback>();
                HashMap<String, RestPlaybackListener> playbackListenerMap = new HashMap<String, RestPlaybackListener>();

                final class RestPlaybackListener implements PlaybackListener {
                    private String device;
                    private int time;
                    private int duration;
                    private int state;

                    public RestPlaybackListener(String device) {
                        this.device = device;
                    }

                    @Override
                    public void updateTime(Playback playback, int time) {
                        Log.d(LOG_TAG, "updateTime: " + time);
                        this.time = time;
                    }

                    @Override
                    public void updateDuration(Playback playback, int duration) {
                        Log.d(LOG_TAG, "updateDuration: " + duration);
                        this.duration = duration;
                    }

                    @Override
                    public void updateState(Playback playback, int state) {
                        Log.d(LOG_TAG, "updateState: " + state);
                        this.state = state;
                        // Stop the app if the video reaches the end
                        if (this.time > 0 && this.time == this.duration && state == 0) {
                            playback.doStop();
                            playbackMap.remove(device);
                            playbackListenerMap.remove(device);
                        }
                    }

                    public int getTime() {
                        return time;
                    }

                    public int getDuration() {
                        return duration;
                    }

                    public int getState() {
                        return state;
                    }

                }

                @Override
                public Response handleRequest(String uri, String method, Properties header, Properties parms) {
                    Log.d(LOG_TAG, "handleRequest: " + uri);

                    if (method.equals("GET")) {
                        if (uri.startsWith(prefixes[0])) { // playback
                            String device = parms.getProperty("device");
                            if (device != null) {
                                RestPlaybackListener playbackListener = playbackListenerMap.get(device);
                                if (playbackListener != null) {
                                    // https://code.google.com/p/json-simple/wiki/EncodingExamples
                                    JSONObject obj = new JSONObject();
                                    obj.put("time", playbackListener.getTime());
                                    obj.put("duration", playbackListener.getDuration());
                                    switch (playbackListener.getState()) {
                                    case 0:
                                        obj.put("state", "idle");
                                        break;
                                    case 1:
                                        obj.put("state", "stopped");
                                        break;
                                    case 2:
                                        obj.put("state", "playing");
                                        break;
                                    default:
                                        obj.put("state", "idle");
                                        break;
                                    }
                                    return new Response(HttpServer.HTTP_OK, "text/plain", obj.toJSONString());
                                } else {
                                    // Nothing is playing
                                    JSONObject obj = new JSONObject();
                                    obj.put("time", 0);
                                    obj.put("duration", 0);
                                    obj.put("state", "stopped");
                                    return new Response(HttpServer.HTTP_OK, "text/plain", obj.toJSONString());
                                }
                            }
                        } else if (uri.startsWith(prefixes[1])) { // devices
                            // https://code.google.com/p/json-simple/wiki/EncodingExamples
                            JSONArray list = new JSONArray();
                            TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers();
                            for (DialServer dialServer : trackedDialServers) {
                                JSONObject obj = new JSONObject();
                                obj.put("name", dialServer.getFriendlyName());
                                obj.put("ip_address", dialServer.getIpAddress().getHostAddress());
                                list.add(obj);
                            }
                            return new Response(HttpServer.HTTP_OK, "text/plain", list.toJSONString());
                        }
                    } else if (method.equals("POST")) {
                        if (uri.startsWith(prefixes[0])) { // playback
                            String device = parms.getProperty("device");
                            if (device != null) {
                                String stream = parms.getProperty("stream");
                                String file = parms.getProperty("file");
                                String state = parms.getProperty("state");
                                String transcode = parms.getProperty("transcode");
                                String transcodeParameters = parms.getProperty("transcode-parameters");
                                Log.d(LOG_TAG, "transcodeParameters=" + transcodeParameters);
                                if (stream != null) {
                                    try {
                                        if (playbackMap.get(device) == null) {
                                            DialServer dialServer = deviceFinder.getTrackedDialServers()
                                                    .findDialServer(InetAddress.getByName(device));
                                            if (dialServer != null) {
                                                RestPlaybackListener playbackListener = new RestPlaybackListener(
                                                        device);
                                                playbackMap.put(device, new Playback(platform, appId,
                                                        dialServer, playbackListener));
                                                playbackListenerMap.put(device, playbackListener);
                                            }
                                        }
                                        Playback playback = playbackMap.get(device);
                                        if (playback != null) {
                                            playback.stream(stream);
                                            return new Response(HttpServer.HTTP_OK, "text/plain", "Ok");
                                        }
                                    } catch (Exception e1) {
                                        Log.e(LOG_TAG, "playback", e1);
                                    }
                                } else if (file != null) {
                                    try {
                                        if (playbackMap.get(device) == null) {
                                            DialServer dialServer = deviceFinder.getTrackedDialServers()
                                                    .findDialServer(InetAddress.getByName(device));
                                            if (dialServer != null) {
                                                RestPlaybackListener playbackListener = new RestPlaybackListener(
                                                        device);
                                                playbackMap.put(device, new Playback(platform, appId,
                                                        dialServer, playbackListener));
                                                playbackListenerMap.put(device, playbackListener);
                                            }
                                        }
                                        Playback playback = playbackMap.get(device);
                                        if (transcodeParameters != null) {
                                            playback.setTranscodingParameters(transcodeParameters);
                                        }
                                        if (playback != null) {
                                            playback.play(file, transcode != null);
                                            return new Response(HttpServer.HTTP_OK, "text/plain", "Ok");
                                        }
                                    } catch (Exception e1) {
                                        Log.e(LOG_TAG, "playback", e1);
                                    }
                                } else if (state != null) {
                                    try {
                                        if (playbackMap.get(device) == null) {
                                            DialServer dialServer = deviceFinder.getTrackedDialServers()
                                                    .findDialServer(InetAddress.getByName(device));
                                            if (dialServer != null) {
                                                RestPlaybackListener playbackListener = new RestPlaybackListener(
                                                        device);
                                                playbackMap.put(device, new Playback(platform, appId,
                                                        dialServer, playbackListener));
                                                playbackListenerMap.put(device, playbackListener);
                                            }
                                        }
                                        Playback playback = playbackMap.get(device);
                                        if (playback != null) {
                                            // Handle case where current app wasn't started with caster
                                            playback.setDialServer(deviceFinder.getTrackedDialServers()
                                                    .findDialServer(InetAddress.getByName(device)));
                                            // Change the playback state
                                            if (state.equals("play")) {
                                                playback.doPlay();
                                                return new Response(HttpServer.HTTP_OK, "text/plain", "Ok");
                                            } else if (state.equals("pause")) {
                                                playback.doPause();
                                                return new Response(HttpServer.HTTP_OK, "text/plain", "Ok");
                                            } else if (state.equals("stop")) {
                                                playback.doStop();
                                                playbackMap.remove(device);
                                                playbackListenerMap.remove(device);
                                                return new Response(HttpServer.HTTP_OK, "text/plain", "Ok");
                                            } else {
                                                Log.e(LOG_TAG, "playback invalid state: " + state);
                                            }
                                        }
                                    } catch (Exception e1) {
                                        Log.e(LOG_TAG, "playback", e1);
                                    }
                                }
                            }
                        }
                    }

                    return new Response(HttpServer.HTTP_BADREQUEST, "text/plain", "Bad Request");
                }

                @Override
                public String[] uriPrefixes() {
                    return prefixes;
                }

            });
            Log.d(LOG_TAG, "REST server ready");

            // Run forever...
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
            }
        }

        // Print help
        if (line.hasOption("h")) {
            printHelp(options);
        }
    } catch (ParseException exp) {
        System.out.println("ERROR: " + exp.getMessage());
        System.out.println();
        printHelp(options);
    }
}

From source file:NTP_Example.java

public static void main(String[] args) {
    if (args.length == 0) {
        System.err.println("Usage: NTPClient <hostname-or-address-list>");
        System.exit(1);//from   w ww.  j av a  2s .  c om
    }

    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);
    try {
        client.open();
        for (String arg : args) {
            System.out.println();
            try {
                InetAddress hostAddr = InetAddress.getByName(arg);
                System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
                TimeInfo info = client.getTime(hostAddr);
                processResponse(info);
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }

    client.close();
}

From source file:com.phonytive.astive.server.AstiveServer.java

public static void main(String[] args) throws Exception {
    astivedSP = getServiceProperties(ASTIVED_PROPERTIES, "astived");
    adminDaemonSP = getServiceProperties(ADMIN_DAEMON_PROPERTIES, "admin thread");
    telnedSP = getServiceProperties(TELNED_PROPERTIES, "telned");

    ArrayList<ServiceProperties> serviceProperties = new ArrayList();
    serviceProperties.add(astivedSP);/* www . ja  v  a 2s  .  c o  m*/

    if (!adminDaemonSP.isDisabled()) {
        serviceProperties.add(adminDaemonSP);
    }

    if (!telnedSP.isDisabled()) {
        serviceProperties.add(telnedSP);
    }

    if ((args.length == 0) || args[0].equals("-h") || args[0].equals("--help")) {
        printUsage();
        System.exit(1);
    }

    // Create a Parser
    CommandLineParser parser = new BasicParser();

    Options start = new Options();
    start.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage"));
    start.addOption("v", "version", false, "Prints the Astive Server version and exits.");
    start.addOption("d", "debug", false, AppLocale.getI18n("cli.option.debug"));
    start.addOption("q", "quiet", false, AppLocale.getI18n("cli.option.daemonMode"));
    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("admin-bind")
            .withDescription("" + AppLocale.getI18n("cli.option.bind", new Object[] { "admin" })).create());
    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("admin-port")
            .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "admin" })).create());
    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("astived-port")
            .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "astived" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("astived-host")
            .withDescription("" + AppLocale.getI18n("cli.option.bind", new Object[] { "astived" })).create());
    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("telned-port")
            .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "telned" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("telned-host")
            .withDescription("" + AppLocale.getI18n("cli.option.host", new Object[] { "telned" })).create());

    Options stop = new Options();
    stop.addOption(OptionBuilder.withLongOpt("--help")
            .withDescription("" + AppLocale.getI18n("cli.option.printUsage")).create());

    stop.addOption("h", "host", false,
            AppLocale.getI18n("cli.option.stop.host", new Object[] { DEFAULT_AGI_SERVER_BIND_ADDR }));

    stop.addOption("p", "port", false,
            AppLocale.getI18n("cli.option.stop.port", new Object[] { DEFAULT_AGI_SERVER_PORT }));

    Options deploy = new Options();
    deploy.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage"));

    Options undeploy = new Options();
    undeploy.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage"));

    if (args.length == 0) {
        printUsage();
        System.exit(1);
    } else if (!isCommand(args[0])) {
        printUnavailableCmd(args[0]);
        System.exit(1);
    }

    AdminCommand cmd = AdminCommand.get(args[0]);

    if (cmd.equals(AdminCommand.DEPLOY) && ((args.length < 2) || !isFileJar(args[1]))) {
        logger.error(AppLocale.getI18n("cli.invalid.app"));
        printUsage(AdminCommand.DEPLOY, deploy);
        System.exit(1);
    }

    if (cmd.equals(AdminCommand.UNDEPLOY) && ((args.length < 2) || !isFileJar(args[1]))) {
        printUsage(AdminCommand.UNDEPLOY, undeploy);
        System.exit(1);
    }

    // Parse the program arguments
    try {
        if (cmd.equals(AdminCommand.START)) {
            CommandLine commandLine = parser.parse(start, args);

            if (commandLine.hasOption('h')) {
                printUsage(cmd, start);
                System.exit(0);
            }

            if (commandLine.hasOption('v')) {
                // Them start the server without noise
            }

            if (commandLine.hasOption("astived-bind")) {
                astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("astived-port")));
            }

            if (commandLine.hasOption("astived-port")) {
                astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue("astived-port")));
            }

            if (commandLine.hasOption("admin-bind")) {
                adminDaemonSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("admin-bind")));
            }

            if (commandLine.hasOption("admin-port")) {
                adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("admin-port")));
            }

            if (commandLine.hasOption("telned-bind")) {
                telnedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("telned-bind")));
            }

            if (commandLine.hasOption("telned-port")) {
                adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("telned-port")));
            }

            if (!NetUtil.available(astivedSP.getPort())) {
                out.println(AppLocale.getI18n("cantStartFastAgiServerSocket",
                        new Object[] { astivedSP.getBindAddr().getHostAddress(), astivedSP.getPort() }));
                System.exit(-1);
            }

            if (!NetUtil.available(adminDaemonSP.getPort())) {
                adminDaemonSP.setUnableToOpen(true);
            }

            if (!NetUtil.available(telnedSP.getPort())) {
                telnedSP.setUnableToOpen(true);
            }

            InitOutput.printInit(serviceProperties);

            AstiveServer server = new AstiveServer(astivedSP.getPort(), astivedSP.getBacklog(),
                    astivedSP.getBindAddr());
            server.start();
        }

        if (!cmd.equals(AdminCommand.START) && adminDaemonSP.isDisabled()) {
            logger.info("unableToAccessAdminDaemon");
        }

        if (cmd.equals(AdminCommand.STOP)) {
            CommandLine commandLine = parser.parse(stop, args);

            if (commandLine.hasOption("--help")) {
                printUsage(cmd, stop);
                System.exit(0);
            }

            if (commandLine.hasOption('h')) {
                if (commandLine.getOptionValue('h') == null) {
                    printUsage(cmd, stop);
                    System.exit(0);
                }

                astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue('h')));
            }

            if (commandLine.hasOption('p')) {
                if (commandLine.getOptionValue('p') == null) {
                    printUsage(cmd, stop);
                    System.exit(0);
                }

                astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue('p')));
            }

            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.stop();
        }

        // TODO: This needs to be researched before a full implementation.
        // for now is only possible to do deployments into the local server.
        if (cmd.equals(AdminCommand.DEPLOY)) {
            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.deploy(args[1]);
        }

        if (cmd.equals(AdminCommand.UNDEPLOY)) {
            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.undeploy(args[1]);
        }
    } catch (java.net.ConnectException ex) {
        logger.info("serverNotRunning");
    } catch (Exception ex) {
        logger.error(AppLocale.getI18n("unexpectedError", new Object[] { ex.getMessage() }));
    }
}

From source file:com.fonoster.astive.server.AstiveServer.java

public static void main(String[] args) throws Exception {

    DOMConfigurator.configure(AbstractAstiveServer.ASTIVE_HOME + "/conf/log4j.xml");

    astivedSP = getServiceProperties(ASTIVED_PROPERTIES, "astived");
    adminDaemonSP = getServiceProperties(ADMIN_DAEMON_PROPERTIES, "admin thread");
    telnedSP = getServiceProperties(TELNED_PROPERTIES, "telned");

    ArrayList<ServiceProperties> serviceProperties = new ArrayList();
    serviceProperties.add(astivedSP);/*ww  w.j a  va2s.  co m*/

    // Adding security measure
    AstPolicy ap = AstPolicy.getInstance();
    ap.addPermissions(astivedSP);
    ap.addPermissions(adminDaemonSP);
    ap.addPermissions(telnedSP);

    if (!adminDaemonSP.isDisabled()) {
        serviceProperties.add(adminDaemonSP);
    }

    if (!telnedSP.isDisabled()) {
        serviceProperties.add(telnedSP);
    }

    if ((args.length == 0) || args[0].equals("-h") || args[0].equals("--help")) {
        printUsage();
        System.exit(1);
    }

    // Create a Parser
    CommandLineParser parser = new BasicParser();

    Options start = new Options();

    start.addOption("h", "help", false, AppLocale.getI18n("optionHelp"));
    start.addOption("v", "version", false, AppLocale.getI18n("optionVersion"));
    start.addOption("d", "debug", false, AppLocale.getI18n("optionDebug"));
    start.addOption("q", "quiet", false, AppLocale.getI18n("optionQuiet"));

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("admin-bind")
            .withDescription(AppLocale.getI18n("optionBind", new Object[] { "admin" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("admin-port")
            .withDescription(AppLocale.getI18n("optionPort", new Object[] { "admin" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("astived-port")
            .withDescription(AppLocale.getI18n("optionPort", new Object[] { "astived" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("astived-host")
            .withDescription(AppLocale.getI18n("optionBind", new Object[] { "astived" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("telned-port")
            .withDescription(AppLocale.getI18n("optionPort", new Object[] { "telned" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("telned-host")
            .withDescription(AppLocale.getI18n("optionBind", new Object[] { "telned" })).create());

    Options stop = new Options();
    stop.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("host")
            .withDescription(AppLocale.getI18n("optionHelp")).create());

    stop.addOption("h", "host", false,
            AppLocale.getI18n("optionStopHost", new Object[] { DEFAULT_AGI_SERVER_BIND_ADDR }));

    stop.addOption("p", "port", false,
            AppLocale.getI18n("optionStopPort", new Object[] { DEFAULT_AGI_SERVER_PORT }));

    Options deploy = new Options();
    deploy.addOption("h", "help", false, AppLocale.getI18n("optionHelp"));

    Options undeploy = new Options();
    undeploy.addOption("h", "help", false, AppLocale.getI18n("optionHelp"));

    if (args.length == 0) {
        printUsage();
        System.exit(1);
    } else if (!isCommand(args[0])) {
        printUnavailableCmd(args[0]);
        System.exit(1);
    }

    AdminCommand cmd = AdminCommand.get(args[0]);

    // Parse the program arguments
    try {
        if (cmd.equals(AdminCommand.START)) {

            CommandLine commandLine = parser.parse(start, args);

            Logger root = LogManager.getRootLogger();
            Enumeration allLoggers = root.getLoggerRepository().getCurrentLoggers();

            if (commandLine.hasOption('q')) {
                root.setLevel(Level.ERROR);
                while (allLoggers.hasMoreElements()) {
                    Category tmpLogger = (Category) allLoggers.nextElement();
                    tmpLogger.setLevel(Level.ERROR);
                }
            } else if (commandLine.hasOption('d')) {
                root.setLevel(Level.DEBUG);
                while (allLoggers.hasMoreElements()) {
                    Category tmpLogger = (Category) allLoggers.nextElement();
                    tmpLogger.setLevel(Level.DEBUG);
                }
            } else {
                root.setLevel(Level.INFO);
                while (allLoggers.hasMoreElements()) {
                    Category tmpLogger = (Category) allLoggers.nextElement();
                    tmpLogger.setLevel(Level.INFO);
                }
            }

            if (commandLine.hasOption('h')) {
                printUsage(cmd, start);
                System.exit(0);
            }

            if (commandLine.hasOption('v')) {
                out.println(AppLocale.getI18n("astivedVersion",
                        new String[] { Version.VERSION, Version.BUILD_TIME }));
                System.exit(0);
            }

            if (commandLine.hasOption("astived-bind")) {
                astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("astived-port")));
            }

            if (commandLine.hasOption("astived-port")) {
                astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue("astived-port")));
            }

            if (commandLine.hasOption("admin-bind")) {
                adminDaemonSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("admin-bind")));
            }

            if (commandLine.hasOption("admin-port")) {
                adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("admin-port")));
            }

            if (commandLine.hasOption("telned-bind")) {
                telnedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("telned-bind")));
            }

            if (commandLine.hasOption("telned-port")) {
                telnedSP.setPort(Integer.parseInt(commandLine.getOptionValue("telned-port")));
            }

            if (!NetUtil.isPortAvailable(astivedSP.getPort())) {
                out.println(AppLocale.getI18n("errorCantStartFastAgiServerSocket",
                        new Object[] { astivedSP.getBindAddr().getHostAddress(), astivedSP.getPort() }));
                System.exit(-1);
            }

            if (!NetUtil.isPortAvailable(adminDaemonSP.getPort())) {
                adminDaemonSP.setUnableToOpen(true);
            }

            if (!NetUtil.isPortAvailable(telnedSP.getPort())) {
                telnedSP.setUnableToOpen(true);
            }

            new InitOutput().printInit(serviceProperties);

            AstiveServer server = new AstiveServer(astivedSP.getPort(), astivedSP.getBacklog(),
                    astivedSP.getBindAddr());
            server.start();
        }

        if (!cmd.equals(AdminCommand.START) && adminDaemonSP.isDisabled()) {
            LOG.warn("errorUnableToAccessAdminDaemon");
        }

        if (cmd.equals(AdminCommand.STOP)) {
            CommandLine commandLine = parser.parse(stop, args);

            if (commandLine.hasOption("--help")) {
                printUsage(cmd, stop);
                System.exit(0);
            }

            if (commandLine.hasOption('h')) {
                if (commandLine.getOptionValue('h') == null) {
                    printUsage(cmd, stop);
                    System.exit(0);
                }

                astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue('h')));
            }

            if (commandLine.hasOption('p')) {
                if (commandLine.getOptionValue('p') == null) {
                    printUsage(cmd, stop);
                    System.exit(0);
                }

                astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue('p')));
            }

            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.stop();
        }

        // TODO: This needs to be researched before a full implementation.
        // for now is only possible to do deployments into a local server.
        if (cmd.equals(AdminCommand.DEPLOY)) {
            CommandLine commandLine = parser.parse(deploy, args);

            if (args.length < 2) {
                printUsage(cmd, deploy);
                System.exit(1);
            } else if (commandLine.hasOption('h')) {
                printUsage(cmd, deploy);
                System.exit(0);
            }

            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.deploy(args[1]);
        }

        if (cmd.equals(AdminCommand.UNDEPLOY)) {

            CommandLine commandLine = parser.parse(undeploy, args);

            if (args.length < 2) {
                printUsage(cmd, undeploy);
                System.exit(1);
            } else if (commandLine.hasOption('h')) {
                printUsage(cmd, undeploy);
                System.exit(0);
            }

            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.undeploy(args[1]);
        }
    } catch (java.net.ConnectException ex) {
        LOG.error(AppLocale.getI18n("errorServerNotRunning"));
    } catch (Exception ex) {
        LOG.error(AppLocale.getI18n("errorUnexpectedFailure", new Object[] { ex.getMessage() }));
    }
}

From source file:edu.berkeley.sparrow.examples.BBackend.java

public static void main(String[] args) throws IOException, TException {
    ipAddress = InetAddress.getLocalHost().toString();
    OptionParser parser = new OptionParser();
    parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class);
    parser.accepts("help", "print help statement");
    OptionSet options = parser.parse(args);

    if (options.has("help")) {
        parser.printHelpOn(System.out);
        System.exit(-1);// ww w .  j a  v a  2 s  . c  om
    }

    // Logger configuration: log to the console
    BasicConfigurator.configure();

    Configuration conf = new PropertiesConfiguration();

    if (options.has("c")) {
        String configFile = (String) options.valueOf("c");
        try {
            conf = new PropertiesConfiguration(configFile);
        } catch (ConfigurationException e) {
        }
    }
    // Start backend server
    LOG.setLevel(Level.toLevel(conf.getString(LOG_LEVEL, DEFAULT_LOG_LEVEL)));
    LOG.debug("debug logging on");
    int listenPort = conf.getInt(LISTEN_PORT, DEFAULT_LISTEN_PORT);
    int nodeMonitorPort = conf.getInt(NODE_MONITOR_PORT, NodeMonitorThrift.DEFAULT_NM_THRIFT_PORT);
    batchingDelay = conf.getLong(BATCHING_DELAY, DEFAULT_BATCHING_DELAY);
    String nodeMonitorHost = conf.getString(NODE_MONITOR_HOST, DEFAULT_NODE_MONITOR_HOST);
    int workerThread = conf.getInt(WORKER_THREADS, DEFAULT_WORKER_THREADS);
    appClientAdress = InetAddress.getByName(conf.getString(APP_CLIENT_IP));
    appClientPortNumber = conf.getInt(APP_CLIENT_PORT_NUMBER, DEFAULT_APP_CLIENT_PORT_NUMBER);
    executor = Executors.newFixedThreadPool(workerThread);
    // Starting logging of results
    resultLog = new SynchronizedWrite("ResultsBackend.txt");
    Thread resultLogTh = new Thread(resultLog);
    resultLogTh.start();

    BBackend protoBackend = new BBackend();
    BackendService.Processor<BackendService.Iface> processor = new BackendService.Processor<BackendService.Iface>(
            protoBackend);

    TServers.launchSingleThreadThriftServer(listenPort, processor);
    protoBackend.initialize(listenPort, nodeMonitorHost, nodeMonitorPort);

}

From source file:Main.java

public static boolean isIPV6Address(String address) {
    try {//from w w  w  .  j av a  2s. co m
        return InetAddress.getByName(address) instanceof Inet6Address;
    } catch (Throwable e) {
        return false;
    }
}

From source file:Main.java

public static boolean pingIP(String ip) {
    boolean isReachable = false;
    try {/*from  w w w  .j ava  2s. co  m*/
        InetAddress address = InetAddress.getByName(ip);
        isReachable = address.isReachable(3000);
    } catch (Exception e) {
    }
    return isReachable;
}

From source file:Main.java

public static byte[] stringToIPAddress(final String pString) throws UnknownHostException {
    return InetAddress.getByName(pString).getAddress();
}

From source file:Main.java

public static boolean scanWithPing(String ip, int timeout) throws IOException {
    return InetAddress.getByName(ip).isReachable(timeout);
}