Example usage for java.lang IllegalStateException IllegalStateException

List of usage examples for java.lang IllegalStateException IllegalStateException

Introduction

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

Prototype

public IllegalStateException(Throwable cause) 

Source Link

Document

Constructs a new exception with the specified cause and a detail message of (cause==null ?

Usage

From source file:com.github.jramos.snowplow.RedshiftSink.java

public static void main(String[] args) {
    try {/*  w  w w . ja v a 2 s.c  om*/
        // make sure PostGres driver is on class path
        Class.forName(POSTGRES_DRIVER);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Could not load PostgreSQL driver from classpath");
    }

    Map<String, String> argMap = validateArgs(args);
    if (argMap != null) {
        String configFile = argMap.get(CMD_ARG_CONFIG_FILE);
        KinesisConnectorExecutorBase<SnowplowEventModel, byte[]> redshiftExecutor = new RedshiftSink(
                configFile);
        redshiftExecutor.run();
    }
}

From source file:es.upm.oeg.tools.rdfshapes.utils.CadinalityResultGenerator.java

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

    String endpoint = "http://3cixty.eurecom.fr/sparql";

    List<String> classList = Files.readAllLines(Paths.get(classListPath), Charset.defaultCharset());

    String classPropertyQueryString = readFile(classPropertyQueryPath, Charset.defaultCharset());
    String propertyCardinalityQueryString = readFile(propertyCardinalityQueryPath, Charset.defaultCharset());
    String individualCountQueryString = readFile(individualCountQueryPath, Charset.defaultCharset());

    DecimalFormat df = new DecimalFormat("0.0000");

    //Create the Excel workbook and sheet
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet("Cardinality");

    int currentExcelRow = 0;
    int classStartRow = 0;

    for (String clazz : classList) {

        Map<String, String> litMap = new HashMap<>();
        Map<String, String> iriMap = ImmutableMap.of("class", clazz);

        String queryString = bindQueryString(individualCountQueryString,
                ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));

        int individualCount;
        List<RDFNode> c = executeQueryForList(queryString, endpoint, "c");
        if (c.size() == 1) {
            individualCount = c.get(0).asLiteral().getInt();
        } else {//  w  w w .ja va 2 s.c o  m
            continue;
        }

        // If there are zero individuals, continue
        if (individualCount == 0) {
            throw new IllegalStateException("Check whether " + classListPath + " and " + endpoint + " match.");
        }

        //            System.out.println("***");
        //            System.out.println("### **" + clazz + "** (" + individualCount + ")");
        //            System.out.println("***");
        //            System.out.println();

        classStartRow = currentExcelRow;
        XSSFRow row = sheet.createRow(currentExcelRow);
        XSSFCell cell = row.createCell(0);
        cell.setCellValue(clazz);
        cell.getCellStyle().setAlignment(CellStyle.ALIGN_CENTER);

        queryString = bindQueryString(classPropertyQueryString,
                ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));

        List<RDFNode> nodeList = executeQueryForList(queryString, endpoint, "p");

        for (RDFNode property : nodeList) {
            if (property.isURIResource()) {

                DescriptiveStatistics stats = new DescriptiveStatistics();

                String propertyURI = property.asResource().getURI();
                //                    System.out.println("* " + propertyURI);
                //                    System.out.println();

                XSSFRow propertyRow = sheet.getRow(currentExcelRow);
                if (propertyRow == null) {
                    propertyRow = sheet.createRow(currentExcelRow);
                }
                currentExcelRow++;

                XSSFCell propertyCell = propertyRow.createCell(1);
                propertyCell.setCellValue(propertyURI);

                Map<String, String> litMap2 = new HashMap<>();
                Map<String, String> iriMap2 = ImmutableMap.of("class", clazz, "p", propertyURI);

                queryString = bindQueryString(propertyCardinalityQueryString,
                        ImmutableMap.of(IRI_BINDINGS, iriMap2, LITERAL_BINDINGS, litMap2));

                List<Map<String, RDFNode>> solnMaps = executeQueryForList(queryString, endpoint,
                        ImmutableSet.of("card", "count"));

                int sum = 0;
                List<CardinalityCount> cardinalityList = new ArrayList<>();
                if (solnMaps.size() > 0) {

                    for (Map<String, RDFNode> soln : solnMaps) {
                        int count = soln.get("count").asLiteral().getInt();
                        int card = soln.get("card").asLiteral().getInt();

                        for (int i = 0; i < count; i++) {
                            stats.addValue(card);
                        }

                        CardinalityCount cardinalityCount = new CardinalityCount(card, count,
                                (((double) count) / individualCount) * 100);
                        cardinalityList.add(cardinalityCount);
                        sum += count;
                    }

                    // Check for zero cardinality instances
                    int count = individualCount - sum;
                    if (count > 0) {
                        for (int i = 0; i < count; i++) {
                            stats.addValue(0);
                        }
                        CardinalityCount cardinalityCount = new CardinalityCount(0, count,
                                (((double) count) / individualCount) * 100);
                        cardinalityList.add(cardinalityCount);
                    }
                }

                Map<Integer, Double> cardMap = new HashMap<>();
                for (CardinalityCount count : cardinalityList) {
                    cardMap.put(count.getCardinality(), count.getPrecentage());
                }

                XSSFCell instanceCountCell = propertyRow.createCell(2);
                instanceCountCell.setCellValue(individualCount);

                XSSFCell minCell = propertyRow.createCell(3);
                minCell.setCellValue(stats.getMin());

                XSSFCell maxCell = propertyRow.createCell(4);
                maxCell.setCellValue(stats.getMax());

                XSSFCell p1 = propertyRow.createCell(5);
                p1.setCellValue(stats.getPercentile(1));

                XSSFCell p99 = propertyRow.createCell(6);
                p99.setCellValue(stats.getPercentile(99));

                XSSFCell mean = propertyRow.createCell(7);
                mean.setCellValue(df.format(stats.getMean()));

                for (int i = 0; i < 21; i++) {
                    XSSFCell dataCell = propertyRow.createCell(8 + i);
                    Double percentage = cardMap.get(i);
                    if (percentage != null) {
                        dataCell.setCellValue(df.format(percentage));
                    } else {
                        dataCell.setCellValue(0);
                    }
                }

                //                    System.out.println("| Min Card. |Max Card. |");
                //                    System.out.println("|---|---|");
                //                    System.out.println("| ? | ? |");
                //                    System.out.println();

            }
        }

        //System.out.println("class start: " + classStartRow + ", class end: " + (currentExcelRow -1));
        //We have finished writting properties of one class, now it's time to merge the cells
        int classEndRow = currentExcelRow - 1;
        if (classStartRow < classEndRow) {
            sheet.addMergedRegion(new CellRangeAddress(classStartRow, classEndRow, 0, 0));
        }

    }

    String filename = "3cixty.xls";
    FileOutputStream fileOut = new FileOutputStream(filename);
    wb.write(fileOut);
    fileOut.close();
}

