Example usage for java.util Set add

List of usage examples for java.util Set add

Introduction

In this page you can find the example usage for java.util Set add.

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (optional operation).

Usage

From source file:hyperloglog.tools.HyperLogLogCLI.java

public static void main(String[] args) {
    Options options = new Options();
    addOptions(options);//from   www  .j  a v  a2s.  c om

    CommandLineParser parser = new BasicParser();
    CommandLine cli = null;
    long n = 0;
    long seed = 123;
    EncodingType enc = EncodingType.SPARSE;
    int p = 14;
    int hb = 64;
    boolean bitPack = true;
    boolean noBias = true;
    int unique = -1;
    String filePath = null;
    BufferedReader br = null;
    String outFile = null;
    String inFile = null;
    FileOutputStream fos = null;
    DataOutputStream out = null;
    FileInputStream fis = null;
    DataInputStream in = null;
    try {
        cli = parser.parse(options, args);

        if (!(cli.hasOption('n') || cli.hasOption('f') || cli.hasOption('d'))) {
            System.out.println("Example usage: hll -n 1000 " + "<OR> hll -f /tmp/input.txt "
                    + "<OR> hll -d -i /tmp/out.hll");
            usage(options);
            return;
        }

        if (cli.hasOption('n')) {
            n = Long.parseLong(cli.getOptionValue('n'));
        }

        if (cli.hasOption('e')) {
            String value = cli.getOptionValue('e');
            if (value.equals(EncodingType.DENSE.name())) {
                enc = EncodingType.DENSE;
            }
        }

        if (cli.hasOption('p')) {
            p = Integer.parseInt(cli.getOptionValue('p'));
            if (p < 4 && p > 16) {
                System.out.println("Warning! Out-of-range value specified for p. Using to p=14.");
                p = 14;
            }
        }

        if (cli.hasOption('h')) {
            hb = Integer.parseInt(cli.getOptionValue('h'));
        }

        if (cli.hasOption('c')) {
            noBias = Boolean.parseBoolean(cli.getOptionValue('c'));
        }

        if (cli.hasOption('b')) {
            bitPack = Boolean.parseBoolean(cli.getOptionValue('b'));
        }

        if (cli.hasOption('f')) {
            filePath = cli.getOptionValue('f');
            br = new BufferedReader(new FileReader(new File(filePath)));
        }

        if (filePath != null && cli.hasOption('n')) {
            System.out.println("'-f' (input file) specified. Ignoring -n.");
        }

        if (cli.hasOption('s')) {
            if (cli.hasOption('o')) {
                outFile = cli.getOptionValue('o');
                fos = new FileOutputStream(new File(outFile));
                out = new DataOutputStream(fos);
            } else {
                System.err.println("Specify output file. Example usage: hll -s -o /tmp/out.hll");
                usage(options);
                return;
            }
        }

        if (cli.hasOption('d')) {
            if (cli.hasOption('i')) {
                inFile = cli.getOptionValue('i');
                fis = new FileInputStream(new File(inFile));
                in = new DataInputStream(fis);
            } else {
                System.err.println("Specify input file. Example usage: hll -d -i /tmp/in.hll");
                usage(options);
                return;
            }
        }

        // return after deserialization
        if (fis != null && in != null) {
            long start = System.currentTimeMillis();
            HyperLogLog deserializedHLL = HyperLogLogUtils.deserializeHLL(in);
            long end = System.currentTimeMillis();
            System.out.println(deserializedHLL.toString());
            System.out.println("Count after deserialization: " + deserializedHLL.count());
            System.out.println("Deserialization time: " + (end - start) + " ms");
            return;
        }

        // construct hll and serialize it if required
        HyperLogLog hll = HyperLogLog.builder().enableBitPacking(bitPack).enableNoBias(noBias).setEncoding(enc)
                .setNumHashBits(hb).setNumRegisterIndexBits(p).build();

        if (br != null) {
            Set<String> hashset = new HashSet<String>();
            String line;
            while ((line = br.readLine()) != null) {
                hll.addString(line);
                hashset.add(line);
            }
            n = hashset.size();
        } else {
            Random rand = new Random(seed);
            for (int i = 0; i < n; i++) {
                if (unique < 0) {
                    hll.addLong(rand.nextLong());
                } else {
                    int val = rand.nextInt(unique);
                    hll.addLong(val);
                }
            }
        }

        long estCount = hll.count();
        System.out.println("Actual count: " + n);
        System.out.println(hll.toString());
        System.out.println("Relative error: " + HyperLogLogUtils.getRelativeError(n, estCount) + "%");
        if (fos != null && out != null) {
            long start = System.currentTimeMillis();
            HyperLogLogUtils.serializeHLL(out, hll);
            long end = System.currentTimeMillis();
            System.out.println("Serialized hyperloglog to " + outFile);
            System.out.println("Serialized size: " + out.size() + " bytes");
            System.out.println("Serialization time: " + (end - start) + " ms");
            out.close();
        }
    } catch (ParseException e) {
        System.err.println("Invalid parameter.");
        usage(options);
    } catch (NumberFormatException e) {
        System.err.println("Invalid type for parameter.");
        usage(options);
    } catch (FileNotFoundException e) {
        System.err.println("Specified file not found.");
        usage(options);
    } catch (IOException e) {
        System.err.println("Exception occured while reading file.");
        usage(options);
    }
}

