Example usage for java.lang StringBuffer append

List of usage examples for java.lang StringBuffer append

Introduction

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

Prototype

@Override
    public synchronized StringBuffer append(double d) 

Source Link

Usage

From source file:com.github.chrbayer84.keybits.KeyBits.java

/**
 * @param args//from  w ww .  j  a v  a  2  s . c o  m
 */
public static void main(String[] args) throws Exception {
    int number_of_addresses = 1;
    int depth = 1;

    String usage = "java -jar KeyBits.jar [options]";
    // create parameters which can be chosen
    Option help = new Option("h", "print this message");
    Option verbose = new Option("v", "verbose");
    Option exprt = new Option("e", "export public key to blockchain");
    Option imprt = OptionBuilder.withArgName("string").hasArg()
            .withDescription("import public key from blockchain").create("i");

    Option blockchain_address = OptionBuilder.withArgName("string").hasArg().withDescription("bitcoin address")
            .create("a");
    Option create_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("create wallet")
            .create("c");
    Option update_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("update wallet")
            .create("u");
    Option balance_wallet = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("return balance of wallet").create("b");
    Option show_wallet = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("show content of wallet").create("w");
    Option send_coins = OptionBuilder.withArgName("file name").hasArg().withDescription("send satoshis")
            .create("s");
    Option monitor_pending = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("monitor pending transactions of wallet").create("p");
    Option monitor_depth = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("monitor transaction depths of wallet").create("d");
    Option number = OptionBuilder.withArgName("integer").hasArg()
            .withDescription("in combination with -c, -d, -r or -s").create("n");
    Option reset = OptionBuilder.withArgName("file name").hasArg().withDescription("reset wallet").create("r");

    Options options = new Options();

    options.addOption(help);
    options.addOption(verbose);
    options.addOption(imprt);
    options.addOption(exprt);

    options.addOption(blockchain_address);
    options.addOption(create_wallet);
    options.addOption(update_wallet);
    options.addOption(balance_wallet);
    options.addOption(show_wallet);
    options.addOption(send_coins);
    options.addOption(monitor_pending);
    options.addOption(monitor_depth);
    options.addOption(number);
    options.addOption(reset);

    BasicParser parser = new BasicParser();
    CommandLine cmd = null;

    String header = "This is KeyBits v0.01b.1412953962" + System.getProperty("line.separator");
    // show help if wrong usage
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        printHelp(usage, options, header);
    }

    if (cmd.getOptions().length == 0)
        printHelp(usage, options, header);

    if (cmd.hasOption("h"))
        printHelp(usage, options, header);

    if (cmd.hasOption("v"))
        System.out.println(header);

    if (cmd.hasOption("c") && cmd.hasOption("n"))
        number_of_addresses = new Integer(cmd.getOptionValue("n")).intValue();

    if (cmd.hasOption("d") && cmd.hasOption("n"))
        depth = new Integer(cmd.getOptionValue("n")).intValue();

    String checkpoints_file_name = "checkpoints";
    if (!new File(checkpoints_file_name).exists())
        checkpoints_file_name = null;

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

    if (cmd.hasOption("c")) {
        String wallet_file_name = cmd.getOptionValue("c");

        String passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name);
        if (!new File(wallet_file_name).exists()) {
            String passphrase_ = HelpfulStuff.reInsertPassphrase("enter password for " + wallet_file_name);

            if (!passphrase.equals(passphrase_)) {
                System.out.println("passwords do not match");
                System.exit(0);
            }
        }

        MyWallet.createWallet(wallet_file_name, wallet_file_name + ".chain", number_of_addresses, passphrase);
        System.exit(0);
    }

    if (cmd.hasOption("u")) {
        String wallet_file_name = cmd.getOptionValue("u");
        MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name);
        System.exit(0);
    }

    if (cmd.hasOption("b")) {
        String wallet_file_name = cmd.getOptionValue("b");
        System.out.println(
                MyWallet.getBalanceOfWallet(wallet_file_name, wallet_file_name + ".chain").longValue());
        System.exit(0);
    }

    if (cmd.hasOption("w")) {
        String wallet_file_name = cmd.getOptionValue("w");
        System.out.println(MyWallet.showContentOfWallet(wallet_file_name, wallet_file_name + ".chain"));
        System.exit(0);
    }

    if (cmd.hasOption("p")) {
        System.out.println("monitoring of pending transactions ... ");
        String wallet_file_name = cmd.getOptionValue("p");
        MyWallet.monitorPendingTransactions(wallet_file_name, wallet_file_name + ".chain",
                checkpoints_file_name);
        System.exit(0);
    }

    if (cmd.hasOption("d")) {
        System.out.println("monitoring of transaction depth ... ");
        String wallet_file_name = cmd.getOptionValue("d");
        MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name,
                depth);
        System.exit(0);
    }

    if (cmd.hasOption("r") && cmd.hasOption("n")) {
        long epoch = new Long(cmd.getOptionValue("n"));
        System.out.println("resetting wallet ... ");
        String wallet_file_name = cmd.getOptionValue("r");

        File chain_file = (new File(wallet_file_name + ".chain"));
        if (chain_file.exists())
            chain_file.delete();

        MyWallet.setCreationTime(wallet_file_name, epoch);
        MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name);

        System.exit(0);
    }

    if (cmd.hasOption("s") && cmd.hasOption("a") && cmd.hasOption("n")) {
        String wallet_file_name = cmd.getOptionValue("s");
        String address = cmd.getOptionValue("a");
        Integer amount = new Integer(cmd.getOptionValue("n"));

        String wallet_passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name);
        MyWallet.sendCoins(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, address,
                new BigInteger(amount + ""), wallet_passphrase);

        System.out.println("waiting ...");
        Thread.sleep(10000);
        System.out.println("monitoring of transaction depth ... ");
        MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name,
                1);
        System.out.println("transaction fixed in blockchain with depth " + depth);
        System.exit(0);
    }

    // ----------------------------------------------------------------------------------------
    //                                  creates public key
    // ----------------------------------------------------------------------------------------

    GnuPGP gpg = new GnuPGP();

    if (cmd.hasOption("e")) {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        StringBuffer sb = new StringBuffer();
        while ((line = input.readLine()) != null)
            sb.append(line + "\n");

        PGPPublicKeyRing public_key_ring = gpg.getDearmored(sb.toString());
        //System.out.println(gpg.showPublicKeys(public_key_ring));

        byte[] public_key_ring_encoded = gpg.getEncoded(public_key_ring);

        String[] addresses = (new Encoding()).encodePublicKey(public_key_ring_encoded);
        //         System.out.println(gpg.showPublicKey(gpg.getDecoded(encoding.decodePublicKey(addresses))));

        // file names for message
        String public_key_file_name = Long.toHexString(public_key_ring.getPublicKey().getKeyID()) + ".wallet";
        String public_key_wallet_file_name = public_key_file_name;
        String public_key_chain_file_name = public_key_wallet_file_name + ".chain";

        // hier muss dass passwort noch nach encodeAddresses weitergeleitet werden da sonst zweimal abfrage
        String public_key_wallet_passphrase = HelpfulStuff
                .insertPassphrase("enter password for " + public_key_wallet_file_name);
        if (!new File(public_key_wallet_file_name).exists()) {
            String public_key_wallet_passphrase_ = HelpfulStuff
                    .reInsertPassphrase("enter password for " + public_key_wallet_file_name);

            if (!public_key_wallet_passphrase.equals(public_key_wallet_passphrase_)) {
                System.out.println("passwords do not match");
                System.exit(0);
            }
        }

        MyWallet.createWallet(public_key_wallet_file_name, public_key_chain_file_name, 1,
                public_key_wallet_passphrase);
        MyWallet.updateWallet(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name);
        String public_key_address = MyWallet.getAddress(public_key_wallet_file_name, public_key_chain_file_name,
                0);
        System.out.println("address of public key: " + public_key_address);

        // 10000 additional satoshis for sending transaction to address of recipient of message and 10000 for fees
        KeyBits.encodeAddresses(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name,
                addresses, 2 * SendRequest.DEFAULT_FEE_PER_KB.intValue(), depth, public_key_wallet_passphrase);
    }

    if (cmd.hasOption("i")) {
        String location = cmd.getOptionValue("i");

        String[] addresses = null;
        if (location.indexOf(",") > -1) {
            String[] locations = location.split(",");
            addresses = MyWallet.getAddressesFromBlockAndTransaction("main.wallet", "main.wallet.chain",
                    checkpoints_file_name, locations[0], locations[1]);
        } else {
            addresses = BlockchainDotInfo.getKeys(location);
        }

        byte[] encoded = (new Encoding()).decodePublicKey(addresses);
        PGPPublicKeyRing public_key_ring = gpg.getDecoded(encoded);

        System.out.println(gpg.getArmored(public_key_ring));

        System.exit(0);
    }
}

