Example usage for java.lang RuntimeException RuntimeException

List of usage examples for java.lang RuntimeException RuntimeException

Introduction

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

Prototype

public RuntimeException(Throwable cause) 

Source Link

Document

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

Usage

From source file:hydrograph.server.execution.tracking.client.main.HydrographMain.java

/**
 * The main method./* ww  w.j  a va 2  s . c  om*/
 *
 * @param args
 *            the arguments
 * @throws Exception
 *             the exception
 */
public static void main(String[] args) throws Exception {

    HydrographMain hydrographMain = new HydrographMain();
    final Timer timer = new Timer();
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        Session session = null;
        boolean isExecutionTracking = false;
        String[] argsList = args;
        List<String> argumentList = new ArrayList<String>(Arrays.asList(args));
        final String jobId = hydrographMain.getJobId(argumentList);

        getLogLevel(argumentList).ifPresent(x -> {
            if (!x.equalsIgnoreCase(String.valueOf(logger.getLevel()))) {
                setLoglevel(x);
            } else {
                Optional.empty();
            }

        });

        logger.info("Argument List: " + argumentList.toString());

        String trackingClientSocketPort = hydrographMain.getTrackingClientSocketPort(argumentList);

        if (argumentList.contains(Constants.IS_TRACKING_ENABLE)) {
            int index = argumentList.indexOf(Constants.IS_TRACKING_ENABLE);
            isExecutionTracking = Boolean.valueOf(argsList[index + 1]);
            argumentList = removeItemFromIndex(index, argumentList);
        }

        if (argumentList.contains(Constants.TRACKING_CLIENT_SOCKET_PORT)) {
            int index = argumentList.indexOf(Constants.TRACKING_CLIENT_SOCKET_PORT);
            argumentList = removeItemFromIndex(index, argumentList);
        }

        argsList = argumentList.toArray(new String[argumentList.size()]);

        logger.debug("Execution tracking enabled - " + isExecutionTracking);
        logger.info("Tracking Client Port: " + trackingClientSocketPort);

        /**
         * Start new thread to run job
         */
        final HydrographService execution = new HydrographService();

        FutureTask task = hydrographMain.executeGraph(latch, jobId, argsList, execution, isExecutionTracking);

        hydrographMain.executorService = Executors.newSingleThreadExecutor();
        hydrographMain.executorService.submit(task);

        if (isExecutionTracking) {
            //If tracking is enabled, start to post execution tracking status.
            final HydrographEngineCommunicatorSocket socket = new HydrographEngineCommunicatorSocket(execution);
            session = hydrographMain.connectToServer(socket, jobId, trackingClientSocketPort);
            hydrographMain.sendExecutionTrackingStatus(latch, session, jobId, timer, execution, socket);
        }

        //waiting for execute graph thread 
        task.get();

    } catch (Exception exp) {
        logger.info("Getting exception from HydrographMain");
        throw new RuntimeException(exp);
    } finally {
        //cleanup threads --> executor thread and timer thread 
        logger.info("HydrographMain releasing resources");
        if (!hydrographMain.executorService.isShutdown() && !hydrographMain.executorService.isTerminated()) {
            hydrographMain.executorService.shutdown();
        }
        timer.cancel();

    }
}

From source file:com.linkedin.databus.bootstrap.utils.BootstrapDbControlMain.java

public static void main(String[] args) throws IOException, DatabusException, InstantiationException,
        IllegalAccessException, ClassNotFoundException, SQLException {
    Cli cli = new Cli("java " + BootstrapDbControlMain.class.getSimpleName() + " [options]");
    cli.processCommandLineArgs(args);//from   w ww.  ja v  a  2 s .c om

    Properties cfgProps = cli.getConfigProps();
    BootstrapConfig cfgBuilder = new BootstrapConfig();
    ConfigLoader<BootstrapReadOnlyConfig> configLoad = new ConfigLoader<BootstrapReadOnlyConfig>(
            "databus.bootstrap.", cfgBuilder);
    configLoad.loadConfig(cfgProps);

    BootstrapReadOnlyConfig cfg = cfgBuilder.build();
    BootstrapConn conn = new BootstrapConn();
    try {
        conn.initBootstrapConn(true, cfg.getBootstrapDBUsername(), cfg.getBootstrapDBPassword(),
                cfg.getBootstrapDBHostname(), cfg.getBootstrapDBName());
        BootstrapDBMetaDataDAO dao = new BootstrapDBMetaDataDAO(conn, cfg.getBootstrapDBHostname(),
                cfg.getBootstrapDBUsername(), cfg.getBootstrapDBPassword(), cfg.getBootstrapDBName(), false);
        switch (cli.getAction()) {
        case CREATE_LOG_TABLE:
            dao.createNewLogTable(cli.getSrcId());
            break;
        case CREATE_TAB_TABLE:
            dao.createNewSrcTable(cli.getSrcId());
            break;
        default:
            throw new RuntimeException("unknown action: " + cli.getAction());
        }
    } finally {
        conn.close();
    }
}

