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:com.archivas.clienttools.arcmover.cli.ManagedCLIJob.java

@SuppressWarnings({ "UseOfSystemOutOrSystemErr" })
public static void main(String args[]) {
    if (LOG.isLoggable(Level.FINE)) {
        StringBuffer sb = new StringBuffer();
        sb.append("Program Arguments").append(NEWLINE);
        for (int i = 0; i < args.length; i++) {
            sb.append("    ").append(i).append(": ").append(args[i]);
            sb.append(NEWLINE);//from   w  ww  .  java  2 s.  c  om
        }
        LOG.log(Level.FINE, sb.toString());
    }

    ConfigurationHelper.validateLaunchOK();

    ManagedCLIJob arcCmd = null;
    try {
        if (args[0].equals("copy")) {
            arcCmd = new ArcCopy(args, 2);
        } else if (args[0].equals("delete")) {
            arcCmd = new ArcDelete(args, 2);
        } else if (args[0].equals("metadata")) {
            arcCmd = new ArcMetadata(args, 2);
        } else {
            throw new RuntimeException("Unsupported operation: " + args[0]);
        }

        arcCmd.parseArgs();

        if (arcCmd.shouldPrintHelp()) {
            System.out.println(arcCmd.helpScreen());
        } else {
            arcCmd.execute(new PrintWriter(System.out), new PrintWriter(System.err));
        }
    } catch (ParseException e) {
        System.out.println("Error: " + e.getMessage());
        System.out.println();
        System.out.println(arcCmd.helpScreen());
        arcCmd.setExitCode(EXIT_CODE_OPTION_PARSE_ERROR);
    } catch (Exception e) {
        LOG.log(Level.SEVERE, e.getMessage(), e);
        System.out.println();
        System.err.println("Job failed.  " + e.getMessage());
        if (arcCmd != null) {
            arcCmd.setExitCode(EXIT_CODE_DM_ERROR);
        }
    } finally {
        if (arcCmd != null) {
            arcCmd.exit();
        }
    }
}

From source file:com.joliciel.jochre.search.JochreSearch.java

/**
 * @param args/*from ww w  . j av a 2  s  . c  o  m*/
 */
