Example usage for java.io BufferedReader readLine

List of usage examples for java.io BufferedReader readLine

Introduction

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

Prototype

public String readLine() throws IOException 

Source Link

Document

Reads a line of text.

Usage

From source file:com.bitsofproof.example.Simple.java

public static void main(String[] args) {
    Security.addProvider(new BouncyCastleProvider());

    final CommandLineParser parser = new GnuParser();
    final Options gnuOptions = new Options();
    gnuOptions.addOption("h", "help", false, "I can't help you yet");
    gnuOptions.addOption("s", "server", true, "Server URL");
    gnuOptions.addOption("u", "user", true, "User");
    gnuOptions.addOption("p", "password", true, "Password");

    System.out.println("BOP Bitcoin Server Simple Client 3.5.0 (c) 2013-2014 bits of proof zrt.");
    CommandLine cl = null;//from   w w  w.ja v a  2s.  c  o  m
    String url = null;
    String user = null;
    String password = null;
    try {
        cl = parser.parse(gnuOptions, args);
        url = cl.getOptionValue('s');
        user = cl.getOptionValue('u');
        password = cl.getOptionValue('p');
    } catch (org.apache.commons.cli.ParseException e) {
        e.printStackTrace();
        System.exit(1);
    }
    if (url == null || user == null || password == null) {
        System.err.println("Need -s server -u user -p password");
        System.exit(1);
    }

    BCSAPI api = getServer(url, user, password);
    try {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        long start = System.currentTimeMillis();
        api.ping(start);
        System.out.println("Server round trip " + (System.currentTimeMillis() - start) + "ms");
        api.addAlertListener(new AlertListener() {
            @Override
            public void alert(String s, int severity) {
                System.err.println("ALERT: " + s);
            }
        });
        System.out.println("Talking to " + (api.isProduction() ? "PRODUCTION" : "test") + " server");
        ConfirmationManager confirmationManager = new ConfirmationManager();
        confirmationManager.init(api, 144);
        System.out.printf("Please enter wallet name: ");
        String wallet = input.readLine();
        SimpleFileWallet w = new SimpleFileWallet(wallet + ".wallet");
        TransactionFactory am = null;
        if (!w.exists()) {
            System.out.printf("Enter passphrase: ");
            String passphrase = input.readLine();
            System.out.printf("Enter master (empty for new): ");
            String master = input.readLine();
            if (master.equals("")) {
                w.init(passphrase);
                w.unlock(passphrase);
                System.out.printf("First account: ");
                String account = input.readLine();
                am = w.createAccountManager(account);
                w.lock();
                w.persist();
            } else {
                StringTokenizer tokenizer = new StringTokenizer(master, "@");
                String key = tokenizer.nextToken();
                long since = 0;
                if (tokenizer.hasMoreElements()) {
                    since = Long.parseLong(tokenizer.nextToken()) * 1000;
                }
                w.init(passphrase, ExtendedKey.parse(key), true, since);
                w.unlock(passphrase);
                System.out.printf("First account: ");
                String account = input.readLine();
                am = w.createAccountManager(account);
                w.lock();
                w.persist();
                w.sync(api);
            }
        } else {
            w = SimpleFileWallet.read(wallet + ".wallet");
            w.sync(api);
            List<String> names = w.getAccountNames();
            System.out.println("Accounts:");
            System.out.println("---------");
            String first = null;
            for (String name : names) {
                System.out.println(name);
                if (first == null) {
                    first = name;
                }
            }
            System.out.println("---------");
            am = w.getAccountManager(first);
            System.out.println("Using account " + first);
        }
        confirmationManager.addAccount(am);
        api.registerTransactionListener(am);

        while (true) {
            printMenu();
            String answer = input.readLine();
            System.out.printf("\n");
            if (answer.equals("1")) {
                System.out.printf("The balance is: " + printBit(am.getBalance()) + "\n");
                System.out.printf("     confirmed: " + printBit(am.getConfirmed()) + "\n");
                System.out.printf("    receiveing: " + printBit(am.getReceiving()) + "\n");
                System.out.printf("        change: " + printBit(am.getChange()) + "\n");
                System.out.printf("(      sending: " + printBit(am.getSending()) + ")\n");
            } else if (answer.equals("2")) {
                for (Address a : am.getAddresses()) {
                    System.out.printf(a + "\n");
                }
            } else if (answer.equals("3")) {
                ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am;
                System.out.printf(
                        im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n");
            } else if (answer.equals("4")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am;
                System.out.printf(
                        im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n");
                w.lock();
            } else if (answer.equals("5")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                System.out.printf("Number of recipients");
                Integer nr = Integer.valueOf(input.readLine());
                Transaction spend;
                if (nr.intValue() == 1) {
                    System.out.printf("Receiver address: ");
                    String address = input.readLine();
                    System.out.printf("amount (Bit): ");
                    long amount = parseBit(input.readLine());
                    spend = am.pay(Address.fromSatoshiStyle(address), amount);
                    System.out.println("About to send " + printBit(amount) + " to " + address);
                } else {
                    List<Address> addresses = new ArrayList<>();
                    List<Long> amounts = new ArrayList<>();
                    long total = 0;
                    for (int i = 0; i < nr; ++i) {
                        System.out.printf("Receiver address: ");
                        String address = input.readLine();
                        addresses.add(Address.fromSatoshiStyle(address));
                        System.out.printf("amount (Bit): ");
                        long amount = parseBit(input.readLine());
                        amounts.add(amount);
                        total += amount;
                    }
                    spend = am.pay(addresses, amounts);
                    System.out.println("About to send " + printBit(total));
                }
                System.out.println("inputs");
                for (TransactionInput in : spend.getInputs()) {
                    System.out.println(in.getSourceHash() + " " + in.getIx());
                }
                System.out.println("outputs");
                for (TransactionOutput out : spend.getOutputs()) {
                    System.out.println(out.getOutputAddress() + " " + printBit(out.getValue()));
                }
                w.lock();
                System.out.printf("Type yes to go: ");
                if (input.readLine().equals("yes")) {
                    api.sendTransaction(spend);
                    System.out.printf("Sent transaction: " + spend.getHash());
                } else {
                    System.out.printf("Nothing happened.");
                }
            } else if (answer.equals("6")) {
                System.out.printf("Address: ");
                Set<Address> match = new HashSet<Address>();
                match.add(Address.fromSatoshiStyle(input.readLine()));
                api.scanTransactionsForAddresses(match, 0, new TransactionListener() {
                    @Override
                    public boolean process(Transaction t) {
                        System.out.printf("Found transaction: " + t.getHash() + "\n");
                        return true;
                    }
                });
            } else if (answer.equals("7")) {
                System.out.printf("Public key: ");
                ExtendedKey ek = ExtendedKey.parse(input.readLine());
                api.scanTransactions(ek, 0, 10, 0, new TransactionListener() {
                    @Override
                    public boolean process(Transaction t) {
                        System.out.printf("Found transaction: " + t.getHash() + "\n");
                        return true;
                    }
                });
            } else if (answer.equals("a")) {
                System.out.printf("Enter account name: ");
                String account = input.readLine();
                am = w.getAccountManager(account);
                api.registerTransactionListener(am);
                confirmationManager.addAccount(am);
            } else if (answer.equals("c")) {
                System.out.printf("Enter account name: ");
                String account = input.readLine();
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                am = w.createAccountManager(account);
                System.out.println("using account: " + account);
                w.lock();
                w.persist();
                api.registerTransactionListener(am);
                confirmationManager.addAccount(am);
            } else if (answer.equals("m")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                System.out.println(w.getMaster().serialize(api.isProduction()));
                System.out.println(w.getMaster().getReadOnly().serialize(true));
                w.lock();
            } else if (answer.equals("s")) {
                System.out.printf("Enter private key: ");
                String key = input.readLine();
                ECKeyPair k = ECKeyPair.parseWIF(key);
                KeyListAccountManager alm = new KeyListAccountManager();
                alm.addKey(k);
                alm.syncHistory(api);
                Address a = am.getNextReceiverAddress();
                Transaction t = alm.pay(a, alm.getBalance(), PaymentOptions.receiverPaysFee);
                System.out.println("About to sweep " + printBit(alm.getBalance()) + " to " + a);
                System.out.println("inputs");
                for (TransactionInput in : t.getInputs()) {
                    System.out.println(in.getSourceHash() + " " + in.getIx());
                }
                System.out.println("outputs");
                for (TransactionOutput out : t.getOutputs()) {
                    System.out.println(out.getOutputAddress() + " " + printBit(out.getValue()));
                }
                System.out.printf("Type yes to go: ");
                if (input.readLine().equals("yes")) {
                    api.sendTransaction(t);
                    System.out.printf("Sent transaction: " + t.getHash());
                } else {
                    System.out.printf("Nothing happened.");
                }
            } else {
                System.exit(0);
            }
        }
    } catch (Exception e) {
        System.err.println("Something went wrong");
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.l2jfree.security.Base64.java

public static void main(String[] args) throws IOException {
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter String to encode: ");
    System.out.println(Base64.encodeBytes(bf.readLine().getBytes()));
}

From source file:net.java.sen.tools.MkSenDic.java

/**
 * Build sen dictionary.//  www .  ja va 2 s  .c  o  m
 * 
 * @param args
 *            custom dictionary files. see dic/build.xml.
 */
public static void main(String args[]) {
    ResourceBundle rb = ResourceBundle.getBundle("dictionary");
    DictionaryMaker dm1 = new DictionaryMaker();
    DictionaryMaker dm2 = new DictionaryMaker();
    DictionaryMaker dm3 = new DictionaryMaker();

    // 1st field information of connect file.
    Vector rule1 = new Vector();

    // 2nd field information of connect file.
    Vector rule2 = new Vector();

    // 3rd field information of connect file.
    Vector rule3 = new Vector();

    // 4th field information of connect file.
    // this field shows cost of morpheme connection
    // [size3*(x3*size2+x2)+x1]
    // [size3*(Attr1*size2+Attr2)+Attl]
    short score[] = new short[20131];

    long start = System.currentTimeMillis();

    // /////////////////////////////////////////
    //
    // Step1. Loading connetion file.
    //
    log.info("(1/7): reading connection matrix ... ");
    try {
        log.info("connection file = " + rb.getString("text_connection_file"));
        log.info("charset = " + rb.getString("dic.charset"));
        CSVParser csvparser = new CSVParser(new FileInputStream(rb.getString("text_connection_file")),
                rb.getString("dic.charset"));
        String t[];
        int line = 0;
        while ((t = csvparser.nextTokens()) != null) {
            if (t.length < 4) {
                log.warn("invalid line in " + rb.getString("text_connection_file") + ":" + line);
                log.warn(rb.getString("text_connection_file") + "may be broken.");
                break;
            }
            dm1.add(t[0]);
            rule1.add(t[0]);

            dm2.add(t[1]);
            rule2.add(t[1]);

            dm3.add(t[2]);
            rule3.add(t[2]);

            if (line == score.length) {
                score = resize(score);
            }

            score[line++] = (short) Integer.parseInt(t[3]);
        }

        // /////////////////////////////////////////
        //
        // Step2. Building internal dictionary
        //
        log.info("(2/7): building type dictionary ... ");
        dm1.build();
        dm2.build();
        dm3.build();

        // if you want check specified morpheme, you uncomment and modify
        // following line:
        /*
         * System.out.print("22="); dm3.getById(22);
         * System.out.print("368="); dm3.getById(368);
         * 
         * System.out.println(dm3.getDicId("?????*,*,*,*,?"));
         * DictionaryMaker.debug = true;
         * System.out.println(dm3.getDicId("?????*,*,*,*,?"));
         * System.out.println(dm3.getDicIdNoCache("?????*,*,*,*,?"));
         */

    } catch (IOException e) {
        e.printStackTrace();
        System.exit(0);
    }

    // -------------------------------------------------

    int size1 = dm1.size();
    int size2 = dm2.size();
    int size3 = dm3.size();
    int ruleSize = rule1.size();
    short matrix[] = new short[size1 * size2 * size3];
    short default_cost = (short) Integer.parseInt(rb.getString("default_connection_cost"));

    // /////////////////////////////////////////
    //
    // Step3. Writing Connection Matrix
    //
    log.info("(3/7): writing conection matrix (" + size1 + " x " + size2 + " x " + size3 + " = "
            + size1 * size2 * size3 + ") ...");

    for (int i = 0; i < (int) (size1 * size2 * size3); i++)
        matrix[i] = default_cost;

    for (int i = 0; i < ruleSize; i++) {
        Vector r1 = dm1.getRuleIdList((String) rule1.get(i));
        Vector r2 = dm2.getRuleIdList((String) rule2.get(i));
        Vector r3 = dm3.getRuleIdList((String) rule3.get(i));

        for (Iterator i1 = r1.iterator(); i1.hasNext();) {
            int ii1 = ((Integer) i1.next()).intValue();
            for (Iterator i2 = r2.iterator(); i2.hasNext();) {
                int ii2 = ((Integer) i2.next()).intValue();
                for (Iterator i3 = r3.iterator(); i3.hasNext();) {
                    int ii3 = ((Integer) i3.next()).intValue();
                    int pos = size3 * (size2 * ii1 + ii2) + ii3;
                    matrix[pos] = score[i];
                }
            }
        }
    }

    try {
        DataOutputStream out = new DataOutputStream(
                new BufferedOutputStream(new FileOutputStream(rb.getString("matrix_file"))));
        out.writeShort(size1);
        out.writeShort(size2);
        out.writeShort(size3);
        for (int i1 = 0; i1 < size1; i1++)
            for (int i2 = 0; i2 < size2; i2++)
                for (int i3 = 0; i3 < size3; i3++) {
                    out.writeShort(matrix[size3 * (size2 * i1 + i2) + i3]);
                    // if (matrix[size3 * (size2 * i1 + i2) + i3] !=
                    // default_cost) {
                    // }
                }
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(0);
    }

    matrix = null;
    score = null;

    // -------------------------------------------------

    int pos_start = Integer.parseInt(rb.getString("pos_start"));
    int pos_size = Integer.parseInt(rb.getString("pos_size"));

    int di = 0;
    int offset = 0;
    ArrayList dicList = new ArrayList();

    // /////////////////////////////////////////
    //
    // Step4. Reading Morpheme Information
    //
    log.info("(4/7): reading morpheme information ... ");
    String t = null;
    String[] csv = null;
    try {
        // writer for feature file.
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(rb.getString("pos_file")), rb.getString("sen.charset")));

        log.info("load dic: " + rb.getString("text_dic_file"));
        BufferedReader dicStream = null;
        int custom_dic = -1;
        if (args.length == 0) {
            dicStream = new BufferedReader(new InputStreamReader(
                    new FileInputStream(rb.getString("text_dic_file")), rb.getString("dic.charset")));
        } else {
            custom_dic = 0;
            dicStream = new BufferedReader(
                    new InputStreamReader(new FileInputStream(args[custom_dic]), rb.getString("dic.charset")));
        }

        int line = 0;

        CSVData key_b = new CSVData();
        CSVData pos_b = new CSVData();

        while (true) {
            t = dicStream.readLine();
            if (t == null) {
                dicStream.close();
                custom_dic++;
                if (args.length == custom_dic) {
                    break;
                } else {
                    // read custum dictionary
                    log.info("load dic: " + "args[custum_dic]");
                    dicStream = new BufferedReader(new InputStreamReader(new FileInputStream(args[custom_dic]),
                            rb.getString("dic.charset")));
                }
                continue;
            }

            CSVParser parser = new CSVParser(t);
            csv = parser.nextTokens();
            if (csv.length < (pos_size + pos_start)) {
                throw new RuntimeException("format error:" + t);
            }

            key_b.clear();
            pos_b.clear();
            for (int i = pos_start; i < (pos_start + pos_size - 1); i++) {
                key_b.append(csv[i]);
                pos_b.append(csv[i]);
            }

            key_b.append(csv[pos_start + pos_size - 1]);
            pos_b.append(csv[pos_start + pos_size - 1]);

            for (int i = pos_start + pos_size; i < (csv.length - 1); i++) {
                pos_b.append(csv[i]);
            }
            pos_b.append(csv[csv.length - 1]);

            CToken token = new CToken();

            token.rcAttr2 = (short) dm1.getDicId(key_b.toString());
            token.rcAttr1 = (short) dm2.getDicId(key_b.toString());
            token.lcAttr = (short) dm3.getDicId(key_b.toString());
            token.posid = 0;
            token.posID = offset;
            token.length = (short) csv[0].length();
            token.cost = (short) Integer.parseInt(csv[1]);

            dicList.add(new PairObject(csv[0], token));

            byte b[] = pos_b.toString().getBytes(rb.getString("sen.charset"));
            offset += (b.length + 1);
            String pos_b_str = pos_b.toString();
            bw.write(pos_b_str, 0, pos_b_str.length());
            // bw.write(b, 0, b.length);
            bw.write(0);
            if (++di % 50000 == 0)
                log.info("" + di + "... ");
        }
        bw.close();
        // ----end of writing feature.cha ----
    } catch (Exception e) {
        log.error("Error: " + t);
        e.printStackTrace();
        System.exit(1);
    }

    rule1 = null;
    rule2 = null;
    rule3 = null;

    // /////////////////////////////////////////
    //
    // Step5. Sort lexs and write to file
    //
    log.info("(5/7): sorting lex... ");

    int value[] = new int[dicList.size()];
    char key[][] = new char[dicList.size()][];
    int spos = 0;
    int dsize = 0;
    int bsize = 0;
    String prev = "";
    Collections.sort(dicList);

    // /////////////////////////////////////////
    //
    // Step6. Writing Token Information
    //
    log.info("(6/7): writing token... ");
    try {
        // writer for token file.
        DataOutputStream out = new DataOutputStream(
                new BufferedOutputStream(new FileOutputStream(rb.getString("token_file"))));

        // writing 'bos' and 'eos' and 'unknown' token.
        CToken token = new CToken();
        token.rcAttr2 = (short) dm1.getDicId(rb.getString("bos_pos"));
        token.rcAttr1 = (short) dm2.getDicId(rb.getString("bos_pos"));
        token.lcAttr = (short) dm3.getDicId(rb.getString("bos_pos"));
        token.write(out);

        token.rcAttr2 = (short) dm1.getDicId(rb.getString("eos_pos"));
        token.rcAttr1 = (short) dm2.getDicId(rb.getString("eos_pos"));
        token.lcAttr = (short) dm3.getDicId(rb.getString("eos_pos"));
        token.write(out);

        token.rcAttr2 = (short) dm1.getDicId(rb.getString("unknown_pos"));
        token.rcAttr1 = (short) dm2.getDicId(rb.getString("unknown_pos"));
        token.lcAttr = (short) dm3.getDicId(rb.getString("unknown_pos"));
        token.posID = -1;
        token.write(out);
        log.info("key size = " + key.length);
        for (int i = 0; i < key.length; i++) {
            String k = (String) ((PairObject) dicList.get(i)).key;
            if (!prev.equals(k) && i != 0) {
                key[dsize] = ((String) ((PairObject) dicList.get(spos)).key).toCharArray();
                value[dsize] = bsize + (spos << 8);
                dsize++;
                bsize = 1;
                spos = i;
            } else {
                bsize++;
            }
            prev = (String) ((PairObject) dicList.get(i)).key;
            ((CToken) (((PairObject) dicList.get(i)).value)).write(out);
        }
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    key[dsize] = ((String) ((PairObject) dicList.get(spos)).key).toCharArray();

    value[dsize] = bsize + (spos << 8);
    dsize++;

    dm1 = null;
    dm2 = null;
    dm3 = null;
    dicList = null;

    // /////////////////////////////////////////
    //
    // Step7. Build Double Array
    //
    log.info("(7/7): building Double-Array (size = " + dsize + ") ...");

    DoubleArrayTrie da = new DoubleArrayTrie();

    da.build(key, null, value, dsize);
    try {
        da.save(rb.getString("double_array_file"));
    } catch (Exception e) {
        e.printStackTrace();
    }

    log.info("total time = " + (System.currentTimeMillis() - start) / 1000 + "[ms]");
}

From source file:edu.nyu.tandon.query.Query.java

@SuppressWarnings("unchecked")
public static void main(final String[] arg) throws Exception {

    SimpleJSAP jsap = new SimpleJSAP(Query.class.getName(),
            "Loads indices relative to a collection, possibly loads the collection, and answers to queries.",
            new Parameter[] {
                    new FlaggedOption("collection", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'c',
                            "collection", "The collection of documents indexed by the given indices."),
                    new FlaggedOption("objectCollection",
                            new ObjectParser(DocumentCollection.class, MG4JClassParser.PACKAGE),
                            JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'o', "object-collection",
                            "An object specification describing a document collection."),
                    new FlaggedOption("titleList", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 't',
                            "title-list",
                            "A serialized big list of titles (will override collection titles if specified)."),
                    new FlaggedOption("titleFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'T',
                            "title-file",
                            "A file of newline-separated, UTF-8 titles (will override collection titles if specified)."),
                    new FlaggedOption("input", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'I',
                            "input", "A file containing the input."),
                    new Switch("noSizes", 'n', "no-sizes",
                            "Disable loading document sizes (they are necessary for BM25 scoring)."),
                    new Switch("http", 'h', "http", "Starts an HTTP query server."),
                    new Switch("verbose", 'v', "verbose", "Print full exception stack traces."),
                    new FlaggedOption("itemClass", MG4JClassParser.getParser(), JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'i', "item-class",
                            "The class that will handle item display in the HTTP server."),
                    new FlaggedOption("itemMimeType", JSAP.STRING_PARSER, "text/html", JSAP.NOT_REQUIRED, 'm',
                            "item-mime-type",
                            "A MIME type suggested to the class handling item display in the HTTP server."),
                    new FlaggedOption("port", JSAP.INTEGER_PARSER, "4242", JSAP.NOT_REQUIRED, 'p', "port",
                            "The port on localhost where the server will appear."),
                    new UnflaggedOption("basenameWeight", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED,
                            JSAP.GREEDY,
                            "The indices that the servlet will use. Indices are specified using their basename, optionally followed by a colon and a double representing the weight used to score results from that index. Indices without a specified weight are weighted 1."),

                    new Switch("noMplex", 'P', "noMplex", "Starts with multiplex disabled."),
                    new FlaggedOption("results", JSAP.INTEGER_PARSER, "1000", JSAP.NOT_REQUIRED, 'r', "results",
                            "The # of results to display"),
                    new FlaggedOption("mode", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'M',
                            "time", "The results display mode") });

    final JSAPResult jsapResult = jsap.parse(arg);
    if (jsap.messagePrinted())
        return;/*from   w w w .ja  v  a  2s. c o m*/

    final DocumentCollection documentCollection = (DocumentCollection) (jsapResult.userSpecified("collection")
            ? AbstractDocumentSequence.load(jsapResult.getString("collection"))
            : jsapResult.userSpecified("objectCollection") ? jsapResult.getObject("objectCollection") : null);
    final BigList<? extends CharSequence> titleList = (BigList<? extends CharSequence>) (jsapResult
            .userSpecified("titleList")
                    ? BinIO.loadObject(jsapResult.getString("titleList"))
                    : jsapResult.userSpecified("titleFile")
                            ? new FileLinesBigList(jsapResult.getString("titleFile"), "UTF-8")
                            : null);
    final String[] basenameWeight = jsapResult.getStringArray("basenameWeight");
    final Object2ReferenceLinkedOpenHashMap<String, Index> indexMap = new Object2ReferenceLinkedOpenHashMap<String, Index>(
            Hash.DEFAULT_INITIAL_SIZE, .5f);
    final Reference2DoubleOpenHashMap<Index> index2Weight = new Reference2DoubleOpenHashMap<Index>();
    final boolean verbose = jsapResult.getBoolean("verbose");
    final boolean loadSizes = !jsapResult.getBoolean("noSizes");
    Query.loadIndicesFromSpec(basenameWeight, loadSizes, documentCollection, indexMap, index2Weight);

    final long numberOfDocuments = indexMap.values().iterator().next().numberOfDocuments;
    if (titleList != null && titleList.size64() != numberOfDocuments)
        throw new IllegalArgumentException("The number of titles (" + titleList.size64()
                + " and the number of documents (" + numberOfDocuments + ") do not match");

    final Object2ObjectOpenHashMap<String, TermProcessor> termProcessors = new Object2ObjectOpenHashMap<String, TermProcessor>(
            indexMap.size());
    for (String alias : indexMap.keySet())
        termProcessors.put(alias, indexMap.get(alias).termProcessor);

    final SimpleParser simpleParser = new SimpleParser(indexMap.keySet(), indexMap.firstKey(), termProcessors);

    final Reference2ReferenceMap<Index, Object> index2Parser = new Reference2ReferenceOpenHashMap<Index, Object>();
    /*
    // Fetch parsers for payload-based fields.
    for( Index index: indexMap.values() ) if ( index.hasPayloads ) {
     if ( index.payload.getClass() == DatePayload.class ) index2Parser.put( index, DateFormat.getDateInstance( DateFormat.SHORT, Locale.UK ) );
    }
    */

    final QueryEngine queryEngine = new QueryEngine(simpleParser, new DocumentIteratorBuilderVisitor(indexMap,
            index2Parser, indexMap.get(indexMap.firstKey()), MAX_STEMMING), indexMap);
    queryEngine.setWeights(index2Weight);
    queryEngine.score(new Scorer[] { new BM25Scorer(), new VignaScorer() }, new double[] { 1, 1 });
    // We set up an interval selector only if there is a collection for snippeting
    queryEngine.intervalSelector = documentCollection != null ? new IntervalSelector(4, 40)
            : new IntervalSelector();

    queryEngine.multiplex = !jsapResult.userSpecified("moPlex") || jsapResult.getBoolean("noMplex");

    queryEngine.equalize(1000);

    Query query = new Query(queryEngine);
    query.displayMode = OutputType.TIME;

    query.maxOutput = jsapResult.getInt("results", 1000);

    query.interpretCommand("$score BM25Scorer");

    String q;

    System.err.println(
            "Welcome to the MG4J query class (setup with $mode snippet, $score BM25Scorer VignaScorer, $mplex on, $equalize 1000, $select "
                    + (documentCollection != null ? "4 40" : "all") + ")");
    System.err.println("Please type $ for help.");

    String prompt = indexMap.keySet().toString() + ">";
    int n;

    try {
        final BufferedReader br = new BufferedReader(new InputStreamReader(
                jsapResult.userSpecified("input") ? new FileInputStream(jsapResult.getString("input"))
                        : System.in));
        final ObjectArrayList<DocumentScoreInfo<Reference2ObjectMap<Index, SelectedInterval[]>>> results = new ObjectArrayList<DocumentScoreInfo<Reference2ObjectMap<Index, SelectedInterval[]>>>();

        for (;;) {
            if (query.displayMode != OutputType.TREC)
                System.out.print(prompt);
            q = br.readLine();
            if (q == null) {
                System.err.println();
                break; // CTRL-D
            }
            if (q.length() == 0)
                continue;
            if (q.charAt(0) == '$') {
                if (!query.interpretCommand(q))
                    break;
                continue;
            }

            long time = -System.nanoTime();

            try {
                n = queryEngine.process(q, 0, query.maxOutput, results);
            } catch (QueryParserException e) {
                if (verbose)
                    e.getCause().printStackTrace(System.err);
                else
                    System.err.println(e.getCause());
                continue;
            } catch (Exception e) {
                if (verbose)
                    e.printStackTrace(System.err);
                else
                    System.err.println(e);
                continue;
            }

            time += System.nanoTime();
            query.output(results, documentCollection, titleList, TextMarker.TEXT_BOLDFACE);
            System.err.println(results.size() + " results; " + n + " documents examined; " + time / 1000000.
                    + " ms; " + Util.format((n * 1000000000.0) / time) + " documents/s, "
                    + Util.format(time / (double) n) + " ns/document");
        }

    } finally {
        if (query.output != System.out)
            query.output.close();
    }
}

From source file:DIA_Umpire_SE.DIA_Umpire_SE.java

/**
 * @param args the command line arguments DIA_Umpire parameterfile
 *///from w w w . ja  v a  2  s  . c o  m
public static void main(String[] args) throws InterruptedException, FileNotFoundException, ExecutionException,
        IOException, ParserConfigurationException, DataFormatException, SAXException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println(
            "DIA-Umpire singal extraction analysis  (version: " + UmpireInfo.GetInstance().Version + ")");
    if (args.length < 2 || args.length > 3) {
        System.out.println(
                "command format error, the correct format is: java -jar -Xmx8G DIA_Umpire_SE.jar mzMXL_file diaumpire_se.params");
        System.out.println(
                "To fix DIA setting, use : java -jar -Xmx8G DIA_Umpire_SE.jar mzMXL_file diaumpire_se.params -f");
        return;
    }
    try {
        //Define logger level for console
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        //Define logger level and file path for text log file
        ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_se.log");
    } catch (Exception e) {
    }

    boolean Fix = false;
    boolean Resume = false;

    if (args.length == 3 && args[2].equals("-f")) {
        Fix = true;
    }
    String parameterfile = args[1];
    String MSFilePath = args[0];
    Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
    Logger.getRootLogger().info("Parameter file:" + parameterfile);
    Logger.getRootLogger().info("Spectra file:" + MSFilePath);
    BufferedReader reader = new BufferedReader(new FileReader(parameterfile));

    String line = "";
    InstrumentParameter param = new InstrumentParameter(InstrumentParameter.InstrumentType.TOF5600);
    param.DetermineBGByID = false;
    param.EstimateBG = true;
    int NoCPUs = 2;

    SpectralDataType.DataType dataType = SpectralDataType.DataType.DIA_F_Window;
    String WindowType = "";
    int WindowSize = 25;

    ArrayList<XYData> WindowList = new ArrayList<>();

    boolean ExportPrecursorPeak = false;
    boolean ExportFragmentPeak = false;

    //<editor-fold defaultstate="collapsed" desc="Read parameter file">
    while ((line = reader.readLine()) != null) {
        Logger.getRootLogger().info(line);
        if (!"".equals(line) && !line.startsWith("#")) {
            //System.out.println(line);
            if (line.equals("==window setting begin")) {
                while (!(line = reader.readLine()).equals("==window setting end")) {
                    if (!"".equals(line)) {
                        WindowList.add(new XYData(Float.parseFloat(line.split("\t")[0]),
                                Float.parseFloat(line.split("\t")[1])));
                    }
                }
                continue;
            }
            if (line.split("=").length < 2) {
                continue;
            }
            String type = line.split("=")[0].trim();
            if (type.startsWith("para.")) {
                type = type.replace("para.", "SE.");
            }
            String value = line.split("=")[1].trim();
            switch (type) {
            case "Thread": {
                NoCPUs = Integer.parseInt(value);
                break;
            }
            case "ExportPrecursorPeak": {
                ExportPrecursorPeak = Boolean.parseBoolean(value);
                break;
            }
            case "ExportFragmentPeak": {
                ExportFragmentPeak = Boolean.parseBoolean(value);
                break;
            }

            //<editor-fold defaultstate="collapsed" desc="instrument parameters">
            case "RPmax": {
                param.PrecursorRank = Integer.parseInt(value);
                break;
            }
            case "RFmax": {
                param.FragmentRank = Integer.parseInt(value);
                break;
            }
            case "CorrThreshold": {
                param.CorrThreshold = Float.parseFloat(value);
                break;
            }
            case "DeltaApex": {
                param.ApexDelta = Float.parseFloat(value);
                break;
            }
            case "RTOverlap": {
                param.RTOverlapThreshold = Float.parseFloat(value);
                break;
            }
            case "BoostComplementaryIon": {
                param.BoostComplementaryIon = Boolean.parseBoolean(value);
                break;
            }
            case "AdjustFragIntensity": {
                param.AdjustFragIntensity = Boolean.parseBoolean(value);
                break;
            }
            case "SE.MS1PPM": {
                param.MS1PPM = Float.parseFloat(value);
                break;
            }
            case "SE.MS2PPM": {
                param.MS2PPM = Float.parseFloat(value);
                break;
            }
            case "SE.SN": {
                param.SNThreshold = Float.parseFloat(value);
                break;
            }
            case "SE.MS2SN": {
                param.MS2SNThreshold = Float.parseFloat(value);
                break;
            }
            case "SE.MinMSIntensity": {
                param.MinMSIntensity = Float.parseFloat(value);
                break;
            }
            case "SE.MinMSMSIntensity": {
                param.MinMSMSIntensity = Float.parseFloat(value);
                break;
            }
            case "SE.MinRTRange": {
                param.MinRTRange = Float.parseFloat(value);
                break;
            }
            case "SE.MaxNoPeakCluster": {
                param.MaxNoPeakCluster = Integer.parseInt(value);
                param.MaxMS2NoPeakCluster = Integer.parseInt(value);
                break;
            }
            case "SE.MinNoPeakCluster": {
                param.MinNoPeakCluster = Integer.parseInt(value);
                param.MinMS2NoPeakCluster = Integer.parseInt(value);
                break;
            }
            case "SE.MinMS2NoPeakCluster": {
                param.MinMS2NoPeakCluster = Integer.parseInt(value);
                break;
            }
            case "SE.MaxCurveRTRange": {
                param.MaxCurveRTRange = Float.parseFloat(value);
                break;
            }
            case "SE.Resolution": {
                param.Resolution = Integer.parseInt(value);
                break;
            }
            case "SE.RTtol": {
                param.RTtol = Float.parseFloat(value);
                break;
            }
            case "SE.NoPeakPerMin": {
                param.NoPeakPerMin = Integer.parseInt(value);
                break;
            }
            case "SE.StartCharge": {
                param.StartCharge = Integer.parseInt(value);
                break;
            }
            case "SE.EndCharge": {
                param.EndCharge = Integer.parseInt(value);
                break;
            }
            case "SE.MS2StartCharge": {
                param.MS2StartCharge = Integer.parseInt(value);
                break;
            }
            case "SE.MS2EndCharge": {
                param.MS2EndCharge = Integer.parseInt(value);
                break;
            }
            case "SE.NoMissedScan": {
                param.NoMissedScan = Integer.parseInt(value);
                break;
            }
            case "SE.Denoise": {
                param.Denoise = Boolean.valueOf(value);
                break;
            }
            case "SE.EstimateBG": {
                param.EstimateBG = Boolean.valueOf(value);
                break;
            }
            case "SE.RemoveGroupedPeaks": {
                param.RemoveGroupedPeaks = Boolean.valueOf(value);
                break;
            }
            case "SE.MinFrag": {
                param.MinFrag = Integer.parseInt(value);
                break;
            }
            case "SE.IsoPattern": {
                param.IsoPattern = Float.valueOf(value);
                break;
            }
            case "SE.StartRT": {
                param.startRT = Float.valueOf(value);
                break;
            }
            case "SE.EndRT": {
                param.endRT = Float.valueOf(value);
                break;
            }
            case "SE.RemoveGroupedPeaksRTOverlap": {
                param.RemoveGroupedPeaksRTOverlap = Float.valueOf(value);
                break;
            }
            case "SE.RemoveGroupedPeaksCorr": {
                param.RemoveGroupedPeaksCorr = Float.valueOf(value);
                break;
            }
            case "SE.MinMZ": {
                param.MinMZ = Float.valueOf(value);
                break;
            }
            case "SE.MinPrecursorMass": {
                param.MinPrecursorMass = Float.valueOf(value);
                break;
            }
            case "SE.MaxPrecursorMass": {
                param.MaxPrecursorMass = Float.valueOf(value);
                break;
            }
            case "SE.IsoCorrThreshold": {
                param.IsoCorrThreshold = Float.valueOf(value);
                break;
            }
            case "SE.MassDefectFilter": {
                param.MassDefectFilter = Boolean.parseBoolean(value);
                break;
            }
            case "SE.MassDefectOffset": {
                param.MassDefectOffset = Float.valueOf(value);
                break;
            }

            //</editor-fold>//</editor-fold>

            case "WindowType": {
                WindowType = value;
                switch (WindowType) {
                case "SWATH": {
                    dataType = SpectralDataType.DataType.DIA_F_Window;
                    break;
                }
                case "V_SWATH": {
                    dataType = SpectralDataType.DataType.DIA_V_Window;
                    break;
                }
                case "MSX": {
                    dataType = SpectralDataType.DataType.MSX;
                    break;
                }
                case "MSE": {
                    dataType = SpectralDataType.DataType.MSe;
                    break;
                }
                }
                break;
            }
            case "WindowSize": {
                WindowSize = Integer.parseInt(value);
                break;
            }
            }
        }
    }
    //</editor-fold>

    try {
        File MSFile = new File(MSFilePath);
        if (MSFile.exists()) {
            long time = System.currentTimeMillis();
            Logger.getRootLogger().info(
                    "=================================================================================================");
            Logger.getRootLogger().info("Processing " + MSFilePath + "....");

            //Initialize a DIA file data structure                
            DIAPack DiaFile = new DIAPack(MSFile.getAbsolutePath(), NoCPUs);
            DiaFile.Resume = Resume;
            DiaFile.SetDataType(dataType);
            DiaFile.SetParameter(param);

            //Set DIA isolation window setting
            if (dataType == SpectralDataType.DataType.DIA_F_Window) {
                DiaFile.SetWindowSize(WindowSize);
            } else if (dataType == SpectralDataType.DataType.DIA_V_Window) {
                for (XYData window : WindowList) {
                    DiaFile.AddVariableWindow(window);
                }
            }
            DiaFile.SaveDIASetting();
            DiaFile.SaveParams();

            if (Fix) {
                DiaFile.FixScanidx();
                return;
            }
            DiaFile.ExportPrecursorPeak = ExportPrecursorPeak;
            DiaFile.ExportFragmentPeak = ExportFragmentPeak;
            Logger.getRootLogger().info("Module A: Signal extraction");
            //Start DIA signal extraction process to generate pseudo MS/MS files
            DiaFile.process();
            time = System.currentTimeMillis() - time;
            Logger.getRootLogger().info(MSFilePath + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
        } else {
            throw new RuntimeException("file: " + MSFile + "? does not exist!");
        }
        Logger.getRootLogger().info("Job complete");
        Logger.getRootLogger().info(
                "=================================================================================================");

    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

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

    logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName());

    Options options = new Options();
    options.addOption("unisonXMLFile", true, "The full path to the Unison xml file");
    options.addOption("keystorePath", true, "The full path to the Unison keystore");
    options.addOption("chainName", true, "The name of the authentication chain");
    options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2");
    options.addOption("idpName", true, "The name of the identity provider application");
    options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file");
    options.addOption("createDefault", false, "If set, add default parameters");
    options.addOption("action", true,
            "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey");
    options.addOption("urlBase", true, "Base URL, no URI; https://host:port");
    options.addOption("alias", true, "Key alias");
    options.addOption("newKeystorePath", true, "Path to the new keystore");
    options.addOption("newKeystorePassword", true, "Password for the new keystore");
    options.addOption("help", false, "Prints this message");
    options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key");
    options.addOption("dlqName", true, "The name of the dead letter queue");
    options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6");
    options.addOption("secretkey", true, "base64 encoded secret key");
    options.addOption("envFile", true, "Environment variables for parmaterized configs");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);

    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("OpenUnisonUtils", options);
    }//from  w  w w  .  ja  v  a2  s .co m

    logger.info("Loading Unison Configuration");
    String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options);
    TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options);

    String action = loadOption(cmd, "action", options);
    TremoloType ttWrite = null;
    if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) {
        ttWrite = loadTremoloType(unisonXMLFile);
    }

    logger.info("Configuration loaded");

    logger.info("Loading the keystore...");
    String ksPath = loadOption(cmd, "keystorePath", options);

    KeyStore ks = loadKeyStore(ksPath, ttRead);

    logger.info("...loaded");

    if (action.equalsIgnoreCase("import-sp-metadata")) {

        importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);
    } else if (action.equalsIgnoreCase("export-sp-metadata")) {
        exportSPMetaData(options, cmd, ttRead, ks);

    } else if (action.equalsIgnoreCase("print-secretkey")) {
        printSecreyKey(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("import-secretkey")) {
        importSecreyKey(options, cmd, ttRead, ks, ksPath);
    } else if (action.equalsIgnoreCase("create-secretkey")) {
        Security.addProvider(new BouncyCastleProvider());
        logger.info("Creating AES-256 secret key");
        String alias = loadOption(cmd, "alias", options);
        logger.info("Alias : '" + alias + "'");
        KeyGenerator kg = KeyGenerator.getInstance("AES", "BC");
        kg.init(256, new SecureRandom());
        SecretKey sk = kg.generateKey();
        ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null);
        logger.info("Saving key");
        ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray());
        logger.info("Finished");
    } else if (action.equalsIgnoreCase("export-secretkey")) {
        logger.info("Export Secret Key");

        logger.info("Loading key");
        String alias = loadOption(cmd, "alias", options);
        SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray());
        logger.info("Loading new keystore path");
        String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options);
        logger.info("Loading new keystore password");
        String ksPassword = loadOption(cmd, "newKeystorePassword", options);

        KeyStore newKS = KeyStore.getInstance("PKCS12");
        newKS.load(null, ttRead.getKeyStorePassword().toCharArray());
        newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null);
        newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray());
        logger.info("Exported");
    } else if (action.equalsIgnoreCase("import-idp-metadata")) {
        importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);

    } else if (action.equalsIgnoreCase("export-idp-metadata")) {
        exportIdPMetadata(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("clear-dlq")) {
        logger.info("Getting the DLQ Name...");
        String dlqName = loadOption(cmd, "dlqName", options);
        QueUtils.emptyDLQ(ttRead, dlqName);
    } else if (action.equalsIgnoreCase("upgradeFrom106")) {
        logger.info("Upgrading OpenUnison's configuration from 1.0.6");

        String backupFileName = unisonXMLFile + ".bak";

        logger.info("Backing up to '" + backupFileName + "'");

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile)));
        PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName));
        String line = null;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        out.flush();
        out.close();
        in.close();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout);
        FileOutputStream fsout = new FileOutputStream(unisonXMLFile);
        fsout.write(bout.toByteArray());
        fsout.flush();
        fsout.close();

    }

}

