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:ca.uqac.info.monitor.BeepBeepMonitor.java

public static void main(String[] args) {
    int verbosity = 1, slowdown = 0, tcp_port = 0;
    boolean show_stats = false, to_stdout = false;
    String trace_filename = "", pipe_filename = "", event_name = "message";
    final MonitorFactory mf = new MonitorFactory();

    // In case we open a socket
    ServerSocket m_serverSocket = null;
    Socket m_connection = null;/*from   ww w  .j a va  2s . c  o  m*/

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (verbosity > 0) {
        showHeader();
    }
    if (c_line.hasOption("version")) {
        System.err.println("(C) 2008-2013 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.err.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.err.println("This is a free software, and you are welcome to redistribute it");
        System.err.println("under certain conditions. See the file COPYING for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("version")) {
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("slowdown")) {
        slowdown = Integer.parseInt(c_line.getOptionValue("slowdown"));
        if (verbosity > 0)
            System.err.println("Slowdown factor: " + slowdown + " ms");
    }
    if (c_line.hasOption("stats")) {
        show_stats = true;
    }
    if (c_line.hasOption("csv")) {
        // Will output data in CSV format to stdout
        to_stdout = true;
    }
    if (c_line.hasOption("eventname")) {
        // Set event name
        event_name = c_line.getOptionValue("eventname");
    }
    if (c_line.hasOption("t")) {
        // Read events from a trace
        trace_filename = c_line.getOptionValue("t");
    }
    if (c_line.hasOption("p")) {
        // Read events from a pipe
        pipe_filename = c_line.getOptionValue("p");
    }
    if (c_line.hasOption("k")) {
        // Read events from a TCP port
        tcp_port = Integer.parseInt(c_line.getOptionValue("k"));
    }
    if (!trace_filename.isEmpty() && !pipe_filename.isEmpty()) {
        System.err.println("ERROR: you must specify at most one of trace file or named pipe");
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    @SuppressWarnings("unchecked")
    List<String> remaining_args = c_line.getArgList();
    if (remaining_args.isEmpty()) {
        System.err.println("ERROR: no input formula specified");
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    // Instantiate the event notifier
    boolean notify = (verbosity > 0);
    EventNotifier en = new EventNotifier(notify);
    en.m_slowdown = slowdown;
    en.m_csvToStdout = to_stdout;
    // Create one monitor for each input file and add it to the notifier 
    for (String formula_filename : remaining_args) {
        try {
            String formula_contents = FileReadWrite.readFile(formula_filename);
            Operator op = Operator.parseFromString(formula_contents);
            op.accept(mf);
            Monitor mon = mf.getMonitor();
            Map<String, String> metadata = getMetadata(formula_contents);
            metadata.put("Filename", formula_filename);
            en.addMonitor(mon, metadata);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(ERR_IO);
        } catch (Operator.ParseException e) {
            System.err.println("Error parsing input formula");
            System.exit(ERR_PARSE);
        }
    }

    // Read trace and iterate
    // Opens file
    PipeReader pr = null;
    try {
        if (!pipe_filename.isEmpty()) {
            // We tell the pipe reader we read a pipe
            File f = new File(pipe_filename);
            if (verbosity > 0)
                System.err.println("Reading from pipe named " + f.getName());
            pr = new PipeReader(new FileInputStream(f), en, false);
        } else if (!trace_filename.isEmpty()) {
            // We tell the pipe reader we read a regular file
            File f = new File(trace_filename);
            if (verbosity > 0)
                System.err.println("Reading from file " + f.getName());
            pr = new PipeReader(new FileInputStream(f), en, true);
        } else if (tcp_port > 0) {
            // We tell the pipe reader we read from a socket
            if (verbosity > 0)
                System.err.println("Reading from TCP port " + tcp_port);
            m_serverSocket = new ServerSocket(tcp_port);
            m_connection = m_serverSocket.accept();
            pr = new PipeReader(m_connection.getInputStream(), en, false);
        } else {
            // We tell the pipe reader we read from standard input
            if (verbosity > 0)
                System.err.println("Reading from standard input");
            pr = new PipeReader(System.in, en, false);
        }
    } catch (FileNotFoundException ex) {
        // We print both trace and pipe since one of them must be empty
        System.err.println("ERROR: file not found " + trace_filename + pipe_filename);
        System.exit(ERR_IO);
    } catch (IOException e) {
        // Caused by socket error
        e.printStackTrace();
        System.exit(ERR_IO);
    }
    pr.setSeparator("<" + event_name + ">", "</" + event_name + ">");

    // Check parameters for the event notifier
    if (c_line.hasOption("no-trigger")) {
        en.m_notifyOnVerdict = false;
    } else {
        en.m_notifyOnVerdict = true;
    }
    if (c_line.hasOption("mirror")) {
        en.m_mirrorEventsOnStdout = true;
    }

    // Start event notifier
    en.reset();
    Thread th = new Thread(pr);
    long clock_start = System.nanoTime();
    th.start();
    try {
        th.join(); // Wait for thread to finish
    } catch (InterruptedException e1) {
        // Thread is finished
    }
    if (tcp_port > 0 && m_serverSocket != null) {
        // We opened a socket; now we close it
        try {
            m_serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    long clock_end = System.nanoTime();
    int ret_code = pr.getReturnCode();
    switch (ret_code) {
    case PipeReader.ERR_EOF:
        if (verbosity > 0)
            System.err.println("\nEnd of file reached");
        break;
    case PipeReader.ERR_EOT:
        if (verbosity > 0)
            System.err.println("\nEOT received on pipe: closing");
        break;
    case PipeReader.ERR_OK:
        // Do nothing
        break;
    default:
        // An error
        System.err.println("Runtime error");
        System.exit(ERR_RUNTIME);
        break;
    }
    if (show_stats) {
        if (verbosity > 0) {
            System.out.println("Messages:   " + en.m_numEvents);
            System.out.println("Time:       " + (int) (en.m_totalTime / 1000000f) + " ms");
            System.out.println("Clock time: " + (int) ((clock_end - clock_start) / 1000000f) + " ms");
            System.out.println("Max heap:   " + (int) (en.heapSize / 1048576f) + " MB");
        } else {
            // If stats are asked but verbosity = 0, only show time value
            // (both monitor and wall clock) 
            System.out.print((int) (en.m_totalTime / 1000000f));
            System.out.print(",");
            System.out.print((int) ((clock_end - clock_start) / 1000000f));
        }
    }
    System.exit(ERR_OK);
}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(Option.builder("Xfu").longOpt("Xforceupdate").desc("Force the patching process").build());
    options.addOption(Option.builder("Xh").longOpt("Xhelp").desc("Help!").build());
    CommandLineParser parser = new DefaultParser();
    try {/*from   w  w w . j  av a2s .c  o  m*/
        CommandLine commandLine = parser.parse(options, args, true);
        if (commandLine.hasOption("Xhelp")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar bootstrapper.jar", options);
        } else if (commandLine.hasOption("Xforceupdate")) {
            forceUpdate();
        } else {
            //                boolean shouldStart = true;
            //                ServerSocket socket = null;
            //                try {
            //                    socket = new ServerSocket(21354);
            //                } catch (IOException e) {
            //                    shouldStart = false;
            //                } finally {
            //                    if (socket != null) {
            //                        socket.close();
            //                    }
            //                }

            //                if (shouldStart) {
            String[] forward = commandLine.getArgs();
            HeliosData heliosData = loadHelios();
            System.out.println("Running Helios version " + heliosData.buildNumber);

            System.getProperties().put("com.heliosdecompiler.buildNumber",
                    String.valueOf(heliosData.buildNumber));
            System.getProperties().put("com.heliosdecompiler.version", String.valueOf(heliosData.version));
            System.getProperties().put("com.heliosdecompiler.args", args);

            new Thread(new UpdaterTask(heliosData.buildNumber)).start();

            ClassLoader classLoader = new URLClassLoader(new URL[] { IMPL_FILE.toURI().toURL() }, null);
            Class<?> bootloader = Class.forName(heliosData.mainClass, false, classLoader);
            bootloader.getMethod("main", String[].class).invoke(null, new Object[] { forward });
            //                } else {
            //                    String message = Arrays.asList(forward).stream().collect(Collectors.joining(" "));
            //                    Socket clientSocket = new Socket("127.0.0.1", 21354);
            //                    clientSocket.getOutputStream().write(message.getBytes(StandardCharsets.UTF_8));
            //                    clientSocket.getOutputStream().close();
            //                    clientSocket.close();
            //                }
        }
    } catch (Throwable t) {
        displayError(t);
        System.exit(1);
    }
}

From source file:com.vangent.hieos.empi.pixpdq.loader.PIDFeedLoader.java

/**
 *
 * @param args//from   w  w w .  j a  va  2 s.  c  om
 */
public static void main(String[] args) {
    PIDFeedLoader pfl = new PIDFeedLoader();
    long start = System.currentTimeMillis();
    for (int i = 0; i < DEMOGRAPHIC_FILES.length; i++) {
        String demographicFile = DEMOGRAPHIC_FILES[i];
        PIDFeedRunnable pidFeedRunnable = pfl.getPIDFeedRunnable(TEMPLATE, demographicFile, ENDPOINT);
        Thread thread = new Thread(pidFeedRunnable);
        thread.start();
    }
    System.out.println(" done ... TOTAL TIME - " + (System.currentTimeMillis() - start) + "ms.");
}

From source file:com.singhasdev.calamus.app.sentimentanalysis.SentimentAnalyzer.java

public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "sentiment-analyzer");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());

    // setting offset reset to earliest so that we can re-run the demo code with the same pre-loaded data
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    TopologyBuilder builder = new TopologyBuilder();

    builder.addSource("Source", "test");

    builder.addProcessor("Process", new CalculateSentiment(), "Source");
    builder.addStateStore(/*from   w ww .j a v a  2  s.  co m*/
            Stores.create("SentimentAnalysis").withStringKeys().withStringValues().inMemory().build(),
            "Process");

    builder.addSink("Sink", "test-output", "Process");

    STREAMS = new KafkaStreams(builder, props);
    STREAMS.start();

    Runtime.getRuntime().addShutdownHook(new Thread("MirrorMakerShutdownHook") {
        @Override
        public void run() {
            System.out.println("Closing Calamus sentiment-analyzer.");
            STREAMS.close();
        }
    });
}

From source file:com.hpe.nv.samples.basic.BasicNVTest.java

public static void main(String[] args) {
    try {//from w  w  w.  j  ava2 s . c  o m
        // program arguments
        Options options = new Options();
        options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP");
        options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port");
        options.addOption("u", "username", true, "[mandatory] NV username");
        options.addOption("w", "password", true, "[mandatory] NV password");
        options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false");
        options.addOption("y", "proxy", true, "[optional] Proxy server host:port");
        options.addOption("b", "browser", true,
                "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome and Firefox. Default: Firefox");
        options.addOption("d", "debug", true,
                "[optional] Pass true to view console debug messages during execution. Default: false");
        options.addOption("h", "help", false, "[optional] Generates and prints help information");

        // parse and validate the command line arguments
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            // print help if help argument is passed
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("BasicNVTest.java", options);
            return;
        }

        if (line.hasOption("server-ip")) {
            serverIp = line.getOptionValue("server-ip");
            if (serverIp.equals("0.0.0.0")) {
                throw new Exception(
                        "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP");
            }
        } else {
            throw new Exception("Missing argument -i/--server-ip <serverIp>");
        }

        if (line.hasOption("server-port")) {
            serverPort = Integer.parseInt(line.getOptionValue("server-port"));
        } else {
            throw new Exception("Missing argument -o/--server-port <serverPort>");
        }

        if (line.hasOption("username")) {
            username = line.getOptionValue("username");
        } else {
            throw new Exception("Missing argument -u/--username <username>");
        }

        if (line.hasOption("password")) {
            password = line.getOptionValue("password");
        } else {
            throw new Exception("Missing argument -w/--password <password>");
        }

        if (line.hasOption("ssl")) {
            ssl = Boolean.parseBoolean(line.getOptionValue("ssl"));
        }

        if (line.hasOption("proxy")) {
            proxySetting = line.getOptionValue("proxy");
        }

        if (line.hasOption("browser")) {
            browser = line.getOptionValue("browser");
        } else {
            browser = "Firefox";
        }

        if (line.hasOption("debug")) {
            debug = Boolean.parseBoolean(line.getOptionValue("debug"));
        }

        String newLine = System.getProperty("line.separator");
        String testDescription = "***   This sample demonstrates the use of the most basic NV methods.                               ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   First, the sample creates a TestManager object and initializes it.                           ***"
                + newLine
                + "***   The sample starts an NV test over an emulated \"3G Busy\" network.                             ***"
                + newLine
                + "***   (\"3G Busy\" is one of NV's built-in network profiles. A network profile specifies the         ***"
                + newLine
                + "***   network traffic behavior, including latency, packet loss, and incoming/outgoing bandwidth.   ***"
                + newLine
                + "***   Network profiles are used to emulate traffic over real-world networks.)                      ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   Next, the sample navigates to the home page in the HPE Network Virtualization website        ***"
                + newLine
                + "***   using the Selenium WebDriver.                                                                ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   Finally, the sample stops the NV test.                                                       ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   You can view the actual steps of this sample in the BasicNVTest.java file.                   ***"
                + newLine;

        // print the sample's description
        System.out.println(testDescription);

        // start console spinner
        if (!debug) {
            spinner = new Thread(new Spinner());
            spinner.start();
        }

        // sample execution steps
        /*****    Part 1 - Create a TestManager object and initialize it                                   *****/
        printPartDescription("\b------    Part 1 - Create a TestManager object and initialize it");
        initTestManager();
        printPartSeparator();
        /*****    Part 2 - Start the NV test with the "3G Busy" network scenario                           *****/
        printPartDescription("------    Part 2 - Start the NV test with the \"3G Busy\" network scenario");
        startTest();
        testRunning = true;
        printPartSeparator();
        /*****    Part 3 - Navigate to the HPE Network Virtualization website                              *****/
        printPartDescription("------    Part 3 - Navigate to the HPE Network Virtualization website");
        buildSeleniumWebDriver();
        seleniumNavigateToPage();
        driverCloseAndQuit();
        printPartSeparator();
        /*****    Part 4 - Stop the NV test                                                                *****/
        printPartDescription("------    Part 4 - Stop the NV test");
        stopTest();
        testRunning = false;
        printPartSeparator();
        doneCallback();
    } catch (Exception e) {
        try {
            handleError(e.getMessage());
        } catch (Exception e2) {
            System.out.println("Error occurred: " + e2.getMessage());
        }
    }
}

From source file:LamportBasicVersion.java

public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException {
    totalMessageCount = 0;//  w w w.  j  a va2 s  . c om
    //For parsing the file and storing the information
    String line;
    String configurationFile = "configuration.txt";
    int lineCountInFile = 0;
    myProcessId = Integer.parseInt(args[0]);
    FileReader fileReader = new FileReader(configurationFile);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    while ((line = bufferedReader.readLine()) != null) {
        if ((!(line.startsWith("#"))) && (!(line.isEmpty()))) {
            lineCountInFile = lineCountInFile + 1;
            String[] splitLine = line.split(" ");
            switch (lineCountInFile) {
            case 1:
                numberOfProcesses = Integer.parseInt(splitLine[0]);
                interRequestDelay = Integer.parseInt(splitLine[1]);
                csExecutionTime = Integer.parseInt(splitLine[2]);
                maxNumberOfRequest = Integer.parseInt(splitLine[3]);
                machineNames = new String[Integer.parseInt(splitLine[0])];
                portNumbers = new int[Integer.parseInt(splitLine[0])];
                break;
            default:
                machineNames[lineCountInFile - 2] = splitLine[1];
                portNumbers[lineCountInFile - 2] = Integer.parseInt(splitLine[2]);
                break;
            }
        }
    }
    conditionArray = new int[numberOfProcesses];
    finishFlagArray = new int[numberOfProcesses];
    //Initializing vector class
    VectorClass.initialize(numberOfProcesses);
    //Fill the arrays with zero false value
    for (int o = 0; o < numberOfProcesses; o++) {
        conditionArray[o] = 0;
        finishFlagArray[o] = 0;
    }
    // Write output to file
    filename = filename + Integer.toString(myProcessId) + ".out";
    file = new File(filename);
    file.createNewFile();
    writer = new FileWriter(file);
    // Write clocks to file
    filenameClock = filenameClock + Integer.toString(myProcessId) + ".out";
    fileClock = new File(filenameClock);
    fileClock.createNewFile();
    //writerClock = new FileWriter(fileClock);
    fw = new FileWriter(fileClock);
    bw = new BufferedWriter(fw);
    //
    // Expo mean insert
    csExecutionExpoDelay = new ExponentialDistribution(csExecutionTime);
    interRequestExpoDelay = new ExponentialDistribution(interRequestDelay);
    //
    System.out.println("********************************************************");
    System.out.println("My process id : " + myProcessId);
    System.out.println("Number of processes : " + numberOfProcesses);
    System.out.println("Inter-request delay : " + interRequestDelay);
    System.out.println("Critical section execution time : " + csExecutionTime);
    System.out.println("Maximum number of request : " + maxNumberOfRequest);
    System.out.println(
            "My process name : " + machineNames[myProcessId] + " My port number : " + portNumbers[myProcessId]);
    for (int i = 0; i < numberOfProcesses; i++) {
        System.out.println("Process name : " + machineNames[i] + " Port number : " + portNumbers[i]);
    }
    System.out.println("********************************************************");
    //For hosting server localhost
    SctpServerChannel sctpServerChannel = SctpServerChannel.open();
    InetSocketAddress serverAddr = new InetSocketAddress(portNumbers[myProcessId]);
    sctpServerChannel.bind(serverAddr);
    System.out.println("********************************************************");
    System.out.println("Local server hosted");
    System.out.println("********************************************************");
    //For creating neighbor SCTP channels
    Thread.sleep(30000);
    socketAddress = new SocketAddress[numberOfProcesses];
    sctpChannel = new SctpChannel[numberOfProcesses];
    System.out.println("********************************************************");
    System.out.println("Neighbor channels created");
    System.out.println("********************************************************");
    //Thread spanned for generating critical section request
    new Thread(new LamportBasicVersion()).start();
    //while loop to receive all the requests and other messages
    while (true) {
        try (SctpChannel sctpChannelFromClient = sctpServerChannel.accept()) {
            mutex.acquire();
            byteBufferFromNeighbor.clear();
            String receiveMessage;
            MessageInfo messageInfoFromNeighbor = sctpChannelFromClient.receive(byteBufferFromNeighbor, null,
                    null);
            //System.out.println("Raw Message : " + messageInfoFromNeighbor);
            receiveMessage = byteToString(byteBufferFromNeighbor, messageInfoFromNeighbor);
            //write to file start
            writer.write("Received Message : " + receiveMessage);
            writer.write("\n");
            writer.flush();
            //write to file end
            System.out.println("Received Message : " + receiveMessage);
            if (receiveMessage.contains("Request")) {
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                int requestMade = Integer.parseInt(parseMessage[3] + parseMessage[1]);
                queue.add(requestMade);
                //Send reply messages to that process for entering CS
                lamportClock++;
                //vector clock construction
                int[] vector = VectorClass.increment(myProcessId);
                String vectorClockConstruction = "";
                for (int g = 0; g < vector.length; g++) {
                    if (g == 0) {
                        vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]);
                    } else {
                        vectorClockConstruction = vectorClockConstruction + "," + Integer.toString(vector[g]);
                    }
                }
                //
                for (int k = 0; k < numberOfProcesses; k++) {
                    if (k == Integer.parseInt(parseMessage[1])) {
                        try {
                            byteBufferToNeighbor.clear();
                            initializeChannels();
                            sctpChannel[k].connect(socketAddress[k]);
                            String sendMessage = "Reply from Process-" + myProcessId + "-"
                                    + Integer.toString(requestMade) + "-" + lamportClock + "-"
                                    + vectorClockConstruction;
                            System.out.println("Message sent is : " + sendMessage);
                            //write to file start
                            writer.write("Message sent is : " + sendMessage);
                            writer.write("\n");
                            writer.flush();
                            //write to file end
                            MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                            byteBufferToNeighbor.put(sendMessage.getBytes());
                            byteBufferToNeighbor.flip();
                            sctpChannel[k].send(byteBufferToNeighbor, messageInfoToNeighbor);
                            totalMessageCount++;
                            sctpChannel[k].close();
                        } catch (IOException ex) {
                            Logger.getLogger(LamportBasicVersion.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            } else if (receiveMessage.contains("Reply")) {
                conditionArray[myProcessId] = 1;
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                conditionArray[Integer.parseInt(parseMessage[1])] = 1;
                int count = 0;
                for (int v = 0; v < numberOfProcesses; v++) {
                    if (conditionArray[v] == 1) {
                        count = count + 1;
                    }
                }
                if (count == numberOfProcesses) {
                    L1ConditionFlag = 1;
                    System.out.println("Inside L1");
                    blockingQueue.put("L1");
                    //Clearing condition array after receiving all REPLY
                    for (int z = 0; z < numberOfProcesses; z++) {
                        conditionArray[z] = 0;
                    }
                    if (L2ConditionFlag == 0 && outstandingRequest == 1) {
                        Integer[] queueArray = new Integer[queue.size()];
                        queue.toArray(queueArray);
                        Arrays.sort(queueArray);
                        if (queueArray[0] == currentRequestBeingServed) {
                            System.out.println("Inside L2");
                            L2ConditionFlag = 1;
                            blockingQueue.put("L2");
                        }
                    }
                }
            } else if (receiveMessage.contains("Release")) {
                int present = 0;
                int delete = 0;
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                if (queue.size() != 0) {
                    Integer[] queueArray = new Integer[queue.size()];
                    queue.toArray(queueArray);
                    Arrays.sort(queueArray);
                    for (int a = 0; a < queueArray.length; a++) {
                        if (queueArray[a] == Integer.parseInt(parseMessage[2])) {
                            present = 1;
                            delete = a;
                        }
                    }
                    if (present == 1) {
                        for (int s = 0; s <= delete; s++) {
                            queue.remove();
                        }
                    }
                }
                if (L2ConditionFlag == 0 && outstandingRequest == 1) {
                    if (queue.size() != 0) {
                        Integer[] queueArray1 = new Integer[queue.size()];
                        queue.toArray(queueArray1);
                        Arrays.sort(queueArray1);
                        if (currentRequestBeingServed == queueArray1[0]) {
                            L2ConditionFlag = 1;
                            System.out.println("Inside L2");
                            blockingQueue.put("L2");
                        }
                    }
                }
            } else if (receiveMessage.contains("Finish")) {
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                finishFlagArray[Integer.parseInt(parseMessage[1])] = 1;
                int count = 0;
                for (int v = 0; v < numberOfProcesses; v++) {
                    if (finishFlagArray[v] == 1) {
                        count = count + 1;
                    }
                }
                if (count == numberOfProcesses) {
                    break;
                }
            }
            //logic for other messages
            //Print the queue to check
            System.out.println("********************************************************");
            for (Object item : queue) {
                System.out.print(item);
                System.out.print("\t");
            }
            System.out.println("********************************************************");
        }
        mutex.release();
    }
}

From source file:eu.learnpad.simulator.mon.MainMonitoring.java

/**
 * Read the properties and init the connections to the enterprise service bus
 * // w w  w .ja va 2 s .  com
 * @param is the systemSettings file
 */
public static void main(String[] args) {
    try {
        FileOutputStream fos = new FileOutputStream("glimpseLog.log");
        PrintStream ps = new PrintStream(fos);
        System.setErr(ps);

        if (MainMonitoring.initProps(args[0]) && MainMonitoring.init()) {

            System.out.println("Running ActiveMQ instance on "
                    + environmentParameters.getProperty("java.naming.provider.url"));

            ActiveMQRunner anActiveMQInstance = new ActiveMQRunner(
                    environmentParameters.getProperty("java.naming.provider.url"));
            new Thread(anActiveMQInstance).start();

            while (!anActiveMQInstance.isBrokerStarted()) {
                Thread.sleep(1000);
            }

            System.out.println("ActiveMQ is running");
            System.out.println("Running GLIMPSE");
            SplashScreen.Show();
            System.out.println("Please wait until setup is done...");

            //the buffer where the events are stored to be analyzed, in this version
            //the buffer object is not used because Drools has it's own eventStream object
            EventsBuffer<GlimpseBaseEvent<?>> buffer = new EventsBufferImpl<GlimpseBaseEvent<?>>();

            //The complex event engine that will be used (in this case drools)
            ComplexEventProcessor engineOne = new ComplexEventProcessorImpl(Manager.Read(MANAGERPARAMETERFILE),
                    buffer, connFact, initConn);

            engineOne.start();

            RestNotifier notifierEngine = new RestNotifier();
            notifierEngine.start();

            //using H2 database
            DBController databaseController = new H2Controller(Manager.Read(DATABASECONNECTIONSTRINGH2));

            //using MYSQL database
            //DBController databaseController = new MySqlController(Manager.Read(DATABASECONNECTIONSTRINGMYSQL));

            LearnerAssessmentManager lam = new LearnerAssessmentManagerImpl(databaseController);
            lam.start();

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            RuleTemplateManager templateManager = new RuleTemplateManager(DROOLSRULEREQUESTTEMPLATE1,
                    DROOLSRULEREQUESTTEMPLATE2, DROOLSRULEREQUESTTEMPLATE3_1, DROOLSRULEREQUESTTEMPLATE3_2);

            //the component in charge to locate services and load specific rules.
            ServiceLocatorFactory.getServiceLocatorParseViolationReceivedFromBSM(engineOne, templateManager,
                    REGEXPATTERNFILEPATH).start();

            //start MailNotifier component
            MailNotification mailer = new MailNotification(Manager.Read(MAILNOTIFICATIONSETTINGSFILEPATH));
            mailer.start();
            //the manager of all the architecture
            GlimpseManager manager = new GlimpseManager(Manager.Read(MANAGERPARAMETERFILE), connFact, initConn,
                    engineOne.getRuleManager(), lam);

            manager.start();
        }
    } catch (Exception e) {
        System.out.println("USAGE: java -jar MainMonitoring.jar \"systemSettings\"");
    }
}

From source file:com.chicm.cmraft.rpc.RpcClient.java

public static void main(String[] args) throws Exception {
    if (args.length < 3) {
        System.out.println(//from ww w.ja va  2 s .  c  o m
                "usage: RpcClient <server host> <server port> <clients number> <threads number> <packetsize>");
        return;
    }
    String host = args[0];
    int port = Integer.parseInt(args[1]);
    int nclients = Integer.parseInt(args[2]);
    int nThreads = Integer.parseInt(args[3]);
    int nPacketSize = 1024;

    if (args.length >= 5) {
        nPacketSize = Integer.parseInt(args[4]);
    }

    for (int j = 0; j < nclients; j++) {
        RpcClient client = new RpcClient(CmRaftConfiguration.create(), new ServerInfo(host, port));

        for (int i = 0; i < nThreads; i++) {
            new Thread(new TestRpcWorker(client, nPacketSize)).start();
        }
    }
}

From source file:RoucairolCarvahloBasicVersion.java

public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException {
    //For parsing the file and storing the information
    String line;/*  w w w .j av a  2s. c o  m*/
    String configurationFile = "configuration.txt";
    int lineCountInFile = 0;
    myProcessId = Integer.parseInt(args[0]);
    FileReader fileReader = new FileReader(configurationFile);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    while ((line = bufferedReader.readLine()) != null) {
        if ((!(line.startsWith("#"))) && (!(line.isEmpty()))) {
            lineCountInFile = lineCountInFile + 1;
            String[] splitLine = line.split(" ");
            switch (lineCountInFile) {
            case 1:
                numberOfProcesses = Integer.parseInt(splitLine[0]);
                interRequestDelay = Integer.parseInt(splitLine[1]);
                csExecutionTime = Integer.parseInt(splitLine[2]);
                maxNumberOfRequest = Integer.parseInt(splitLine[3]);
                machineNames = new String[Integer.parseInt(splitLine[0])];
                portNumbers = new int[Integer.parseInt(splitLine[0])];
                break;
            default:
                machineNames[lineCountInFile - 2] = splitLine[1];
                portNumbers[lineCountInFile - 2] = Integer.parseInt(splitLine[2]);
                break;
            }
        }
    }
    //Initializing finish array
    finishFlagArray = new int[numberOfProcesses];
    //Initializing vector class
    VectorClass.initialize(numberOfProcesses);
    //Fill the arrays with zero false value
    for (int o = 0; o < numberOfProcesses; o++) {
        finishFlagArray[o] = 0;
    }
    //Initializing key array and inserting values
    keyArray = new int[numberOfProcesses];
    for (int q = 0; q < numberOfProcesses; q++) {
        if (q >= myProcessId) {
            keyArray[q] = 1;
        }
    }
    filename = filename + Integer.toString(myProcessId) + ".out";
    file = new File(filename);
    file.createNewFile();
    writer = new FileWriter(file);
    // Write clocks to file
    filenameClock = filenameClock + Integer.toString(myProcessId) + ".out";
    fileClock = new File(filenameClock);
    fileClock.createNewFile();
    //writerClock = new FileWriter(fileClock);
    fw = new FileWriter(fileClock);
    bw = new BufferedWriter(fw);
    //
    // Expo mean insert
    csExecutionExpoDelay = new ExponentialDistribution(csExecutionTime);
    interRequestExpoDelay = new ExponentialDistribution(interRequestDelay);
    //
    System.out.println("********************************************************");
    System.out.println("My process id : " + myProcessId);
    System.out.println("Number of processes : " + numberOfProcesses);
    System.out.println("Inter-request delay : " + interRequestDelay);
    System.out.println("Critical section execution time : " + csExecutionTime);
    System.out.println("Maximum number of request : " + maxNumberOfRequest);
    System.out.println(
            "My process name : " + machineNames[myProcessId] + " My port number : " + portNumbers[myProcessId]);
    for (int i = 0; i < numberOfProcesses; i++) {
        System.out.println("Process name : " + machineNames[i] + " Port number : " + portNumbers[i]);
    }
    System.out.println("********************************************************");
    for (int q = 0; q < numberOfProcesses; q++) {
        System.out.println("KeyArray" + q + " - " + keyArray[q]);
    }
    System.out.println("********************************************************");
    //For hosting server localhost
    SctpServerChannel sctpServerChannel = SctpServerChannel.open();
    InetSocketAddress serverAddr = new InetSocketAddress(portNumbers[myProcessId]);
    sctpServerChannel.bind(serverAddr);
    System.out.println("********************************************************");
    System.out.println("Local server hosted");
    System.out.println("********************************************************");
    //For creating neighbor SCTP channels
    Thread.sleep(30000);
    socketAddress = new SocketAddress[numberOfProcesses];
    sctpChannel = new SctpChannel[numberOfProcesses];
    System.out.println("********************************************************");
    System.out.println("Neighbor channels created");
    System.out.println("********************************************************");
    //Thread spanned for generating critical section request
    new Thread(new RoucairolCarvahloBasicVersion()).start();
    while (true) {
        try (SctpChannel sctpChannelFromClient = sctpServerChannel.accept()) {
            mutex.acquire();
            byteBufferFromNeighbor.clear();
            String receiveMessage;
            MessageInfo messageInfoFromNeighbor = sctpChannelFromClient.receive(byteBufferFromNeighbor, null,
                    null);
            //System.out.println("Raw Message : " + messageInfoFromNeighbor);
            receiveMessage = byteToString(byteBufferFromNeighbor, messageInfoFromNeighbor);
            System.out.println("Received Message : " + receiveMessage);
            if (receiveMessage.contains("Request")) {
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                int requestMade = Integer.parseInt(parseMessage[3] + parseMessage[1]);
                if (outstandingRequest == 1) {
                    if (requestMade < currentRequestBeingServed) {
                        lamportClock++;
                        //Newly inserted for vector timesatmp
                        int[] vector = VectorClass.increment(myProcessId);
                        String vectorClockConstruction = "";
                        for (int g = 0; g < vector.length; g++) {
                            if (g == 0) {
                                vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]);
                            } else {
                                vectorClockConstruction = vectorClockConstruction + ","
                                        + Integer.toString(vector[g]);
                            }
                        }
                        //
                        keyArray[Integer.parseInt(parseMessage[1])] = 0;
                        try {
                            byteBufferToNeighbor.clear();
                            initializeChannels();
                            sctpChannel[Integer.parseInt(parseMessage[1])]
                                    .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                            String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-"
                                    + lamportClock + "-" + vectorClockConstruction;
                            System.out.println("Message sent is : " + sendMessage);
                            MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                            byteBufferToNeighbor.put(sendMessage.getBytes());
                            byteBufferToNeighbor.flip();
                            sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                    messageInfoToNeighbor);
                            totalMessageCount++;
                            sctpChannel[Integer.parseInt(parseMessage[1])].close();
                        } catch (IOException ex) {
                            Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE,
                                    null, ex);
                        }
                        //Include block for reverse request
                        lamportClock++;
                        //Newly inserted for vector timesatmp
                        int[] vector1 = VectorClass.increment(myProcessId);
                        String vectorClockConstruction1 = "";
                        for (int g = 0; g < vector1.length; g++) {
                            if (g == 0) {
                                vectorClockConstruction1 = vectorClockConstruction1
                                        + Integer.toString(vector1[g]);
                            } else {
                                vectorClockConstruction1 = vectorClockConstruction1 + ","
                                        + Integer.toString(vector1[g]);
                            }
                        }
                        //
                        try {
                            byteBufferToNeighbor.clear();
                            initializeChannels();
                            sctpChannel[Integer.parseInt(parseMessage[1])]
                                    .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                            String sendMessage = "ReverseSend from Process-" + myProcessId + "-"
                                    + currentRequestBeingServed + "-" + lamportClock + "-"
                                    + vectorClockConstruction1;
                            System.out.println("Message sent is : " + sendMessage);
                            MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                            byteBufferToNeighbor.put(sendMessage.getBytes());
                            byteBufferToNeighbor.flip();
                            sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                    messageInfoToNeighbor);
                            totalMessageCount++;
                            sctpChannel[Integer.parseInt(parseMessage[1])].close();
                        } catch (IOException ex) {
                            Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE,
                                    null, ex);
                        }
                    } else if (requestMade == currentRequestBeingServed) {
                        if (Integer.parseInt(parseMessage[1]) < myProcessId) {
                            lamportClock++;
                            //Newly inserted for vector timesatmp
                            int[] vector = VectorClass.increment(myProcessId);
                            String vectorClockConstruction = "";
                            for (int g = 0; g < vector.length; g++) {
                                if (g == 0) {
                                    vectorClockConstruction = vectorClockConstruction
                                            + Integer.toString(vector[g]);
                                } else {
                                    vectorClockConstruction = vectorClockConstruction + ","
                                            + Integer.toString(vector[g]);
                                }
                            }
                            //
                            keyArray[Integer.parseInt(parseMessage[1])] = 0;
                            try {
                                byteBufferToNeighbor.clear();
                                initializeChannels();
                                sctpChannel[Integer.parseInt(parseMessage[1])]
                                        .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                                String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-"
                                        + lamportClock + "-" + vectorClockConstruction;
                                System.out.println("Message sent is : " + sendMessage);
                                MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                                byteBufferToNeighbor.put(sendMessage.getBytes());
                                byteBufferToNeighbor.flip();
                                sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                        messageInfoToNeighbor);
                                totalMessageCount++;
                                sctpChannel[Integer.parseInt(parseMessage[1])].close();
                            } catch (IOException ex) {
                                Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }
                            //Include block for reverse request
                            lamportClock++;
                            //Newly inserted for vector timesatmp
                            int[] vector1 = VectorClass.increment(myProcessId);
                            String vectorClockConstruction1 = "";
                            for (int g = 0; g < vector1.length; g++) {
                                if (g == 0) {
                                    vectorClockConstruction1 = vectorClockConstruction1
                                            + Integer.toString(vector1[g]);
                                } else {
                                    vectorClockConstruction1 = vectorClockConstruction1 + ","
                                            + Integer.toString(vector1[g]);
                                }
                            }
                            //
                            try {
                                byteBufferToNeighbor.clear();
                                initializeChannels();
                                sctpChannel[Integer.parseInt(parseMessage[1])]
                                        .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                                String sendMessage = "ReverseSend from Process-" + myProcessId + "-"
                                        + currentRequestBeingServed + "-" + lamportClock + "-"
                                        + vectorClockConstruction1;
                                System.out.println("Message sent is : " + sendMessage);
                                MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                                byteBufferToNeighbor.put(sendMessage.getBytes());
                                byteBufferToNeighbor.flip();
                                sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                        messageInfoToNeighbor);
                                totalMessageCount++;
                                sctpChannel[Integer.parseInt(parseMessage[1])].close();
                            } catch (IOException ex) {
                                Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }
                        } else if (myProcessId < Integer.parseInt(parseMessage[1])) {
                            queue.add(requestMade);
                        }
                    } else if (requestMade > currentRequestBeingServed) {
                        queue.add(requestMade);
                    }
                } else if (outstandingRequest == 0) {
                    lamportClock++;
                    //Newly inserted for vector timesatmp
                    int[] vector = VectorClass.increment(myProcessId);
                    String vectorClockConstruction = "";
                    for (int g = 0; g < vector.length; g++) {
                        if (g == 0) {
                            vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]);
                        } else {
                            vectorClockConstruction = vectorClockConstruction + ","
                                    + Integer.toString(vector[g]);
                        }
                    }
                    //
                    keyArray[Integer.parseInt(parseMessage[1])] = 0;
                    try {
                        byteBufferToNeighbor.clear();
                        initializeChannels();
                        sctpChannel[Integer.parseInt(parseMessage[1])]
                                .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                        String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-"
                                + lamportClock + "-" + vectorClockConstruction;
                        System.out.println("Message sent is : " + sendMessage);
                        MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                        byteBufferToNeighbor.put(sendMessage.getBytes());
                        byteBufferToNeighbor.flip();
                        sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                messageInfoToNeighbor);
                        totalMessageCount++;
                        sctpChannel[Integer.parseInt(parseMessage[1])].close();
                    } catch (IOException ex) {
                        Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }
            } else if (receiveMessage.contains("Key")) {
                //receive check condition execute critical section block
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                keyArray[Integer.parseInt(parseMessage[1])] = 1;
                int countOnes = 0;
                for (int y = 0; y < numberOfProcesses; y++) {
                    if (keyArray[y] == 1) {
                        countOnes = countOnes + 1;
                    }
                }
                if (countOnes == numberOfProcesses) {
                    outstandingRequest = 0;
                    currentRequestBeingServed = 0;
                    enterCriticalSectionExecution();
                    timestamp2 = new Timestamp(System.currentTimeMillis());
                    csExit();
                }
            } else if (receiveMessage.contains("ReverseSend")) {
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                int requestMade = Integer.parseInt(parseMessage[2]);
                if (outstandingRequest == 1) {
                    if (requestMade < currentRequestBeingServed) {
                        lamportClock++;
                        //Newly inserted for vector timesatmp
                        int[] vector = VectorClass.increment(myProcessId);
                        String vectorClockConstruction = "";
                        for (int g = 0; g < vector.length; g++) {
                            if (g == 0) {
                                vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]);
                            } else {
                                vectorClockConstruction = vectorClockConstruction + ","
                                        + Integer.toString(vector[g]);
                            }
                        }
                        //
                        keyArray[Integer.parseInt(parseMessage[1])] = 0;
                        try {
                            byteBufferToNeighbor.clear();
                            initializeChannels();
                            sctpChannel[Integer.parseInt(parseMessage[1])]
                                    .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                            String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-"
                                    + lamportClock + "-" + vectorClockConstruction;
                            System.out.println("Message sent is : " + sendMessage);
                            MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                            byteBufferToNeighbor.put(sendMessage.getBytes());
                            byteBufferToNeighbor.flip();
                            sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                    messageInfoToNeighbor);
                            totalMessageCount++;
                            sctpChannel[Integer.parseInt(parseMessage[1])].close();
                        } catch (IOException ex) {
                            Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE,
                                    null, ex);
                        }
                        //Include block for reverse request
                        lamportClock++;
                        //Newly inserted for vector timesatmp
                        int[] vector1 = VectorClass.increment(myProcessId);
                        String vectorClockConstruction1 = "";
                        for (int g = 0; g < vector1.length; g++) {
                            if (g == 0) {
                                vectorClockConstruction1 = vectorClockConstruction1
                                        + Integer.toString(vector1[g]);
                            } else {
                                vectorClockConstruction1 = vectorClockConstruction1 + ","
                                        + Integer.toString(vector1[g]);
                            }
                        }
                        //
                        try {
                            byteBufferToNeighbor.clear();
                            initializeChannels();
                            sctpChannel[Integer.parseInt(parseMessage[1])]
                                    .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                            String sendMessage = "ReverseSend from Process-" + myProcessId + "-"
                                    + currentRequestBeingServed + "-" + lamportClock + "-"
                                    + vectorClockConstruction1;
                            System.out.println("Message sent is : " + sendMessage);
                            MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                            byteBufferToNeighbor.put(sendMessage.getBytes());
                            byteBufferToNeighbor.flip();
                            sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                    messageInfoToNeighbor);
                            totalMessageCount++;
                            sctpChannel[Integer.parseInt(parseMessage[1])].close();
                        } catch (IOException ex) {
                            Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE,
                                    null, ex);
                        }
                    } else if (requestMade == currentRequestBeingServed) {
                        if (Integer.parseInt(parseMessage[1]) < myProcessId) {
                            lamportClock++;
                            //Newly inserted for vector timesatmp
                            int[] vector = VectorClass.increment(myProcessId);
                            String vectorClockConstruction = "";
                            for (int g = 0; g < vector.length; g++) {
                                if (g == 0) {
                                    vectorClockConstruction = vectorClockConstruction
                                            + Integer.toString(vector[g]);
                                } else {
                                    vectorClockConstruction = vectorClockConstruction + ","
                                            + Integer.toString(vector[g]);
                                }
                            }
                            //
                            keyArray[Integer.parseInt(parseMessage[1])] = 0;
                            try {
                                byteBufferToNeighbor.clear();
                                initializeChannels();
                                sctpChannel[Integer.parseInt(parseMessage[1])]
                                        .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                                String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-"
                                        + lamportClock + "-" + vectorClockConstruction;
                                System.out.println("Message sent is : " + sendMessage);
                                MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                                byteBufferToNeighbor.put(sendMessage.getBytes());
                                byteBufferToNeighbor.flip();
                                sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                        messageInfoToNeighbor);
                                totalMessageCount++;
                                sctpChannel[Integer.parseInt(parseMessage[1])].close();
                            } catch (IOException ex) {
                                Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }
                            //Include block for reverse request
                            lamportClock++;
                            //Newly inserted for vector timesatmp
                            int[] vector1 = VectorClass.increment(myProcessId);
                            String vectorClockConstruction1 = "";
                            for (int g = 0; g < vector1.length; g++) {
                                if (g == 0) {
                                    vectorClockConstruction1 = vectorClockConstruction1
                                            + Integer.toString(vector1[g]);
                                } else {
                                    vectorClockConstruction1 = vectorClockConstruction1 + ","
                                            + Integer.toString(vector1[g]);
                                }
                            }
                            //
                            try {
                                byteBufferToNeighbor.clear();
                                initializeChannels();
                                sctpChannel[Integer.parseInt(parseMessage[1])]
                                        .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                                String sendMessage = "ReverseSend from Process-" + myProcessId + "-"
                                        + currentRequestBeingServed + "-" + lamportClock + "-"
                                        + vectorClockConstruction1;
                                System.out.println("Message sent is : " + sendMessage);
                                MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                                byteBufferToNeighbor.put(sendMessage.getBytes());
                                byteBufferToNeighbor.flip();
                                sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                        messageInfoToNeighbor);
                                totalMessageCount++;
                                sctpChannel[Integer.parseInt(parseMessage[1])].close();
                            } catch (IOException ex) {
                                Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }
                        } else if (myProcessId < Integer.parseInt(parseMessage[1])) {
                            queue.add(requestMade);
                        }
                    } else if (requestMade > currentRequestBeingServed) {
                        queue.add(requestMade);
                    }
                } else if (outstandingRequest == 0) {
                    lamportClock++;
                    //Newly inserted for vector timesatmp
                    int[] vector = VectorClass.increment(myProcessId);
                    String vectorClockConstruction = "";
                    for (int g = 0; g < vector.length; g++) {
                        if (g == 0) {
                            vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]);
                        } else {
                            vectorClockConstruction = vectorClockConstruction + ","
                                    + Integer.toString(vector[g]);
                        }
                    }
                    //
                    keyArray[Integer.parseInt(parseMessage[1])] = 0;
                    try {
                        byteBufferToNeighbor.clear();
                        initializeChannels();
                        sctpChannel[Integer.parseInt(parseMessage[1])]
                                .connect(socketAddress[Integer.parseInt(parseMessage[1])]);
                        String sendMessage = "Key from Process-" + myProcessId + "-" + requestMade + "-"
                                + lamportClock + "-" + vectorClockConstruction;
                        System.out.println("Message sent is : " + sendMessage);
                        MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                        byteBufferToNeighbor.put(sendMessage.getBytes());
                        byteBufferToNeighbor.flip();
                        sctpChannel[Integer.parseInt(parseMessage[1])].send(byteBufferToNeighbor,
                                messageInfoToNeighbor);
                        totalMessageCount++;
                        sctpChannel[Integer.parseInt(parseMessage[1])].close();
                    } catch (IOException ex) {
                        Logger.getLogger(RoucairolCarvahloBasicVersion.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }
            } else if (receiveMessage.contains("Finish")) {
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                finishFlagArray[Integer.parseInt(parseMessage[1])] = 1;
                int count = 0;
                for (int v = 0; v < numberOfProcesses; v++) {
                    if (finishFlagArray[v] == 1) {
                        count = count + 1;
                    }
                }
                if (count == numberOfProcesses) {
                    break;
                }
            }
        }
        mutex.release();
    }
}