public static void main(String[] args) {
    try {
        Map<String, String> argMap = new HashMap<String, String>();

        for (String arg : args) {
            int equalsPos = arg.indexOf('=');
            String argName = arg.substring(0, equalsPos);
            String argValue = arg.substring(equalsPos + 1);
            argMap.put(argName, argValue);
        }

        String command = argMap.get("command");
        argMap.remove("command");

        String logConfigPath = argMap.get("logConfigFile");
        if (logConfigPath != null) {
            argMap.remove("logConfigFile");
            Properties props = new Properties();
            props.load(new FileInputStream(logConfigPath));
            PropertyConfigurator.configure(props);
        }

        LOG.debug("##### Arguments:");
        for (Entry<String, String> arg : argMap.entrySet()) {
            LOG.debug(arg.getKey() + ": " + arg.getValue());
        }

        SearchServiceLocator locator = SearchServiceLocator.getInstance();
        SearchService searchService = locator.getSearchService();

        if (command.equals("buildIndex")) {
            String indexDirPath = argMap.get("indexDir");
            String documentDirPath = argMap.get("documentDir");
            File indexDir = new File(indexDirPath);
            indexDir.mkdirs();
            File documentDir = new File(documentDirPath);

            JochreIndexBuilder builder = searchService.getJochreIndexBuilder(indexDir);
            builder.updateDocument(documentDir);
        } else if (command.equals("updateIndex")) {
            String indexDirPath = argMap.get("indexDir");
            String documentDirPath = argMap.get("documentDir");
            boolean forceUpdate = false;
            if (argMap.containsKey("forceUpdate")) {
                forceUpdate = argMap.get("forceUpdate").equals("true");
            }
            File indexDir = new File(indexDirPath);
            indexDir.mkdirs();
            File documentDir = new File(documentDirPath);

            JochreIndexBuilder builder = searchService.getJochreIndexBuilder(indexDir);
            builder.updateIndex(documentDir, forceUpdate);
        } else if (command.equals("search")) {
            HighlightServiceLocator highlightServiceLocator = HighlightServiceLocator.getInstance(locator);
            HighlightService highlightService = highlightServiceLocator.getHighlightService();

            String indexDirPath = argMap.get("indexDir");
            File indexDir = new File(indexDirPath);
            JochreQuery query = searchService.getJochreQuery(argMap);

            JochreIndexSearcher searcher = searchService.getJochreIndexSearcher(indexDir);
            TopDocs topDocs = searcher.search(query);

            Set<Integer> docIds = new LinkedHashSet<Integer>();
            for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
                docIds.add(scoreDoc.doc);
            }
            Set<String> fields = new HashSet<String>();
            fields.add("text");

            Highlighter highlighter = highlightService.getHighlighter(query, searcher.getIndexSearcher());
            HighlightManager highlightManager = highlightService
                    .getHighlightManager(searcher.getIndexSearcher());
            highlightManager.setDecimalPlaces(query.getDecimalPlaces());
            highlightManager.setMinWeight(0.0);
            highlightManager.setIncludeText(true);
            highlightManager.setIncludeGraphics(true);

            Writer out = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8));
            if (command.equals("highlight")) {
                highlightManager.highlight(highlighter, docIds, fields, out);
            } else {
                highlightManager.findSnippets(highlighter, docIds, fields, out);
            }
        } else {
            throw new RuntimeException("Unknown command: " + command);
        }
    } catch (RuntimeException e) {
        LogUtils.logError(LOG, e);
        throw e;
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:alluxio.cli.MiniBenchmark.java

/**
 * @param args there are no arguments needed
 * @throws Exception if error occurs during tests
 *//*from  ww  w .  j  a  v  a 2  s. c  o  m*/
public static void main(String[] args) throws Exception {
    if (!parseInputArgs(args)) {
        usage();
        System.exit(-1);
    }
    if (sHelp) {
        usage();
        System.exit(0);
    }

    CommonUtils.warmUpLoop();

    for (int i = 0; i < sIterations; ++i) {
        final AtomicInteger count = new AtomicInteger(0);
        final CyclicBarrier barrier = new CyclicBarrier(sConcurrency);
        ExecutorService executorService = Executors.newFixedThreadPool(sConcurrency);
        final AtomicLong runtime = new AtomicLong(0);
        for (int j = 0; j < sConcurrency; ++j) {
            switch (sType) {
            case READ:
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            readFile(barrier, runtime, count.addAndGet(1));
                        } catch (Exception e) {
                            LOG.error("Failed to read file.", e);
                            System.exit(-1);
                        }
                    }
                });
                break;
            case WRITE:
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            writeFile(barrier, runtime, count.addAndGet(1));
                        } catch (Exception e) {
                            LOG.error("Failed to write file.", e);
                            System.exit(-1);
                        }
                    }
                });
                break;
            default:
                throw new RuntimeException("Unsupported type.");
            }
        }
        executorService.shutdown();
        Preconditions.checkState(executorService.awaitTermination(1, TimeUnit.HOURS));
        double time = runtime.get() * 1.0 / sConcurrency / Constants.SECOND_NANO;
        System.out.printf("Iteration: %d; Duration: %f seconds; Aggregated throughput: %f GB/second.%n", i,
                time, sConcurrency * 1.0 * sFileSize / time / Constants.GB);
    }
}

From source file:com.yahoo.pasc.paxos.server.PaxosServer.java

/**
 * @param args/*w  w w . j a  va 2s .  co  m*/
 * @throws NoSuchFieldException
 * @throws SecurityException
 * @throws IOException 
 * @throws MalformedURLException
 */
