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.rest.samples.getReportFromJasperServerWithSeparateAuthFormatURL.java

public static void main(String[] args) {
    // TODO code application logic here
    Map<String, String> params = new HashMap<String, String>();
    params.put("host", "10.49.28.3");
    params.put("port", "8081");
    params.put("reportName", "vencimientos");
    params.put("parametros", "feini=2016-09-30&fefin=2016-09-30");
    StrSubstitutor sub = new StrSubstitutor(params, "{", "}");
    String urlTemplate = "http://{host}:{port}/jasperserver/rest_v2/reports/Reportes/{reportName}.pdf?{parametros}";
    String url = sub.replace(urlTemplate);

    try {/*from w w w . ja  v  a 2 s. c om*/
        CredentialsProvider cp = new BasicCredentialsProvider();
        cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("jasperadmin", "jasperadmin"));
        CloseableHttpClient hc = HttpClientBuilder.create().setDefaultCredentialsProvider(cp).build();

        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/pdf");
        HttpResponse res = hc.execute(getMethod);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        InputStream is = res.getEntity().getContent();
        OutputStream os = new FileOutputStream(new File("vencimientos.pdf"));
        int read = 0;
        byte[] bytes = new byte[2048];

        while ((read = is.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        is.close();
        os.close();

        if (Desktop.isDesktopSupported()) {
            File pdfFile = new File("vencimientos.pdf");
            Desktop.getDesktop().open(pdfFile);
        }

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:net.java.sen.tools.MkCompoundTable.java

/**
 * Build compound word table.//from   www . j  a  v  a  2  s  . c o  m
 */
public static void main(String args[]) {
    ResourceBundle rb = ResourceBundle.getBundle("dictionary");
    int pos_start = Integer.parseInt(rb.getString("pos_start"));
    int pos_size = Integer.parseInt(rb.getString("pos_size"));

    try {
        log.info("reading compound word information ... ");
        HashMap compoundTable = new HashMap();

        log.info("load dic: " + rb.getString("compound_word_file"));
        BufferedReader dicStream = new BufferedReader(new InputStreamReader(
                new FileInputStream(rb.getString("compound_word_file")), rb.getString("dic.charset")));

        String t;
        int line = 0;

        StringBuffer pos_b = new StringBuffer();
        while ((t = dicStream.readLine()) != null) {
            CSVParser parser = new CSVParser(t);
            String csv[] = parser.nextTokens();
            if (csv.length < (pos_size + pos_start)) {
                throw new RuntimeException("format error:" + line);
            }

            pos_b.setLength(0);
            for (int i = pos_start; i < (pos_start + pos_size - 1); i++) {
                pos_b.append(csv[i]);
                pos_b.append(',');
            }

            pos_b.append(csv[pos_start + pos_size - 1]);
            pos_b.append(',');

            for (int i = pos_start + pos_size; i < (csv.length - 2); i++) {
                pos_b.append(csv[i]);
                pos_b.append(',');
            }
            pos_b.append(csv[csv.length - 2]);
            compoundTable.put(pos_b.toString(), csv[csv.length - 1]);
        }
        dicStream.close();
        log.info("done.");
        log.info("writing compound word table ... ");
        ObjectOutputStream os = new ObjectOutputStream(
                new FileOutputStream(rb.getString("compound_word_table")));
        os.writeObject(compoundTable);
        os.close();
        log.info("done.");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.fivesticks.time.config.DatabaseUpdater.java

public static void main(String[] args) {
    try {//from  w  ww . j  a  va2  s .c o  m
        new DatabaseUpdater().initializeTables();
    } catch (DatabaseInitializeFailedException e) {
        throw new RuntimeException("failed");
    }
}

From source file:chibi.gemmaanalysis.cli.deprecated.BioSequenceCleanupCli.java

public static void main(String[] args) {
    BioSequenceCleanupCli p = new BioSequenceCleanupCli();
    try {/*w ww  . j  a v  a  2  s.c  om*/
        Exception ex = p.doWork(args);
        if (ex != null) {
            ex.printStackTrace();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.sm.test.TestError.java

public static void main(String[] args) throws Exception {
    String[] opts = new String[] { "-configPath", "-url", "-store", "-times" };
    String[] defaults = new String[] { "", "localhost:6172", "store1", "2" };
    String[] paras = getOpts(args, opts, defaults);

    String configPath = paras[0];
    if (configPath.length() == 0) {
        logger.error("missing config path or host");
        throw new RuntimeException("missing -configPath or -host");
    }/*from   w  w w .j  a v a2s  . c  om*/

    String url = paras[1];
    String store = paras[2];
    int times = Integer.valueOf(paras[3]);
    ClusterClientFactory ccf = ClusterClientFactory.connect(url, store);
    ClusterClient client = ccf.getDefaultStore(8000L);
    TestError testClient = new TestError(client);
    for (int i = 0; i < times; i++) {
        try {
            Key key = Key.createKey("test" + i);
            //client.put(key, "times-" + i);
            Value value = client.get(key);
            value.setVersion(value.getVersion() - 2);
            client.put(key, value);
            logger.info(value == null ? "null" : value.getData().toString());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
    testClient.client.close();
    ccf.close();
}

From source file:androidimporter.AndroidImporter.java

public static void main(String[] args) throws ParseException {
    //"/usr/local/apache-ant/bin/ant"
    String antPath = System.getProperty("ANT_PATH", System.getenv("ANT_PATH"));
    if (antPath == null || !new File(antPath).exists()) {
        throw new RuntimeException("Cannot find ant at " + antPath
                + ".  Please specify location to ant via the ANT_PATH environment variable or java system property.");
    }//www.  j  a  va  2 s .c  o m

    Options opts = new Options()
            .addOption("i", "android-resource-dir", true, "Android project res directory path")
            .addOption("o", "cn1-project-dir", true, "Path to the CN1 output project directory.")
            .addOption("r", "cn1-resource-file", false,
                    "Path to CN1 output .res file.  Defaults to theme.res in project dir")
            .addOption("p", "package", true, "Java package to place GUI forms in.")
            .addOption("h", "help", false, "Usage instructions");

    CommandLineParser parser = new DefaultParser();

    CommandLine line = parser.parse(opts, args);

    if (line.hasOption("help")) {
        showHelp(opts);
        System.exit(0);
    }
    args = line.getArgs();

    if (args.length < 1) {
        System.out.println("No command provided.");
        showHelp(opts);
        System.exit(0);
    }

    switch (args[0]) {
    case "import-project": {

        if (!line.hasOption("android-resource-dir") || !line.hasOption("cn1-project-dir")
                || !line.hasOption("package")) {
            System.out.println("Please provide android-resource-dir, package, and cn1-project-dir options");
            showHelp(opts);
            System.exit(1);
        }
        File resDir = findResDir(new File(line.getOptionValue("android-resource-dir")));
        if (resDir == null || !resDir.isDirectory()) {
            System.out.println("Failed to find android resource directory from provided value");
            showHelp(opts);
            System.exit(1);
        }

        File projDir = new File(line.getOptionValue("cn1-project-dir"));
        File resFile = new File(projDir, "src" + File.separator + "theme.res");
        if (line.hasOption("cn1-resource-file")) {
            resFile = new File(line.getOptionValue("cn1-resource-file"));
        }

        JavaSEPort.setShowEDTViolationStacks(false);
        JavaSEPort.setShowEDTWarnings(false);
        JFrame frm = new JFrame("Placeholder");
        frm.setVisible(false);
        Display.init(frm.getContentPane());
        JavaSEPort.setBaseResourceDir(resFile.getParentFile());
        try {
            System.out.println("About to import project at " + resDir.getAbsolutePath());
            System.out.println("Codename One Output Project: " + projDir.getAbsolutePath());
            System.out.println("Resource file: " + resFile.getAbsolutePath());
            System.out.println("Java Package: " + line.getOptionValue("package"));
            AndroidProjectImporter.importProject(resDir, projDir, resFile, line.getOptionValue("package"));
            Runtime.getRuntime().exec(new String[] { antPath, "init" }, new String[] {},
                    resFile.getParentFile().getParentFile());
            //runAnt(new File(resFile.getParentFile().getParentFile(), "build.xml"), "init");
            System.exit(0);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            System.exit(0);
        }
        break;
    }

    default:
        System.out.println("Unknown command " + args[0]);
        showHelp(opts);
        break;

    }

}

From source file:com.quix.aia.cn.imo.mapper.UrlForUserData.java

public static void main(String[] args) {
    // TODO Auto-generated method stub
    UserAuthResponds userAuth = new UserAuthResponds();
    try {//from www .java2 s . co m

        GsonBuilder builder = new GsonBuilder();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String username = "", psw = "", co = "";
        username = "NSNP306";
        psw = "A111111A";
        co = "0986";

        HttpGet getRequest = new HttpGet("http://211.144.219.243/isp/rest/index.do?isAjax=true&account="
                + username + "&co=" + co + "&password=" + psw + "");
        getRequest.addHeader("accept", "application/json");
        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            Gson googleJson = new Gson();
            userAuth = googleJson.fromJson(output, UserAuthResponds.class);
            System.out.println("Success " + userAuth.getSuccess());
            if (userAuth.getSuccess().equals("1")) {
                System.out.println("Login successfully Done");
            } else {

                System.out.println("Login Failed ");
            }

        }
        httpClient.getConnectionManager().shutdown();

        //           googleJson = builder.create();
        //           Type listType = new TypeToken<List<UserAuthResponds>>() {}.getType();

    } catch (ClientProtocolException e) {
        log.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    }

}

From source file:com.rk.grid.federation.FederatedCluster.java

/**
 * @param args//  w w  w.j a  v  a2s.  c om
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    int port = Integer.parseInt(args[0]);
    String clusterName = args[1];
    String masterBrokerServiceName = args[2];
    int masterPort = Integer.parseInt(args[3]);
    String masterHost = args[4];

    IBroker<Object> masterBroker = null;
    for (int i = 0; i < 100; i++) {
        try {
            masterBroker = getConnection(masterBrokerServiceName, masterPort, masterHost);
            if (masterBroker != null)
                break;
        } catch (RemoteLookupFailureException e) {
            if (i % 100 == 0)
                System.out.println("Sleeping....");
        }
        Thread.sleep(100);
    }

    if (masterBroker == null)
        throw new RuntimeException("Unable to find master broker " + masterBrokerServiceName);

    BrokerInfo brokerInfo = masterBroker.getBrokerInfo();
    GridConfig gridConfig = brokerInfo.getConfig();
    List<String> jvmNodeParams = masterBroker.getBrokerInfo().getJvmNodeParams();
    GridExecutorService cluster = new GridExecutorService(port, jvmNodeParams, gridConfig, clusterName);
    cluster.getBroker().unPause();

    final TaskExecutor taskExecutor = new TaskExecutor(cluster);

    final IRemoteResultsHandler<Object> callback = masterBroker.getCallback();
    IWorkQueue<Object> workQueue = masterBroker.getWorkQueue();

    ExecutorService pool = Executors.newFixedThreadPool(3);

    masterBroker.unPause();

    while (!Thread.currentThread().isInterrupted()) {
        final IExecutable<?> executable = workQueue.take();

        if (executable == null)
            continue;

        if (executable.equals(IExecutable.POISON)) {
            break;
        }

        Callable<Object> callable = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Future<ITaskResult<?>> future = taskExecutor.submit(executable);
                ITaskResult<?> iResult = future.get();

                String uid = executable.getUID();
                try {
                    callback.accept(new RemoteResult<Object>(iResult, uid));
                } catch (Throwable t) {
                    t.printStackTrace();
                    try {
                        callback.accept(new RemoteResult<Object>(
                                new RemoteExecutorException("Error execution remote task '" + uid + "'", t),
                                uid));
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                }
                return null;
            }

        };

        pool.submit(callable);
    }
    pool.shutdown();
    taskExecutor.shutdown();
    System.out.println("Finished...!");
}

From source file:com.ibm.watson.developer_cloud.professor_languo.pipeline.PipelineDriver.java

public static void main(String[] args) {
    Properties properties = new Properties();
    try (FileInputStream propertiesFileStream = new FileInputStream(args[0])) {
        // Load the properties from the properties file
        properties.load(propertiesFileStream);

        // Load the bluemix properties
        IndexerAndSearcherFactory.loadStaticBluemixProperties(properties);

        // Launch the pipeline
        drive(properties);// w  w  w  . j  a  va 2s  .  c  o  m
    } catch (IOException | PipelineException e) {
        logger.fatal(e.getMessage());
        throw new RuntimeException(e);
    }
}

From source file:ReflexiveInvocation.java

/**
 * Main demo method.//w w w. j  a v a  2  s  .c om
 * 
 * @param args
 *          the command line arguments
 * 
 * @throws RuntimeException
 *           __UNDOCUMENTED__
 */
public static void main(final String[] args) {
    try {
        final int CALL_AMOUNT = 1000000;
        final ReflexiveInvocation ri = new ReflexiveInvocation();
        int idx = 0;

        // Call the method without using reflection.
        long millis = System.currentTimeMillis();

        for (idx = 0; idx < CALL_AMOUNT; idx++) {
            ri.getValue();
        }

        System.out.println("Calling method " + CALL_AMOUNT + " times programatically took "
                + (System.currentTimeMillis() - millis) + " millis");

        // Call while looking up the method in each iteration.
        Method md = null;
        millis = System.currentTimeMillis();

        for (idx = 0; idx < CALL_AMOUNT; idx++) {
            md = ri.getClass().getMethod("getValue", null);
            md.invoke(ri, null);
        }

        System.out.println("Calling method " + CALL_AMOUNT + " times reflexively with lookup took "
                + (System.currentTimeMillis() - millis) + " millis");

        // Call using a cache of the method.
        md = ri.getClass().getMethod("getValue", null);
        millis = System.currentTimeMillis();

        for (idx = 0; idx < CALL_AMOUNT; idx++) {
            md.invoke(ri, null);
        }

        System.out.println("Calling method " + CALL_AMOUNT + " times reflexively with cache took "
                + (System.currentTimeMillis() - millis) + " millis");
    } catch (final NoSuchMethodException ex) {
        throw new RuntimeException(ex);
    } catch (final InvocationTargetException ex) {
        throw new RuntimeException(ex);
    } catch (final IllegalAccessException ex) {
        throw new RuntimeException(ex);
    }
}