Example usage for java.io FileWriter FileWriter

List of usage examples for java.io FileWriter FileWriter

Introduction

In this page you can find the example usage for java.io FileWriter FileWriter.

Prototype

public FileWriter(FileDescriptor fd) 

Source Link

Document

Constructs a FileWriter given a file descriptor, using the platform's java.nio.charset.Charset#defaultCharset() default charset .

Usage

From source file:LamportBasicVersion.java

public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException {
    totalMessageCount = 0;//from www  . ja  v a 2s.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:com.tuplejump.stargate.util.CQLUnitD.java

public static void main(String[] args) throws Exception {
    Person[] persons = jsonMapper.readValue(is2, Person[].class);
    File file = new File("samples/sample-json.cql");
    FileWriter fileWriter = new FileWriter(file);
    for (Person person : persons) {
        fileWriter.write(person.toInsertString() + "\n");
    }//from  w w  w. j av  a  2s. com
    fileWriter.flush();
    fileWriter.close();
}

From source file:com.qwazr.utils.HtmlUtils.java

public static void main(String args[]) throws IOException {
     if (args != null && args.length == 2) {
         List<String> lines = FileUtils.readLines(new File(args[0]));
         FileWriter fw = new FileWriter(new File(args[1]));
         PrintWriter pw = new PrintWriter(fw);
         for (String line : lines)
             pw.println(StringEscapeUtils.unescapeHtml4(line));
         pw.close();/*from  ww  w.ja v  a2 s  . co  m*/
         fw.close();
     }
     String text = "file://&shy;Users/ekeller/Moteur/infotoday_enterprisesearchsourcebook08/Open_on_Windows.exe";
     System.out.println(htmlWrap(text, 20));
     System.out.println(htmlWrapReduce(text, 20, 80));
     String url = "file://Users/ekeller/Moteur/infotoday_enterprisesearchsourcebook08/Open_on_Windows.exe?test=2";
     System.out.println(urlHostPathWrapReduce(url, 80));
 }

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;//  www.j  a v a  2s  . com
    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:apps.quantification.QuantifySVMPerf.java

public static void main(String[] args) throws IOException {
    String cmdLineSyntax = QuantifySVMPerf.class.getName()
            + " [OPTIONS] <path to svm_perf_classify> <testIndexDirectory> <quantificationModelDirectory>";

    Options options = new Options();

    OptionBuilder.withArgName("d");
    OptionBuilder.withDescription("Dump confidences file");
    OptionBuilder.withLongOpt("d");
    OptionBuilder.isRequired(false);//from   ww  w.  j  a  va 2 s .c o  m
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("t");
    OptionBuilder.withDescription("Path for temporary files");
    OptionBuilder.withLongOpt("t");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("v");
    OptionBuilder.withDescription("Verbose output");
    OptionBuilder.withLongOpt("v");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("s");
    OptionBuilder.withDescription("Don't delete temporary files in svm_perf format (default: delete)");
    OptionBuilder.withLongOpt("s");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    SvmPerfClassifierCustomizer customizer = null;

    GnuParser parser = new GnuParser();
    String[] remainingArgs = null;
    try {
        CommandLine line = parser.parse(options, args);

        remainingArgs = line.getArgs();

        customizer = new SvmPerfClassifierCustomizer(remainingArgs[0]);

        if (line.hasOption("v"))
            customizer.printSvmPerfOutput(true);

        if (line.hasOption("s")) {
            System.out.println("Keeping temporary files.");
            customizer.setDeleteTestFiles(false);
            customizer.setDeletePredictionsFiles(false);
        }

        if (line.hasOption("t"))
            customizer.setTempPath(line.getOptionValue("t"));

    } catch (Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    if (remainingArgs.length != 3) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    String indexFile = remainingArgs[1];

    File file = new File(indexFile);

    String indexName = file.getName();
    String indexPath = file.getParent();

    String quantifierFilename = remainingArgs[2];

    FileSystemStorageManager indexFssm = new FileSystemStorageManager(indexPath, false);
    indexFssm.open();

    IIndex test = TroveReadWriteHelper.readIndex(indexFssm, indexName, TroveContentDBType.Full,
            TroveClassificationDBType.Full);

    indexFssm.close();

    FileSystemStorageManager quantifierFssm = new FileSystemStorageManager(quantifierFilename, false);
    quantifierFssm.open();

    SvmPerfDataManager classifierDataManager = new SvmPerfDataManager(customizer);

    FileSystemStorageManager fssm = new FileSystemStorageManager(quantifierFilename, false);
    fssm.open();

    IQuantifier[] quantifiers = QuantificationLearner.read(fssm, classifierDataManager,
            ClassificationMode.PER_CATEGORY);
    fssm.close();

    quantifierFssm.close();

    Quantification ccQuantification = quantifiers[0].quantify(test);
    Quantification paQuantification = quantifiers[1].quantify(test);
    Quantification accQuantification = quantifiers[2].quantify(test);
    Quantification maxQuantification = quantifiers[3].quantify(test);
    Quantification sccQuantification = quantifiers[4].quantify(test);
    Quantification spaQuantification = quantifiers[5].quantify(test);
    Quantification trueQuantification = new Quantification("True", test.getClassificationDB());

    File quantifierFile = new File(quantifierFilename);

    String quantificationName = quantifierFile.getParent() + Os.pathSeparator() + indexName + "_"
            + quantifierFile.getName() + ".txt";

    BufferedWriter writer = new BufferedWriter(new FileWriter(quantificationName));
    IShortIterator iterator = test.getCategoryDB().getCategories();
    while (iterator.hasNext()) {
        short category = iterator.next();
        String prefix = quantifierFile.getName() + "\t" + indexName + "\t"
                + test.getCategoryDB().getCategoryName(category) + "\t" + category + "\t"
                + trueQuantification.getQuantification(category) + "\t";

        writer.write(prefix + ccQuantification.getName() + "\t" + ccQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + paQuantification.getName() + "\t" + paQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + accQuantification.getName() + "\t" + accQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + maxQuantification.getName() + "\t" + maxQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + sccQuantification.getName() + "\t" + sccQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + spaQuantification.getName() + "\t" + spaQuantification.getQuantification(category)
                + "\n");
    }
    writer.close();

    BufferedWriter bfs = new BufferedWriter(new FileWriter(quantifierFile.getParent() + Os.pathSeparator()
            + indexName + "_" + quantifierFile.getName() + "_rates.txt"));
    TShortDoubleHashMap simpleTPRs = ((CCQuantifier) quantifiers[0]).getSimpleTPRs();
    TShortDoubleHashMap simpleFPRs = ((CCQuantifier) quantifiers[0]).getSimpleFPRs();
    TShortDoubleHashMap maxTPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier())
            .getSimpleTPRs();
    TShortDoubleHashMap maxFPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier())
            .getSimpleFPRs();
    TShortDoubleHashMap scaledTPRs = ((PAQuantifier) quantifiers[1]).getScaledTPRs();
    TShortDoubleHashMap scaledFPRs = ((PAQuantifier) quantifiers[1]).getScaledFPRs();

    ContingencyTableSet simpleContingencyTableSet = ((CCQuantifier) quantifiers[0]).getContingencyTableSet();
    ContingencyTableSet maxContingencyTableSet = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3])
            .getInternalQuantifier()).getContingencyTableSet();

    short[] cats = simpleTPRs.keys();
    for (int i = 0; i < cats.length; ++i) {
        short cat = cats[i];
        String catName = test.getCategoryDB().getCategoryName(cat);
        ContingencyTable simpleContingencyTable = simpleContingencyTableSet.getCategoryContingencyTable(cat);
        ContingencyTable maxContingencyTable = maxContingencyTableSet.getCategoryContingencyTable(cat);
        double simpleTPR = simpleTPRs.get(cat);
        double simpleFPR = simpleFPRs.get(cat);
        double maxTPR = maxTPRs.get(cat);
        double maxFPR = maxFPRs.get(cat);
        double scaledTPR = scaledTPRs.get(cat);
        double scaledFPR = scaledFPRs.get(cat);
        String line = indexName + "_" + quantifierFile.getName() + "\ttest\tsimple\t" + catName + "\t" + cat
                + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t"
                + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + simpleTPR + "\t"
                + simpleFPR + "\n";
        bfs.write(line);
        line = indexName + "_" + quantifierFile.getName() + "\ttest\tmax\t" + catName + "\t" + cat + "\t"
                + maxContingencyTable.tp() + "\t" + maxContingencyTable.fp() + "\t" + maxContingencyTable.fn()
                + "\t" + maxContingencyTable.tn() + "\t" + maxTPR + "\t" + maxFPR + "\n";
        bfs.write(line);
        line = indexName + "_" + quantifierFile.getName() + "\ttest\tscaled\t" + catName + "\t" + cat + "\t"
                + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t"
                + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + scaledTPR + "\t"
                + scaledFPR + "\n";
        bfs.write(line);
    }
    bfs.close();
}