From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java

public static void main(String[] args) throws Exception {
    // Let's use some colors :)
    //        AnsiConsole.systemInstall();
    CommandLineParser cliParser = new BasicParser();
    CommandLine cli = null;// w w w.  j a  v  a2 s  .co  m
    try {
        cli = cliParser.parse(OPTIONS, args);
    } catch (ParseException e) {
        printHelp();
    }
    if (!cli.hasOption("s")) {
        printHelp();
    }

    String sourcePattern;
    if (cli.hasOption("p")) {
        sourcePattern = cli.getOptionValue("p");
    } else {
        sourcePattern = DEFAULT_SOURCE_PATTERN;
    }

    String defaultAnswer;
    if (cli.hasOption("default-answer")) {
        defaultAnswer = cli.getOptionValue("default-answer");
    } else {
        defaultAnswer = DEFAULT_DEFAULT_PROMPT_ANSWER;
    }

    boolean defaultAnswerYes = defaultAnswer.equalsIgnoreCase("y");
    boolean quiet = cli.hasOption("q");
    boolean testWrite = cli.hasOption("t");
    Path sourceDirectory = Paths.get(cli.getOptionValue("s")).toAbsolutePath();
    // Since we use IO we will have some blocking threads hanging around
    int threadCount = Runtime.getRuntime().availableProcessors() * 2;
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());
    BlockingQueue<WidgetVarLocation> foundUsages = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> unusedOrAmbiguous = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> skippedUsages = new LinkedBlockingQueue<>();
    List<Future<?>> futures = new ArrayList<>();

    findWidgetVars(sourceDirectory, sourcePattern, threadPool).forEach(widgetVarLocation -> {
        // We can't really find usages of widget vars that use EL expressions :(
        if (widgetVarLocation.widgetVar.contains("#")) {
            unusedOrAmbiguous.add(widgetVarLocation);
            return;
        }

        try {
            FileActionVisitor visitor = new FileActionVisitor(sourceDirectory, sourcePattern,
                    sourceFile -> futures.add(threadPool.submit((Callable<?>) () -> {
                        findWidgetVarUsages(sourceFile, widgetVarLocation, foundUsages, skippedUsages,
                                unusedOrAmbiguous);
                        return null;
                    })));

            Files.walkFileTree(sourceDirectory, visitor);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });

    awaitAll(futures);

    new TreeSet<>(skippedUsages).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped " + relativePath + " at line " + widgetUsage.lineNr + " and col "
                + widgetUsage.columnNr + " for widgetVar '" + widgetUsage.widgetVar + "'");
        System.out.println("\t" + previous);
    });

    Map<WidgetVarLocation, List<WidgetVarLocation>> written = new HashMap<>();

    new TreeSet<>(foundUsages).forEach(widgetUsage -> {
        WidgetVarLocation key = new WidgetVarLocation(null, widgetUsage.location, widgetUsage.lineNr, -1, null);
        List<WidgetVarLocation> writtenList = written.get(key);
        int existing = writtenList == null ? 0 : writtenList.size();
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String next = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED)
                .a("PF('" + widgetUsage.widgetVar + "')").reset().toString());
        System.out
                .println(relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + next);
        System.out.print("Replace (Y/N)? [" + (defaultAnswerYes ? "Y" : "N") + "]: ");

        String input;

        if (quiet) {
            input = "";
            System.out.println();
        } else {
            try {
                do {
                    input = in.readLine();
                } while (input != null && !input.isEmpty() && !"y".equalsIgnoreCase(input)
                        && !"n".equalsIgnoreCase(input));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        if (input == null) {
            System.out.println("Aborted!");
        } else if (input.isEmpty() && defaultAnswerYes || !input.isEmpty() && !"n".equalsIgnoreCase(input)) {
            System.out.println("Replaced!");
            System.out.print("\t");
            if (writtenList == null) {
                writtenList = new ArrayList<>();
                written.put(key, writtenList);
            }

            writtenList.add(widgetUsage);
            List<String> lines;
            try {
                lines = Files.readAllLines(widgetUsage.location);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

            try (OutputStream os = testWrite ? new ByteArrayOutputStream()
                    : Files.newOutputStream(widgetUsage.location);
                    PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
                String line;

                for (int i = 0; i < lines.size(); i++) {
                    int lineNr = i + 1;
                    line = lines.get(i);

                    if (lineNr == widgetUsage.lineNr) {
                        int begin = widgetUsage.columnNr + (testWrite ? 0 : existing * 6);
                        int end = begin + widgetUsage.widgetVar.length();
                        String newLine = replace(line, begin, end, "PF('" + widgetUsage.widgetVar + "')",
                                false);

                        if (testWrite) {
                            System.out.println(newLine);
                        } else {
                            pw.println(newLine);
                        }
                    } else {
                        if (!testWrite) {
                            pw.println(line);
                        }
                    }
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } else {
            System.out.println("Skipped!");
        }
    });

    new TreeSet<>(unusedOrAmbiguous).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped unused or ambiguous " + relativePath + " at line " + widgetUsage.lineNr
                + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + previous);
    });

    threadPool.shutdown();
}