From source file:DataCrawler.OpenAIRE.XMLGenerator.java

public static void main(String[] args) {
    String text = "";

    try {//  ww  w .  j  a  va  2 s. c  o  m
        if (args.length < 4) {
            System.out.println("<command> template_file csv_file output_dir log_file [start_id]");
        }

        // InputStream fis = new FileInputStream("E:/Downloads/result-r-00000");
        InputStream fis = new FileInputStream(args[1]);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));

        // String content = new String(Files.readAllBytes(Paths.get("publications_template.xml")));
        String content = new String(Files.readAllBytes(Paths.get(args[0])));
        Document doc = Jsoup.parse(content, "UTF-8", Parser.xmlParser());
        // String outputDirectory = "G:/";
        String outputDirectory = args[2];
        // PrintWriter logWriter = new PrintWriter(new FileOutputStream("publication.log",false));
        PrintWriter logWriter = new PrintWriter(new FileOutputStream(args[3], false));
        Element objectId = null, title = null, publisher = null, dateofacceptance = null, bestlicense = null,
                resulttype = null, originalId = null, originalId2 = null;
        boolean start = true;
        // String startID = "dedup_wf_001::207a098867b64f3b5af505fa3aeecd24";
        String startID = "";
        if (args.length >= 5) {
            start = false;
            startID = args[4];
        }
        String previousText = "";
        while ((text = br.readLine()) != null) {
            /*  For publications:
                0. dri:objIdentifier context
               9. title context
               12. publisher context
               18. dateofacceptance
               19. bestlicense @classname
               21. resulttype  @classname
               26. originalId context  
               (Notice that the prefix is null and will use space to separate two different "originalId")
            */

            if (!previousText.isEmpty()) {
                text = previousText + text;
                start = true;
                previousText = "";
            }

            String[] items = text.split("!");
            for (int i = 0; i < items.length; ++i) {
                items[i] = StringUtils.strip(items[i], "#");
            }
            if (objectId == null)
                objectId = doc.getElementsByTag("dri:objIdentifier").first();
            objectId.text(items[0]);

            if (!start && items[0].equals(startID)) {
                start = true;
            }

            if (title == null)
                title = doc.getElementsByTag("title").first();
            title.text(items[9]);

            if (publisher == null)
                publisher = doc.getElementsByTag("publisher").first();

            if (items.length < 12) {
                previousText = text;
                continue;
            }
            publisher.text(items[12]);

            if (dateofacceptance == null)
                dateofacceptance = doc.getElementsByTag("dateofacceptance").first();
            dateofacceptance.text(items[18]);

            if (bestlicense == null)
                bestlicense = doc.getElementsByTag("bestlicense").first();
            bestlicense.attr("classname", items[19]);

            if (resulttype == null)
                resulttype = doc.getElementsByTag("resulttype").first();
            resulttype.attr("classname", items[21]);

            if (originalId == null || originalId2 == null) {
                Elements elements = doc.getElementsByTag("originalId");
                String[] context = items[26].split(" ");
                if (elements.size() > 0) {
                    if (elements.size() >= 1) {
                        originalId = elements.get(0);
                        if (context.length >= 1) {
                            int indexOfnull = context[0].trim().indexOf("null");
                            String value = "";
                            if (indexOfnull != -1) {
                                if (context[0].trim().length() >= (indexOfnull + 5))
                                    value = context[0].trim().substring(indexOfnull + 5);

                            } else {
                                value = context[0].trim();
                            }
                            originalId.text(value);
                        }
                    }
                    if (elements.size() >= 2) {
                        originalId2 = elements.get(1);
                        if (context.length >= 2) {
                            int indexOfnull = context[1].trim().indexOf("null");
                            String value = "";
                            if (indexOfnull != -1) {
                                if (context[1].trim().length() >= (indexOfnull + 5))
                                    value = context[1].trim().substring(indexOfnull + 5);

                            } else {
                                value = context[1].trim();
                            }
                            originalId2.text(value);
                        }
                    }
                }
            } else {
                String[] context = items[26].split(" ");
                if (context.length >= 1) {
                    int indexOfnull = context[0].trim().indexOf("null");
                    String value = "";
                    if (indexOfnull != -1) {
                        if (context[0].trim().length() >= (indexOfnull + 5))
                            value = context[0].trim().substring(indexOfnull + 5);

                    } else {
                        value = context[0].trim();
                    }
                    originalId.text(value);
                }
                if (context.length >= 2) {
                    int indexOfnull = context[1].trim().indexOf("null");
                    String value = "";
                    if (indexOfnull != -1) {
                        if (context[1].trim().length() >= (indexOfnull + 5))
                            value = context[1].trim().substring(indexOfnull + 5);

                    } else {
                        value = context[1].trim();
                    }
                    originalId2.text(value);
                }
            }
            if (start) {
                String filePath = outputDirectory + items[0].replace(":", "#") + ".xml";
                PrintWriter writer = new PrintWriter(new FileOutputStream(filePath, false));
                logWriter.write(filePath + " > Start" + System.lineSeparator());
                writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + System.lineSeparator());
                writer.write(doc.getElementsByTag("response").first().toString());
                writer.close();
                logWriter.write(filePath + " > OK" + System.lineSeparator());
                logWriter.flush();
            }

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

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;//from  w  ww  .  java 2  s.  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:ebay.Ebay.java