From source file:edu.umass.cs.gigapaxos.PaxosPacketBatcher.java

/**
 * @param args/*from  w  w w  . j a  v a  2s.c  o m*/
 */
public static void main(String[] args) {
    Util.assertAssertionsEnabled();
    Ballot b1 = new Ballot(23, 456);
    Ballot b2 = new Ballot(23, 456);
    assert (b1.equals(b2));
    Set<Ballot> bset = new HashSet<Ballot>();
    bset.add(b1);
    assert (bset.contains(b1));
    assert (bset.contains(b2));
    bset.add(b2);
    assert (bset.size() == 1) : bset.size();
}

From source file:com.clustercontrol.poller.impl.WbemPollerImpl.java

/**
 * ?/*from ww w  .  ja  va  2 s.c om*/
 * 
 * @param args
 */
public static void main(String[] args) {
    // 
    WbemPollerImpl poller = new WbemPollerImpl();

    String ipAddress = args[0];
    int port = Integer.parseInt(args[1]);
    String protocol = args[2];
    String user = args[3];
    String password = args[4];
    String nameSpace = args[5]; // ??
    int retries = Integer.parseInt(args[6]);
    int timeout = Integer.parseInt(args[7]);
    Set<String> cims = new HashSet<String>();

    for (int i = 8; i < args.length; i++) {
        cims.add(args[i]);
    }

    DataTable table = poller.polling(ipAddress, port, protocol, user, password, nameSpace, retries, timeout,
            cims);
    System.out.println(table);
}

From source file:com.glaf.jbpm.action.MultiPooledTaskInstanceAction.java

public static void main(String[] args) throws Exception {
    String actorIdxy = "{joy,sam},{pp,qq},{kit,cora},{eyb2000,huangcw}";
    StringTokenizer st2 = new StringTokenizer(actorIdxy, ";");
    while (st2.hasMoreTokens()) {
        String elem2 = st2.nextToken();
        if (StringUtils.isNotEmpty(elem2)) {
            elem2 = elem2.trim();//from   w ww  .j  a  v  a 2  s.  co m
            if ((elem2.length() > 0 && elem2.charAt(0) == '{') && elem2.endsWith("}")) {
                elem2 = elem2.substring(elem2.indexOf("{") + 1, elem2.indexOf("}"));
                Set<String> actorIds = new HashSet<String>();
                StringTokenizer st4 = new StringTokenizer(elem2, ",");
                while (st4.hasMoreTokens()) {
                    String elem4 = st4.nextToken();
                    elem4 = elem4.trim();
                    if (elem4.length() > 0) {
                        actorIds.add(elem4);
                    }
                }
                System.out.println(actorIds);
            }
        }
    }
}

From source file:com.music.tools.ScaleTester.java