From source file:bamboo.openhash.fileshare.FileShare.java

public static void main(String[] args) throws Exception {
    PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n");
    ConsoleAppender ca = new ConsoleAppender(pl);
    Logger.getRoot().addAppender(ca);
    Logger.getRoot().setLevel(Level.INFO);

    // create Options object
    Options options = new Options();

    // add t option
    options.addOption("r", "read", false, "read a file from the DHT");
    options.addOption("w", "write", false, "write a file to the DHT");
    options.addOption("g", "gateway", true, "the gateway IP:port");
    options.addOption("k", "key", true, "the key to read a file from");
    options.addOption("f", "file", true, "the file to read or write");
    options.addOption("s", "secret", true, "the secret used to hide data");
    options.addOption("t", "ttl", true, "how long in seconds data should persist");

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

    String gw = null;//  ww  w.  j  a  v a2  s  .  c  om
    String mode = null;
    String secret = null;
    String ttl = null;
    String key = null;
    String file = null;

    if (cmd.hasOption("r")) {
        mode = "read";
    }
    if (cmd.hasOption("w")) {
        mode = "write";
    }
    if (cmd.hasOption("g")) {
        gw = cmd.getOptionValue("g");
    }
    if (cmd.hasOption("k")) {
        key = cmd.getOptionValue("k");
    }
    if (cmd.hasOption("f")) {
        file = cmd.getOptionValue("f");
    }
    if (cmd.hasOption("s")) {
        secret = cmd.getOptionValue("s");
    }
    if (cmd.hasOption("t")) {
        ttl = cmd.getOptionValue("t");
    }

    if (mode == null) {
        System.err.println("ERROR: either --read or --write is required");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fileshare", options);
        System.exit(1);
    }

    if (gw == null) {
        System.err.println("ERROR: --gateway is required");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fileshare", options);
        System.exit(1);
    }

    if (file == null) {
        System.err.println("ERROR: --file is required");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fileshare", options);
        System.exit(1);
    }

    if (secret == null) {
        System.err.println("ERROR: --secret is required");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fileshare", options);
        System.exit(1);
    }

    StringBuffer sbuf = new StringBuffer(1000);
    sbuf.append("<sandstorm>\n");
    sbuf.append("<global>\n");
    sbuf.append("<initargs>\n");
    sbuf.append("node_id localhost:3630\n");
    sbuf.append("</initargs>\n");
    sbuf.append("</global>\n");
    sbuf.append("<stages>\n");
    sbuf.append("<GatewayClient>\n");
    sbuf.append("class bamboo.dht.GatewayClient\n");
    sbuf.append("<initargs>\n");
    sbuf.append("debug_level 0\n");
    sbuf.append("gateway " + gw + "\n");
    sbuf.append("</initargs>\n");
    sbuf.append("</GatewayClient>\n");
    sbuf.append("\n");
    sbuf.append("<FileShare>\n");
    sbuf.append("class bamboo.openhash.fileshare.FileShare\n");
    sbuf.append("<initargs>\n");
    sbuf.append("debug_level 0\n");
    sbuf.append("secret " + secret + "\n");
    sbuf.append("mode " + mode + "\n");
    if (mode.equals("write")) {
        if (ttl == null) {
            System.err.println("ERROR: --ttl is required for write mode");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("fileshare", options);
            System.exit(1);
        }

        sbuf.append("ttl " + ttl + "\n");
        sbuf.append("file " + file + "\n");
    } else {
        if (key == null) {
            System.err.println("ERROR: --key is required for write mode");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("fileshare", options);
            System.exit(1);
        }

        sbuf.append("key " + key + "\n");
        sbuf.append("file " + file + "\n");
    }
    sbuf.append("client_stage_name GatewayClient\n");
    sbuf.append("</initargs>\n");
    sbuf.append("</FileShare>\n");
    sbuf.append("</stages>\n");
    sbuf.append("</sandstorm>\n");
    ASyncCore acore = new bamboo.lss.ASyncCoreImpl();
    DustDevil dd = new DustDevil();
    dd.set_acore_instance(acore);
    dd.main(new CharArrayReader(sbuf.toString().toCharArray()));
    acore.async_main();
}

From source file:ElementIteratorExample.java

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

    if (args.length != 1) {
        System.err.println("Usage: java ElementIteratorExample input-URL");
    }//from   w w w  .j a  v a2 s .  c o m

    // Load HTML file synchronously
    URL url = new URL(args[0]);
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    HTMLEditorKit htmlKit = new HTMLEditorKit();
    HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
    parser.parse(br, callback, true);

    // Parse
    ElementIterator iterator = new ElementIterator(htmlDoc);
    Element element;
    while ((element = iterator.next()) != null) {
        AttributeSet attributes = element.getAttributes();
        Object name = attributes.getAttribute(StyleConstants.NameAttribute);
        if ((name instanceof HTML.Tag)
                && ((name == HTML.Tag.H1) || (name == HTML.Tag.H2) || (name == HTML.Tag.H3))) {
            // Build up content text as it may be within multiple elements
            StringBuffer text = new StringBuffer();
            int count = element.getElementCount();
            for (int i = 0; i < count; i++) {
                Element child = element.getElement(i);
                AttributeSet childAttributes = child.getAttributes();
                if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                    int startOffset = child.getStartOffset();
                    int endOffset = child.getEndOffset();
                    int length = endOffset - startOffset;
                    text.append(htmlDoc.getText(startOffset, length));
                }
            }
            System.out.println(name + ": " + text.toString());
        }
    }
    System.exit(0);
}