/**
 * @param args the command line arguments
 *///w  w w. j ava2s.  c  o  m
public static void main(String[] args) {
    HttpClient client = null;
    HttpResponse response = null;
    BufferedReader rd = null;
    Document doc = null;
    String xml = "";
    EbayDAO<Producto> db = new EbayDAO<>(Producto.class);
    String busqueda;

    while (true) {
        busqueda = JOptionPane.showInputDialog(null, "ingresa una busqueda");
        if (busqueda != null) {
            busqueda = busqueda.replaceAll(" ", "%20");
            try {
                client = new DefaultHttpClient();
                /*
                 peticion GET
                 */
                HttpGet request = new HttpGet("http://open.api.ebay.com/shopping?" + "callname=FindPopularItems"
                        + "&appid=student11-6428-4bd4-ac0d-6ed9d84e345" + "&version=517&QueryKeywords="
                        + busqueda + "&siteid=0" + "&responseencoding=XML");
                /*
                 se ejecuta la peticion GET
                 */
                response = client.execute(request);
                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                /*
                 comienza la lectura de la respuesta a la peticion GET
                 */
                String line;
                while ((line = rd.readLine()) != null) {
                    xml += line + "\n";
                }
            } catch (IOException ex) {
                Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex);
            }

            /*
             creamos nuestro documentBulder(documento constructor) y obtenemos 
             nuestro objeto documento apartir de documentBuilder
             */
            try {
                DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                doc = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
            } catch (ParserConfigurationException | SAXException | IOException ex) {
                Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex);
            }

            Element raiz = doc.getDocumentElement();
            if (raiz == null) {
                System.exit(0);
            }
            if (raiz.getElementsByTagName("Ack").item(0).getTextContent().equals("Success")) {
                NodeList array = raiz.getElementsByTagName("ItemArray").item(0).getChildNodes();
                for (int i = 0; i < array.getLength(); ++i) {
                    Node n = array.item(i);

                    if (n.getNodeType() != Node.TEXT_NODE) {
                        Producto p = new Producto();
                        if (((Element) n).getElementsByTagName("ItemID").item(0) != null)
                            p.setId(new Long(
                                    ((Element) n).getElementsByTagName("ItemID").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("EndTime").item(0) != null)
                            p.setEndtime(
                                    ((Element) n).getElementsByTagName("EndTime").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch").item(0) != null)
                            p.setViewurl(((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch")
                                    .item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ListingType").item(0) != null)
                            p.setListingtype(
                                    ((Element) n).getElementsByTagName("ListingType").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("GalleryURL").item(0) != null)
                            p.setGalleryurl(
                                    ((Element) n).getElementsByTagName("GalleryURL").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("PrimaryCategoryID").item(0) != null)
                            p.setPrimarycategoryid(new Integer(((Element) n)
                                    .getElementsByTagName("PrimaryCategoryID").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("PrimaryCategoryName").item(0) != null)
                            p.setPrimarycategoryname(((Element) n).getElementsByTagName("PrimaryCategoryName")
                                    .item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("BidCount").item(0) != null)
                            p.setBidcount(new Integer(
                                    ((Element) n).getElementsByTagName("BidCount").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ConvertedCurrentPrice").item(0) != null)
                            p.setConvertedcurrentprice(new Double(((Element) n)
                                    .getElementsByTagName("ConvertedCurrentPrice").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ListingStatus").item(0) != null)
                            p.setListingstatus(((Element) n).getElementsByTagName("ListingStatus").item(0)
                                    .getTextContent());
                        if (((Element) n).getElementsByTagName("TimeLeft").item(0) != null)
                            p.setTimeleft(
                                    ((Element) n).getElementsByTagName("TimeLeft").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("Title").item(0) != null)
                            p.setTitle(((Element) n).getElementsByTagName("Title").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ShippingServiceCost").item(0) != null)
                            p.setShippingservicecost(new Double(((Element) n)
                                    .getElementsByTagName("ShippingServiceCost").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ShippingType").item(0) != null)
                            p.setShippingtype(((Element) n).getElementsByTagName("ShippingType").item(0)
                                    .getTextContent());
                        if (((Element) n).getElementsByTagName("WatchCount").item(0) != null)
                            p.setWatchcount(new Integer(
                                    ((Element) n).getElementsByTagName("WatchCount").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ListedShippingServiceCost").item(0) != null)
                            p.setListedshippingservicecost(
                                    new Double(((Element) n).getElementsByTagName("ListedShippingServiceCost")
                                            .item(0).getTextContent()));
                        try {
                            db.insert(p);
                        } catch (Exception e) {
                            db.update(p);
                        }
                    }
                }
            }
            Ventana.crear(xml);
        } else
            System.exit(0);

    }
}

From source file:edu.oregonstate.eecs.mcplan.domains.spbj.SpBjSimulator.java

public static void main(final String[] argv) throws IOException {
    final int seed = 43;
    final RandomGenerator rng = new MersenneTwister(seed);
    //      final Deck deck = new InfiniteSpanishDeck( rng );

    // TODO: Debugging code
    final Deque<Card> stacked = new ArrayDeque<Card>();
    for (int i = 0; i < 20; ++i) {
        stacked.push(Card.C_2c);/*from w  w w.  j  a  v  a 2  s . co  m*/
        stacked.push(Card.C_2d);
        stacked.push(Card.C_2h);
        stacked.push(Card.C_2s);
    }
    final Deck deck = new StackedDeck(stacked);

    //      final ArrayList<ArrayList<Card>> test_hands = new ArrayList<ArrayList<Card>>();
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_Kc, Card.C_9h, Card.C_2c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_6c, Card.C_7h, Card.C_8c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_6c, Card.C_7c, Card.C_8c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_6s, Card.C_7s, Card.C_8s ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_7c, Card.C_7h, Card.C_7c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_7c, Card.C_7c, Card.C_7c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_7s, Card.C_7s, Card.C_7s ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_9c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_6c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_2c, Card.C_Ac ) ) );
    //
    //      final ArrayList<ArrayList<Card>> dealer_test_hands = new ArrayList<ArrayList<Card>>();
    //      dealer_test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_Kc, Card.C_Kc ) ) );
    //      dealer_test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_Kc, Card.C_Ac ) ) );
    //
    //      for( final ArrayList<Card> dealer_cards : dealer_test_hands ) {
    //         for( final ArrayList<Card> cards : test_hands ) {
    //            final SpBjState s = new SpBjState( deck );
    //            s.init();
    //            s.dealer_hand.clear();
    //            s.dealer_hand.addAll( dealer_cards );
    //            s.player_hand.hands.set( 0, cards );
    //            final SpBjSimulator sim = new SpBjSimulator( s );
    //            sim.takeAction( new JointAction<SpBjAction>(
    //               new SpBjAction( new SpBjActionCategory[] { SpBjActionCategory.Pass } ) ) );
    //
    //            System.out.print( "Hand: " );
    //            System.out.print( sim.state().player_hand );
    //            System.out.print( " (" );
    //            final ArrayList<int[]> values = sim.state().player_hand.values();
    //            for( int i = 0; i < values.size(); ++i ) {
    //               if( i > 0 ) {
    //                  System.out.print( ", " );
    //               }
    //               System.out.print( Arrays.toString( values.get( i ) ) );
    //            }
    //            System.out.println( ")" );
    //
    //            System.out.print( "Reward: " );
    //            System.out.println( Arrays.toString( sim.reward() ) );
    //            System.out.print( "Dealer hand: " );
    //            System.out.print( sim.state().dealerHand().toString() );
    //            System.out.print( " (" );
    //            System.out.print( SpBjHand.handValue( sim.state().dealerHand() )[0] );
    //            System.out.println( ")" );
    //            System.out.println( "----------------------------------------" );
    //         }
    //      }

    while (true) {
        final SpBjState s = new SpBjState(deck);
        s.init();
        final SpBjSimulator sim = new SpBjSimulator(s);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (!s.isTerminal()) {
            System.out.print("Dealer showing: ");
            System.out.println(sim.state().dealerUpcard());

            System.out.print("Hand: ");
            System.out.print(sim.state().player_hand);
            System.out.print(" (");
            final ArrayList<int[]> values = sim.state().player_hand.values();
            for (int i = 0; i < values.size(); ++i) {
                if (i > 0) {
                    System.out.print(", ");
                }
                System.out.print(Arrays.toString(values.get(i)));
            }
            System.out.println(")");

            final SpBjActionGenerator actions = new SpBjActionGenerator();
            actions.setState(sim.state(), 0);
            for (final SpBjAction a : Fn.in(actions)) {
                System.out.println(a);
            }

            final String cmd = reader.readLine();
            assert (cmd.length() == sim.state().player_hand.Nhands);
            final SpBjActionCategory[] cat = new SpBjActionCategory[cmd.length()];
            for (int i = 0; i < cmd.length(); ++i) {
                final char c = cmd.charAt(i);
                if ('h' == c) {
                    cat[i] = SpBjActionCategory.Hit;
                } else if ('p' == c) {
                    cat[i] = SpBjActionCategory.Pass;
                } else if ('d' == c) {
                    cat[i] = SpBjActionCategory.Double;
                } else if ('s' == c) {
                    cat[i] = SpBjActionCategory.Split;
                }
            }
            sim.takeAction(new JointAction<SpBjAction>(new SpBjAction(cat)));
        }

        System.out.print("Hand: ");
        System.out.print(sim.state().player_hand);
        System.out.print(" (");
        final ArrayList<int[]> values = sim.state().player_hand.values();
        for (int i = 0; i < values.size(); ++i) {
            if (i > 0) {
                System.out.print(", ");
            }
            System.out.print(Arrays.toString(values.get(i)));
        }
        System.out.println(")");

        System.out.print("Reward: ");
        System.out.println(Arrays.toString(sim.reward()));
        System.out.print("Dealer hand: ");
        System.out.print(sim.state().dealerHand().toString());
        System.out.print(" (");
        System.out.print(SpBjHand.handValue(sim.state().dealerHand())[0]);
        System.out.println(")");
        System.out.println("----------------------------------------");
    }
}