Example usage for java.lang Exception Exception

List of usage examples for java.lang Exception Exception

Introduction

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

Prototype

public Exception(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.example.geomesa.kafka08.KafkaListener.java

public static void main(String[] args) throws Exception {
    // read command line args for a connection to Kafka
    CommandLineParser parser = new BasicParser();
    Options options = getCommonRequiredOptions();
    CommandLine cmd = parser.parse(options, args);

    // create the consumer KafkaDataStore object
    Map<String, String> dsConf = getKafkaDataStoreConf(cmd);
    dsConf.put("isProducer", "false");
    DataStore consumerDS = DataStoreFinder.getDataStore(dsConf);

    // verify that we got back our KafkaDataStore object properly
    if (consumerDS == null) {
        throw new Exception("Null consumer KafkaDataStore");
    }//from  www. j  ava  2 s.c om

    // create the schema which creates a topic in Kafka
    // (only needs to be done once)
    // TODO: This should be rolled into the Command line options to make this more general.
    registerListeners(consumerDS);

    while (true) {
        // Wait for user to terminate with ctrl-C.
    }
}

From source file:edu.cmu.lti.oaqa.annographix.apps.SolrSimpleIndexApp.java

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

    options.addOption("i", null, true, "Input File");
    options.addOption("u", null, true, "Solr URI");
    options.addOption("n", null, true, "Batch size");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {/* ww w.  j  a v a  2 s.c o  m*/
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("i")) {
            inputFile = cmd.getOptionValue("i");
        } else {
            Usage("Specify Input File");
        }

        if (cmd.hasOption("u")) {
            solrURI = cmd.getOptionValue("u");
        } else {
            Usage("Specify Solr URI");
        }

        if (cmd.hasOption("n")) {
            batchQty = Integer.parseInt(cmd.getOptionValue("n"));
        }

        SolrServerWrapper solrServer = new SolrServerWrapper(solrURI);

        BufferedReader inpText = new BufferedReader(
                new InputStreamReader(CompressUtils.createInputStream(inputFile)));

        XmlHelper xmlHlp = new XmlHelper();

        String docText = XmlHelper.readNextXMLIndexEntry(inpText);

        for (int docNum = 1; docText != null; ++docNum, docText = XmlHelper.readNextXMLIndexEntry(inpText)) {

            // 1. Read document text
            Map<String, String> docFields = null;
            HashMap<String, Object> objDocFields = new HashMap<String, Object>();

            try {
                docFields = xmlHlp.parseXMLIndexEntry(docText);
            } catch (SAXException e) {
                System.err.println("Parsing error, offending DOC:" + NL + docText);
                throw new Exception("Parsing error.");
            }

            for (Map.Entry<String, String> e : docFields.entrySet()) {
                //System.out.println(e.getKey() + " " + e.getValue());
                objDocFields.put(e.getKey(), e.getValue());
            }

            solrServer.indexDocument(objDocFields);
            if ((docNum - 1) % batchQty == 0)
                solrServer.indexCommit();
        }
        solrServer.indexCommit();

    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:com.meltmedia.rodimus.RodimusCli.java

public static void main(String... args) {
    try {/*  w  w  w  .j  a  v  a 2 s  . co m*/
        final Cli<RodimusInterface> cli = CliFactory.createCli(RodimusInterface.class);
        final RodimusInterface options = cli.parseArguments(args);

        // if help was requested, then display the help message and exit.
        if (options.isHelp()) {
            System.out.println(cli.getHelpMessage());
            return;
        }

        final boolean verbose = options.isVerbose();

        if (options.getFiles() == null || options.getFiles().size() < 1) {
            System.out.println(cli.getHelpMessage());
            return;
        }

        // get the input file.
        File inputFile = options.getFiles().get(0);

        // get the output file.
        File outputDir = null;
        if (options.getFiles().size() > 1) {
            outputDir = options.getFiles().get(1);
        } else {
            outputDir = new File(inputFile.getName().replaceFirst("\\.[^.]+\\Z", ""));
        }
        if (outputDir.exists() && !outputDir.isDirectory()) {
            throw new Exception(outputDir + " is not a directory.");
        }
        outputDir.mkdirs();

        transformDocument(inputFile, outputDir, verbose);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:org.switchyard.quickstarts.demo.security.propagation.jms.WorkServiceMain.java

public static void main(String... args) throws Exception {
    Set<String> policies = new HashSet<String>();
    for (String arg : args) {
        arg = Strings.trimToNull(arg);/*from   www  .  j  a v  a2 s  .c o m*/
        if (arg != null) {
            if (arg.equals(CONFIDENTIALITY) || arg.equals(CLIENT_AUTHENTICATION) || arg.equals(HELP)) {
                policies.add(arg);
            } else {
                LOGGER.error(MAVEN_USAGE);
                throw new Exception(MAVEN_USAGE);
            }
        }
    }
    if (policies.contains(HELP)) {
        LOGGER.info(MAVEN_USAGE);
    } else {
        final String scheme;
        final int port;
        if (policies.contains(CONFIDENTIALITY)) {
            scheme = "https";
            port = getPort(8443);
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, null, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            Scheme https = new Scheme(scheme, port, sf);
            SchemeRegistry sr = new SchemeRegistry();
            sr.register(https);
        } else {
            scheme = "http";
            port = getPort(8080);
        }
        String[] userPass = policies.contains(CLIENT_AUTHENTICATION) ? new String[] { "kermit", "the-frog-1" }
                : null;
        invokeWorkService(scheme, port, getContext(), userPass);
    }
}

From source file:com.example.geomesa.kafka.KafkaListener.java

public static void main(String[] args) throws Exception {
    // read command line args for a connection to Kafka
    CommandLineParser parser = new BasicParser();
    Options options = getCommonRequiredOptions();
    CommandLine cmd = parser.parse(options, args);

    // create the consumer KafkaDataStore object
    Map<String, String> dsConf = getKafkaDataStoreConf(cmd);
    DataStore consumerDS = DataStoreFinder.getDataStore(dsConf);

    // verify that we got back our KafkaDataStore object properly
    if (consumerDS == null) {
        throw new Exception("Null consumer KafkaDataStore");
    }/*from   w ww. ja  va  2 s. c o  m*/

    Map<String, FeatureListener> listeners = new HashMap<>();

    try {
        for (String typeName : consumerDS.getTypeNames()) {
            System.out.println("Registering a feature listener for type " + typeName + ".");
            FeatureListener listener = new FeatureListener() {
                @Override
                public void changed(FeatureEvent featureEvent) {
                    System.out.println("Received FeatureEvent from layer " + typeName + " of Type: "
                            + featureEvent.getType());
                    if (featureEvent.getType() == FeatureEvent.Type.CHANGED
                            && featureEvent instanceof KafkaFeatureChanged) {
                        printFeature(((KafkaFeatureChanged) featureEvent).feature());
                    } else if (featureEvent.getType() == FeatureEvent.Type.REMOVED) {
                        System.out.println("Received Delete for filter: " + featureEvent.getFilter());
                    }
                }
            };
            consumerDS.getFeatureSource(typeName).addFeatureListener(listener);
            listeners.put(typeName, listener);
        }

        while (true) {
            // Wait for user to terminate with ctrl-C.
        }
    } finally {
        for (Entry<String, FeatureListener> entry : listeners.entrySet()) {
            consumerDS.getFeatureSource(entry.getKey()).removeFeatureListener(entry.getValue());
        }
        consumerDS.dispose();
    }
}

From source file:org.switchyard.quickstarts.demo.policy.security.basic.propagate.WorkServiceMain.java

public static void main(String... args) throws Exception {
    Set<String> policies = new HashSet<String>();
    for (String arg : args) {
        arg = Strings.trimToNull(arg);//  w  w  w . j av a2 s .  c  o  m
        if (arg != null) {
            if (arg.equals(CONFIDENTIALITY) || arg.equals(CLIENT_AUTHENTICATION) || arg.equals(HELP)) {
                policies.add(arg);
            } else {
                LOGGER.error(MAVEN_USAGE);
                throw new Exception(MAVEN_USAGE);
            }
        }
    }
    if (policies.contains(HELP)) {
        LOGGER.info(MAVEN_USAGE);
    } else {
        final String scheme;
        final int port;
        if (policies.contains(CONFIDENTIALITY)) {
            scheme = "https";
            port = 8443;
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, null, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            Scheme https = new Scheme(scheme, port, sf);
            SchemeRegistry sr = new SchemeRegistry();
            sr.register(https);
        } else {
            scheme = "http";
            port = 8080;
        }
        String[] userPass = policies.contains(CLIENT_AUTHENTICATION) ? new String[] { "kermit", "the-frog-1" }
                : null;
        invokeWorkService(scheme, port, userPass);
    }
}

From source file:eu.annocultor.converters.geonames.GeonamesDumpToRdf.java

public static void main(String[] args) throws Exception {
    File root = new File("input_source");

    // load country-continent match
    countryToContinent// w w  w .  jav a 2s  .  c o  m
            .load((new GeonamesDumpToRdf()).getClass().getResourceAsStream("/country-to-continent.properties"));

    // creating files
    Map<String, BufferedWriter> files = new HashMap<String, BufferedWriter>();
    Map<String, Boolean> started = new HashMap<String, Boolean>();

    for (Object string : countryToContinent.keySet()) {
        String continent = countryToContinent.getProperty(string.toString());
        File dir = new File(root, continent);
        if (!dir.exists()) {
            dir.mkdir();
        }
        files.put(string.toString(), new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(new File(root, continent + "/" + string + ".rdf")), "UTF-8")));
        System.out.println(continent + "/" + string + ".rdf");
        started.put(string.toString(), false);
    }

    System.out.println(started);

    Pattern countryPattern = Pattern
            .compile("<inCountry rdf\\:resource\\=\"http\\://www\\.geonames\\.org/countries/\\#(\\w\\w)\"/>");
    long counter = 0;
    LineIterator it = FileUtils.lineIterator(new File(root, "all-geonames-rdf.txt"), "UTF-8");
    try {
        while (it.hasNext()) {
            String text = it.nextLine();
            if (text.startsWith("http://sws.geonames"))
                continue;

            // progress
            counter++;
            if (counter % 100000 == 0) {
                System.out.print("*");
            }
            //         System.out.println(counter);
            // get country
            String country = null;
            Matcher matcher = countryPattern.matcher(text);
            if (matcher.find()) {
                country = matcher.group(1);
            }
            //         System.out.println(country);
            if (country == null)
                country = "null";
            text = text.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><rdf:RDF",
                    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><rdf:RDF");
            if (started.get(country) == null)
                throw new Exception("Unknow country " + country);
            if (started.get(country).booleanValue()) {
                // remove RDF opening
                text = text.substring(text.indexOf("<rdf:RDF "));
                text = text.substring(text.indexOf(">") + 1);
            }
            // remove RDF ending
            text = text.substring(0, text.indexOf("</rdf:RDF>"));
            files.get(country).append(text + "\n");
            if (!started.get(country).booleanValue()) {
                // System.out.println("Started with country " + country);
            }
            started.put(country, true);
        }
    } finally {
        LineIterator.closeQuietly(it);
    }

    for (Object string : countryToContinent.keySet()) {
        boolean hasStarted = started.get(string.toString()).booleanValue();
        if (hasStarted) {
            BufferedWriter bf = files.get(string.toString());
            bf.append("</rdf:RDF>");
            bf.flush();
            bf.close();
        }
    }
    return;
}

From source file:edu.cmu.lti.oaqa.annographix.apps.SolrQueryApp.java

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

    options.addOption("u", null, true, "Solr URI");
    options.addOption("q", null, true, "Query");
    options.addOption("n", null, true, "Max # of results");
    options.addOption("o", null, true, "An optional TREC-style output file");
    options.addOption("w", null, false, "Do a warm-up query call, before each query");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    BufferedWriter trecOutFile = null;

    try {//  ww w. j a  v a2 s  .  c  o  m
        CommandLine cmd = parser.parse(options, args);
        String queryFile = null, solrURI = null;

        if (cmd.hasOption("u")) {
            solrURI = cmd.getOptionValue("u");
        } else {
            Usage("Specify Solr URI");
        }

        SolrServerWrapper solr = new SolrServerWrapper(solrURI);

        if (cmd.hasOption("q")) {
            queryFile = cmd.getOptionValue("q");
        } else {
            Usage("Specify Query file");
        }

        int numRet = 100;

        if (cmd.hasOption("n")) {
            numRet = Integer.parseInt(cmd.getOptionValue("n"));
        }

        if (cmd.hasOption("o")) {
            trecOutFile = new BufferedWriter(new FileWriter(new File(cmd.getOptionValue("o"))));
        }

        List<String> fieldList = new ArrayList<String>();
        fieldList.add(UtilConst.ID_FIELD);
        fieldList.add(UtilConst.SCORE_FIELD);

        double totalTime = 0;
        double retQty = 0;

        ArrayList<Double> queryTimes = new ArrayList<Double>();

        boolean bDoWarmUp = cmd.hasOption("w");

        if (bDoWarmUp) {
            System.out.println("Using a warmup step!");
        }

        int queryQty = 0;
        for (String t : FileUtils.readLines(new File(queryFile))) {
            t = t.trim();
            if (t.isEmpty())
                continue;
            int ind = t.indexOf('|');
            if (ind < 0)
                throw new Exception("Wrong format, line: '" + t + "'");
            String qID = t.substring(0, ind);
            String q = t.substring(ind + 1);

            SolrDocumentList res = null;

            if (bDoWarmUp) {
                res = solr.runQuery(q, fieldList, numRet);
            }

            Long tm1 = System.currentTimeMillis();
            res = solr.runQuery(q, fieldList, numRet);
            Long tm2 = System.currentTimeMillis();
            retQty += res.getNumFound();
            System.out.println(qID + " Obtained: " + res.getNumFound() + " entries in " + (tm2 - tm1) + " ms");
            double delta = (tm2 - tm1);
            totalTime += delta;
            queryTimes.add(delta);
            ++queryQty;

            if (trecOutFile != null) {

                ArrayList<SolrRes> resArr = new ArrayList<SolrRes>();
                for (SolrDocument doc : res) {
                    String id = (String) doc.getFieldValue(UtilConst.ID_FIELD);
                    float score = (Float) doc.getFieldValue(UtilConst.SCORE_FIELD);
                    resArr.add(new SolrRes(id, "", score));
                }
                SolrRes[] results = resArr.toArray(new SolrRes[resArr.size()]);
                Arrays.sort(results);

                SolrEvalUtils.saveTrecResults(qID, results, trecOutFile, TREC_RUN, results.length);
            }
        }
        double devTime = 0, meanTime = totalTime / queryQty;
        for (int i = 0; i < queryQty; ++i) {
            double d = queryTimes.get(i) - meanTime;
            devTime += d * d;
        }
        devTime = Math.sqrt(devTime / (queryQty - 1));
        System.out.println(String.format("Query time, mean/standard dev: %.2f/%.2f (ms)", meanTime, devTime));
        System.out.println(String.format("Avg # of docs returned: %.2f", retQty / queryQty));

        solr.close();
        trecOutFile.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:com.hortonworks.atlas.trash.MySqlIngester.java

public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub

    if (args.length < 1) {
        throw new Exception("Please provide the DGI host url");
    }/*  ww w. j a  va  2s.c  o  m*/

    System.setProperty("atlas.conf", "/Users/sdutta/Applications/conf");

    String baseUrl = getServerUrl(args);

    MySqlIngester sqlIngester = new MySqlIngester(baseUrl);

    sqlIngester.createTypes();
    System.out.println("Creating Entitites");
    sqlIngester.createEntities("testers", "this is data being laoded", "TestDB");

}

From source file:com.khubla.jvmbasic.jvmbasicc.JVMBasic.java

/**
 * start here/*  w  ww  .  j  a v  a2  s  .c o m*/
 * <p>
 * -file src\test\resources\bas\easy\print.bas -verbose true
 * </p>
 */
public static void main(String[] args) {
    try {
        System.out.println("khubla.com jvmBASIC Compiler");
        /*
         * options
         */
        final Options options = new Options();
        Option oo = Option.builder().argName(OUTPUT_OPTION).longOpt(OUTPUT_OPTION).type(String.class).hasArg()
                .required(false).desc("target directory to output to").build();
        options.addOption(oo);
        oo = Option.builder().argName(FILE_OPTION).longOpt(FILE_OPTION).type(String.class).hasArg()
                .required(true).desc("file to compile").build();
        options.addOption(oo);
        oo = Option.builder().argName(VERBOSE_OPTION).longOpt(VERBOSE_OPTION).type(String.class).hasArg()
                .required(false).desc("verbose output").build();
        options.addOption(oo);
        /*
         * parse
         */
        final CommandLineParser parser = new DefaultParser();
        CommandLine cmd = null;
        try {
            cmd = parser.parse(options, args);
        } catch (final Exception e) {
            e.printStackTrace();
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("posix", options);
            System.exit(0);
        }
        /*
         * verbose output?
         */
        final Boolean verbose = Boolean.parseBoolean(cmd.getOptionValue(VERBOSE_OPTION));
        /*
         * get the file
         */
        final String filename = cmd.getOptionValue(FILE_OPTION);
        final String outputDirectory = cmd.getOptionValue(OUTPUT_OPTION);
        if (null != filename) {
            /*
             * filename
             */
            final String basFileName = System.getProperty("user.dir") + "/" + filename;
            final File fl = new File(basFileName);
            if (true == fl.exists()) {
                /*
                 * show the filename
                 */
                System.out.println("Compiling: " + fl.getCanonicalFile());
                /*
                 * compiler
                 */
                final JVMBasicCompiler jvmBasicCompiler = new JVMBasicCompiler();
                /*
                 * compile
                 */
                jvmBasicCompiler.compileToClassfile(basFileName, null, outputDirectory, verbose, true, true);
            } else {
                throw new Exception("Unable to find: '" + basFileName + "'");
            }
        } else {
            throw new Exception("File was not supplied");
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
}