From source file:com.act.lcms.CompareTwoNetCDFAroundMass.java

public static void main(String[] args) throws Exception {
    if (args.length < 5 || !areNCFiles(Arrays.copyOfRange(args, 3, args.length))) {
        throw new RuntimeException("Needs: \n" + "(1) mass value, e.g., 132.0772 for debugging, \n"
                + "(2) how many timepoints to process (-1 for all), \n"
                + "(3) prefix for .data and rendered .pdf \n" + "(4,5..) 2 or more NetCDF .nc files");
    }//from   w w w  . j av a 2s. c o  m

    String fmt = "pdf";
    Double mz = Double.parseDouble(args[0]);
    Integer numSpectraToProcess = Integer.parseInt(args[1]);
    String outPrefix = args[2];
    String outImg = outPrefix.equals("-") ? null : outPrefix + "." + fmt;
    String outData = outPrefix.equals("-") ? null : outPrefix + ".data";

    CompareTwoNetCDFAroundMass c = new CompareTwoNetCDFAroundMass();
    String[] netCDF_fnames = Arrays.copyOfRange(args, 3, args.length);
    List<List<Pair<Double, Double>>> spectra = c.getSpectraForMass(mz, netCDF_fnames, numSpectraToProcess);

    // Write data output to outfile
    PrintStream out = outData == null ? System.out : new PrintStream(new FileOutputStream(outData));

    // print out the spectra to outData
    for (List<Pair<Double, Double>> spectraInFile : spectra) {
        for (Pair<Double, Double> xy : spectraInFile) {
            out.format("%.4f\t%.4f\n", xy.getLeft(), xy.getRight());
            out.flush();
        }
        // delimit this dataset from the rest
        out.print("\n\n");
    }
    // find the ymax across all spectra, so that we can have a uniform y scale
    Double yrange = 0.0;
    for (List<Pair<Double, Double>> spectraInFile : spectra) {
        Double ymax = 0.0;
        for (Pair<Double, Double> xy : spectraInFile) {
            Double intensity = xy.getRight();
            if (ymax < intensity)
                ymax = intensity;
        }
        if (yrange < ymax)
            yrange = ymax;
    }

    if (outData != null) {
        // if outData is != null, then we have written to .data file
        // now render the .data to the corresponding .pdf file

        // first close the .data
        out.close();

        // render outData to outFILE using gnuplo
        Gnuplotter plotter = new Gnuplotter();
        plotter.plot2D(outData, outImg, netCDF_fnames, "time in seconds", yrange, "intensity", fmt);
    }
}