From source file:interoperabilite.webservice.fluent.FluentResponseHandling.java

public static void main(String[] args) throws Exception {
    Document result = Request.Get("http://somehost/content").execute()
            .handleResponse(new ResponseHandler<Document>() {

                @Override//ww w  . ja va  2  s  .co  m
                public Document handleResponse(final HttpResponse response) throws IOException {
                    StatusLine statusLine = response.getStatusLine();
                    HttpEntity entity = response.getEntity();
                    if (statusLine.getStatusCode() >= 300) {
                        throw new HttpResponseException(statusLine.getStatusCode(),
                                statusLine.getReasonPhrase());
                    }
                    if (entity == null) {
                        throw new ClientProtocolException("Response contains no content");
                    }
                    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
                    try {
                        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
                        ContentType contentType = ContentType.getOrDefault(entity);
                        if (!contentType.equals(ContentType.APPLICATION_XML)) {
                            throw new ClientProtocolException("Unexpected content type:" + contentType);
                        }
                        Charset charset = contentType.getCharset();
                        if (charset == null) {
                            charset = Consts.ISO_8859_1;
                        }
                        return docBuilder.parse(entity.getContent(), charset.name());
                    } catch (ParserConfigurationException ex) {
                        throw new IllegalStateException(ex);
                    } catch (SAXException ex) {
                        throw new ClientProtocolException("Malformed XML document", ex);
                    }
                }

            });
    // Do something useful with the result
    System.out.println(result);
}

From source file:com.github.aliteralmind.codelet.examples.non_xbn.PrintJDBlocksStartStopLineNumsXmpl.java

/**
   <p>The main function.</p>
 *///from   w w  w .jav  a 2  s.c  om