From source file:net.dontdrinkandroot.lastfm.api.CheckImplementationStatus.java

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

    CheckImplementationStatus.xmlReader = new Parser();
    CheckImplementationStatus.saxReader = new SAXReader(CheckImplementationStatus.xmlReader);

    final String packagePrefix = "net.dontdrinkandroot.lastfm.api.model.";

    final Map<String, Map<String, URL>> packages = CheckImplementationStatus.parseOverview();

    final StringBuffer html = new StringBuffer();
    html.append("<html>\n");
    html.append("<head>\n");
    html.append("<title>Implementation Status</title>\n");
    html.append("</head>\n");
    html.append("<body>\n");
    html.append("<h1>Implementation Status</h1>\n");

    final StringBuffer wiki = new StringBuffer();

    int numImplemented = 0;
    int numTested = 0;
    int numMethods = 0;

    final List<String> packageList = new ArrayList<String>(packages.keySet());
    Collections.sort(packageList);

    for (final String pkg : packageList) {

        System.out.println("Parsing " + pkg);
        html.append("<h2>" + pkg + "</h2>\n");
        wiki.append("\n===== " + pkg + " =====\n\n");

        Class<?> modelClass = null;
        final String className = packagePrefix + pkg;
        try {//from  ww w .  jav  a  2  s .  com
            modelClass = Class.forName(className);
            System.out.println("\tClass " + modelClass.getName() + " exists");
        } catch (final ClassNotFoundException e) {
            // e.printStackTrace();
            System.out.println("\t" + className + ": DOES NOT exist");
        }

        Class<?> testClass = null;
        final String testClassName = packagePrefix + pkg + "Test";
        try {
            testClass = Class.forName(testClassName);
            System.out.println("\tTestClass " + testClass.getName() + " exists");
        } catch (final ClassNotFoundException e) {
            // e.printStackTrace();
            System.out.println("\t" + testClassName + ": TestClass for DOES NOT exist");
        }

        final List<String> methods = new ArrayList<String>(packages.get(pkg).keySet());
        Collections.sort(methods);

        final Method[] classMethods = modelClass.getMethods();
        final Method[] testMethods = testClass.getMethods();

        html.append("<table>\n");
        html.append("<tr><th>Method</th><th>Implemented</th><th>Tested</th></tr>\n");
        wiki.append("^ Method  ^ Implemented  ^ Tested  ^\n");

        numMethods += methods.size();

        for (final String method : methods) {

            System.out.println("\t\t parsing " + method);

            html.append("<tr>\n");
            html.append("<td>" + method + "</td>\n");
            wiki.append("| " + method + "  ");

            boolean classMethodFound = false;
            for (final Method classMethod : classMethods) {
                if (classMethod.getName().equals(method)) {
                    classMethodFound = true;
                    break;
                }
            }

            if (classMethodFound) {
                System.out.println("\t\t\tMethod " + method + " found");
                html.append("<td style=\"background-color: green\">true</td>\n");
                wiki.append("| yes  ");
                numImplemented++;
            } else {
                System.out.println("\t\t\t" + method + " NOT found");
                html.append("<td style=\"background-color: red\">false</td>\n");
                wiki.append("| **no**  ");
            }

            boolean testMethodFound = false;
            final String testMethodName = "test" + StringUtils.capitalize(method);
            for (final Method testMethod : testMethods) {
                if (testMethod.getName().equals(testMethodName)) {
                    testMethodFound = true;
                    break;
                }
            }

            if (testMethodFound) {
                System.out.println("\t\t\tTestMethod " + method + " found");
                html.append("<td style=\"background-color: green\">true</td>\n");
                wiki.append("| yes  |\n");
                numTested++;
            } else {
                System.out.println("\t\t\t" + testMethodName + " NOT found");
                html.append("<td style=\"background-color: red\">false</td>\n");
                wiki.append("| **no**  |\n");
            }

            html.append("</tr>\n");

        }

        html.append("</table>\n");

        // for (String methodName : methods) {
        // URL url = pkg.getValue().get(methodName);
        // System.out.println("PARSING: " + pkg.getKey() + "." + methodName + ": " + url);
        // String html = loadIntoString(url);
        // String description = null;
        // Matcher descMatcher = descriptionPattern.matcher(html);
        // if (descMatcher.find()) {
        // description = descMatcher.group(1).trim();
        // }
        // boolean post = false;
        // Matcher postMatcher = postPattern.matcher(html);
        // if (postMatcher.find()) {
        // post = true;
        // }
        // Matcher paramsMatcher = paramsPattern.matcher(html);
        // List<String[]> params = new ArrayList<String[]>();
        // boolean authenticated = false;
        // if (paramsMatcher.find()) {
        // String paramsString = paramsMatcher.group(1);
        // Matcher paramMatcher = paramPattern.matcher(paramsString);
        // while (paramMatcher.find()) {
        // String[] param = new String[3];
        // param[0] = paramMatcher.group(1);
        // param[1] = paramMatcher.group(3);
        // param[2] = paramMatcher.group(5);
        // // System.out.println(paramMatcher.group(1) + "|" + paramMatcher.group(3) + "|" +
        // paramMatcher.group(5));
        // if (param[0].equals("")) {
        // /* DO NOTHING */
        // } else if (param[0].equals("api_key")) {
        // /* DO NOTHING */
        // } else if (param[0].equals("api_sig")) {
        // authenticated = true;
        // } else {
        // params.add(param);
        // }
        // }
        // }
        // }
        // count++;
        //
    }

    html.append("<hr />");
    html.append("<p>" + numImplemented + "/" + numMethods + " implemented (" + numImplemented * 100 / numMethods
            + "%)</p>");
    html.append("<p>" + numTested + "/" + numMethods + " tested (" + numTested * 100 / numMethods + "%)</p>");

    html.append("</body>\n");
    html.append("</html>\n");

    FileOutputStream out = new FileOutputStream(new File(FileUtils.getTempDirectory(), "apistatus.html"));
    IOUtils.write(html, out);
    IOUtils.closeQuietly(out);

    out = new FileOutputStream(new File(FileUtils.getTempDirectory(), "apistatus.wiki.txt"));
    IOUtils.write(wiki, out);
    IOUtils.closeQuietly(out);
}

From source file:TextVerifyInputRegularExpression.java