From source file:com.ibm.bi.dml.yarn.DMLAppMaster.java

/**
 * Main entrance for starting the SystemML app master.
 * /*from w w  w  . j a  va  2  s  .c  om*/
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    try {
        DMLAppMaster am = new DMLAppMaster();
        am.runApplicationMaster(args);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.datagator.tools.importer.Main.java

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

    int columnHeaders = 0; // cli input
    int rowHeaders = 0; // cli input

    try {/*from  www. j ava2  s  .c o  m*/
        CommandLine cmds = parser.parse(opts, args);
        if (cmds.hasOption("filter")) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
        if (cmds.hasOption("layout")) {
            String[] layout = cmds.getOptionValues("layout");
            if ((layout == null) || (layout.length != 2)) {
                throw new IllegalArgumentException("Bad layout.");
            }
            try {
                columnHeaders = Integer.valueOf(layout[0]);
                rowHeaders = Integer.valueOf(layout[1]);
                if ((columnHeaders < 0) || (rowHeaders < 0)) {
                    throw new IllegalArgumentException("Bad layout.");
                }
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException(ex);
            }
        }
        if (cmds.hasOption("help")) {
            help.printHelp("importer", opts, true);
            System.exit(EX_OK);
        }
        // positional arguments, i.e., input file name(s)
        args = cmds.getArgs();
    } catch (ParseException ex) {
        throw new IllegalArgumentException(ex);
    } catch (IllegalArgumentException ex) {
        help.printHelp("importer", opts, true);
        throw ex;
    }

    JsonGenerator jg = json.createGenerator(System.out, JsonEncoding.UTF8);
    jg.setPrettyPrinter(new StandardPrinter());

    final Extractor extractor;

    if (args.length == 1) {
        extractor = new FileExtractor(new File(args[0]));
    } else if (args.length > 1) {
        throw new UnsupportedOperationException("Not supported yet.");
    } else {
        throw new IllegalArgumentException("Missing input.");
    }

    int columnsCount = -1;
    int matrixCount = 0;

    ArrayDeque<String> stack = new ArrayDeque<String>();

    AtomType token = extractor.nextAtom();
    while (token != null) {
        switch (token) {
        case FLOAT:
        case INTEGER:
        case STRING:
        case NULL:
            jg.writeObject(extractor.getCurrentAtomData());
            break;
        case START_RECORD:
            jg.writeStartArray();
            break;
        case END_RECORD:
            int _numFields = (Integer) extractor.getCurrentAtomData();
            if (columnsCount < 0) {
                columnsCount = _numFields;
            } else if (columnsCount != _numFields) {
                throw new RuntimeException(String.format("row %s has different length than previous rows",
                        String.valueOf(_numFields - 1)));
            }
            jg.writeEndArray();
            break;
        case START_GROUP:
            stack.push(String.valueOf(extractor.getCurrentAtomData()));
            jg.writeStartObject();
            jg.writeStringField("kind", "datagator#Matrix");
            jg.writeNumberField("columnHeaders", columnHeaders);
            jg.writeNumberField("rowHeaders", rowHeaders);
            jg.writeFieldName("rows");
            jg.writeStartArray();
            break;
        case END_GROUP:
            int rowsCount = (Integer) extractor.getCurrentAtomData();
            if (rowsCount == 0) {
                jg.writeStartArray();
                jg.writeEndArray();
                rowsCount = 1;
                columnsCount = 0;
            }
            jg.writeEndArray();
            jg.writeNumberField("rowsCount", rowsCount);
            jg.writeNumberField("columnsCount", columnsCount);
            jg.writeEndObject();
            matrixCount += 1;
            stack.pop();
            break;
        default:
            break;
        }
        token = extractor.nextAtom();
    }

    jg.close();

    System.exit(EX_OK);
}