public static void main(String[] args) throws SecurityException, NoSuchFieldException, IOException {

    CommandLineParser parser = new PosixParser();
    Options options;

    {
        Option id = new Option("i", true, "client id");
        Option port = new Option("p", true, "port used by server");
        Option buffer = new Option("b", true, "number of batched messages");
        //            Option clients      = new Option("c", true, "clients (hostname:port,...)");
        Option servers = new Option("s", true, "servers (hostname:port,...)");
        Option maxInstances = new Option("m", true, "max number of instances");
        Option anm = new Option("a", false, "protection against ANM faults");
        Option udp = new Option("u", false, "use UDP");
        Option cWindow = new Option("w", true, "congestion window");
        Option threads = new Option("t", true, "number of threads");
        Option digests = new Option("d", true, "max digests");
        Option ckPeriod = new Option("k", true, "checkpointing period");
        Option inlineThresh = new Option("n", true, "threshold for sending requests iNline with accepts ");
        Option twoStages = new Option("2", false, "2 stages");
        Option digestQuorum = new Option("q", true, "digest quorum");
        Option leaderReplies = new Option("r", false, "leader replies");
        Option zookeeper = new Option("z", true, "zookeeper connection string");

        options = new Options();
        options.addOption(id).addOption(port).addOption(buffer).addOption(servers).addOption(threads)
                .addOption(anm).addOption(udp).addOption(maxInstances) //.addOption(leader)
                .addOption(cWindow).addOption(digests).addOption(ckPeriod).addOption(inlineThresh)
                .addOption(twoStages).addOption(digestQuorum).addOption(leaderReplies).addOption(zookeeper);
    }

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

        String serverAddresses[] = line.hasOption('s') ? line.getOptionValue('s').split(",")
                : new String[] { "10.78.36.104:20548", "10.78.36.104:20748" };
        //            String clientAddresses[] = line.hasOption('c') ? line.getOptionValue('c').split(",") : new String[] { "localhost:9000" };
        String zookeeper = line.hasOption('z') ? line.getOptionValue('z') : "localhost:2181";
        int serverId = line.hasOption('i') ? Integer.parseInt(line.getOptionValue('i')) : 0;
        int batchSize = line.hasOption('b') ? Integer.parseInt(line.getOptionValue('b')) : 1;
        int port = line.hasOption('p') ? Integer.parseInt(line.getOptionValue('p')) : 20548;
        int maxInstances = line.hasOption('m') ? Integer.parseInt(line.getOptionValue('m')) : 16 * 1024;
        int congestionWindow = line.hasOption('w') ? Integer.parseInt(line.getOptionValue('w')) : 1;
        int digests = line.hasOption('d') ? Integer.parseInt(line.getOptionValue('d')) : 16;
        int inlineThreshold = line.hasOption('n') ? Integer.parseInt(line.getOptionValue('n')) : 1000;
        boolean protection = line.hasOption('a');
        boolean udp = line.hasOption('u');
        boolean twoStages = line.hasOption('2');
        int quorum = serverAddresses.length / 2 + 1;
        int digestQuorum = line.hasOption('q') ? Integer.parseInt(line.getOptionValue('q')) : quorum;
        int threads = line.hasOption('t') ? Integer.parseInt(line.getOptionValue('t'))
                : Runtime.getRuntime().availableProcessors() * 2 + 1;

        if (batchSize <= 0) {
            throw new RuntimeException("BatchSize must be greater than 0");
        }

        PaxosState state = new PaxosState(maxInstances, batchSize, serverId, quorum, digestQuorum,
                serverAddresses.length, congestionWindow, digests);
        if (line.hasOption('k'))
            state.setCheckpointPeriod(Integer.parseInt(line.getOptionValue('k')));
        if (line.hasOption('r'))
            state.setLeaderReplies(true);
        state.setRequestThreshold(inlineThreshold);

        if (!protection) {
            System.out.println("PANM disabled!");
        }

        final PascRuntime<PaxosState> runtime = new PascRuntime<PaxosState>(protection);
        runtime.setState(state);
        runtime.addHandler(Accept.class, new AcceptorAccept());
        runtime.addHandler(Prepare.class, new AcceptorPrepare());
        runtime.addHandler(Accepted.class, new Learner());
        runtime.addHandler(Prepared.class, new ProposerPrepared());
        runtime.addHandler(Request.class, new ProposerRequest());
        runtime.addHandler(InlineRequest.class, new ProposerRequest());
        runtime.addHandler(Digest.class, new DigestHandler());
        runtime.addHandler(PreReply.class, new LearnerPreReply());
        runtime.addHandler(Leader.class, new LeadershipHandler());

        if (udp) {
            new UdpServer(runtime, serverAddresses, null, port, threads, serverId).run();
        } else {
            new TcpServer(runtime, new EmptyStateMachine(), null, zookeeper, serverAddresses, port, threads,
                    serverId, twoStages).run();
        }
    } catch (Exception e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Paxos", options);

        System.err.println("Unexpected exception: " + e);
        e.printStackTrace();

        System.exit(-1);
    }
}