public static void main(String[] args) {

    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    Font font = new Font(display, "Courier New", 10, SWT.NONE); //$NON-NLS-1$
    text.setFont(font);/* w  ww.  j a va2  s. c  om*/
    text.setText(template);
    text.addListener(SWT.Verify, new Listener() {
        // create the pattern for verification
        Pattern pattern = Pattern.compile(REGEX);

        // ignore event when caused by inserting text inside event handler
        boolean ignore;

        public void handleEvent(Event e) {
            if (ignore)
                return;
            e.doit = false;
            if (e.start > 13 || e.end > 14)
                return;
            StringBuffer buffer = new StringBuffer(e.text);

            // handle backspace
            if (e.character == '\b') {
                for (int i = e.start; i < e.end; i++) {
                    // skip over separators
                    switch (i) {
                    case 0:
                        if (e.start + 1 == e.end) {
                            return;
                        } else {
                            buffer.append('(');
                        }
                        break;
                    case 4:
                        if (e.start + 1 == e.end) {
                            buffer.append(new char[] { '#', ')' });
                            e.start--;
                        } else {
                            buffer.append(')');
                        }
                        break;
                    case 8:
                        if (e.start + 1 == e.end) {
                            buffer.append(new char[] { '#', '-' });
                            e.start--;
                        } else {
                            buffer.append('-');
                        }
                        break;
                    default:
                        buffer.append('#');
                    }
                }
                text.setSelection(e.start, e.start + buffer.length());
                ignore = true;
                text.insert(buffer.toString());
                ignore = false;
                // move cursor backwards over separators
                if (e.start == 5 || e.start == 9)
                    e.start--;
                text.setSelection(e.start, e.start);
                return;
            }

            StringBuffer newText = new StringBuffer(defaultText);
            char[] chars = e.text.toCharArray();
            int index = e.start - 1;
            for (int i = 0; i < e.text.length(); i++) {
                index++;
                switch (index) {
                case 0:
                    if (chars[i] == '(')
                        continue;
                    index++;
                    break;
                case 4:
                    if (chars[i] == ')')
                        continue;
                    index++;
                    break;
                case 8:
                    if (chars[i] == '-')
                        continue;
                    index++;
                    break;
                }
                if (index >= newText.length())
                    return;
                newText.setCharAt(index, chars[i]);
            }
            // if text is selected, do not paste beyond range of selection
            if (e.start < e.end && index + 1 != e.end)
                return;
            Matcher matcher = pattern.matcher(newText);
            if (matcher.lookingAt()) {
                text.setSelection(e.start, index + 1);
                ignore = true;
                text.insert(newText.substring(e.start, index + 1));
                ignore = false;
            }
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    font.dispose();
    display.dispose();
}

From source file:com.frostvoid.trekwar.server.TrekwarServer.java

public static void main(String[] args) {
    // load language
    try {/*from w  w w .j a v a  2 s.  c  o  m*/
        lang = new Language(Language.ENGLISH);
    } catch (IOException ioe) {
        System.err.println("FATAL ERROR: Unable to load language file!");
        System.exit(1);
    }

    System.out.println(lang.get("trekwar_server") + " " + VERSION);
    System.out.println("==============================================".substring(0,
            lang.get("trekwar_server").length() + 1 + VERSION.length()));

    // Handle parameters
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("file").withLongOpt("galaxy").hasArg()
            .withDescription("the galaxy file to load").create("g")); //"g", "galaxy", true, "the galaxy file to load");
    options.addOption(OptionBuilder.withArgName("port number").withLongOpt("port").hasArg()
            .withDescription("the port number to bind to (default 8472)").create("p"));
    options.addOption(OptionBuilder.withArgName("number").withLongOpt("save-interval").hasArg()
            .withDescription("how often (in turns) to save the galaxy to disk (default: 5)").create("s"));
    options.addOption(OptionBuilder.withArgName("log level").withLongOpt("log").hasArg()
            .withDescription("sets the log level: ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF")
            .create("l"));
    options.addOption("h", "help", false, "prints this help message");

    CommandLineParser cliParser = new BasicParser();

    try {
        CommandLine cmd = cliParser.parse(options, args);
        String portStr = cmd.getOptionValue("p");
        String galaxyFileStr = cmd.getOptionValue("g");
        String saveIntervalStr = cmd.getOptionValue("s");
        String logLevelStr = cmd.getOptionValue("l");

        if (cmd.hasOption("h")) {
            HelpFormatter help = new HelpFormatter();
            help.printHelp("TrekwarServer", options);
            System.exit(0);
        }

        if (cmd.hasOption("g") && galaxyFileStr != null) {
            galaxyFileName = galaxyFileStr;
        } else {
            throw new ParseException("galaxy file not specified");
        }

        if (cmd.hasOption("p") && portStr != null) {
            port = Integer.parseInt(portStr);
            if (port < 1 || port > 65535) {
                throw new NumberFormatException(lang.get("port_number_out_of_range"));
            }
        } else {
            port = 8472;
        }

        if (cmd.hasOption("s") && saveIntervalStr != null) {
            saveInterval = Integer.parseInt(saveIntervalStr);
            if (saveInterval < 1 || saveInterval > 100) {
                throw new NumberFormatException("Save Interval out of range (1-100)");
            }
        } else {
            saveInterval = 5;
        }

        if (cmd.hasOption("l") && logLevelStr != null) {
            if (logLevelStr.equalsIgnoreCase("finest")) {
                LOG.setLevel(Level.FINEST);
            } else if (logLevelStr.equalsIgnoreCase("finer")) {
                LOG.setLevel(Level.FINER);
            } else if (logLevelStr.equalsIgnoreCase("fine")) {
                LOG.setLevel(Level.FINE);
            } else if (logLevelStr.equalsIgnoreCase("config")) {
                LOG.setLevel(Level.CONFIG);
            } else if (logLevelStr.equalsIgnoreCase("info")) {
                LOG.setLevel(Level.INFO);
            } else if (logLevelStr.equalsIgnoreCase("warning")) {
                LOG.setLevel(Level.WARNING);
            } else if (logLevelStr.equalsIgnoreCase("severe")) {
                LOG.setLevel(Level.SEVERE);
            } else if (logLevelStr.equalsIgnoreCase("off")) {
                LOG.setLevel(Level.OFF);
            } else if (logLevelStr.equalsIgnoreCase("all")) {
                LOG.setLevel(Level.ALL);
            } else {
                System.err.println("ERROR: invalid log level: " + logLevelStr);
                System.err.println("Run again with -h flag to see valid log level values");
                System.exit(1);
            }
        } else {
            LOG.setLevel(Level.INFO);
        }
        // INIT LOGGING
        try {
            LOG.setUseParentHandlers(false);
            initLogging();
        } catch (IOException ex) {
            System.err.println("Unable to initialize logging to file");
            System.err.println(ex);
            System.exit(1);
        }

    } catch (Exception ex) {
        System.err.println("ERROR: " + ex.getMessage());
        System.err.println("use -h for help");
        System.exit(1);
    }

    LOG.log(Level.INFO, "Trekwar2 server " + VERSION + " starting up");

    // LOAD GALAXY
    File galaxyFile = new File(galaxyFileName);
    if (galaxyFile.exists()) {
        try {
            long timer = System.currentTimeMillis();
            LOG.log(Level.INFO, "Loading galaxy file {0}", galaxyFileName);
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(galaxyFile));
            galaxy = (Galaxy) ois.readObject();
            timer = System.currentTimeMillis() - timer;
            LOG.log(Level.INFO, "Galaxy file loaded in {0} ms", timer);
            ois.close();
        } catch (IOException ioe) {
            LOG.log(Level.SEVERE, "IO error while trying to load galaxy file", ioe);
        } catch (ClassNotFoundException cnfe) {
            LOG.log(Level.SEVERE, "Unable to find class while loading galaxy", cnfe);
        }
    } else {
        System.err.println("Error: file " + galaxyFileName + " not found");
        System.exit(1);
    }

    // if turn == 0 (start of game), execute first turn to update fog of war.
    if (galaxy.getCurrentTurn() == 0) {
        TurnExecutor.executeTurn(galaxy);
    }

    LOG.log(Level.INFO, "Current turn  : {0}", galaxy.getCurrentTurn());
    LOG.log(Level.INFO, "Turn speed    : {0} seconds", galaxy.getTurnSpeed() / 1000);
    LOG.log(Level.INFO, "Save Interval : {0}", saveInterval);
    LOG.log(Level.INFO, "Users / max   : {0} / {1}",
            new Object[] { galaxy.getUserCount(), galaxy.getMaxUsers() });

    // START SERVER
    try {
        server = new ServerSocket(port);
        LOG.log(Level.INFO, "Server listening on port {0}", port);
    } catch (BindException be) {
        LOG.log(Level.SEVERE, "Error: Unable to bind to port {0}", port);
        System.err.println(be);
        System.exit(1);
    } catch (IOException ioe) {
        LOG.log(Level.SEVERE, "Error: IO error while binding to port {0}", port);
        System.err.println(ioe);
        System.exit(1);
    }

    galaxy.startup();

    Thread timerThread = new Thread(new Runnable() {

        @Override
        @SuppressWarnings("SleepWhileInLoop")
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    // && galaxy.getLoggedInUsers().size() > 0 will make server pause when nobody is logged in (TESTING)
                    if (System.currentTimeMillis() > galaxy.nextTurnDate) {
                        StringBuffer loggedInUsers = new StringBuffer();
                        for (User u : galaxy.getLoggedInUsers()) {
                            loggedInUsers.append(u.getUsername()).append(", ");
                        }

                        long time = TurnExecutor.executeTurn(galaxy);
                        LOG.log(Level.INFO, "Turn {0} executed in {1} ms",
                                new Object[] { galaxy.getCurrentTurn(), time });
                        LOG.log(Level.INFO, "Logged in users: " + loggedInUsers.toString());
                        LOG.log(Level.INFO,
                                "====================================================================================");

                        if (galaxy.getCurrentTurn() % saveInterval == 0) {
                            saveGalaxy();
                        }

                        galaxy.lastTurnDate = System.currentTimeMillis();
                        galaxy.nextTurnDate = galaxy.lastTurnDate + galaxy.turnSpeed;
                    }

                } catch (InterruptedException e) {
                    LOG.log(Level.SEVERE, "Error in main server loop, interrupted", e);
                }
            }
        }
    });
    timerThread.start();

    // ACCEPT CONNECTIONS AND DELEGATE TO CLIENT SESSIONS
    while (true) {
        Socket clientConnection;
        try {
            clientConnection = server.accept();
            ClientSession c = new ClientSession(clientConnection, galaxy);
            Thread t = new Thread(c);
            t.start();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "IO Exception while trying to handle incoming client connection", ex);
        }
    }
}