From source file:com.xiaoxiaomo.flink.batch.distcp.DistCp.java

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

    // set up the execution environment
    final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

    ParameterTool params = ParameterTool.fromArgs(args);
    if (!params.has("input") || !params.has("output")) {
        System.err.println("Usage: --input <path> --output <path> [--parallelism <n>]");
        return;//w w  w.j  a  va 2s  .c o m
    }

    final Path sourcePath = new Path(params.get("input"));
    final Path targetPath = new Path(params.get("output"));
    if (!isLocal(env) && !(isOnDistributedFS(sourcePath) && isOnDistributedFS(targetPath))) {
        System.out.println("In a distributed mode only HDFS input/output paths are supported");
        return;
    }

    final int parallelism = params.getInt("parallelism", 10);
    if (parallelism <= 0) {
        System.err.println("Parallelism should be greater than 0");
        return;
    }

    // make parameters available in the web interface
    env.getConfig().setGlobalJobParameters(params);

    env.setParallelism(parallelism);

    long startTime = System.currentTimeMillis();
    LOGGER.info("Initializing copy tasks");
    List<FileCopyTask> tasks = getCopyTasks(sourcePath);
    LOGGER.info("Copy task initialization took " + (System.currentTimeMillis() - startTime) + "ms");

    DataSet<FileCopyTask> inputTasks = new DataSource<FileCopyTask>(env, new FileCopyTaskInputFormat(tasks),
            new GenericTypeInfo<FileCopyTask>(FileCopyTask.class), "fileCopyTasks");

    FlatMapOperator<FileCopyTask, Object> res = inputTasks
            .flatMap(new RichFlatMapFunction<FileCopyTask, Object>() {

                private static final long serialVersionUID = 1109254230243989929L;
                private LongCounter fileCounter;
                private LongCounter bytesCounter;

                @Override
                public void open(Configuration parameters) throws Exception {
                    bytesCounter = getRuntimeContext().getLongCounter(BYTES_COPIED_CNT_NAME);
                    fileCounter = getRuntimeContext().getLongCounter(FILES_COPIED_CNT_NAME);
                }

                @Override
                public void flatMap(FileCopyTask task, Collector<Object> out) throws Exception {
                    LOGGER.info("Processing task: " + task);
                    Path outPath = new Path(targetPath, task.getRelativePath());

                    FileSystem targetFs = targetPath.getFileSystem();
                    // creating parent folders in case of a local FS
                    if (!targetFs.isDistributedFS()) {
                        //dealing with cases like file:///tmp or just /tmp
                        File outFile = outPath.toUri().isAbsolute() ? new File(outPath.toUri())
                                : new File(outPath.toString());
                        File parentFile = outFile.getParentFile();
                        if (!parentFile.mkdirs() && !parentFile.exists()) {
                            throw new RuntimeException(
                                    "Cannot create local file system directories: " + parentFile);
                        }
                    }
                    FSDataOutputStream outputStream = null;
                    FSDataInputStream inputStream = null;
                    try {
                        outputStream = targetFs.create(outPath, true);
                        inputStream = task.getPath().getFileSystem().open(task.getPath());
                        int bytes = IOUtils.copy(inputStream, outputStream);
                        bytesCounter.add(bytes);
                    } finally {
                        IOUtils.closeQuietly(inputStream);
                        IOUtils.closeQuietly(outputStream);
                    }
                    fileCounter.add(1L);
                }
            });

    // no data sinks are needed, therefore just printing an empty result
    res.print();

    Map<String, Object> accumulators = env.getLastJobExecutionResult().getAllAccumulatorResults();
    LOGGER.info("== COUNTERS ==");
    for (Map.Entry<String, Object> e : accumulators.entrySet()) {
        LOGGER.info(e.getKey() + ": " + e.getValue());
    }
}

From source file:com.openteach.diamond.network.waverider.command.Command.java