From source file:com.hpe.nv.samples.basic.BasicAnalyzeNVTest.java

public static void main(String[] args) {
    try {/*from w  w  w .  j a va 2s .  c  o m*/
        // program arguments
        Options options = new Options();
        options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP");
        options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port");
        options.addOption("u", "username", true, "[mandatory] NV username");
        options.addOption("w", "password", true, "[mandatory] NV password");
        options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false");
        options.addOption("y", "proxy", true, "[optional] Proxy server host:port");
        options.addOption("z", "zip-result-file-path", true,
                "[optional] File path to store the analysis results as a .zip file");
        options.addOption("k", "analysis-ports", true,
                "[optional] A comma-separated list of ports for test analysis");
        options.addOption("b", "browser", true,
                "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome and Firefox. Default: Firefox");
        options.addOption("d", "debug", true,
                "[optional] Pass true to view console debug messages during execution. Default: false");
        options.addOption("h", "help", false, "[optional] Generates and prints help information");

        // parse and validate the command line arguments
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            // print help if help argument is passed
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("BasicAnalyzeNVTest.java", options);
            return;
        }

        if (line.hasOption("server-ip")) {
            serverIp = line.getOptionValue("server-ip");
            if (serverIp.equals("0.0.0.0")) {
                throw new Exception(
                        "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP");
            }
        } else {
            throw new Exception("Missing argument -i/--server-ip <serverIp>");
        }

        if (line.hasOption("server-port")) {
            serverPort = Integer.parseInt(line.getOptionValue("server-port"));
        } else {
            throw new Exception("Missing argument -o/--server-port <serverPort>");
        }

        if (line.hasOption("username")) {
            username = line.getOptionValue("username");
        } else {
            throw new Exception("Missing argument -u/--username <username>");
        }

        if (line.hasOption("password")) {
            password = line.getOptionValue("password");
        } else {
            throw new Exception("Missing argument -w/--password <password>");
        }

        if (line.hasOption("ssl")) {
            ssl = Boolean.parseBoolean(line.getOptionValue("ssl"));
        }

        if (line.hasOption("zip-result-file-path")) {
            zipResultFilePath = line.getOptionValue("zip-result-file-path");
        }

        if (line.hasOption("proxy")) {
            proxySetting = line.getOptionValue("proxy");
        }

        if (line.hasOption("analysis-ports")) {
            String analysisPortsStr = line.getOptionValue("analysis-ports");
            analysisPorts = analysisPortsStr.split(",");
        } else {
            analysisPorts = new String[] { "80", "8080" };
        }

        if (line.hasOption("browser")) {
            browser = line.getOptionValue("browser");
        } else {
            browser = "Firefox";
        }

        if (line.hasOption("debug")) {
            debug = Boolean.parseBoolean(line.getOptionValue("debug"));
        }

        String newLine = System.getProperty("line.separator");
        String testDescription = "***   This sample demonstrates the use of the most basic NV methods.                                                      ***"
                + newLine
                + "***                                                                                                                       ***"
                + newLine
                + "***   First, the sample creates a TestManager object and initializes it.                                                  ***"
                + newLine
                + "***   The sample starts an NV test over an emulated \"3G Busy\" network.                                                    ***"
                + newLine
                + "***                                                                                                                       ***"
                + newLine
                + "***   Next, the sample navigates to the home page in the HPE Network Virtualization website                               ***"
                + newLine
                + "***   using the Selenium WebDriver.                                                                                       ***"
                + newLine
                + "***                                                                                                                       ***"
                + newLine
                + "***   Finally, the sample stops the NV test, analyzes it, and prints the path of the analysis .zip file to the console.   ***"
                + newLine
                + "***                                                                                                                       ***"
                + newLine
                + "***   You can view the actual steps of this sample in the BasicAnalyzeNVTest.java file.                                   ***"
                + newLine;

        // print the sample's description
        System.out.println(testDescription);

        // start console spinner
        if (!debug) {
            spinner = new Thread(new Spinner());
            spinner.start();
        }

        // sample execution steps
        /*****    Part 1 - Create a TestManager object and initialize it                                            *****/
        printPartDescription("\b------    Part 1 - Create a TestManager object and initialize it");
        initTestManager();
        printPartSeparator();
        /*****    Part 2 - Start the NV test with the "3G Busy" network scenario                                    *****/
        printPartDescription("------    Part 2 - Start the NV test with the \"3G Busy\" network scenario");
        startTest();
        testRunning = true;
        printPartSeparator();
        /*****    Part 3 - Navigate to the HPE Network Virtualization website                                       *****/
        printPartDescription("------    Part 3 - Navigate to the HPE Network Virtualization website");
        buildSeleniumWebDriver();
        seleniumNavigateToPage();
        driverCloseAndQuit();
        printPartSeparator();
        /*****    Part 4 - Stop the NV test, analyze it and print the results to the console                        *****/
        printPartDescription(
                "------    Part 4 - Stop the NV test, analyze it and print the results to the console");
        stopTestAndAnalyze();
        testRunning = false;
        printPartSeparator();
        doneCallback();
    } catch (Exception e) {
        try {
            handleError(e.getMessage());
        } catch (Exception e2) {
            System.out.println("Error occurred: " + e2.getMessage());
        }
    }
}