Example usage for java.lang Thread Thread

List of usage examples for java.lang Thread Thread

Introduction

In this page you can find the example usage for java.lang Thread Thread.

Prototype

public Thread(String name) 

Source Link

Document

Allocates a new Thread object.

Usage

From source file:com.groupC1.control.network.TelnetClientExample.java

/***
 * Main for the TelnetClient.// w  w w . ja v  a2 s .co  m
 ***/
public static void main(String[] args) throws Exception {
    args = new String[] { "169.254.0.10", "10001" };
    FileOutputStream fout = null;
    if (args.length < 1) {
        System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
        System.exit(1);
    }
    String remoteip = args[0];
    int remoteport;
    if (args.length > 1) {
        remoteport = (new Integer(args[1])).intValue();
    } else {
        remoteport = 23;
    }
    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (IOException e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }
    tc = new org.apache.commons.net.telnet.TelnetClient();
    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }
    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);
            Thread reader = new Thread(new TelnetClientExample());
            tc.registerNotifHandler(new TelnetClientExample());
            System.out.println("TelnetClient");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;
            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        if ((new String(buff, 0, ret_read)).startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");
                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (IOException e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++) {
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = Integer.parseInt(st.nextToken());
                                boolean initlocal = Boolean.parseBoolean(st.nextToken());
                                boolean initremote = Boolean.parseBoolean(st.nextToken());
                                boolean acceptlocal = Boolean.parseBoolean(st.nextToken());
                                boolean acceptremote = Boolean.parseBoolean(st.nextToken());
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) {
                            tc.registerSpyStream(fout);
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (IOException e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (IOException e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (IOException e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}

From source file:com.github.vatbub.awsvpnlauncher.Main.java

public static void main(String[] args) {
    Common.getInstance().setAppName("awsVpnLauncher");
    FOKLogger.enableLoggingOfUncaughtExceptions();
    prefs = new Preferences(Main.class.getName());

    // enable the shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();/* ww w .  j  a va2 s.  co  m*/
            }
        }
    }));

    UpdateChecker.completeUpdate(args, (oldVersion, oldFile) -> {
        if (oldVersion != null) {
            FOKLogger.info(Main.class.getName(), "Successfully upgraded " + Common.getInstance().getAppName()
                    + " from v" + oldVersion.toString() + " to v" + Common.getInstance().getAppVersion());
        }
    });
    List<String> argsAsList = new ArrayList<>(Arrays.asList(args));

    for (String arg : args) {
        if (arg.toLowerCase().matches("mockappversion=.*")) {
            // Set the mock version
            String version = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockAppVersion(version);
            argsAsList.remove(arg);
        } else if (arg.toLowerCase().matches("mockbuildnumber=.*")) {
            // Set the mock build number
            String buildnumber = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockBuildNumber(buildnumber);
            argsAsList.remove(arg);
        } else if (arg.toLowerCase().matches("mockpackaging=.*")) {
            // Set the mock packaging
            String packaging = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockPackaging(packaging);
            argsAsList.remove(arg);
        }
    }

    args = argsAsList.toArray(new String[0]);

    try {
        mvnRepoConfig = new Config(
                new URL("https://www.dropbox.com/s/vnhs4nax2lczccf/mavenRepoConfig.properties?dl=1"),
                Main.class.getResource("mvnRepoFallbackConfig.properties"), true, "mvnRepoCachedConfig", true);
        projectConfig = new Config(
                new URL("https://www.dropbox.com/s/d36hwrrufoxfmm7/projectConfig.properties?dl=1"),
                Main.class.getResource("projectFallbackConfig.properties"), true, "projectCachedConfig", true);
    } catch (IOException e) {
        FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not load the remote config", e);
    }

    try {
        installUpdates(args);
    } catch (Exception e) {
        FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not install updates", e);
    }

    if (args.length == 0) {
        // not enough arguments
        printHelpMessage();
        throw new NotEnoughArgumentsException();
    }

    switch (args[0].toLowerCase()) {
    case "setup":
        setup();
        break;
    case "launch":
        initAWSConnection();
        launch();
        break;
    case "terminate":
        initAWSConnection();
        terminate();
        break;
    case "config":
        // require a second arg
        if (args.length == 2) {
            // not enough arguments
            printHelpMessage();
            throw new NotEnoughArgumentsException();
        }

        config(Property.valueOf(args[1]), args[2]);
        break;
    case "getconfig":
        // require a second arg
        if (args.length == 1) {
            // not enough arguments
            printHelpMessage();
            throw new NotEnoughArgumentsException();
        }

        getConfig(Property.valueOf(args[1]));
        break;
    case "printconfig":
        printConfig();
        break;
    case "deleteconfig":
        // require a second arg
        if (args.length == 1) {
            // not enough arguments
            printHelpMessage();
            throw new NotEnoughArgumentsException();
        }

        deleteConfig(Property.valueOf(args[1]));
        break;
    case "ssh":
        String sshInstanceId;
        if (args.length == 2) {
            // a instanceID is specified
            sshInstanceId = args[1];
        } else {
            String instanceIdsPrefValue = prefs.getPreference("instanceIDs", "");
            if (instanceIdsPrefValue.equals("")) {
                throw new NotEnoughArgumentsException(
                        "No instanceId was specified to connect to and no instanceId was saved in the preference file. Please either start another instance using the launch command or specify the instance id of the instance to connect to as a additional parameter.");
            }

            List<String> instanceIds = Arrays.asList(instanceIdsPrefValue.split(";"));
            if (instanceIds.size() == 1) {
                // exactly one instance found
                sshInstanceId = instanceIds.get(0);
            } else {
                FOKLogger.severe(Main.class.getName(), "Multiple instance ids found:");

                for (String instanceId : instanceIds) {
                    FOKLogger.severe(Main.class.getName(), instanceId);
                }
                throw new NotEnoughArgumentsException(
                        "Multiple instance ids were found in the preference file. Please specify the instance id of the instance to connect to as a additional parameter.");
            }
        }

        initAWSConnection();
        ssh(sshInstanceId);
        break;
    default:
        printHelpMessage();
    }
}