From source file:edu.ksu.cis.indus.staticanalyses.concurrency.escape.EscapeAndReadWriteCLI.java

/**
 * The entry point to this class./*from w  ww .  j a  v a 2s.c  o  m*/
 * 
 * @param args command line arguments.
 * @throws RuntimeException when escape information and side-effect information calculation fails.
 */
public static void main(final String[] args) {
    final Options _options = new Options();
    Option _option = new Option("h", "help", false, "Display message.");
    _option.setOptionalArg(false);
    _options.addOption(_option);
    _option = new Option("p", "soot-classpath", false, "Prepend this to soot class path.");
    _option.setArgs(1);
    _option.setArgName("classpath");
    _option.setOptionalArg(false);
    _options.addOption(_option);
    _option = new Option("S", "scope", true, "The scope that should be analyzed.");
    _option.setArgs(1);
    _option.setArgName("scope");
    _option.setRequired(false);
    _options.addOption(_option);

    final CommandLineParser _parser = new GnuParser();

    try {
        final CommandLine _cl = _parser.parse(_options, args);

        if (_cl.hasOption("h")) {
            final String _cmdLineSyn = "java " + EscapeAndReadWriteCLI.class.getName()
                    + " <options> <classnames>";
            (new HelpFormatter()).printHelp(_cmdLineSyn, _options);
            System.exit(1);
        }

        if (_cl.getArgList().isEmpty()) {
            throw new MissingArgumentException("Please specify atleast one class.");
        }

        final EscapeAndReadWriteCLI _cli = new EscapeAndReadWriteCLI();

        if (_cl.hasOption('p')) {
            _cli.addToSootClassPath(_cl.getOptionValue('p'));
        }

        if (_cl.hasOption('S')) {
            _cli.setScopeSpecFile(_cl.getOptionValue('S'));
        }
        _cli.setClassNames(_cl.getArgList());
        _cli.<ITokens>execute();
    } catch (final ParseException _e) {
        LOGGER.error("Error while parsing command line.", _e);
        System.out.println("Error while parsing command line." + _e);
        final String _cmdLineSyn = "java " + EscapeAndReadWriteCLI.class.getName() + " <options> <classnames>";
        (new HelpFormatter()).printHelp(_cmdLineSyn, "Options are:", _options, "");
    } catch (final Throwable _e) {
        LOGGER.error("Beyond our control. May day! May day!", _e);
        throw new RuntimeException(_e);
    }
}

From source file:edu.ksu.cis.indus.staticanalyses.concurrency.DeadlockAnalysisCLI.java

/**
 * The entry point to this class./*from w  ww . j a  v  a 2 s .  c  o m*/
 * 
 * @param args command line arguments.
 * @throws RuntimeException when escape information and side-effect information calculation fails.
 */