From source file:com.twitter.hraven.rest.client.HRavenRestClient.java

public static void main(String[] args) throws IOException {
    String apiHostname = null;// w w  w .jav a2 s.  c  o m
    String cluster = null;
    String username = null;
    String batchDesc = null;
    String signature = null;
    int limit = 2;
    boolean useHBaseAPI = false;
    boolean dumpJson = false;
    boolean hydrateTasks = false;
    List<String> taskResponseFilters = new ArrayList<String>();
    List<String> jobResponseFilters = new ArrayList<String>();
    List<String> flowResponseFilters = new ArrayList<String>();
    List<String> configFields = new ArrayList<String>();

    StringBuffer usage = new StringBuffer("Usage: java ");
    usage.append(HRavenRestClient.class.getName()).append(" [-options]\n");
    usage.append("Returns data from recent flows and their associated jobs\n");
    usage.append("where options include: \n");
    usage.append(" -a <API hostname> [required]\n");
    usage.append(" -c <cluster> [required]\n");
    usage.append(" -u <username> [required]\n");
    usage.append(" -f <flowName> [required]\n");
    usage.append(" -s <signature>\n");
    usage.append(" -l <limit>\n");
    usage.append(" -h - print this message and return\n");
    usage.append(" -H - use HBase API, not the REST API\n");
    usage.append(" -j - output json\n");
    usage.append(" -t - retrieve task information as well");
    usage.append(" -w - config field to be included in job response");
    usage.append(" -z - field to be included in task response");
    usage.append(" -y - field to be included in job response");
    usage.append(" -x - field to be included in flow response");

    for (int i = 0; i < args.length; i++) {
        if ("-a".equals(args[i])) {
            apiHostname = args[++i];
            continue;
        } else if ("-c".equals(args[i])) {
            cluster = args[++i];
            continue;
        } else if ("-u".equals(args[i])) {
            username = args[++i];
            continue;
        } else if ("-f".equals(args[i])) {
            batchDesc = args[++i];
            continue;
        } else if ("-s".equals(args[i])) {
            signature = args[++i];
            continue;
        } else if ("-l".equals(args[i])) {
            limit = Integer.parseInt(args[++i]);
            continue;
        } else if ("-H".equals(args[i])) {
            useHBaseAPI = true;
            continue;
        } else if ("-j".equals(args[i])) {
            dumpJson = true;
            continue;
        } else if ("-t".equals(args[i])) {
            hydrateTasks = true;
            continue;
        } else if ("-z".equals(args[i])) {
            String taskFilters = args[++i];
            taskResponseFilters = Arrays.asList(taskFilters.split(","));
            continue;
        } else if ("-y".equals(args[i])) {
            String jobFilters = args[++i];
            jobResponseFilters = Arrays.asList(jobFilters.split(","));
            continue;
        } else if ("-x".equals(args[i])) {
            String flowFilters = args[++i];
            flowResponseFilters = Arrays.asList(flowFilters.split(","));
            continue;
        } else if ("-w".equals(args[i])) {
            String configFilters = args[++i];
            configFields = Arrays.asList(configFilters.split(","));
            continue;
        } else if ("-h".equals(args[i])) {
            System.err.println(usage.toString());
            System.exit(1);
        } else {

        }
    }

    if (apiHostname == null || cluster == null || username == null || batchDesc == null) {
        System.err.println(usage.toString());
        System.exit(1);
    }

    List<Flow> flows;
    if (useHBaseAPI) {
        JobHistoryService jobHistoryService = new JobHistoryService(HBaseConfiguration.create());
        flows = jobHistoryService.getFlowSeries(cluster, username, batchDesc, signature, hydrateTasks, limit);
    } else {
        HRavenRestClient client = new HRavenRestClient(apiHostname, 100000, 100000);

        // use this call to call flows without configs
        flows = client.fetchFlows(cluster, username, batchDesc, signature, flowResponseFilters,
                jobResponseFilters, limit);
        // use this call to call flows with configs
        flows = client.fetchFlowsWithConfig(cluster, username, batchDesc, signature, limit, flowResponseFilters,
                jobResponseFilters, configFields);
        // use this call to call flows with config patterns
        flows = client.fetchFlowsWithConfig(cluster, username, batchDesc, signature, limit, flowResponseFilters,
                jobResponseFilters, configFields);

        if (hydrateTasks) {
            for (Flow flow : flows) {
                for (JobDetails jd : flow.getJobs()) {
                    String jobId = jd.getJobId();
                    List<TaskDetails> td = client.fetchTaskDetails(cluster, jobId, taskResponseFilters);
                    jd.addTasks(td);
                }
            }
        }
    }

    if (dumpJson) {
        ObjectMapper om = ObjectMapperProvider.createCustomMapper();
        SimpleModule module = new SimpleModule("hRavenModule", new Version(0, 4, 0, null));
        module.addSerializer(Flow.class, new FlowSerializer());
        module.addSerializer(JobDetails.class, new JobDetailsSerializer());
        om.registerModule(module);
        if (flows.size() > 0) {
            System.out.println(om.writeValueAsString(flows.get(0)));
        }
        return;
    }

    System.out.println("Found " + flows.size() + " flows");
    StringBuilder sb = new StringBuilder();
    sb.append("\t\t").append("jobId");
    sb.append("\t\t").append("version");
    sb.append("\t\t").append("status");
    sb.append("\t").append("maps");
    sb.append("\t").append("reduces");
    sb.append("\t").append("rBytesRead");
    sb.append("\t").append("feature");
    sb.append("\t\t\t").append("alias");
    System.out.println(sb.toString());

    int i = 0;
    for (Flow flow : flows) {
        long minSubmitTime = -1, maxFinishTime = -1;
        for (JobDetails job : flow.getJobs()) {
            if (minSubmitTime == -1 && job.getSubmitTime() > 0) {
                minSubmitTime = job.getSubmitTime();
            }
            minSubmitTime = Math.min(minSubmitTime, job.getSubmitTime());
            maxFinishTime = Math.max(maxFinishTime, job.getFinishTime());
        }

        if (minSubmitTime > 0 && maxFinishTime > 0) {
            System.out.println(String.format("Flow #%d: %s - %s", i++, DATE_FORMAT.format(minSubmitTime),
                    DATE_FORMAT.format(maxFinishTime)));
        } else {
            System.out.println(String.format("Flow #%d:", i++));
        }

        for (JobDetails job : flow.getJobs()) {
            sb = new StringBuilder();
            sb.append(" - ").append(job.getJobId());
            sb.append("\t").append(job.getVersion());
            sb.append("\t").append(job.getStatus());
            sb.append("\t").append(job.getTotalMaps());
            sb.append("\t").append(job.getTotalReduces());
            long reduceBytesRead = job.getReduceCounters().getCounter("FileSystemCounters",
                    "FILE_BYTES_READ") != null
                            ? job.getReduceCounters().getCounter("FileSystemCounters", "FILE_BYTES_READ")
                                    .getValue()
                            : -1;
            sb.append("\t").append(reduceBytesRead);
            sb.append("\t").append(job.getConfiguration().get("pig.job.feature"));
            sb.append("\t").append(job.getConfiguration().get("pig.alias"));
            System.out.println(sb.toString());
        }
    }
}