From source file:playground.app.Application.java

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

    HttpHandler httpHandler = createHttpHandler();

    HttpServer server = new TomcatHttpServer();
    server.setPort(8080);//from  w  w  w.java  2s  .  c  o  m
    server.setHandler(httpHandler);
    server.afterPropertiesSet();
    server.start();

    CompletableFuture<Void> stop = new CompletableFuture<>();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        stop.complete(null);
    }));
    synchronized (stop) {
        stop.wait();
    }
}

From source file:com.sm.transport.netty.TestEchoClient.java

public static void main(String[] args) throws Exception {
    String[] opts = new String[] { "-thread", "-times", "-host", "-port", "-size" };
    String[] defaults = new String[] { "2", "10", "localhost", "7120", "2000" };
    String[] paras = getOpts(args, opts, defaults);
    int threads = Integer.valueOf(paras[0]);
    int times = Integer.valueOf(paras[1]);
    String host = paras[2];/*from w  w  w  . j  a  v  a2s  .c o  m*/
    int size = Integer.valueOf(paras[4]);
    int port = Integer.valueOf(paras[3]);
    for (int i = 0; i < threads; i++) {
        logger.info("start thread # " + i);
        TCPClient client = createTCPClient(host, port);
        new Thread(new ClientThread(client, times, size)).start();
    }
    //System.exit(0);
}

From source file:com.sm.transport.TestClient.java

public static void main(String[] args) throws Exception {
    String[] opts = new String[] { "-thread", "-times", "-host", "-port", "-size" };
    String[] defaults = new String[] { "2", "10", "localhost", "7100", "20000" };
    String[] paras = getOpts(args, opts, defaults);
    int threads = Integer.valueOf(paras[0]);
    int times = Integer.valueOf(paras[1]);
    String host = paras[2];//w  ww .j a va2s . c  o  m
    int size = Integer.valueOf(paras[4]);
    int port = Integer.valueOf(paras[3]);
    for (int i = 0; i < threads; i++) {
        logger.info("start thread # " + i);
        TCPClient client = createTCPClient(host, port);
        new Thread(new ClientThread(client, times, size)).start();
    }
    //System.exit(0);
}

From source file:eu.interedition.collatex.http.Server.java