public static void main(String[] args) {
    System.out.println(//ww w  .j  a va  2s  .  c  o m
            "Usage: java ScaleTester <fundamental frequency> <chromatic scale size> <scale size> <use ET>");
    final AudioFormat af = new AudioFormat(sampleRate, 16, 1, true, true);
    try {
        fundamentalFreq = getArgument(args, 0, FUNDAMENTAL_FREQUENCY, Double.class);
        int pitchesInChromaticScale = getArgument(args, 1, CHROMATIC_SCALE_SILZE, Integer.class);

        List<Double> harmonicFrequencies = new ArrayList<>();
        List<String> ratios = new ArrayList<>();
        Set<Double> frequencies = new HashSet<Double>();
        frequencies.add(fundamentalFreq);
        int octaveMultiplier = 2;
        for (int i = 2; i < 100; i++) {
            // Exclude the 7th harmonic TODO exclude the 11th as well?
            // http://www.phy.mtu.edu/~suits/badnote.html
            if (i % 7 == 0) {
                continue;
            }
            double actualFreq = fundamentalFreq * i;
            double closestTonicRatio = actualFreq / (fundamentalFreq * octaveMultiplier);
            if (closestTonicRatio < 1 || closestTonicRatio > 2) {
                octaveMultiplier *= 2;
            }
            double closestTonic = actualFreq - actualFreq % (fundamentalFreq * octaveMultiplier);
            double normalizedFreq = fundamentalFreq * (actualFreq / closestTonic);

            harmonicFrequencies.add(actualFreq);
            frequencies.add(normalizedFreq);
            if (frequencies.size() == pitchesInChromaticScale) {
                break;
            }
        }

        System.out.println("Harmonic (overtone) frequencies: " + harmonicFrequencies);
        System.out.println("Transposed harmonic frequencies: " + frequencies);

        List<Double> chromaticScale = new ArrayList<>(frequencies);
        Collections.sort(chromaticScale);

        // find the "perfect" interval (e.g. perfect fifth)
        int perfectIntervalIndex = 0;
        int idx = 0;
        for (Iterator<Double> it = chromaticScale.iterator(); it.hasNext();) {
            Double noteFreq = it.next();
            long[] fraction = findCommonFraction(noteFreq / fundamentalFreq);
            fractionCache.put(noteFreq, fraction);
            if (fraction[0] == 3 && fraction[1] == 2) {
                perfectIntervalIndex = idx;
                System.out.println("Perfect interval (3/2) idx: " + perfectIntervalIndex);
            }
            idx++;
            ratios.add(Arrays.toString(fraction));
        }
        System.out.println("Ratios to fundemental frequency: " + ratios);

        if (getBooleanArgument(args, 4, USE_ET)) {
            chromaticScale = temper(chromaticScale);
        }

        System.out.println();
        System.out.println("Chromatic scale: " + chromaticScale);

        Set<Double> scaleSet = new HashSet<Double>();
        scaleSet.add(chromaticScale.get(0));
        idx = 0;
        List<Double> orderedInCircle = new ArrayList<>();
        // now go around the circle of perfect intervals and put the notes
        // in order
        while (orderedInCircle.size() < chromaticScale.size()) {
            orderedInCircle.add(chromaticScale.get(idx));
            idx += perfectIntervalIndex;
            idx = idx % chromaticScale.size();
        }
        System.out.println("Pitches Ordered in circle of perfect intervals: " + orderedInCircle);

        List<Double> scale = new ArrayList<Double>(scaleSet);
        int currentIdxInCircle = orderedInCircle.size() - 1; // start with
                                                             // the last
                                                             // note in the
                                                             // circle
        int scaleSize = getArgument(args, 3, SCALE_SIZE, Integer.class);
        while (scale.size() < scaleSize) {
            double pitch = orderedInCircle.get(currentIdxInCircle % orderedInCircle.size());
            if (!scale.contains(pitch)) {
                scale.add(pitch);
            }
            currentIdxInCircle++;
        }
        Collections.sort(scale);

        System.out.println("Scale: " + scale);

        SourceDataLine line = AudioSystem.getSourceDataLine(af);
        line.open(af);
        line.start();

        Double[] scaleFrequencies = scale.toArray(new Double[scale.size()]);

        // first play the whole scale
        WaveMelodyGenerator.playScale(line, scaleFrequencies);
        // then generate a random melody in the scale
        WaveMelodyGenerator.playMelody(line, scaleFrequencies);

        line.drain();
        line.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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 ww w. j  a va2s  .com
    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:de.tu_berlin.dima.oligos.Oligos.java

public static void main(String[] args) throws TypeNotSupportedException {
    BasicConfigurator.configure();/*ww w  . j a v  a2  s  . co m*/

    // TODO create cmdline option for setting logger level
    Logger.getRootLogger().setLevel(Level.INFO);
    CommandLineInterface cli = new CommandLineInterface(args);
    try {
        // TODO hard exit if the parsing fails!
        // better catch exceptions and log them
        if (!cli.parse()) {
            System.exit(2);
        }

        Properties props = new Properties();
        props.setProperty("user", cli.getUsername());
        props.setProperty("password", cli.getPassword());
        Connection connection = DriverManager.getConnection(cli.getConnectionString(), props);
        JdbcConnector jdbcConnector = new JdbcConnector(connection);
        MetaConnector metaConnector = null;
        Driver dbDriver = cli.dbDriver;
        switch (dbDriver.driverName) {
        case db2:
            LOGGER.trace("metaConnector = Db2MetaConnector");
            metaConnector = new Db2MetaConnector(jdbcConnector);
            break;
        case oracle:
            metaConnector = new OracleMetaConnector(jdbcConnector);
            break;
        default:
            LOGGER.error("Unknown database driver. Supported drivers are: " + DriverName.values());
        }

        // validating schema
        LOGGER.info("Validating input schema ...");
        SparseSchema sparseSchema = cli.getInputSchema();
        LOGGER.trace("User specified schema " + sparseSchema);
        DenseSchema inputSchema = DbUtils.populateSchema(sparseSchema, jdbcConnector, metaConnector);
        LOGGER.trace("Populated and validated schema " + inputSchema);

        // obtaining type information/ column meta data
        LOGGER.info("Retrieving column meta data ...");
        Map<ColumnId, TypeInfo> columnTypes = Maps.newLinkedHashMap();
        for (ColumnId columnId : inputSchema) {
            TypeInfo type = metaConnector.getColumnType(columnId);
            columnTypes.put(columnId, type);
        }

        // creating connectors and profilers
        LOGGER.info("Establashing database connection ...");
        SchemaConnector schemaConnector = null;
        TableConnector tableConnector = null;
        switch (dbDriver.driverName) {
        case db2:
            schemaConnector = new Db2SchemaConnector(jdbcConnector);
            tableConnector = new Db2TableConnector(jdbcConnector);
            break;
        case oracle:
            schemaConnector = new OracleSchemaConnector(jdbcConnector);
            tableConnector = new OracleTableConnector(jdbcConnector);
        }
        Set<SchemaProfiler> profilers = Sets.newLinkedHashSet();
        for (String schema : inputSchema.schemas()) {
            SchemaProfiler schemaProfiler = new SchemaProfiler(schema, schemaConnector);
            profilers.add(schemaProfiler);
            for (String table : inputSchema.tablesIn(schema)) {
                TableProfiler tableProfiler = new TableProfiler(schema, table, tableConnector);
                schemaProfiler.add(tableProfiler);
                for (String column : inputSchema.columnsIn(schema, table)) {
                    ColumnId columnId = new ColumnId(schema, table, column);
                    TypeInfo type = columnTypes.get(columnId);
                    ColumnProfiler<?> columnProfiler = null;
                    switch (dbDriver.driverName) {
                    case db2:
                        columnProfiler = getProfiler(schema, table, column, type, jdbcConnector, metaConnector);
                        break;
                    case oracle:
                        columnProfiler = getProfilerOracle(schema, table, column, type, jdbcConnector,
                                metaConnector);
                    }
                    tableProfiler.addColumnProfiler(columnProfiler);
                }
            }
        }
        // profiling statistical data
        LOGGER.info("Profiling schema ...");
        Set<Schema> profiledSchemas = Sets.newLinkedHashSet();
        for (SchemaProfiler schemaProfiler : profilers) {
            Schema profiledSchema = schemaProfiler.profile();
            profiledSchemas.add(profiledSchema);
        }

        LOGGER.info("Generating generator specification ...");
        File outputDir = cli.getOutputDirectory();
        String generatorName = cli.getGeneratorName();
        LOGGER.info("Writing generator specification ...");
        for (Schema schema : profiledSchemas) {
            MyriadWriter writer = new MyriadWriter(schema, outputDir, generatorName);
            writer.write();
        }
        LOGGER.info("Closing database connection ...");
        connection.close();
    } catch (SQLException e) {
        LOGGER.error(e.getLocalizedMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (IOException e) {
        LOGGER.error(e.getLocalizedMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (ParseException e) {
        LOGGER.error(e.getMessage());
        cli.printHelpMessage();
    }
}

From source file:io.fabric8.vertx.maven.plugin.FileFilterMain.java

public static void main(String[] args) {

    Commandline commandline = new Commandline();
    commandline.setExecutable("java");
    commandline.createArg().setValue("io.vertx.core.Launcher");
    commandline.createArg().setValue("--redeploy=target/**/*");

    System.out.println(commandline);/*from   w w w.  jav  a  2  s  .  c  om*/

    File baseDir = new File("/Users/kameshs/git/fabric8io/vertx-maven-plugin/samples/vertx-demo");
    List<String> includes = new ArrayList<>();
    includes.add("src/**/*.java");
    //FileAlterationMonitor monitor  = null;
    try {

        Set<Path> inclDirs = new HashSet<>();

        includes.forEach(s -> {
            try {

                if (s.startsWith("**")) {
                    Path rootPath = Paths.get(baseDir.toString());
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                } else if (s.contains("**")) {
                    String root = s.substring(0, s.indexOf("/**"));
                    Path rootPath = Paths.get(baseDir.toString(), root);
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                }

                List<Path> dirs = FileUtils.getFileAndDirectoryNames(baseDir, s, null, true, true, true, true)
                        .stream().map(FileUtils::dirname).map(Paths::get)
                        .filter(p -> Files.exists(p) && Files.isDirectory(p)).collect(Collectors.toList());

                inclDirs.addAll(dirs);

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

        FileAlterationMonitor monitor = fileWatcher(inclDirs);

        Runnable monitorTask = () -> {
            try {
                monitor.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        monitorTask.run();

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

}

From source file:io.reactiverse.vertx.maven.plugin.FileFilterMain.java

public static void main(String[] args) {

    Commandline commandline = new Commandline();
    commandline.setExecutable("java");
    commandline.createArg().setValue("io.vertx.core.Launcher");
    commandline.createArg().setValue("--redeploy=target/**/*");

    System.out.println(commandline);//from  w w  w  . j a va  2s .c om

    File baseDir = new File("/Users/kameshs/git/reactiverse/vertx-maven-plugin/samples/vertx-demo");
    List<String> includes = new ArrayList<>();
    includes.add("src/**/*.java");
    //FileAlterationMonitor monitor  = null;
    try {

        Set<Path> inclDirs = new HashSet<>();

        includes.forEach(s -> {
            try {

                if (s.startsWith("**")) {
                    Path rootPath = Paths.get(baseDir.toString());
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                } else if (s.contains("**")) {
                    String root = s.substring(0, s.indexOf("/**"));
                    Path rootPath = Paths.get(baseDir.toString(), root);
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                }

                List<Path> dirs = FileUtils.getFileAndDirectoryNames(baseDir, s, null, true, true, true, true)
                        .stream().map(FileUtils::dirname).map(Paths::get)
                        .filter(p -> Files.exists(p) && Files.isDirectory(p)).collect(Collectors.toList());

                inclDirs.addAll(dirs);

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

        FileAlterationMonitor monitor = fileWatcher(inclDirs);

        Runnable monitorTask = () -> {
            try {
                monitor.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        monitorTask.run();

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

}

From source file:ClassFileUtilities.java

/**
 * Program that computes the dependencies between the Batik jars.
 * <p>/*from w  w  w  . j  av  a2s .c  om*/
 *   Run this from the main Batik distribution directory, after building
 *   the jars.  For every jar file in the batik-xxx/ build directory,
 *   it will determine which other jar files it directly depends on.
 *   The output is lines of the form:
 * </p>
 * <pre>  <i>number</i>,<i>from</i>,<i>to</i></pre>
 * <p>
 *   where mean that the <i>from</i> jar has <i>number</i> class files
 *   that depend on class files in the <i>to</i> jar.
 * </p>
 */
public static void main(String[] args) {
    boolean showFiles = false;
    if (args.length == 1 && args[0].equals("-f")) {
        showFiles = true;
    } else if (args.length != 0) {
        System.err.println("usage: ClassFileUtilities [-f]");
        System.err.println();
        System.err.println("  -f    list files that cause each jar file dependency");
        System.exit(1);
    }

    File cwd = new File(".");
    File buildDir = null;
    String[] cwdFiles = cwd.list();
    for (int i = 0; i < cwdFiles.length; i++) {
        if (cwdFiles[i].startsWith("batik-")) {
            buildDir = new File(cwdFiles[i]);
            if (!buildDir.isDirectory()) {
                buildDir = null;
            } else {
                break;
            }
        }
    }
    if (buildDir == null || !buildDir.isDirectory()) {
        System.out.println("Directory 'batik-xxx' not found in current directory!");
        return;
    }

    try {
        Map cs = new HashMap();
        Map js = new HashMap();
        collectJars(buildDir, js, cs);

        Set classpath = new HashSet();
        Iterator i = js.values().iterator();
        while (i.hasNext()) {
            classpath.add(((Jar) i.next()).jarFile);
        }

        i = cs.values().iterator();
        while (i.hasNext()) {
            ClassFile fromFile = (ClassFile) i.next();
            // System.out.println(fromFile.name);
            Set result = getClassDependencies(fromFile.getInputStream(), classpath, false);
            Iterator j = result.iterator();
            while (j.hasNext()) {
                ClassFile toFile = (ClassFile) cs.get(j.next());
                if (fromFile != toFile && toFile != null) {
                    fromFile.deps.add(toFile);
                }
            }
        }

        i = cs.values().iterator();
        while (i.hasNext()) {
            ClassFile fromFile = (ClassFile) i.next();
            Iterator j = fromFile.deps.iterator();
            while (j.hasNext()) {
                ClassFile toFile = (ClassFile) j.next();
                Jar fromJar = fromFile.jar;
                Jar toJar = toFile.jar;
                if (fromFile.name.equals(toFile.name) || toJar == fromJar
                        || fromJar.files.contains(toFile.name)) {
                    continue;
                }
                Integer n = (Integer) fromJar.deps.get(toJar);
                if (n == null) {
                    fromJar.deps.put(toJar, new Integer(1));
                } else {
                    fromJar.deps.put(toJar, new Integer(n.intValue() + 1));
                }
            }
        }

        List triples = new ArrayList(10);
        i = js.values().iterator();
        while (i.hasNext()) {
            Jar fromJar = (Jar) i.next();
            Iterator j = fromJar.deps.keySet().iterator();
            while (j.hasNext()) {
                Jar toJar = (Jar) j.next();
                Triple t = new Triple();
                t.from = fromJar;
                t.to = toJar;
                t.count = ((Integer) fromJar.deps.get(toJar)).intValue();
                triples.add(t);
            }
        }
        Collections.sort(triples);

        i = triples.iterator();
        while (i.hasNext()) {
            Triple t = (Triple) i.next();
            System.out.println(t.count + "," + t.from.name + "," + t.to.name);
            if (showFiles) {
                Iterator j = t.from.files.iterator();
                while (j.hasNext()) {
                    ClassFile fromFile = (ClassFile) j.next();
                    Iterator k = fromFile.deps.iterator();
                    while (k.hasNext()) {
                        ClassFile toFile = (ClassFile) k.next();
                        if (toFile.jar == t.to && !t.from.files.contains(toFile.name)) {
                            System.out.println("\t" + fromFile.name + " --> " + toFile.name);
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}