From source file:apps.quantification.QuantifySVMLight.java

public static void main(String[] args) throws IOException {
    String cmdLineSyntax = QuantifySVMLight.class.getName()
            + " [OPTIONS] <path to svm_light_classify> <testIndexDirectory> <quantificationModelDirectory>";

    Options options = new Options();

    OptionBuilder.withArgName("d");
    OptionBuilder.withDescription("Dump confidences file");
    OptionBuilder.withLongOpt("d");
    OptionBuilder.isRequired(false);/*from  w  w  w  . ja v a2 s .  c om*/
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("t");
    OptionBuilder.withDescription("Path for temporary files");
    OptionBuilder.withLongOpt("t");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("v");
    OptionBuilder.withDescription("Verbose output");
    OptionBuilder.withLongOpt("v");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("s");
    OptionBuilder.withDescription("Don't delete temporary files in svm_light format (default: delete)");
    OptionBuilder.withLongOpt("s");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    SvmLightClassifierCustomizer customizer = null;

    GnuParser parser = new GnuParser();
    String[] remainingArgs = null;
    try {
        CommandLine line = parser.parse(options, args);

        remainingArgs = line.getArgs();

        customizer = new SvmLightClassifierCustomizer(remainingArgs[0]);

        if (line.hasOption("v"))
            customizer.printSvmLightOutput(true);

        if (line.hasOption("s")) {
            System.out.println("Keeping temporary files.");
            customizer.setDeleteTestFiles(false);
            customizer.setDeletePredictionsFiles(false);
        }

        if (line.hasOption("t"))
            customizer.setTempPath(line.getOptionValue("t"));

    } catch (Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    if (remainingArgs.length != 3) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    String indexFile = remainingArgs[1];

    File file = new File(indexFile);

    String indexName = file.getName();
    String indexPath = file.getParent();

    String quantifierFilename = remainingArgs[2];

    FileSystemStorageManager indexFssm = new FileSystemStorageManager(indexPath, false);
    indexFssm.open();

    IIndex test = TroveReadWriteHelper.readIndex(indexFssm, indexName, TroveContentDBType.Full,
            TroveClassificationDBType.Full);

    indexFssm.close();

    FileSystemStorageManager quantifierFssm = new FileSystemStorageManager(quantifierFilename, false);
    quantifierFssm.open();

    SvmLightDataManager classifierDataManager = new SvmLightDataManager(customizer);

    FileSystemStorageManager fssm = new FileSystemStorageManager(quantifierFilename, false);
    fssm.open();

    IQuantifier[] quantifiers = QuantificationLearner.read(fssm, classifierDataManager,
            ClassificationMode.PER_CATEGORY);
    fssm.close();

    quantifierFssm.close();

    Quantification ccQuantification = quantifiers[0].quantify(test);
    Quantification paQuantification = quantifiers[1].quantify(test);
    Quantification accQuantification = quantifiers[2].quantify(test);
    Quantification maxQuantification = quantifiers[3].quantify(test);
    Quantification sccQuantification = quantifiers[4].quantify(test);
    Quantification spaQuantification = quantifiers[5].quantify(test);
    Quantification trueQuantification = new Quantification("True", test.getClassificationDB());

    File quantifierFile = new File(quantifierFilename);

    String quantificationName = quantifierFile.getParent() + Os.pathSeparator() + indexName + "_"
            + quantifierFile.getName() + ".txt";

    BufferedWriter writer = new BufferedWriter(new FileWriter(quantificationName));
    IShortIterator iterator = test.getCategoryDB().getCategories();
    while (iterator.hasNext()) {
        short category = iterator.next();
        String prefix = quantifierFile.getName() + "\t" + indexName + "\t"
                + test.getCategoryDB().getCategoryName(category) + "\t" + category + "\t"
                + trueQuantification.getQuantification(category) + "\t";

        writer.write(prefix + ccQuantification.getName() + "\t" + ccQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + paQuantification.getName() + "\t" + paQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + accQuantification.getName() + "\t" + accQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + maxQuantification.getName() + "\t" + maxQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + sccQuantification.getName() + "\t" + sccQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + spaQuantification.getName() + "\t" + spaQuantification.getQuantification(category)
                + "\n");
    }
    writer.close();

    BufferedWriter bfs = new BufferedWriter(new FileWriter(quantifierFile.getParent() + Os.pathSeparator()
            + indexName + "_" + quantifierFile.getName() + "_rates.txt"));
    TShortDoubleHashMap simpleTPRs = ((CCQuantifier) quantifiers[0]).getSimpleTPRs();
    TShortDoubleHashMap simpleFPRs = ((CCQuantifier) quantifiers[0]).getSimpleFPRs();
    TShortDoubleHashMap maxTPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier())
            .getSimpleTPRs();
    TShortDoubleHashMap maxFPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier())
            .getSimpleFPRs();
    TShortDoubleHashMap scaledTPRs = ((PAQuantifier) quantifiers[1]).getScaledTPRs();
    TShortDoubleHashMap scaledFPRs = ((PAQuantifier) quantifiers[1]).getScaledFPRs();

    ContingencyTableSet simpleContingencyTableSet = ((CCQuantifier) quantifiers[0]).getContingencyTableSet();
    ContingencyTableSet maxContingencyTableSet = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3])
            .getInternalQuantifier()).getContingencyTableSet();

    short[] cats = simpleTPRs.keys();
    for (int i = 0; i < cats.length; ++i) {
        short cat = cats[i];
        String catName = test.getCategoryDB().getCategoryName(cat);
        ContingencyTable simpleContingencyTable = simpleContingencyTableSet.getCategoryContingencyTable(cat);
        ContingencyTable maxContingencyTable = maxContingencyTableSet.getCategoryContingencyTable(cat);
        double simpleTPR = simpleTPRs.get(cat);
        double simpleFPR = simpleFPRs.get(cat);
        double maxTPR = maxTPRs.get(cat);
        double maxFPR = maxFPRs.get(cat);
        double scaledTPR = scaledTPRs.get(cat);
        double scaledFPR = scaledFPRs.get(cat);
        String line = indexName + "_" + quantifierFile.getName() + "\ttest\tsimple\t" + catName + "\t" + cat
                + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t"
                + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + simpleTPR + "\t"
                + simpleFPR + "\n";
        bfs.write(line);
        line = indexName + "_" + quantifierFile.getName() + "\ttest\tmax\t" + catName + "\t" + cat + "\t"
                + maxContingencyTable.tp() + "\t" + maxContingencyTable.fp() + "\t" + maxContingencyTable.fn()
                + "\t" + maxContingencyTable.tn() + "\t" + maxTPR + "\t" + maxFPR + "\n";
        bfs.write(line);
        line = indexName + "_" + quantifierFile.getName() + "\ttest\tscaled\t" + catName + "\t" + cat + "\t"
                + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t"
                + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + scaledTPR + "\t"
                + scaledFPR + "\n";
        bfs.write(line);
    }
    bfs.close();
}

