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:grakn.core.server.Grakn.java

public static void main(String[] args) {
    Thread.setDefaultUncaughtExceptionHandler(
            (Thread t, Throwable e) -> LOG.error(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(t.getName()), e));

    try {//w  w w.  j  ava 2 s.c o  m
        String graknPidFileProperty = Optional.ofNullable(SystemProperty.GRAKN_PID_FILE.value()).orElseThrow(
                () -> new RuntimeException(ErrorMessage.GRAKN_PIDFILE_SYSTEM_PROPERTY_UNDEFINED.getMessage()));

        Path pidfile = Paths.get(graknPidFileProperty);
        PIDManager pidManager = new PIDManager(pidfile);
        pidManager.trackGraknPid();

        // Start Server with timer
        Stopwatch timer = Stopwatch.createStarted();
        boolean benchmark = parseBenchmarkArg(args);
        Server server = ServerFactory.createServer(benchmark);
        server.start();

        LOG.info("Grakn started in {}", timer.stop());
    } catch (RuntimeException | IOException e) {
        LOG.error(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(e.getMessage()), e);
        System.err.println(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(e.getMessage()));
    }
}

From source file:com.linkedin.pinotdruidbenchmark.PinotResponseTime.java

public static void main(String[] args) throws Exception {
    if (args.length != 4 && args.length != 5) {
        System.err.println(/*from   w w w . j av  a 2  s. co  m*/
                "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    int warmUpRounds = Integer.parseInt(args[2]);
    int testRounds = Integer.parseInt(args[3]);
    File resultDir;
    if (args.length == 4) {
        resultDir = null;
    } else {
        resultDir = new File(args[4]);
        if (!resultDir.exists()) {
            if (!resultDir.mkdirs()) {
                throw new RuntimeException("Failed to create result directory: " + resultDir);
            }
        }
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(resourceUrl);

        for (File queryFile : queryFiles) {
            String query = new BufferedReader(new FileReader(queryFile)).readLine();
            httpPost.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));

            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Running query: " + query);
            System.out.println(
                    "--------------------------------------------------------------------------------");

            // Warm-up Rounds
            System.out.println("Run " + warmUpRounds + " times to warm up...");
            for (int i = 0; i < warmUpRounds; i++) {
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            System.out.println("Run " + testRounds + " times to get response time statistics...");
            long[] responseTimes = new long[testRounds];
            long totalResponseTime = 0L;
            for (int i = 0; i < testRounds; i++) {
                long startTime = System.currentTimeMillis();
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                long responseTime = System.currentTimeMillis() - startTime;
                responseTimes[i] = responseTime;
                totalResponseTime += responseTime;
                System.out.print(responseTime + "ms ");
            }
            System.out.println();

            // Store result.
            if (resultDir != null) {
                File resultFile = new File(resultDir, queryFile.getName() + ".result");
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                try (BufferedInputStream bufferedInputStream = new BufferedInputStream(
                        httpResponse.getEntity().getContent());
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) {
                    int length;
                    while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) {
                        bufferedWriter.write(new String(BYTE_BUFFER, 0, length));
                    }
                }
                httpResponse.close();
            }

            // Process response times.
            double averageResponseTime = (double) totalResponseTime / testRounds;
            double temp = 0;
            for (long responseTime : responseTimes) {
                temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime);
            }
            double standardDeviation = Math.sqrt(temp / testRounds);
            System.out.println("Average response time: " + averageResponseTime + "ms");
            System.out.println("Standard deviation: " + standardDeviation);
        }
    }
}

From source file:com.heliosdecompiler.helios.bootloader.Bootloader.java