public static void main(String... args) {
    try {//  w ww  . ja  v a2  s .c  om
        final CommandLine commandLine = new GnuParser().parse(OPTIONS, args);
        if (commandLine.hasOption("h")) {
            new HelpFormatter().printHelp("collatex-server [<options> ...]\n", OPTIONS);
            return;
        }

        final Collator collator = new Collator(Integer.parseInt(commandLine.getOptionValue("mpc", "2")),
                Integer.parseInt(commandLine.getOptionValue("mcs", "0")),
                commandLine.getOptionValue("dot", null));
        final String staticPath = System.getProperty("collatex.static.path", "");
        final HttpHandler httpHandler = staticPath.isEmpty()
                ? new CLStaticHttpHandler(Server.class.getClassLoader(), "/static/") {
                    @Override
                    protected void onMissingResource(Request request, Response response) throws Exception {
                        collator.service(request, response);
                    }
                }
                : new StaticHttpHandler(staticPath.replaceAll("/+$", "") + "/") {
                    @Override
                    protected void onMissingResource(Request request, Response response) throws Exception {
                        collator.service(request, response);
                    }
                };

        final NetworkListener httpListener = new NetworkListener("http", "0.0.0.0",
                Integer.parseInt(commandLine.getOptionValue("p", "7369")));

        final CompressionConfig compressionConfig = httpListener.getCompressionConfig();
        compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.ON);
        compressionConfig.setCompressionMinSize(860); // http://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits
        compressionConfig.setCompressableMimeTypes("application/javascript", "application/json",
                "application/xml", "text/css", "text/html", "text/javascript", "text/plain", "text/xml");

        final HttpServer httpServer = new HttpServer();
        httpServer.addListener(httpListener);
        httpServer.getServerConfiguration().addHttpHandler(httpHandler,
                commandLine.getOptionValue("cp", "").replaceAll("/+$", "") + "/*");

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            if (LOG.isLoggable(Level.INFO)) {
                LOG.info("Stopping HTTP server");
            }
            httpServer.shutdown();
        }));

        httpServer.start();

        Thread.sleep(Long.MAX_VALUE);
    } catch (Throwable t) {
        LOG.log(Level.SEVERE, "Error while parsing command line", t);
        System.exit(1);
    }
}

From source file:com.odap.server.audit.AuditServer.java