From source file:com.arsdigita.util.parameter.ParameterPrinter.java

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

    CommandLine line = null;//from  ww  w. j  ava  2s  .c om
    try {
        line = new PosixParser().parse(OPTIONS, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    String[] outFile = line.getArgs();
    if (outFile.length != 1) {
        System.out.println("Usage: ParameterPrinter [--html] [--file config-list-file] output-file");
        System.exit(1);
    }
    if (line.hasOption("usage")) {
        System.out.println("Usage: ParameterPrinter [--html] [--file config-list-file] output-file");
        System.exit(0);
    }

    if (line.hasOption("file")) {
        String file = line.getOptionValue("file");
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String configClass;
            while ((configClass = reader.readLine()) != null) {
                register(configClass);
            }
        } catch (IOException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    } else {
        register("com.arsdigita.runtime.RuntimeConfig");
        register("com.arsdigita.web.WebConfig");
        register("com.arsdigita.templating.TemplatingConfig");
        register("com.arsdigita.kernel.KernelConfig");
        register("com.arsdigita.kernel.security.SecurityConfig");
        register("com.arsdigita.mail.MailConfig");
        register("com.arsdigita.versioning.VersioningConfig");
        register("com.arsdigita.search.SearchConfig");
        register("com.arsdigita.search.lucene.LuceneConfig");
        register("com.arsdigita.kernel.security.SecurityConfig");
        register("com.arsdigita.bebop.BebopConfig");
        register("com.arsdigita.dispatcher.DispatcherConfig");
        register("com.arsdigita.workflow.simple.WorkflowConfig");
        register("com.arsdigita.cms.ContentSectionConfig");
    }

    if (line.hasOption("html")) {
        final StringWriter sout = new StringWriter();
        final PrintWriter out = new PrintWriter(sout);

        writeXML(out);

        final XSLTemplate template = new XSLTemplate(
                ParameterPrinter.class.getResource("ParameterPrinter_html.xsl"));

        final Source source = new StreamSource(new StringReader(sout.toString()));
        final Result result = new StreamResult(new File(outFile[0]));

        template.transform(source, result);
    } else {
        final PrintWriter out = new PrintWriter(new FileWriter(outFile[0]));

        writeXML(out);
    }
}

From source file:evaluation.evaluation1VMPolicyGeneration.java

public static void main(String[] args) {

    int VMNumber = 5;
    int attributeNumber = 20;

    JSONObject obj = new JSONObject();
    obj.put("name", "clientTemplate");
    obj.put("context", "VM-deployment");
    //obj.put("Context", new Integer);

    HashMap serviceRequirement = new HashMap();

    HashMap serviceDescription = new HashMap();
    serviceRequirement.put("VM1_volume", "1_GB");
    serviceDescription.put("VM1_purpose", "dev");
    serviceDescription.put("VM1_data", "private");
    serviceDescription.put("VM1_application", "internal");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM1_other" + j, "other");
    }/* w  w  w.j a v  a 2 s.  c o  m*/

    serviceRequirement.put("VM2_volume", "2_GB");
    serviceDescription.put("VM2_purpose", "prod");
    serviceDescription.put("VM2_data", "public");
    serviceDescription.put("VM2_application", "business");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM2_other" + j, "other");
    }

    serviceRequirement.put("VM3_volume", "1_GB");
    serviceDescription.put("VM3_purpose", "test");
    serviceDescription.put("VM3_data", "public");
    serviceDescription.put("VM3_application", "business");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM3_other" + j, "other");
    }

    serviceRequirement.put("VM4_volume", "12_GB");
    serviceDescription.put("VM4_purpose", "prod");
    serviceDescription.put("VM4_data", "public");
    serviceDescription.put("VM4_application", "business");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM4_other" + j, "other");
    }

    for (int i = 5; i < VMNumber; i++) {
        serviceRequirement.put("VM" + i + "_volume", "20_GB");
        serviceDescription.put("VM" + i + "_purpose", "prod");
        serviceDescription.put("VM" + i + "_data", "public");
        serviceDescription.put("VM" + i + "_application", "business");
        for (int j = 5; j < attributeNumber; j++) {
            serviceDescription.put("VM" + i + "_other" + j, "other");
        }

    }

    obj.put("serviceRequirement", serviceRequirement);
    obj.put("serviceDescription", serviceDescription);

    HashMap gauranteeTerm = new HashMap();
    gauranteeTerm.put("VM1_availability", "more_97_percentage");
    gauranteeTerm.put("VM2_availability", "more_99_percentage");
    gauranteeTerm.put("VM3_availability", "more_95_percentage");
    gauranteeTerm.put("VM4_availability", "more_99_percentage");
    obj.put("gauranteeTerm", gauranteeTerm);

    //Constraint1

    HashMap host_rule1 = new HashMap();
    HashMap VM_rule1 = new HashMap();
    host_rule1.put("certificate", "true");
    VM_rule1.put("purpose", "dev");

    ArrayList rule1 = new ArrayList();
    rule1.add("permission");
    rule1.add(host_rule1);
    rule1.add(VM_rule1);

    HashMap host_rule1_2 = new HashMap();
    HashMap VM_rule1_2 = new HashMap();
    host_rule1_2.put("certificate", "true");
    VM_rule1_2.put("purpose", "prod");

    ArrayList rule1_2 = new ArrayList();
    rule1_2.add("permission");
    rule1_2.add(host_rule1_2);
    rule1_2.add(VM_rule1_2);

    HashMap host_rule1_3 = new HashMap();
    HashMap VM_rule1_3 = new HashMap();
    host_rule1_3.put("certificate", "true");
    VM_rule1_3.put("purpose", "test");

    ArrayList rule1_3 = new ArrayList();
    rule1_3.add("permission");
    rule1_3.add(host_rule1_3);
    rule1_3.add(VM_rule1_3);

    HashMap host_rule2 = new HashMap();
    HashMap VM_rule2 = new HashMap();
    host_rule2.put("location", "France");
    VM_rule2.put("ID", "VM2");

    ArrayList rule2 = new ArrayList();
    rule2.add("permission");
    rule2.add(host_rule2);
    rule2.add(VM_rule2);

    HashMap host_rule2_1 = new HashMap();
    HashMap VM_rule2_1 = new HashMap();
    host_rule2_1.put("location", "UK");
    VM_rule2_1.put("ID", "VM2");

    ArrayList rule2_1 = new ArrayList();
    rule2_1.add("permission");
    rule2_1.add(host_rule2_1);
    rule2_1.add(VM_rule2_1);

    HashMap host_rule3 = new HashMap();
    HashMap VM_rule3 = new HashMap();
    host_rule3.put("location", "France");
    VM_rule3.put("application", "business");

    ArrayList rule3 = new ArrayList();
    rule3.add("permission");
    rule3.add(host_rule3);
    rule3.add(VM_rule3);

    HashMap host_rule3_1 = new HashMap();
    HashMap VM_rule3_1 = new HashMap();
    host_rule3_1.put("location", "UK");
    VM_rule3_1.put("application", "business");

    ArrayList rule3_1 = new ArrayList();
    rule3_1.add("permission");
    rule3_1.add(host_rule3_1);
    rule3_1.add(VM_rule3_1);

    HashMap VMSeperation_rule_1_1 = new HashMap();
    HashMap VMSeperation_rule_1_2 = new HashMap();

    VMSeperation_rule_1_1.put("ID", "VM1");
    VMSeperation_rule_1_2.put("ID", "VM3");

    ArrayList rule4 = new ArrayList();
    rule4.add("separation");
    rule4.add(VMSeperation_rule_1_1);
    rule4.add(VMSeperation_rule_1_2);

    ArrayList policyInConstraint1 = new ArrayList();
    policyInConstraint1.add(rule1);
    policyInConstraint1.add(rule1_2);
    policyInConstraint1.add(rule1_3);

    policyInConstraint1.add(rule2);
    policyInConstraint1.add(rule2_1);

    policyInConstraint1.add(rule3);
    policyInConstraint1.add(rule3_1);

    policyInConstraint1.add(rule4);

    ArrayList creationConstraint1 = new ArrayList();
    creationConstraint1.add("RP4");
    creationConstraint1.add("true");
    creationConstraint1.add("true");
    creationConstraint1.add(policyInConstraint1);

    ArrayList totalConstraint = new ArrayList();
    totalConstraint.add(creationConstraint1);

    obj.put("creationConstraint", totalConstraint);

    try {

        FileWriter file = new FileWriter("confClient" + File.separator + "test3.json");
        file.write(obj.toJSONString());
        file.flush();
        file.close();

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

    System.out.print(obj);

    /*
            
    JSONParser parser = new JSONParser();
            
    try {
            
    Object obj2 = parser.parse(new FileReader("test2.json"));
            
    JSONObject jsonObject = (JSONObject) obj2;
            
        HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription");
                 
        method.printHashMap(serviceDescription2);
                
                
        HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm");
                 
        method.printHashMap(gauranteeTerm2);
                
                
                
        ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint");
                
        method.printArrayList(creationConstraint);
            
            
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ParseException e) {
    e.printStackTrace();
    }
            
            
            
            
            
    */

}