public static void main(String[] args) {
    try {/*w  w w .  j a  v  a2  s . co  m*/
        if (!Constants.DATA_DIR.exists() && !Constants.DATA_DIR.mkdirs())
            throw new RuntimeException("Could not create data directory");
        if (!Constants.ADDONS_DIR.exists() && !Constants.ADDONS_DIR.mkdirs())
            throw new RuntimeException("Could not create addons directory");
        if (!Constants.SETTINGS_FILE.exists() && !Constants.SETTINGS_FILE.createNewFile())
            throw new RuntimeException("Could not create settings file");
        if (Constants.DATA_DIR.isFile())
            throw new RuntimeException("Data directory is file");
        if (Constants.ADDONS_DIR.isFile())
            throw new RuntimeException("Addons directory is file");
        if (Constants.SETTINGS_FILE.isDirectory())
            throw new RuntimeException("Settings file is directory");

        try {
            Class<?> clazz = Class.forName("org.eclipse.swt.widgets.Event");
            Object location = clazz.getProtectionDomain() != null
                    && clazz.getProtectionDomain().getCodeSource() != null
                            ? clazz.getProtectionDomain().getCodeSource().getLocation()
                            : "";
            throw new RuntimeException("SWT should not be loaded. Instead, it was loaded from " + location);
        } catch (ClassNotFoundException ignored) {
            loadSWTLibrary();
        }

        DisplayPumper displayPumper = new DisplayPumper();

        if (System.getProperty("os.name").toLowerCase().contains("mac")) {
            System.out.println("Attemting to force main thread");
            Executor executor;
            try {
                Class<?> dispatchClass = Class.forName("com.apple.concurrent.Dispatch");
                Object dispatchInstance = dispatchClass.getMethod("getInstance").invoke(null);
                executor = (Executor) dispatchClass.getMethod("getNonBlockingMainQueueExecutor")
                        .invoke(dispatchInstance);
            } catch (Throwable throwable) {
                throw new RuntimeException("Could not reflectively access Dispatch", throwable);
            }
            if (executor != null) {
                executor.execute(displayPumper);
            } else {
                throw new RuntimeException("Could not load executor");
            }
        } else {
            Thread pumpThread = new Thread(displayPumper);
            pumpThread.setName("Display Pumper");
            pumpThread.start();
        }
        while (!displayPumper.isReady())
            ;

        Display display = displayPumper.getDisplay();
        Shell shell = displayPumper.getShell();
        Splash splashScreen = new Splash(display);
        splashScreen.updateState(BootSequence.CHECKING_LIBRARIES);
        checkPackagedLibrary(splashScreen, "enjarify", Constants.ENJARIFY_VERSION,
                BootSequence.CHECKING_ENJARIFY, BootSequence.CLEANING_ENJARIFY, BootSequence.MOVING_ENJARIFY);
        checkPackagedLibrary(splashScreen, "Krakatau", Constants.KRAKATAU_VERSION,
                BootSequence.CHECKING_KRAKATAU, BootSequence.CLEANING_KRAKATAU, BootSequence.MOVING_KRAKATAU);

        try {
            if (!System.getProperty("os.name").toLowerCase().contains("linux")) {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            }
        } catch (Exception exception) { //Not important. No point notifying the user
        }

        Helios.main(args, shell, splashScreen);
        synchronized (displayPumper.getSynchronizer()) {
            displayPumper.getSynchronizer().wait();
        }
        System.exit(0);
    } catch (Throwable t) {
        displayError(t);
        System.exit(1);
    }
}

From source file:com.linkedin.pinotdruidbenchmark.DruidResponseTime.java

public static void main(String[] args) throws Exception {
    if (args.length != 4 && args.length != 5) {
        System.err.println(//from  w  w  w  . j a  va  2 s  .  c  om
                "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    int warmUpRounds = Integer.parseInt(args[2]);
    int testRounds = Integer.parseInt(args[3]);
    File resultDir;
    if (args.length == 4) {
        resultDir = null;
    } else {
        resultDir = new File(args[4]);
        if (!resultDir.exists()) {
            if (!resultDir.mkdirs()) {
                throw new RuntimeException("Failed to create result directory: " + resultDir);
            }
        }
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        httpPost.addHeader("content-type", "application/json");

        for (File queryFile : queryFiles) {
            StringBuilder stringBuilder = new StringBuilder();
            try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFile))) {
                int length;
                while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) {
                    stringBuilder.append(new String(CHAR_BUFFER, 0, length));
                }
            }
            String query = stringBuilder.toString();
            httpPost.setEntity(new StringEntity(query));

            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Running query: " + query);
            System.out.println(
                    "--------------------------------------------------------------------------------");

            // Warm-up Rounds
            System.out.println("Run " + warmUpRounds + " times to warm up...");
            for (int i = 0; i < warmUpRounds; i++) {
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            System.out.println("Run " + testRounds + " times to get response time statistics...");
            long[] responseTimes = new long[testRounds];
            long totalResponseTime = 0L;
            for (int i = 0; i < testRounds; i++) {
                long startTime = System.currentTimeMillis();
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                long responseTime = System.currentTimeMillis() - startTime;
                responseTimes[i] = responseTime;
                totalResponseTime += responseTime;
                System.out.print(responseTime + "ms ");
            }
            System.out.println();

            // Store result.
            if (resultDir != null) {
                File resultFile = new File(resultDir, queryFile.getName() + ".result");
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                try (BufferedInputStream bufferedInputStream = new BufferedInputStream(
                        httpResponse.getEntity().getContent());
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) {
                    int length;
                    while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) {
                        bufferedWriter.write(new String(BYTE_BUFFER, 0, length));
                    }
                }
                httpResponse.close();
            }

            // Process response times.
            double averageResponseTime = (double) totalResponseTime / testRounds;
            double temp = 0;
            for (long responseTime : responseTimes) {
                temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime);
            }
            double standardDeviation = Math.sqrt(temp / testRounds);
            System.out.println("Average response time: " + averageResponseTime + "ms");
            System.out.println("Standard deviation: " + standardDeviation);
        }
    }
}