public static void main(final String[] args) {
    final Options _options = new Options();
    Option _option = new Option("h", "help", false, "Display message.");
    _option.setOptionalArg(false);
    _options.addOption(_option);
    _option = new Option("p", "soot-classpath", false, "Prepend this to soot class path.");
    _option.setArgs(1);
    _option.setArgName("classpath");
    _option.setOptionalArg(false);
    _options.addOption(_option);
    _option = new Option("S", "scope", true, "The scope that should be analyzed.");
    _option.setArgs(1);
    _option.setArgName("scope");
    _option.setRequired(false);
    _options.addOption(_option);

    final CommandLineParser _parser = new GnuParser();

    try {
        final CommandLine _cl = _parser.parse(_options, args);

        if (_cl.hasOption("h")) {
            final String _cmdLineSyn = "java " + DeadlockAnalysisCLI.class.getName()
                    + " <options> <classnames>";
            (new HelpFormatter()).printHelp(_cmdLineSyn, _options);
            System.exit(1);
        }

        if (_cl.getArgList().isEmpty()) {
            throw new MissingArgumentException("Please specify atleast one class.");
        }

        final DeadlockAnalysisCLI _cli = new DeadlockAnalysisCLI();

        if (_cl.hasOption('p')) {
            _cli.addToSootClassPath(_cl.getOptionValue('p'));
        }

        if (_cl.hasOption('S')) {
            _cli.setScopeSpecFile(_cl.getOptionValue('S'));
        }
        _cli.setClassNames(_cl.getArgList());
        _cli.<ITokens>execute();
    } catch (final ParseException _e) {
        LOGGER.error("Error while parsing command line.", _e);
        System.out.println("Error while parsing command line." + _e);
        final String _cmdLineSyn = "java " + DeadlockAnalysisCLI.class.getName() + " <options> <classnames>";
        (new HelpFormatter()).printHelp(_cmdLineSyn, "Options are:", _options, "");
    } catch (final Throwable _e) {
        LOGGER.error("Beyond our control. May day! May day!", _e);
        throw new RuntimeException(_e);
    }
}

From source file:digital.test.Dlg_test.java