public static final void main(String[] as_1RqdJavaSourcePath) {

    //Read command-line parameter
    String sJPath = null;
    try {
        sJPath = as_1RqdJavaSourcePath[0];
    } catch (ArrayIndexOutOfBoundsException aibx) {
        throw new NullPointerException(
                "Missing one-and-only required parameter: Path to java source-code file.");
    }
    System.out.println("Java source: " + sJPath);

    //Establish line-iterator
    Iterator<String> lineItr = null;
    try {
        lineItr = FileUtils.lineIterator(new File(sJPath)); //Throws npx if null
    } catch (IOException iox) {
        throw new RTIOException("PrintJDBlocksStartStopLinesXmpl", iox);
    }
    Pattern pTrmdJDBlockStart = Pattern.compile("^[\\t ]*/\\*\\*");

    String sDD = "..";
    int lineNum = 1;
    boolean bInJDBlock = false;
    while (lineItr.hasNext()) {
        String sLn = lineItr.next();
        if (!bInJDBlock) {
            if (pTrmdJDBlockStart.matcher(sLn).matches()) {
                bInJDBlock = true;
                System.out.print(lineNum + sDD);
            }
        } else if (sLn.indexOf("*/") != -1) {
            bInJDBlock = false;
            System.out.println(lineNum);
        }
        lineNum++;
    }
    if (bInJDBlock) {
        throw new IllegalStateException("Reach end of file. JavaDoc not closed.");
    }
}

From source file:com.leshazlewood.scms.cli.Main.java

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

    CommandLineParser parser = new PosixParser();

    Options options = new Options();
    options.addOption(CONFIG).addOption(DEBUG).addOption(HELP).addOption(VERSION);

    boolean debug = false;
    File sourceDir = toFile(System.getProperty("user.dir"));
    File configFile = null;//  w w w . j  a va 2s.c o m
    File destDir = null;

    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(VERSION.getOpt())) {
            printVersionAndExit();
        }
        if (line.hasOption(HELP.getOpt())) {
            printHelpAndExit(options, null, debug, 0);
        }
        if (line.hasOption(DEBUG.getOpt())) {
            debug = true;
        }
        if (line.hasOption(CONFIG.getOpt())) {
            String configFilePath = line.getOptionValue(CONFIG.getOpt());
            configFile = toFile(configFilePath);
        }

        String[] remainingArgs = line.getArgs();
        if (remainingArgs == null) {
            printHelpAndExit(options, null, debug, -1);
        }

        assert remainingArgs != null;

        if (remainingArgs.length == 1) {
            String workingDirPath = System.getProperty("user.dir");
            sourceDir = toFile(workingDirPath);
            destDir = toFile(remainingArgs[0]);
        } else if (remainingArgs.length == 2) {
            sourceDir = toFile(remainingArgs[0]);
            destDir = toFile((remainingArgs[1]));
        } else {
            printHelpAndExit(options, null, debug, -1);
        }

        assert sourceDir != null;
        assert destDir != null;

        if (configFile == null) {
            configFile = new File(sourceDir, DEFAULT_CONFIG_FILE_NAME);
        }

        if (configFile.exists()) {
            if (configFile.isDirectory()) {
                throw new IllegalArgumentException(
                        "Expected configuration file " + configFile + " is a directory, not a file.");
            }
        } else {
            String msg = "Configuration file not found.  Create a default " + DEFAULT_CONFIG_FILE_NAME
                    + " file in your source directory or specify the " + CONFIG
                    + " option to provide the file location.";
            throw new IllegalStateException(msg);
        }

        SiteExporter siteExporter = new SiteExporter();
        siteExporter.setSourceDir(sourceDir);
        siteExporter.setDestDir(destDir);
        siteExporter.setConfigFile(configFile);
        siteExporter.init();
        siteExporter.execute();

    } catch (IllegalArgumentException iae) {
        exit(iae, debug);
    } catch (IllegalStateException ise) {
        exit(ise, debug);
    } catch (Exception e) {
        printHelpAndExit(options, e, debug, -1);
    }
}

From source file:com.hortonworks.registries.storage.tool.shell.ShellMigrationInitializer.java