From source file:com.rest.samples.getReportFromJasperServerWithSeparateAuth.java

public static void main(String[] args) {
    // TODO code application logic here

    String host = "10.49.28.3";
    String port = "8081";
    String reportName = "vencimientos";
    String params = "feini=2016-09-30&fefin=2016-09-30";
    String url = "http://{host}:{port}/jasperserver/rest_v2/reports/Reportes/{reportName}.pdf?{params}";
    url = url.replace("{host}", host);
    url = url.replace("{port}", port);
    url = url.replace("{reportName}", reportName);
    url = url.replace("{params}", params);

    try {//from   w  ww.  j  a v  a2s  .  c  o m
        CredentialsProvider cp = new BasicCredentialsProvider();
        cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password"));
        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:com.jdom.mediadownloader.MediaDownloader.java

public static void main(String[] args) {
    if (args.length != 1) {
        throw new IllegalArgumentException(
                "You must pass the location to the properties file to the application!");
    }/*from w w  w .jav  a2s  .  co m*/

    File file = new File(args[0]);

    Properties properties = new Properties();
    FileReader fileReader = null;

    try {
        fileReader = new FileReader(file);
        properties.load(fileReader);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        Closeables.closeQuietly(fileReader);
    }

    System.getProperties().putAll(properties);

    initializeContext();

    MediaDownloader mediaDownloader = ctx.getBean(MediaDownloader.class);
    mediaDownloader.processDownloads();
}

From source file:org.kuali.kfs.rest.AccountingPeriodCloseJob.java

public static void main(String[] args) {
    try {//  ww  w.j a va2s . c o m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost("http://localhost:8080/kfs-dev/coa/accounting_periods/close");
        request.addHeader("accept", "application/json");
        request.addHeader("content-type", "application/json");
        request.addHeader("authorization", "NSA_this_is_for_you");

        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("\"description\":\"Document: The Next Generation\",");
        sb.append("\"universityFiscalYear\": 2016,");
        sb.append("\"universityFiscalPeriodCode\": \"03\"");
        sb.append("}");
        StringEntity data = new StringEntity(sb.toString());
        request.setEntity(data);

        HttpResponse response = httpClient.execute(request);

        System.out.println("Status Code: " + response.getStatusLine().getStatusCode());
        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);
        }

        httpClient.getConnectionManager().shutdown();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.google.demo.translate.Translator.java

public static void main(String[] args) {
    parseInputs();/*from  w ww  .  j  av  a 2  s  .co  m*/

    try {
        String headers = String.join(",", source,
                targets.stream().map(i -> i.toString()).collect(Collectors.joining(",")));

        Files.write(output, Arrays.asList(headers), UTF_8, APPEND, CREATE);

        List<String> texts = new ArrayList<>();
        while (it.hasNext()) {
            texts.add(preTranslationParser(it.next()));
            if (texts.size() == 10 || !it.hasNext()) {
                translate(texts);
                texts = new ArrayList<>();
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        LineIterator.closeQuietly(it);
    }
}

From source file:com.widen.valet.importer.ImportZone.java

public static void main(String[] args) throws IOException {
    Properties properties = new Properties();

    InputStream stream = ImportZone.class.getResourceAsStream("importdns.properties");

    if (stream == null) {
        throw new RuntimeException("File importdns.properties not found!");
    }//from w ww. ja  va  2 s  .  co  m

    properties.load(stream);

    new ImportZone(properties).run();
}

From source file:ddf.metrics.reporting.internal.rrd4j.SampleDataGenerator.java

public static void main(String[] args) {
    if (args.length == 1) {
        try {//from ww w.  j a v  a2 s  .  c o  m
            String installLoc = args[0];
            File metricsDir = new File(installLoc, "/data/metrics");
            File[] files = metricsDir.listFiles();
            if (files != null) {
                for (File metricsFile : files) {
                    String metricsFileName = metricsFile.getName();
                    if (!metricsFileName.endsWith(".rrd")) {
                        continue;
                    }
                    RrdDb oldDb = new RrdDb(metricsFile.getAbsolutePath());
                    if (oldDb.getDsCount() > 1) {
                        continue;
                    }
                    DsType dsType = oldDb.getDatasource(0).getType();
                    String newDb = "target/" + metricsFileName;
                    long startTime = new DateTime().minusYears(1).getMillis();
                    int sampleSize = (int) ((new DateTime().getMillis() - startTime) / (60 * 1000));
                    new RrdMetricsRetrieverTest.RrdFileBuilder().rrdFileName(newDb).dsType(dsType)
                            .numSamples(sampleSize).numRows(sampleSize).startTime(startTime).build();
                    FileUtils.copyFile(new File(newDb), metricsFile);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    exit(0);
}