public static void main(String args[]) {

    try {//from   ww w. j  a va  2  s  . co m
        javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    Dlg_test dialog = Dlg_test.create(new javax.swing.JFrame(), true);
    dialog.setVisible(true);

}

From source file:com.act.utils.parser.UniprotInterpreter.java

public static void main(String[] args)
        throws ParserConfigurationException, IOException, SAXException, CompoundNotFoundException {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//w  w  w.j  a v  a 2s.  com
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        LOGGER.error("Argument parsing failed: %s", e.getMessage());
        HELP_FORMATTER.printHelp(UniprotInterpreter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(UniprotInterpreter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    File uniprotFile = new File(cl.getOptionValue(OPTION_UNIPROT_PATH));

    if (!uniprotFile.exists()) {
        String msg = "Uniprot file path is null";
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    } else {
        UniprotInterpreter reader = new UniprotInterpreter(uniprotFile);
        reader.init();
    }
}

From source file:com.github.ansell.shp.SHPDump.java

public static void main(String... args) throws Exception {
    final OptionParser parser = new OptionParser();

    final OptionSpec<Void> help = parser.accepts("help").forHelp();
    final OptionSpec<File> input = parser.accepts("input").withRequiredArg().ofType(File.class).required()
            .describedAs("The input SHP file");
    final OptionSpec<File> output = parser.accepts("output").withRequiredArg().ofType(File.class).required()
            .describedAs("The output directory to use for debugging files");
    final OptionSpec<String> outputPrefix = parser.accepts("prefix").withRequiredArg().ofType(String.class)
            .defaultsTo("shp-debug").describedAs("The output prefix to use for debugging files");
    final OptionSpec<File> outputMappingTemplate = parser.accepts("output-mapping").withRequiredArg()
            .ofType(File.class).describedAs("The output mapping template file if it needs to be generated.");
    final OptionSpec<Integer> resolution = parser.accepts("resolution").withRequiredArg().ofType(Integer.class)
            .defaultsTo(2048).describedAs("The output image file resolution");
    final OptionSpec<String> format = parser.accepts("format").withRequiredArg().ofType(String.class)
            .defaultsTo("png").describedAs("The output image format");
    final OptionSpec<String> removeIfEmpty = parser.accepts("remove-if-empty").withRequiredArg()
            .ofType(String.class).describedAs(
                    "The name of an attribute to remove if its value is empty before outputting the resulting shapefile. Use multiple times to specify multiple fields to check");

    OptionSet options = null;//from   www.ja v a2  s. c  o  m

    try {
        options = parser.parse(args);
    } catch (final OptionException e) {
        System.out.println(e.getMessage());
        parser.printHelpOn(System.out);
        throw e;
    }

    if (options.has(help)) {
        parser.printHelpOn(System.out);
        return;
    }

    final Path inputPath = input.value(options).toPath();
    if (!Files.exists(inputPath)) {
        throw new FileNotFoundException("Could not find input SHP file: " + inputPath.toString());
    }

    final Path outputPath = output.value(options).toPath();
    if (!Files.exists(outputPath)) {
        throw new FileNotFoundException("Output directory does not exist: " + outputPath.toString());
    }

    final Path outputMappingPath = options.has(outputMappingTemplate)
            ? outputMappingTemplate.value(options).toPath()
            : null;
    if (options.has(outputMappingTemplate) && Files.exists(outputMappingPath)) {
        throw new FileNotFoundException(
                "Output mapping template file already exists: " + outputMappingPath.toString());
    }

    final Set<String> filterFields = ConcurrentHashMap.newKeySet();
    if (options.has(removeIfEmpty)) {
        for (String nextFilterField : removeIfEmpty.values(options)) {
            System.out.println("Will filter field if empty value found: " + nextFilterField);
            filterFields.add(nextFilterField);
        }
    }

    if (!filterFields.isEmpty()) {
        System.out.println("Full set of filter fields: " + filterFields);
    }

    final String prefix = outputPrefix.value(options);

    FileDataStore store = FileDataStoreFinder.getDataStore(inputPath.toFile());

    if (store == null) {
        throw new RuntimeException("Could not read the given input as an ESRI Shapefile: "
                + inputPath.toAbsolutePath().toString());
    }

    for (String typeName : new LinkedHashSet<>(Arrays.asList(store.getTypeNames()))) {
        System.out.println("");
        System.out.println("Type: " + typeName);
        SimpleFeatureSource featureSource = store.getFeatureSource(typeName);
        SimpleFeatureType schema = featureSource.getSchema();

        Name outputSchemaName = new NameImpl(schema.getName().getNamespaceURI(),
                schema.getName().getLocalPart().replace(" ", "").replace("%20", ""));
        System.out.println("Replacing name on schema: " + schema.getName() + " with " + outputSchemaName);
        SimpleFeatureType outputSchema = SHPUtils.changeSchemaName(schema, outputSchemaName);

        List<String> attributeList = new ArrayList<>();
        for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) {
            System.out.println("Attribute: " + attribute.getName().toString());
            attributeList.add(attribute.getName().toString());
        }
        CsvSchema csvSchema = CSVUtil.buildSchema(attributeList);

        SimpleFeatureCollection collection = featureSource.getFeatures();
        int featureCount = 0;
        Path nextCSVFile = outputPath.resolve(prefix + ".csv");
        Path nextSummaryCSVFile = outputPath
                .resolve(prefix + "-" + outputSchema.getTypeName() + "-Summary.csv");
        List<SimpleFeature> outputFeatureList = new CopyOnWriteArrayList<>();

        try (SimpleFeatureIterator iterator = collection.features();
                Writer bufferedWriter = Files.newBufferedWriter(nextCSVFile, StandardCharsets.UTF_8,
                        StandardOpenOption.CREATE_NEW);
                SequenceWriter csv = CSVUtil.newCSVWriter(bufferedWriter, csvSchema);) {
            List<String> nextLine = new ArrayList<>();
            while (iterator.hasNext()) {
                SimpleFeature feature = iterator.next();
                featureCount++;
                if (featureCount <= 2) {
                    System.out.println("");
                    System.out.println(feature.getIdentifier());
                } else if (featureCount % 100 == 0) {
                    System.out.print(".");
                }
                boolean filterThisFeature = false;
                for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) {
                    String featureString = Optional.ofNullable(feature.getAttribute(attribute.getName()))
                            .orElse("").toString();
                    nextLine.add(featureString);
                    if (filterFields.contains(attribute.getName().toString())
                            && featureString.trim().isEmpty()) {
                        filterThisFeature = true;
                    }
                    if (featureString.length() > 100) {
                        featureString = featureString.substring(0, 100) + "...";
                    }
                    if (featureCount <= 2) {
                        System.out.print(attribute.getName() + "=");
                        System.out.println(featureString);
                    }
                }
                if (!filterThisFeature) {
                    outputFeatureList.add(SHPUtils.changeSchemaName(feature, outputSchema));
                    csv.write(nextLine);
                }
                nextLine.clear();
            }
        }
        try (Reader csvReader = Files.newBufferedReader(nextCSVFile, StandardCharsets.UTF_8);
                Writer summaryOutput = Files.newBufferedWriter(nextSummaryCSVFile, StandardCharsets.UTF_8,
                        StandardOpenOption.CREATE_NEW);
                final Writer mappingWriter = options.has(outputMappingTemplate)
                        ? Files.newBufferedWriter(outputMappingPath)
                        : NullWriter.NULL_WRITER) {
            CSVSummariser.runSummarise(csvReader, summaryOutput, mappingWriter,
                    CSVSummariser.DEFAULT_SAMPLE_COUNT, false);
        }
        if (featureCount > 100) {
            System.out.println("");
        }
        System.out.println("");
        System.out.println("Feature count: " + featureCount);

        SimpleFeatureCollection outputCollection = new ListFeatureCollection(outputSchema, outputFeatureList);
        Path outputShapefilePath = outputPath.resolve(prefix + "-" + outputSchema.getTypeName() + "-dump");
        if (!Files.exists(outputShapefilePath)) {
            Files.createDirectory(outputShapefilePath);
        }
        SHPUtils.writeShapefile(outputCollection, outputShapefilePath);

        // Create ZIP file from the contents to keep the subfiles together
        Path outputShapefileZipPath = outputPath
                .resolve(prefix + "-" + outputSchema.getTypeName() + "-dump.zip");
        try (final OutputStream out = Files.newOutputStream(outputShapefileZipPath,
                StandardOpenOption.CREATE_NEW);
                final ZipOutputStream zip = new ZipOutputStream(out, StandardCharsets.UTF_8);) {
            Files.list(outputShapefilePath).forEachOrdered(Unchecked.consumer(e -> {
                zip.putNextEntry(new ZipEntry(e.getFileName().toString()));
                Files.copy(e, zip);
                zip.closeEntry();
            }));
        }

        try (final OutputStream outputStream = Files.newOutputStream(
                outputPath.resolve(prefix + "." + format.value(options)), StandardOpenOption.CREATE_NEW);) {
            MapContent map = new MapContent();
            map.setTitle(prefix + "-" + outputSchema.getTypeName());
            Style style = SLD.createSimpleStyle(featureSource.getSchema());
            Layer layer = new FeatureLayer(new CollectionFeatureSource(outputCollection), style);
            map.addLayer(layer);
            SHPUtils.renderImage(map, outputStream, resolution.value(options), format.value(options));
        }
    }
}

From source file:com.tito.easyyarn.appmaster.ApplicationMaster.java

public static void main(String[] args) {
    boolean result = false;
    try {/*from w  ww .  j a v a2 s . c o m*/
        Options ops = getMainClassOption();
        CommandLine cliParser = new ExtendedGnuParser(true).parse(ops, args);
        if (!cliParser.hasOption("appMasterClass")) {
            throw new RuntimeException("AppMasterClass is not specified failed to load Application Master");
        }

        ApplicationMaster appMaster = (ApplicationMaster) Class
                .forName(cliParser.getOptionValue("appMasterClass")).newInstance();

        LOG.info("Initializing ApplicationMaster");
        appMaster.setupOptionsAll();
        ////reparse args to assign options 
        cliParser = new ExtendedGnuParser(true).parse(appMaster.getOptions(), args);
        boolean doRun = appMaster.initAll(cliParser);

        if (!doRun) {
            System.exit(0);
        }
        appMaster.run();
        result = appMaster.finish();
    } catch (Throwable t) {
        LOG.fatal("Error running ApplicationMaster", t);
        LogManager.shutdown();
        ExitUtil.terminate(1, t);
    }
    if (result) {
        LOG.info("Application Master completed successfully. exiting");
        System.exit(0);
    } else {
        LOG.info("Application Master failed. exiting");
        System.exit(2);
    }
}