From source file:TextVerifyInputFormatDate.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    text.setText("YYYY/MM/DD");
    ;/*  w ww. j  av a  2s  .co  m*/
    final Calendar calendar = Calendar.getInstance();
    text.addListener(SWT.Verify, new Listener() {
        boolean ignore;

        public void handleEvent(Event e) {
            if (ignore)
                return;
            e.doit = false;
            StringBuffer buffer = new StringBuffer(e.text);
            char[] chars = new char[buffer.length()];
            buffer.getChars(0, chars.length, chars, 0);
            if (e.character == '\b') {
                for (int i = e.start; i < e.end; i++) {
                    switch (i) {
                    case 0: /* [Y]YYY */
                    case 1: /* Y[Y]YY */
                    case 2: /* YY[Y]Y */
                    case 3: /* YYY[Y] */ {
                        buffer.append('Y');
                        break;
                    }
                    case 5: /* [M]M */
                    case 6: /* M[M] */ {
                        buffer.append('M');
                        break;
                    }
                    case 8: /* [D]D */
                    case 9: /* D[D] */ {
                        buffer.append('D');
                        break;
                    }
                    case 4: /* YYYY[/]MM */
                    case 7: /* MM[/]DD */ {
                        buffer.append('/');
                        break;
                    }
                    default:
                        return;
                    }
                }
                text.setSelection(e.start, e.start + buffer.length());
                ignore = true;
                text.insert(buffer.toString());
                ignore = false;
                text.setSelection(e.start, e.start);
                return;
            }

            int start = e.start;
            if (start > 9)
                return;
            int index = 0;
            for (int i = 0; i < chars.length; i++) {
                if (start + index == 4 || start + index == 7) {
                    if (chars[i] == '/') {
                        index++;
                        continue;
                    }
                    buffer.insert(index++, '/');
                }
                if (chars[i] < '0' || '9' < chars[i])
                    return;
                if (start + index == 5 && '1' < chars[i])
                    return; /* [M]M */
                if (start + index == 8 && '3' < chars[i])
                    return; /* [D]D */
                index++;
            }
            String newText = buffer.toString();
            int length = newText.length();
            StringBuffer date = new StringBuffer(text.getText());
            date.replace(e.start, e.start + length, newText);
            calendar.set(Calendar.YEAR, 1901);
            calendar.set(Calendar.MONTH, Calendar.JANUARY);
            calendar.set(Calendar.DATE, 1);
            String yyyy = date.substring(0, 4);
            if (yyyy.indexOf('Y') == -1) {
                int year = Integer.parseInt(yyyy);
                calendar.set(Calendar.YEAR, year);
            }
            String mm = date.substring(5, 7);
            if (mm.indexOf('M') == -1) {
                int month = Integer.parseInt(mm) - 1;
                int maxMonth = calendar.getActualMaximum(Calendar.MONTH);
                if (0 > month || month > maxMonth)
                    return;
                calendar.set(Calendar.MONTH, month);
            }
            String dd = date.substring(8, 10);
            if (dd.indexOf('D') == -1) {
                int day = Integer.parseInt(dd);
                int maxDay = calendar.getActualMaximum(Calendar.DATE);
                if (1 > day || day > maxDay)
                    return;
                calendar.set(Calendar.DATE, day);
            } else {
                if (calendar.get(Calendar.MONTH) == Calendar.FEBRUARY) {
                    char firstChar = date.charAt(8);
                    if (firstChar != 'D' && '2' < firstChar)
                        return;
                }
            }
            text.setSelection(e.start, e.start + length);
            ignore = true;
            text.insert(newText);
            ignore = false;
        }
    });
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:fr.inria.edelweiss.kgdqp.core.FedQueryingCLI.java