public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(Option.builder("s").numberOfArgs(1).longOpt(OPTION_SCRIPT_ROOT_PATH)
            .desc("Root directory of script path").build());

    options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH)
            .desc("Config file path").build());

    options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.MIGRATE.toString())
            .desc("Execute schema migration from last check point").build());

    options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.INFO.toString())
            .desc("Show the status of the schema migration compared to the target database").build());

    options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.VALIDATE.toString())
            .desc("Validate the target database changes with the migration scripts").build());

    options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.REPAIR.toString()).desc(
            "Repairs the SCRIPT_CHANGE_LOG by removing failed migrations and correcting checksum of existing migration script")
            .build());//  w w  w. j  a  v  a2  s  .  co m

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);

    if (!commandLine.hasOption(OPTION_SCRIPT_ROOT_PATH)) {
        usage(options);
        System.exit(1);
    }

    boolean isShellMigrationOptionSpecified = false;
    ShellMigrationOption shellMigrationOptionSpecified = null;
    for (ShellMigrationOption shellMigrationOption : ShellMigrationOption.values()) {
        if (commandLine.hasOption(shellMigrationOption.toString())) {
            if (isShellMigrationOptionSpecified) {
                System.out.println(
                        "Only one operation can be execute at once, please select one of ',migrate', 'validate', 'info', 'repair'.");
                System.exit(1);
            }
            isShellMigrationOptionSpecified = true;
            shellMigrationOptionSpecified = shellMigrationOption;
        }
    }

    if (!isShellMigrationOptionSpecified) {
        System.out.println(
                "One of the option 'migrate', 'validate', 'info', 'repair' must be specified to execute.");
        System.exit(1);
    }

    String scriptRootPath = commandLine.getOptionValue(OPTION_SCRIPT_ROOT_PATH);
    String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH);

    StorageProviderConfiguration storageProperties;
    try {
        Map<String, Object> conf = Utils.readConfig(confFilePath);

        StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader();
        storageProperties = confReader.readStorageConfig(conf);
    } catch (IOException e) {
        System.err.println("Error occurred while reading config file: " + confFilePath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    ShellMigrationHelper schemaMigrationHelper = new ShellMigrationHelper(
            ShellFlywayFactory.get(storageProperties, scriptRootPath));
    try {
        schemaMigrationHelper.execute(shellMigrationOptionSpecified);
        System.out.println(String.format("\"%s\" option successful", shellMigrationOptionSpecified.toString()));
    } catch (Exception e) {
        System.err.println(String.format("\"%s\" option failed : %s", shellMigrationOptionSpecified.toString(),
                e.getMessage()));
        System.exit(1);
    }

}

From source file:com.board.games.handler.modx.MODXPokerLoginServiceImpl.java

public static void main(String[] a) {

    Verifier verifier = new Verifier();

    String dbHash = "iDxLTbkejeeaQqpPoZTqUCJfWo1ALcBf7gMlYwwMa+Y="; //"dlgQ65ruCfeVVxqHJ3Bf02j50P0Wvis7WOoTfHYV3Nk=";
    String password = "rememberme";
    String dbSalt = "008747a35b77a4c7e55ab7ea8aec3ee0";
    PasswordResponse response = new PasswordResponse();
    String salt = "008747a35b77a4c7e55ab7ea8aec3ee0";
    response.setAlgorithm(Algorithm.PBKDF2);
    response.setSalt(salt);//from   ww  w.j a v a  2  s. c  o  m
    response.setAlgorithmDetails(new AlgorithmDetails());
    response.getAlgorithmDetails().setIterations(1000);
    response.getAlgorithmDetails().setHashFunction("SHA256");
    response.getAlgorithmDetails().setKeySize(263);
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 1000,
            response.getAlgorithmDetails().getKeySize());
    try {
        SecretKeyFactory skf = PBKDF2Algorithms.getSecretKeyFactory(
                "PBKDF2WithHmac" + response.getAlgorithmDetails().getHashFunction().replace("-", ""));
        byte[] hash = skf.generateSecret(spec).getEncoded();

        String encodedHash = Base64.encodeBase64String(hash);
        response.setHash(encodedHash);

        System.out.println("hash " + response.getHash());
        if (verifier.verify(password, response)) {
            // Check it against database stored hash
            if (encodedHash.equals(dbHash)) {
                System.out.println("Authentication Successful");
            } else {
                System.out.println("Authentication failed");
            }

        } else {
            System.out.println("failed verification of hashing");
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:io.aos.protocol.http.httpcommon.FluentResponseHandling.java

public static void main(String... args) throws Exception {
    Document result = Request.Get("http://somehost/content").execute()
            .handleResponse(new ResponseHandler<Document>() {

                public Document handleResponse(final HttpResponse response) throws IOException {
                    StatusLine statusLine = response.getStatusLine();
                    HttpEntity entity = response.getEntity();
                    if (statusLine.getStatusCode() >= 300) {
                        throw new HttpResponseException(statusLine.getStatusCode(),
                                statusLine.getReasonPhrase());
                    }/*ww w. jav a2s .  co  m*/
                    if (entity == null) {
                        throw new ClientProtocolException("Response contains no content");
                    }
                    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
                    try {
                        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
                        ContentType contentType = ContentType.getOrDefault(entity);
                        if (!contentType.equals(ContentType.APPLICATION_XML)) {
                            throw new ClientProtocolException("Unexpected content type:" + contentType);
                        }
                        Charset charset = contentType.getCharset();
                        if (charset == null) {
                            charset = HTTP.DEF_CONTENT_CHARSET;
                        }
                        return docBuilder.parse(entity.getContent(), charset.name());
                    } catch (ParserConfigurationException ex) {
                        throw new IllegalStateException(ex);
                    } catch (SAXException ex) {
                        throw new ClientProtocolException("Malformed XML document", ex);
                    }
                }

            });
    // Do something useful with the result
    System.out.println(result);
}

From source file:com.hortonworks.registries.storage.tool.TablesInitializer.java

public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(Option.builder("s").numberOfArgs(1).longOpt(OPTION_SCRIPT_ROOT_PATH)
            .desc("Root directory of script path").build());

    options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH)
            .desc("Config file path").build());

    options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH)
            .desc("Mysql client jar url to download").build());

    options.addOption(Option.builder().hasArg(false).longOpt(OPTION_EXECUTE_CREATE_TABLE)
            .desc("Execute 'create table' script").build());

    options.addOption(Option.builder().hasArg(false).longOpt(OPTION_EXECUTE_DROP_TABLE)
            .desc("Execute 'drop table' script").build());

    options.addOption(Option.builder().hasArg(false).longOpt(OPTION_EXECUTE_CHECK_CONNECTION)
            .desc("Check the connection for configured data source").build());

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);

    if (!commandLine.hasOption(OPTION_CONFIG_FILE_PATH) || !commandLine.hasOption(OPTION_SCRIPT_ROOT_PATH)) {
        usage(options);/*  w ww  .j a v a2s .  co  m*/
        System.exit(1);
    }

    // either create or drop should be specified, not both
    boolean executeCreate = commandLine.hasOption(OPTION_EXECUTE_CREATE_TABLE);
    boolean executeDrop = commandLine.hasOption(OPTION_EXECUTE_DROP_TABLE);
    boolean checkConnection = commandLine.hasOption(OPTION_EXECUTE_CHECK_CONNECTION);

    boolean moreThanOneOperationIsSpecified = executeCreate == executeDrop ? executeCreate : checkConnection;
    boolean noOperationSpecified = !(executeCreate || executeDrop || checkConnection);

    if (moreThanOneOperationIsSpecified) {
        System.out.println(
                "Only one operation can be execute at once, please select 'create' or 'drop', or 'check-connection'.");
        System.exit(1);
    } else if (noOperationSpecified) {
        System.out.println(
                "One of 'create', 'drop', 'check-connection' operation should be specified to execute.");
        System.exit(1);
    }

    String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH);
    String scriptRootPath = commandLine.getOptionValue(OPTION_SCRIPT_ROOT_PATH);
    String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH);

    StorageProviderConfiguration storageProperties;
    try {
        Map<String, Object> conf = Utils.readConfig(confFilePath);

        StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader();
        storageProperties = confReader.readStorageConfig(conf);
    } catch (IOException e) {
        System.err.println("Error occurred while reading config file: " + confFilePath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    String bootstrapDirPath = null;
    try {
        bootstrapDirPath = System.getProperty("bootstrap.dir");
        MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl);
    } catch (Exception e) {
        System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    try {
        SQLScriptRunner sqlScriptRunner = new SQLScriptRunner(storageProperties);

        try {
            sqlScriptRunner.initializeDriver();
        } catch (ClassNotFoundException e) {
            System.err.println(
                    "Driver class is not found in classpath. Please ensure that driver is in classpath.");
            System.exit(1);
        }

        if (checkConnection) {
            if (!sqlScriptRunner.checkConnection()) {
                System.exit(1);
            }
        } else if (executeDrop) {
            doExecuteDrop(sqlScriptRunner, storageProperties, scriptRootPath);
        } else {
            // executeCreate
            doExecuteCreate(sqlScriptRunner, storageProperties, scriptRootPath);
        }
    } catch (IOException e) {
        System.err.println("Error occurred while reading script file. Script root path: " + scriptRootPath);
        System.exit(1);
    }
}

From source file:com.hortonworks.registries.storage.tool.sql.DatabaseUserInitializer.java

public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH)
            .desc("Config file path").build());

    options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH)
            .desc("Mysql client jar url to download").build());

    options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_JDBC_URL)
            .desc("JDBC url to connect DBMS via admin.").build());

    options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_DB_USER)
            .desc("Admin user name: should be able to create and grant privileges.").build());

    options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_PASSWORD)
            .desc("Admin user's password: should be able to create and grant privileges.").build());

    options.addOption(//from   w  ww .j  a va 2 s  . co m
            Option.builder().hasArg().longOpt(OPTION_TARGET_USER).desc("Name of target user.").build());

    options.addOption(
            Option.builder().hasArg().longOpt(OPTION_TARGET_PASSWORD).desc("Password of target user.").build());

    options.addOption(
            Option.builder().hasArg().longOpt(OPTION_TARGET_DATABASE).desc("Target database.").build());

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);

    String[] neededOptions = { OPTION_CONFIG_FILE_PATH, OPTION_MYSQL_JAR_URL_PATH, OPTION_ADMIN_JDBC_URL,
            OPTION_ADMIN_DB_USER, OPTION_ADMIN_PASSWORD, OPTION_TARGET_USER, OPTION_TARGET_PASSWORD,
            OPTION_TARGET_DATABASE };

    boolean optNotFound = Arrays.stream(neededOptions).anyMatch(opt -> !commandLine.hasOption(opt));
    if (optNotFound) {
        usage(options);
        System.exit(1);
    }

    String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH);
    String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH);

    Optional<AdminOptions> adminOptionsOptional = AdminOptions.from(commandLine);
    if (!adminOptionsOptional.isPresent()) {
        usage(options);
        System.exit(1);
    }

    AdminOptions adminOptions = adminOptionsOptional.get();

    Optional<TargetOptions> targetOptionsOptional = TargetOptions.from(commandLine);
    if (!targetOptionsOptional.isPresent()) {
        usage(options);
        System.exit(1);
    }

    TargetOptions targetOptions = targetOptionsOptional.get();

    DatabaseType databaseType = findDatabaseType(adminOptions.getJdbcUrl());

    Map<String, Object> conf;
    try {
        conf = Utils.readConfig(confFilePath);
    } catch (IOException e) {
        System.err.println("Error occurred while reading config file: " + confFilePath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    String bootstrapDirPath = null;
    try {
        bootstrapDirPath = System.getProperty("bootstrap.dir");
        Proxy proxy = Proxy.NO_PROXY;
        String httpProxyUrl = (String) conf.get(HTTP_PROXY_URL);
        String httpProxyUsername = (String) conf.get(HTTP_PROXY_USERNAME);
        String httpProxyPassword = (String) conf.get(HTTP_PROXY_PASSWORD);
        if ((httpProxyUrl != null) && !httpProxyUrl.isEmpty()) {
            URL url = new URL(httpProxyUrl);
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort()));
            if ((httpProxyUsername != null) && !httpProxyUsername.isEmpty()) {
                Authenticator.setDefault(getBasicAuthenticator(url.getHost(), url.getPort(), httpProxyUsername,
                        httpProxyPassword));
            }
        }

        StorageProviderConfiguration storageProperties = StorageProviderConfiguration.get(
                adminOptions.getJdbcUrl(), adminOptions.getUsername(), adminOptions.getPassword(),
                adminOptions.getDatabaseType());

        MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl, proxy);
    } catch (Exception e) {
        System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    try (Connection conn = getConnectionViaAdmin(adminOptions)) {
        DatabaseCreator databaseCreator = DatabaseCreatorFactory.newInstance(adminOptions.getDatabaseType(),
                conn);
        UserCreator userCreator = UserCreatorFactory.newInstance(adminOptions.getDatabaseType(), conn);

        String database = targetOptions.getDatabase();
        String username = targetOptions.getUsername();

        createDatabase(databaseCreator, database);
        createUser(targetOptions, userCreator, username);
        grantPrivileges(databaseCreator, database, username);
    }
}