public static void main(String[] args) {
    try {/* w  w  w  .  j ava  2s  .com*/
        logger.info("In main() - " + args[0]);
        args_cpy = args;
        handler = new AuditHandler();
        processor = new AuditEvent.Processor(handler);
        config_handler = new ConfigHandler();
        config_processor = new Config.Processor(config_handler);

        String userName = "root";
        String password = args[1];
        String url = "jdbc:mysql://localhost/auditcloud?zeroDateTimeBehavior=convertToNull";
        keystore_password = args[2];

        DbUtils.loadDriver("com.mysql.jdbc.Driver");

        BoneCPConfig config = new BoneCPConfig(); // create a new configuration object
        config.setJdbcUrl(url); // set the JDBC url
        config.setUsername(userName); // set the username
        config.setPassword(password); // set the password

        connectionPool = new BoneCP(config); // setup the connection pool

        logger.info("Database connection established");

        Configuration conf = HBaseConfiguration.create();
        // conf.set("hbase.zookeeper.quorum", "server1,server2,server3");

        table = new HTable(conf, "sql_audit");
        Runnable simple = new Runnable() {
            public void run() {
                simple(processor, args_cpy[0]);
            }
        };
        Runnable configServer = new Runnable() {
            public void run() {
                configServer(config_processor, args_cpy[0]);
            }
        };

        Runnable heartBeat = new Runnable() {
            public void run() {
                checkHeartBeat();
            }
        };
        new Thread(simple).start();
        new Thread(configServer).start();
        new Thread(heartBeat).start();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.griddynamics.jagger.JaggerLauncher.java

public static void main(String[] args) throws Exception {
    Thread memoryMonitorThread = new Thread("memory-monitor") {
        @Override/*from  w  w w.ja  v  a2s .  c om*/
        public void run() {
            for (;;) {
                try {
                    log.info("Memory info: totalMemory={}, freeMemory={}", Runtime.getRuntime().totalMemory(),
                            Runtime.getRuntime().freeMemory());

                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    };
    memoryMonitorThread.setDaemon(true);
    memoryMonitorThread.start();

    String pid = ManagementFactory.getRuntimeMXBean().getName();
    System.out.println(String.format("PID:%s", pid));

    Properties props = System.getProperties();
    for (Map.Entry<Object, Object> prop : props.entrySet()) {
        log.info("{}: '{}'", prop.getKey(), prop.getValue());
    }
    log.info("");

    URL directory = new URL("file:" + System.getProperty("user.dir") + "/");
    loadBootProperties(directory, args[0], environmentProperties);

    log.debug("Bootstrap properties:");
    for (String propName : environmentProperties.stringPropertyNames()) {
        log.debug("   {}={}", propName, environmentProperties.getProperty(propName));
    }

    String[] roles = environmentProperties.getProperty(ROLES).split(",");
    Set<String> rolesSet = Sets.newHashSet(roles);

    if (rolesSet.contains(Role.COORDINATION_SERVER.toString())) {
        launchCoordinationServer(directory);
    }
    if (rolesSet.contains(Role.HTTP_COORDINATION_SERVER.toString())) {
        launchCometdCoordinationServer(directory);
    }
    if (rolesSet.contains(Role.RDB_SERVER.toString())) {
        launchRdbServer(directory);
    }
    if (rolesSet.contains(Role.MASTER.toString())) {
        launchMaster(directory);
    }
    if (rolesSet.contains(Role.KERNEL.toString())) {
        launchKernel(directory);
    }

    if (rolesSet.contains(Role.REPORTER.toString())) {
        launchReporter(directory);
    }

    LaunchManager launchManager = builder.build();

    int result = launchManager.launch();

    System.exit(result);

}

From source file:jms.Main.java

public static void main(String[] args) throws NamingException, JMSException, FileNotFoundException,
        InterruptedException, ParseException, CloneNotSupportedException {

    Options options = createOptions();//from w w  w. j av  a 2s  .  c o  m

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args, false);

    Histogram latencyHist = Main.metrics.histogram(name(ConsumerThread.class, "global", "consumer", "latency"));
    Meter consumerRate = Main.metrics.meter(name(ConsumerThread.class, "global", "consumer", "rate"));

    if (cmd.hasOption("c")) {
        CONFIG_FILE_PATH = cmd.getOptionValue("c");
    } else {
        CONFIG_FILE_PATH = System.getProperty("user.dir") + "/src/main/resources/client.yaml";
    }

    TestConfiguration config = ConfigReader.parseConfig(CONFIG_FILE_PATH);
    //        System.setProperty("qpid.flow_control_wait_failure", "1500000");
    // Subscribers

    startStatReporting(config.getGlobalConfig());

    int subscriberCount = config.getTopicSubscriberConfigList().size()
            + config.getQueueSubscriberConfigList().size() + config.getDurableSubscriberConfigList().size();
    final List<Thread> threadList = new ArrayList<Thread>(subscriberCount);

    TestTopicSubscriber topicSubscriber;
    for (SubscriberConfig subscriberConfig : config.getTopicSubscriberConfigList()) {
        topicSubscriber = new TestTopicSubscriber();
        topicSubscriber.subscribe(subscriberConfig);
        Thread subThread = new Thread(new ConsumerThread(topicSubscriber, latencyHist, consumerRate));
        subThread.start();
        threadList.add(subThread);
    }

    SimpleJMSConsumer queueReceiver;
    for (SubscriberConfig subscriberConfig : config.getQueueSubscriberConfigList()) {
        queueReceiver = new TestQueueReceiver();
        queueReceiver.subscribe(subscriberConfig);
        Thread subThread = new Thread(new ConsumerThread(queueReceiver, latencyHist, consumerRate));
        subThread.start();
        threadList.add(subThread);
    }

    TestDurableTopicSubscriber durableTopicSubscriber;
    for (SubscriberConfig subscriberConfig : config.getDurableSubscriberConfigList()) {
        durableTopicSubscriber = new TestDurableTopicSubscriber();
        durableTopicSubscriber.subscribe(subscriberConfig);
        Thread subThread = new Thread(new ConsumerThread(durableTopicSubscriber, latencyHist, consumerRate));
        subThread.start();
        threadList.add(subThread);
    }

    // Publishers

    TestTopicPublisher topicPublisher;
    for (PublisherConfig publisherConfig : config.getTopicPublisherList()) {
        topicPublisher = new TestTopicPublisher();
        topicPublisher.init(publisherConfig);
        Thread pubThread = new Thread(new PublisherThread(topicPublisher));
        pubThread.start();
        threadList.add(pubThread);
    }

    TestQueueSender queuePublisher;
    for (PublisherConfig publisherConfig : config.getQueuePublisherConfigList()) {
        queuePublisher = new TestQueueSender();
        queuePublisher.init(publisherConfig);
        Thread pubThread = new Thread(new PublisherThread(queuePublisher));
        pubThread.start();
        threadList.add(pubThread);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            log.info("Shutting down test client.");
            slf4jReporter.report();
            csvGaugeReporter.report();
            reporter.report();
            if (null != jmxReporter) {
                jmxReporter.close();
            }

            if (null != csvReporter) {
                csvReporter.report();
                csvReporter.close();
            }

            for (Thread t : threadList) {
                t.interrupt();
            }
        }
    });

    // barrier. wait till all the done
    for (Thread thread : threadList) {
        thread.join();
    }

    log.info("Test Complete!");
}

From source file:mcnutty.music.get.MusicGet.java

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

    //print out music-get
    System.out.println("                     _                      _   ");
    System.out.println(" _ __ ___  _   _ ___(_) ___       __ _  ___| |_ ");
    System.out.println("| '_ ` _ \\| | | / __| |/ __|____ / _` |/ _ \\ __|");
    System.out.println("| | | | | | |_| \\__ \\ | (_|_____| (_| |  __/ |_ ");
    System.out.println("|_| |_| |_|\\__,_|___/_|\\___|     \\__, |\\___|\\__|");
    System.out.println("                                 |___/          \n");

    //these will always be initialised later (but the compiler doesn't know that)
    String directory = "";
    Properties prop = new Properties();

    try (InputStream input = new FileInputStream("config.properties")) {
        prop.load(input);//from  w w w.j  av a  2  s . com
        if (prop.getProperty("directory") != null) {
            directory = prop.getProperty("directory");
        } else {
            System.out.println(
                    "Error reading config property 'directory' - using default value of /tmp/musicserver/\n");
            directory = "/tmp/musicserver/";
        }
        if (prop.getProperty("password") == null) {
            System.out.println("Error reading config property 'password' - no default value, exiting\n");
            System.exit(1);
        }
    } catch (IOException e) {
        System.out.println("Error reading config file");
        System.exit(1);
    }

    //create a queue object
    ProcessQueue process_queue = new ProcessQueue();

    try {
        if (args.length > 0 && args[0].equals("clean")) {
            Files.delete(Paths.get("queue.json"));
        }
        //load an existing queue if possible
        String raw_queue = Files.readAllLines(Paths.get("queue.json")).toString();
        JSONArray queue_state = new JSONArray(raw_queue);
        ConcurrentLinkedQueue<QueueItem> loaded_queue = new ConcurrentLinkedQueue<>();
        JSONArray queue = queue_state.getJSONArray(0);
        for (int i = 0; i < queue.length(); i++) {
            JSONObject item = ((JSONObject) queue.get(i));
            QueueItem loaded_item = new QueueItem();
            loaded_item.ip = item.getString("ip");
            loaded_item.real_name = item.getString("name");
            loaded_item.disk_name = item.getString("guid");
            loaded_queue.add(loaded_item);
        }
        process_queue.bucket_queue = loaded_queue;
        System.out.println("Loaded queue from disk\n");
    } catch (Exception ex) {
        //otherwise clean out the music directory and start a new queue
        try {
            Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }
            });
            Files.delete(Paths.get(directory));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Files.createDirectory(Paths.get(directory));
        System.out.println("Created a new queue\n");
    }

    //start the web server
    StartServer start_server = new StartServer(process_queue, directory);
    new Thread(start_server).start();

    //wit for the web server to spool up
    Thread.sleep(1000);

    //read items from the queue and play them
    while (true) {
        QueueItem next_item = process_queue.next_item();
        if (!next_item.equals(new QueueItem())) {
            //Check the timeout
            int timeout = 547;
            try (FileInputStream input = new FileInputStream("config.properties")) {
                prop.load(input);
                timeout = Integer.parseInt(prop.getProperty("timeout", "547"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Playing " + next_item.real_name);
            process_queue.set_played(next_item);
            process_queue.save_queue();
            Process p = Runtime.getRuntime().exec("timeout " + timeout
                    + "s mplayer -fs -quiet -af volnorm=2:0.25 " + directory + next_item.disk_name);

            try {
                p.waitFor(timeout, TimeUnit.SECONDS);
                Files.delete(Paths.get(directory + next_item.disk_name));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            process_queue.bucket_played.clear();
        }
        Thread.sleep(1000);
    }
}