@SuppressWarnings("unchecked")
public static void main(String args[]) throws ParseException, EngineException {

    List<String> endpoints = new ArrayList<String>();
    String queryPath = null;//from w  w w.  j ava 2s .c om
    int slice = -1;

    Options options = new Options();
    Option helpOpt = new Option("h", "help", false, "print this message");
    Option queryOpt = new Option("q", "query", true, "specify the sparql query file");
    Option endpointOpt = new Option("e", "endpoints", true, "the list of federated sparql endpoint URLs");
    Option groupingOpt = new Option("g", "grouping", true, "triple pattern optimisation");
    Option slicingOpt = new Option("s", "slicing", true, "size of the slicing parameter");
    Option versionOpt = new Option("v", "version", false, "print the version information and exit");
    options.addOption(queryOpt);
    options.addOption(endpointOpt);
    options.addOption(helpOpt);
    options.addOption(versionOpt);
    options.addOption(groupingOpt);
    options.addOption(slicingOpt);

    String header = "Corese/KGRAM DQP command line interface";
    String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr";

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("kgdqp", header, options, footer, true);
        System.exit(0);
    }
    if (!cmd.hasOption("e")) {
        logger.info("You must specify at least the URL of one sparql endpoint !");
        System.exit(0);
    } else {
        endpoints = new ArrayList<String>(Arrays.asList(cmd.getOptionValues("e")));
    }
    if (!cmd.hasOption("q")) {
        logger.info("You must specify a path for a sparql query !");
        System.exit(0);
    } else {
        queryPath = cmd.getOptionValue("q");
    }
    if (cmd.hasOption("s")) {
        try {
            slice = Integer.parseInt(cmd.getOptionValue("s"));
        } catch (NumberFormatException ex) {
            logger.warn(cmd.getOptionValue("s") + " is not formatted as number for the slicing parameter");
            logger.warn("Slicing disabled");
        }
    }
    if (cmd.hasOption("v")) {
        logger.info("version 3.0.4-SNAPSHOT");
        System.exit(0);
    }

    /////////////////
    Graph graph = Graph.create();
    QueryProcessDQP exec = QueryProcessDQP.create(graph);
    exec.setGroupingEnabled(cmd.hasOption("g"));
    if (slice > 0) {
        exec.setSlice(slice);
    }
    Provider sProv = ProviderImplCostMonitoring.create();
    exec.set(sProv);

    for (String url : endpoints) {
        try {
            exec.addRemote(new URL(url), WSImplem.REST);
        } catch (MalformedURLException ex) {
            logger.error(url + " is not a well-formed URL");
            System.exit(1);
        }
    }

    StringBuffer fileData = new StringBuffer(1000);
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(queryPath));
    } catch (FileNotFoundException ex) {
        logger.error("Query file " + queryPath + " not found !");
        System.exit(1);
    }
    char[] buf = new char[1024];
    int numRead = 0;
    try {
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
    } catch (IOException ex) {
        logger.error("Error while reading query file " + queryPath);
        System.exit(1);
    }

    String sparqlQuery = fileData.toString();

    //        Query q = exec.compile(sparqlQuery, null);
    //        System.out.println(q);

    StopWatch sw = new StopWatch();
    sw.start();
    Mappings map = exec.query(sparqlQuery);
    int dqpSize = map.size();
    System.out.println("--------");
    long time = sw.getTime();
    System.out.println(time + " " + dqpSize);
}

From source file:discovery.compression.kdd2011.ratio.RatioCompressionReport.java