public static void main(String[] args) {

    ByteArrayOutputStream bout = null;
    ObjectOutputStream objOutputStream = null;

    try {/*from ww w .  jav a 2s.c o m*/
        bout = new ByteArrayOutputStream();
        objOutputStream = new ObjectOutputStream(bout);
        SlaveState slaveState = new SlaveState();
        slaveState.setId(1L);
        slaveState.setIsMasterCandidate(false);
        objOutputStream.writeObject(slaveState);
        objOutputStream.flush();
        Command command = CommandFactory.createHeartbeatCommand(ByteBuffer.wrap(bout.toByteArray()));

        ByteBuffer buffer = command.marshall();
        Command cmd = Command.unmarshall(buffer);
        SlaveState ss = SlaveState.fromByteBuffer(cmd.getPayLoad());
        System.out.println(cmd.toString());
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (objOutputStream != null) {
                objOutputStream.close();
            }
            if (bout != null) {
                bout.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.ibm.watson.app.qaclassifier.tools.PopulateAnswerStore.java

public static void main(String[] args) throws Exception {
    Option urlOption = createOption(URL_OPTION, URL_OPTION_LONG, true,
            "The root URL of the application to connect to. If omitted, the default will be used ("
                    + DEFAULT_URL + ")",
            false, URL_OPTION_LONG);
    Option fileOption = createOption(FILE_OPTION, FILE_OPTION_LONG, true,
            "The file to be used to populate the answers, can point to the file system or the class path", true,
            FILE_OPTION_LONG);/*w w w .j a va 2  s  .c o m*/
    Option dirOption = createOption(DIR_OPTION, DIR_OPTION_LONG, true,
            "The directory containing the html answer files, can point to the file system or the class path",
            true, DIR_OPTION_LONG);
    Option userOption = createOption(USER_OPTION, USER_OPTION_LONG, true, "The username for the manage API",
            true, USER_OPTION_LONG);
    Option passwordOption = createOption(PASSWORD_OPTION, PASSWORD_OPTION_LONG, true,
            "The password for the manage API", true, PASSWORD_OPTION_LONG);

    final Options options = buildOptions(urlOption, fileOption, dirOption, userOption, passwordOption);

    CommandLine cmd;
    try {
        CommandLineParser parser = new GnuParser();
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(MessageKey.AQWQAC24008E_could_not_parse_cmd_line_args_1.getMessage(e.getMessage())
                .getFormattedMessage());

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(120, "java " + PopulateAnswerStore.class.getName(), null, options, null);
        return;
    }

    final String url = cmd.getOptionValue(URL_OPTION, DEFAULT_URL);
    final String file = cmd.getOptionValue(FILE_OPTION);
    final String dir = cmd.getOptionValue(DIR_OPTION);
    final String user = cmd.getOptionValue(USER_OPTION);
    final String password = cmd.getOptionValue(PASSWORD_OPTION);

    System.out.println(MessageKey.AQWQAC20002I_checking_answer_store_at_url_2.getMessage(url, DEFAULT_ENDPOINT)
            .getFormattedMessage());

    try {
        AnswerStoreRestClient client = new AnswerStoreRestClient(url, user, password);

        // we only want to populate if there is nothing in the database already
        // start with the assumption that we do want to populate and stop if we find answers in there already
        boolean doPopulate = true;
        String answersResult = getAnswers(client);
        if (answersResult != null && !answersResult.isEmpty()) {
            Gson gson = new Gson();
            Type type = new TypeToken<List<ManagedAnswer>>() {
            }.getType();
            List<ManagedAnswer> answers = gson.fromJson(answersResult, type);
            if (answers != null && answers.size() > 0) {
                System.out.println(MessageKey.AQWQAC20006I_found_answers_in_stop_1.getMessage(answers.size())
                        .getFormattedMessage());
                doPopulate = false;
            }
        }

        if (doPopulate) {
            System.out.println(MessageKey.AQWQAC20003I_populating_answer_store_at_url_2
                    .getMessage(url, DEFAULT_ENDPOINT).getFormattedMessage());
            boolean success = populate(client, file, dir);
            if (!success) {
                throw new RuntimeException(MessageKey.AQWQAC24005E_error_populating_answer_store.getMessage()
                        .getFormattedMessage());
            }
        } else {
            System.out.println(MessageKey.AQWQAC20001I_answer_store_already_populated_doing_nothing.getMessage()
                    .getFormattedMessage());
        }

        System.out.println(MessageKey.AQWQAC20005I_done_population_answers.getMessage().getFormattedMessage());
    } catch (IOException e) {
        System.err.println(MessageKey.AQWQAC24007E_error_populating_answer_store_1.getMessage(e.getMessage())
                .getFormattedMessage());
        e.printStackTrace(System.err);
    }
}

From source file:de.codesourcery.eve.skills.ui.Main.java

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

    setLookAndFeel();//from  w ww .java2  s .  c  om

    SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            try {
                SpringUtil.getInstance().getMain().startUp();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    });
}