From source file:microbiosima.Microbiosima.java

/**
 * @param args/* w ww . ja  v a 2s .c o m*/
 *            the command line arguments
 * @throws java.io.FileNotFoundException
 * @throws java.io.UnsupportedEncodingException
 */
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    //Init with default values
    int populationSize = 500;
    int microSize = 1000;
    int numberOfSpecies = 150;
    int numberOfGeneration = 10000;
    int numberOfObservation = 100;
    int numberOfReplication = 1;
    double pctEnv = 0;
    double pctPool = 0;

    Options options = new Options();

    Option help = new Option("h", "help", false, "print this message");
    Option version = new Option("v", "version", false, "print the version information and exit");
    options.addOption(help);
    options.addOption(version);

    options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS")
            .desc("Number generation for observation [default: 100]").build());
    options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP")
            .desc("Number of replication [default: 1]").build());

    Builder C = Option.builder("c").longOpt("config").numberOfArgs(4).argName("Pop Micro Spec Gen")
            .desc("Four Parameters in the following orders: "
                    + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation"
                    + " [default: 500 1000 150 10000]");
    options.addOption(C.build());

    HelpFormatter formatter = new HelpFormatter();
    String syntax = "microbiosima pctEnv pctPool";
    String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n"
            + "required arguments:\n" + "  pctEnv             Percentage of environmental acquisition\n"
            + "  pctPool            Percentage of pooled environmental component\n" + "\noptional arguments:\n";
    String footer = "\n";

    formatter.setWidth(80);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        String[] pct_config = cmd.getArgs();

        if (cmd.hasOption("h") || args.length == 0) {
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(0);
        }
        if (cmd.hasOption("v")) {
            System.out.println("Microbiosima " + VERSION);
            System.exit(0);
        }
        if (pct_config.length != 2) {
            System.out.println("ERROR! Required exactly two argumennts for pct_env and pct_pool. It got "
                    + pct_config.length + ": " + Arrays.toString(pct_config));
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(3);
        } else {
            pctEnv = Double.parseDouble(pct_config[0]);
            pctPool = Double.parseDouble(pct_config[1]);
            if (pctEnv < 0 || pctEnv > 1) {
                System.out.println(
                        "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv="
                                + pctEnv + ")! EXIT");
                System.exit(3);
            }
            if (pctPool < 0 || pctPool > 1) {
                System.out.println(
                        "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool="
                                + pctPool + ")! EXIT");
                System.exit(3);
            }

        }
        if (cmd.hasOption("config")) {
            String[] configs = cmd.getOptionValues("config");
            populationSize = Integer.parseInt(configs[0]);
            microSize = Integer.parseInt(configs[1]);
            numberOfSpecies = Integer.parseInt(configs[2]);
            numberOfGeneration = Integer.parseInt(configs[3]);
        }
        if (cmd.hasOption("obs")) {
            numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs"));
        }
        if (cmd.hasOption("rep")) {
            numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep"));
        }

    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(3);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize)
            .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ")
            .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration)
            .append("\n\tNumber generation for observation: ").append(numberOfObservation)
            .append("\n\tNumber of replication: ").append(numberOfReplication).append("\n");
    System.out.println(sb.toString());

    //      System.exit(3);
    // LogNormalDistribution lgd=new LogNormalDistribution(0,1);
    // environment=lgd.sample(150);
    // double environment_sum=0;
    // for (int i=0;i<No;i++){
    // environment_sum+=environment[i];
    // }
    // for (int i=0;i<No;i++){
    // environment[i]/=environment_sum;
    // }

    double[] environment = new double[numberOfSpecies];
    for (int i = 0; i < numberOfSpecies; i++) {
        environment[i] = 1 / (double) numberOfSpecies;
    }

    for (int rep = 0; rep < numberOfReplication; rep++) {
        String prefix = "" + (rep + 1) + "_";
        String sufix = "_E" + pctEnv + "_P" + pctPool + ".txt";

        System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix);
        try {

            PrintWriter file1 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix)));
            PrintWriter file2 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix)));
            PrintWriter file3 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix)));
            PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix)));
            PrintWriter file5 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix)));
            PrintWriter file6 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix)));

            Population population = new Population(microSize, environment, populationSize, pctEnv, pctPool, 0,
                    0);

            while (population.getNumberOfGeneration() < numberOfGeneration) {
                population.sumSpecies();
                if (population.getNumberOfGeneration() % numberOfObservation == 0) {
                    file1.println(population.gammaDiversity(true));
                    file2.println(population.alphaDiversity(true));
                    file3.print(population.betaDiversity(true));
                    file3.print("\t");
                    file3.println(population.BrayCurtis(true));
                    file4.println(population.printOut());
                    file5.println(population.interGenerationDistance());
                    file6.println(population.environmentPopulationDistance());
                }
                population.getNextGen();
            }
            file1.close();
            file2.close();
            file3.close();
            file4.close();
            file5.close();
            file6.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:CSVWriter.java

/**
 * Test driver/*w  ww  . j  a  va  2  s  .c  o  m*/
 *
 * @param args  [0]: The name of the file.
 */
static public void main(String[] args) {
    try {
        // write out a test file
        PrintWriter pw = new PrintWriter(new FileWriter(args[0]));
        CSVWriter csv = new CSVWriter(pw, false, ',', System.getProperty("line.separator"));
        csv.writeCommentln("This is a test csv-file: '" + args[0] + "'");
        csv.write("abc");
        csv.write("def");
        csv.write("g h i");
        csv.write("jk,l");
        csv.write("m\"n\'o ");
        csv.writeln();
        csv.write("m\"n\'o ");
        csv.write("    ");
        csv.write("a");
        csv.write("x,y,z");
        csv.write("x;y;z");
        csv.writeln();
        csv.writeln(new String[] { "This", "is", "an", "array." });
        csv.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println(e.getMessage());
    }
}