public static void main(String[] args) throws GraphReadingException, IOException, java.text.ParseException {
    opts.addOption("r", true, "Goal compression ratio");

    //      opts.addOption( "a",
    //       true,
    //       "Algorithm used for compression. The default and only currently available option is \"greedy\"");
    //opts.addOption("cost-output",true,"Output file for costs, default is costs.txt");
    //opts.addOption("cost-format",true,"Output format for ");

    opts.addOption("ctype", true, "Connectivity type: global or local, default is global.");
    opts.addOption("connectivity", false,
            "enables output for connectivity. Connectivity info will be written to connectivity.txt");
    opts.addOption("output_bmg", true, "Write bmg file with groups to given file.");
    opts.addOption("algorithm", true, "Algorithm to use, one of: greedy random1 random2 bruteforce slowgreedy");
    opts.addOption("hop2", false, "Only try to merge nodes that have common neighbors");
    opts.addOption("kmedoids", false, "Enables output for kmedoids clustering");
    opts.addOption("kmedoids_k", true, "Number of clusters to be used in kmedoids. Default is 3");
    opts.addOption("kmedoids_output", true,
            "Output file for kmedoid clusters. Default is clusters.txt. This file will be overwritten.");
    opts.addOption("norefresh", false,
            "Use old style merging: all connectivities are not refreshed when merging");
    opts.addOption("edge_attribute", true, "Attribute from bmgraph used as edge weight");
    opts.addOption("only_times", false, "Only write times.txt");
    //opts.addOption("no_metrics",false,"Exit after compression, don't calculate any metrics or produce output bmg for the compression.");
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//  w ww .j  av  a 2  s  . c o  m

    try {
        cmd = parser.parse(opts, args);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(0);
    }

    boolean connectivity = false;
    double ratio = 0;

    boolean hop2 = cmd.hasOption("hop2");

    RatioCompression compression = new GreedyRatioCompression(hop2);

    if (cmd.hasOption("connectivity"))
        connectivity = true;

    ConnectivityType ctype = ConnectivityType.GLOBAL;
    CompressionMergeModel mergeModel = new PathAverageMergeModel();
    if (cmd.hasOption("ctype")) {
        String ctypeStr = cmd.getOptionValue("ctype");
        if (ctypeStr.equals("local")) {
            ctype = ConnectivityType.LOCAL;
            mergeModel = new EdgeAverageMergeModel();
        } else if (ctypeStr.equals("global")) {
            ctype = ConnectivityType.GLOBAL;
            mergeModel = new PathAverageMergeModel();
        } else {
            System.out.println(PROGRAM_NAME + ": unknown connectivity type " + ctypeStr);
            printHelp();
        }
    }

    if (cmd.hasOption("norefresh"))
        mergeModel = new PathAverageMergeModelNorefresh();
    if (cmd.hasOption("algorithm")) {
        String alg = cmd.getOptionValue("algorithm");
        if (alg.equals("greedy")) {
            compression = new GreedyRatioCompression(hop2);
        } else if (alg.equals("random1")) {
            compression = new RandomRatioCompression(hop2);
        } else if (alg.equals("random2")) {
            compression = new SmartRandomRatioCompression(hop2);
        } else if (alg.equals("bruteforce")) {
            compression = new BruteForceCompression(hop2, ctype == ConnectivityType.LOCAL);
        } else if (alg.equals("slowgreedy")) {
            compression = new SlowGreedyRatioCompression(hop2);
        } else {
            System.out.println("algorithm must be one of: greedy random1 random2 bruteforce slowgreedy");
            printHelp();
        }
    }

    compression.setMergeModel(mergeModel);

    if (cmd.hasOption("r")) {
        ratio = Double.parseDouble(cmd.getOptionValue("r"));
    } else {
        System.out.println(PROGRAM_NAME + ": compression ratio not defined");
        printHelp();
    }

    if (cmd.hasOption("help")) {
        printHelp();
    }

    String infile = null;
    if (cmd.getArgs().length != 0) {
        infile = cmd.getArgs()[0];
    } else {
        printHelp();
    }

    boolean kmedoids = false;
    int kmedoidsK = 3;
    String kmedoidsOutput = "clusters.txt";
    if (cmd.hasOption("kmedoids"))
        kmedoids = true;
    if (cmd.hasOption("kmedoids_k"))
        kmedoidsK = Integer.parseInt(cmd.getOptionValue("kmedoids_k"));
    if (cmd.hasOption("kmedoids_output"))
        kmedoidsOutput = cmd.getOptionValue("kmedoids_output");

    String edgeAttrib = "goodness";
    if (cmd.hasOption("edge_attribute"))
        edgeAttrib = cmd.getOptionValue("edge_attribute");

    // This program should directly use bmgraph-java to read and
    // DefaultGraph should have a constructor that takes a BMGraph as an
    // argument.

    //VisualGraph vg = new VisualGraph(infile, edgeAttrib, false);
    //System.out.println("vg read");
    //SimpleVisualGraph origSG = new SimpleVisualGraph(vg);
    BMGraph bmg = BMGraphUtils.readBMGraph(infile);

    int origN = bmg.getNodes().size();

    //for(int i=0;i<origN;i++)
    //System.out.println(i+"="+origSG.getVisualNode(i));
    System.out.println("bmgraph read");

    BMNode[] i2n = new BMNode[origN];
    HashMap<BMNode, Integer> n2i = new HashMap<BMNode, Integer>();
    {
        int pi = 0;
        for (BMNode nod : bmg.getNodes()) {
            n2i.put(nod, pi);
            i2n[pi++] = nod;
        }
    }

    DefaultGraph dg = new DefaultGraph();
    for (BMEdge e : bmg.getEdges()) {
        dg.addEdge(n2i.get(e.getSource()), n2i.get(e.getTarget()), Double.parseDouble(e.get(edgeAttrib)));
    }

    DefaultGraph origDG = dg.copy();

    System.out.println("inputs read");
    RatioCompression nopCompressor = new RatioCompression.DefaultRatioCompression();
    ResultGraph nopResult = nopCompressor.compressGraph(dg, 1);

    long start = System.currentTimeMillis();
    ResultGraph result = compression.compressGraph(dg, ratio);
    long timeSpent = System.currentTimeMillis() - start;
    double seconds = timeSpent * 0.001;

    BufferedWriter timesWriter = new BufferedWriter(new FileWriter("times.txt", true));
    timesWriter.append("" + seconds + "\n");
    timesWriter.close();

    if (cmd.hasOption("only_times")) {
        System.out.println("Compression done, exiting.");
        System.exit(0);
    }

    BufferedWriter costsWriter = new BufferedWriter(new FileWriter("costs.txt", true));
    costsWriter.append("" + nopResult.getCompressorCosts() + " " + result.getCompressorCosts() + "\n");
    costsWriter.close();

    double[][] origProb;
    double[][] compProb;
    int[] group = new int[origN];

    for (int i = 0; i < result.partition.size(); i++)
        for (int x : result.partition.get(i))
            group[x] = i;

    if (ctype == ConnectivityType.LOCAL) {
        origProb = new double[origN][origN];
        compProb = new double[origN][origN];
        DefaultGraph g = result.uncompressedGraph();
        for (int i = 0; i < origN; i++) {
            for (int j = 0; j < origN; j++) {
                origProb[i][j] = dg.getEdgeWeight(i, j);
                compProb[i][j] = g.getEdgeWeight(i, j);
            }
        }
        System.out.println("Writing edge-dissimilarity");
    } else {

        origProb = ProbDijkstra.getProbMatrix(origDG);

        compProb = new double[origN][origN];

        System.out.println("nodeCount = " + result.graph.getNodeCount());
        double[][] ccProb = ProbDijkstra.getProbMatrix(result.graph);
        System.out.println("ccProb.length = " + ccProb.length);

        System.out.println("ccProb[0].length = " + ccProb[0].length);

        for (int i = 0; i < origN; i++) {
            for (int j = 0; j < origN; j++) {
                if (group[i] == group[j])
                    compProb[i][j] = result.graph.getEdgeWeight(group[i], group[j]);
                else {
                    int gj = group[j];
                    int gi = group[i];
                    compProb[i][j] = ccProb[group[i]][group[j]];
                }
            }
        }

        System.out.println("Writing best-path-dissimilarity");
        //compProb = ProbDijkstra.getProbMatrix(result.uncompressedGraph());

    }

    {
        BufferedWriter connWr = null;//

        if (connectivity) {
            connWr = new BufferedWriter(new FileWriter("connectivity.txt", true));
        }
        double totalDiff = 0;

        for (int i = 0; i < origN; i++) {
            for (int j = i + 1; j < origN; j++) {

                double diff = Math.abs(origProb[i][j] - compProb[i][j]);
                //VisualNode ni = origSG.getVisualNode(i);
                //VisualNode nj = origSG.getVisualNode(j);
                BMNode ni = i2n[i];
                BMNode nj = i2n[j];
                if (connectivity)
                    connWr.append(ni + "\t" + nj + "\t" + origProb[i][j] + "\t" + compProb[i][j] + "\t" + diff
                            + "\n");
                totalDiff += diff * diff;
            }
        }

        if (connectivity) {
            connWr.append("\n");
            connWr.close();
        }

        totalDiff = Math.sqrt(totalDiff);
        BufferedWriter dissWr = new BufferedWriter(new FileWriter("dissimilarity.txt", true));
        dissWr.append("" + totalDiff + "\n");
        dissWr.close();
    }

    if (cmd.hasOption("output_bmg")) {
        BMGraph outgraph = new BMGraph();

        String outputfile = cmd.getOptionValue("output_bmg");
        HashMap<Integer, BMNode> nodes = new HashMap<Integer, BMNode>();

        for (int i = 0; i < result.partition.size(); i++) {
            ArrayList<Integer> g = result.partition.get(i);
            if (g.size() == 0)
                continue;
            BMNode node = new BMNode("Supernode_" + i);
            HashMap<String, String> attributes = new HashMap<String, String>();
            StringBuffer contents = new StringBuffer();
            for (int x : g)
                contents.append(i2n[x] + ",");
            contents.delete(contents.length() - 1, contents.length());

            attributes.put("nodes", contents.toString());
            attributes.put("self-edge", "" + result.graph.getEdgeWeight(i, i));
            node.setAttributes(attributes);
            nodes.put(i, node);
            outgraph.ensureHasNode(node);
        }

        for (int i = 0; i < result.partition.size(); i++) {
            if (result.partition.get(i).size() == 0)
                continue;
            for (int x : result.graph.getNeighbors(i)) {
                if (x < i)
                    continue;
                BMNode from = nodes.get(i);
                BMNode to = nodes.get(x);
                if (from == null || to == null) {
                    System.out.println(from + "->" + to);
                    System.out.println(i + "->" + x);
                    System.out.println("");
                }
                BMEdge e = new BMEdge(nodes.get(i), nodes.get(x), "notype");

                e.setAttributes(new HashMap<String, String>());
                e.put("goodness", "" + result.graph.getEdgeWeight(i, x));
                outgraph.ensureHasEdge(e);
            }
        }
        BMGraphUtils.writeBMGraph(outgraph, outputfile);
    }

    // k medoids!
    if (kmedoids) {
        //KMedoidsResult clustersOrig=KMedoids.runKMedoids(origProb,kmedoidsK);

        if (ctype == ConnectivityType.LOCAL) {
            compProb = ProbDijkstra.getProbMatrix(result.uncompressedGraph());
        }

        //KMedoidsResult compClusters = KMedoids.runKMedoids(ProbDijkstra.getProbMatrix(result.graph),kmedoidsK);
        KMedoidsResult clustersComp = KMedoids.runKMedoids(compProb, kmedoidsK);

        BufferedWriter bw = new BufferedWriter(new FileWriter(kmedoidsOutput));

        for (int i = 0; i < origN; i++) {
            int g = group[i];
            //bw.append(origSG.getVisualNode(i).getBMNode()+" "+compClusters.clusters[g]+"\n");
            bw.append(i2n[i] + " " + clustersComp.clusters[i] + "\n");
        }
        bw.close();
    }

    System.exit(0);
}