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:ee.ria.xroad.asyncdb.AsyncDBMemoryUsageTest.java

/**
 * @param args - arguments of main method, here not used.
 * @throws Exception - thrown when memory usage test fails.
 *//*from   ww  w .  j  av  a  2s. co m*/
public static void main(String[] args) throws Exception {
    File logDir = null;

    try {
        SoapMessageImpl requestMessage = AsyncDBTestUtil.getFirstSoapRequest();
        File logFile = new File(AsyncDBTestUtil.getAsyncLogFilePath());
        logDir = logFile.getParentFile();

        long previousFreeFileDescriptorCount = 0;
        boolean first = true;

        for (int i = 0; i < ITERATIONS; i++) {
            LOG.info("Adding request number {}...", i);

            WritingCtx writingCtx = QUEUE.startWriting();
            writingCtx.getConsumer().soap(requestMessage);
            writingCtx.commit();

            long freeFileDescriptorCount = SystemMetrics.getFreeFileDescriptorCount();
            LOG.info("Free file descriptor count: {}", freeFileDescriptorCount);

            if (!first && freeFileDescriptorCount < previousFreeFileDescriptorCount) {
                throw new RuntimeException("File descriptor count must not increase as requests are added!");
            }

            previousFreeFileDescriptorCount = freeFileDescriptorCount;
            first = false;
        }

        LOG.info("Async DB memory usage test accomplished successfully");
    } finally {
        FileUtils.deleteDirectory(new File(AsyncDBTestUtil.getProviderDirPath()));

        if (logDir != null) {
            FileUtils.deleteDirectory(logDir);
        }
    }
}

From source file:com.googlecode.fannj.FannTest.java

public static void main(String[] args) {
    try {// w  ww .  j  av a2 s.c  o  m
        new FannTest().testFannGetErrNo();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

}

From source file:net.modelbased.proasense.storage.registry.StorageRegistrySensorDataTestClient.java

public static void main(String[] args) {
    // Get client properties from properties file
    //        StorageRegistrySensorDataTestClient client = new StorageRegistrySensorDataTestClient();
    //        client.loadClientProperties();

    // Hardcoded client properties (simple test client)
    String STORAGE_REGISTRY_SERVICE_URL = "http://192.168.84.34:8080/storage-registry";

    // Default HTTP client and common properties for requests
    HttpClient client = new DefaultHttpClient();
    StringBuilder requestUrl = null;
    List<NameValuePair> params = null;
    String queryString = null;//from   ww  w . ja  v a 2s  .c om

    // Default HTTP response and common properties for responses
    HttpResponse response = null;
    ResponseHandler<String> handler = null;
    int status = 0;
    String body = null;

    // Query for sensor list
    requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL);
    requestUrl.append("/query/sensor/list");

    try {
        HttpGet query21 = new HttpGet(requestUrl.toString());
        query21.setHeader("Content-type", "application/json");
        response = client.execute(query21);

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

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        System.out.println("SENSOR LIST: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Query for sensor properties
    requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL);
    requestUrl.append("/query/sensor/properties");

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("sensorId", "visualInspection"));

    queryString = URLEncodedUtils.format(params, "utf-8");
    requestUrl.append("?");
    requestUrl.append(queryString);

    try {
        HttpGet query22 = new HttpGet(requestUrl.toString());
        query22.setHeader("Content-type", "application/json");
        response = client.execute(query22);

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

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        System.out.println("SENSOR PROPERTIES: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:com.wolfsoftco.httpclient.RestClient.java

@SuppressWarnings("resource")
public static void main(String[] args) {
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {//  www .ja  va  2s  .com
        HttpEntity entity = null;
        String responseHtml = null;
        httpclient = HttpClients.custom().build();

        //Based on CURL line:
        //curl localhost:9090/oauth/token -d "grant_type=password&scope=write&username=greg&password=turnquist" -u foo:bar

        //clientid:secret
        String clientID = "foo:bar";

        HttpUriRequest login = RequestBuilder.post().setUri(new URI(URL))
                .addHeader("Authorization", "Basic " + Base64.encodeBase64String(clientID.getBytes()))
                .addParameter("grant_type", "password").addParameter("scope", "read")
                .addParameter("username", "greg").addParameter("password", "turnquist").build();

        response = httpclient.execute(login);
        entity = response.getEntity();

        responseHtml = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        JsonObject jsonObject = null;
        String token = null;
        if (responseHtml.startsWith("{")) {
            JsonParser parser = new JsonParser();
            jsonObject = parser.parse(responseHtml).getAsJsonObject();
            token = jsonObject.get("access_token").getAsString();
        }

        if (token != null) {
            HttpGet request = new HttpGet(URL_FLIGHTS);
            request.addHeader("Authorization", "Bearer " + token);

            response = httpclient.execute(request);
            entity = response.getEntity();
            responseHtml = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            System.out.println(responseHtml);

        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {

            if (httpclient != null)
                httpclient.close();
            if (response != null)
                response.close();

        } catch (IOException e) {
        }
    }
}

From source file:net.geoprism.FileMerger.java

public static void main(String[] args) throws ParseException, IOException {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();
    options.addOption(Option.builder("b").hasArg().argName("baseFile").longOpt("baseFile")
            .desc("The path to the base properties file.").build());
    options.addOption(Option.builder("o").hasArg().argName("overrideFile").longOpt("overrideFile")
            .desc("The path to the override properties file.").build());
    options.addOption(Option.builder("e").hasArg().argName("exportFile").longOpt("exportFile")
            .desc("The path to the export properties file. A null value defaults to base.").build());
    options.addOption(Option.builder("B").hasArg().argName("baseDir").longOpt("baseDir")
            .desc("The path to the base directory.").build());
    options.addOption(Option.builder("O").hasArg().argName("overrideDir").longOpt("overrideDir")
            .desc("The path to the override directory.").build());
    options.addOption(Option.builder("E").hasArg().argName("exportDir").longOpt("exportDir")
            .desc("The path to the export directory. A null value defaults to base.").build());
    CommandLine line = parser.parse(options, args);

    String sBase = line.getOptionValue("b");
    String sOverride = line.getOptionValue("o");
    String sExport = line.getOptionValue("e");
    String sBaseDir = line.getOptionValue("B");
    String sOverrideDir = line.getOptionValue("O");
    String sExportDir = line.getOptionValue("E");

    if (sBase != null && sOverride != null) {
        if (sExport == null) {
            sExport = sBase;//w ww .  j av  a 2  s .c  o m
        }

        File fBase = new File(sBase);
        File fOverride = new File(sOverride);
        File fExport = new File(sExport);
        if (!fBase.exists() || !fOverride.exists()) {
            throw new RuntimeException(
                    "The base [" + sBase + "] and the override [" + sOverride + "] paths must both exist.");
        }

        FileMerger merger = new FileMerger();
        merger.mergeProperties(fBase, fOverride, fExport);
    } else if (sBaseDir != null && sOverrideDir != null) {
        if (sExportDir == null) {
            sExportDir = sBaseDir;
        }

        File fBaseDir = new File(sBaseDir);
        File fOverrideDir = new File(sOverrideDir);
        File fExportDir = new File(sExportDir);
        if (!fBaseDir.exists() || !fOverrideDir.exists()) {
            throw new RuntimeException("The base [" + sBaseDir + "] and the override [" + sOverrideDir
                    + "] paths must both exist.");
        }

        FileMerger merger = new FileMerger();
        merger.mergeDirectories(fBaseDir, fOverrideDir, fExportDir);
    } else {
        throw new RuntimeException("Invalid arguments");
    }
}

From source file:com.joliciel.lefff.Lefff.java

/**
 * @param args/*  w w  w  .  jav  a 2  s. com*/
 */
public static void main(String[] args) throws Exception {
    long startTime = (new Date()).getTime();
    String command = args[0];

    String memoryBaseFilePath = "";
    String lefffFilePath = "";
    String posTagSetPath = "";
    String posTagMapPath = "";
    String word = null;
    List<String> categories = null;
    int startLine = -1;
    int stopLine = -1;

    boolean firstArg = true;
    for (String arg : args) {
        if (firstArg) {
            firstArg = false;
            continue;
        }
        int equalsPos = arg.indexOf('=');
        String argName = arg.substring(0, equalsPos);
        String argValue = arg.substring(equalsPos + 1);
        if (argName.equals("memoryBase"))
            memoryBaseFilePath = argValue;
        else if (argName.equals("lefffFile"))
            lefffFilePath = argValue;
        else if (argName.equals("startLine"))
            startLine = Integer.parseInt(argValue);
        else if (argName.equals("stopLine"))
            stopLine = Integer.parseInt(argValue);
        else if (argName.equals("posTagSet"))
            posTagSetPath = argValue;
        else if (argName.equals("posTagMap"))
            posTagMapPath = argValue;
        else if (argName.equals("word"))
            word = argValue;
        else if (argName.equals("categories")) {
            String[] parts = argValue.split(",");
            categories = new ArrayList<String>();
            for (String part : parts) {
                categories.add(part);
            }
        } else
            throw new RuntimeException("Unknown argument: " + argName);
    }

    final LefffServiceLocator locator = new LefffServiceLocator();
    locator.setDataSourcePropertiesFile("jdbc-live.properties");

    TalismaneServiceLocator talismaneServiceLocator = TalismaneServiceLocator.getInstance();

    final LefffService lefffService = locator.getLefffService();
    if (command.equals("load")) {
        if (lefffFilePath.length() == 0)
            throw new RuntimeException("Required argument: lefffFile");
        final LefffLoader loader = lefffService.getLefffLoader();
        File file = new File(lefffFilePath);
        if (startLine > 0)
            loader.setStartLine(startLine);
        if (stopLine > 0)
            loader.setStopLine(stopLine);

        loader.LoadFile(file);
    } else if (command.equals("serialiseBase")) {
        if (memoryBaseFilePath.length() == 0)
            throw new RuntimeException("Required argument: memoryBase");
        if (posTagSetPath.length() == 0)
            throw new RuntimeException("Required argument: posTagSet");
        if (posTagMapPath.length() == 0)
            throw new RuntimeException("Required argument: posTagMap");

        PosTaggerServiceLocator posTaggerServiceLocator = talismaneServiceLocator.getPosTaggerServiceLocator();
        PosTaggerService posTaggerService = posTaggerServiceLocator.getPosTaggerService();
        File posTagSetFile = new File(posTagSetPath);
        PosTagSet posTagSet = posTaggerService.getPosTagSet(posTagSetFile);

        File posTagMapFile = new File(posTagMapPath);
        LefffPosTagMapper posTagMapper = lefffService.getPosTagMapper(posTagMapFile, posTagSet);

        Map<PosTagSet, LefffPosTagMapper> posTagMappers = new HashMap<PosTagSet, LefffPosTagMapper>();
        posTagMappers.put(posTagSet, posTagMapper);

        LefffMemoryLoader loader = new LefffMemoryLoader();
        LefffMemoryBase memoryBase = loader.loadMemoryBaseFromDatabase(lefffService, posTagMappers, categories);
        File memoryBaseFile = new File(memoryBaseFilePath);
        memoryBaseFile.delete();
        loader.serializeMemoryBase(memoryBase, memoryBaseFile);
    } else if (command.equals("deserialiseBase")) {
        if (memoryBaseFilePath.length() == 0)
            throw new RuntimeException("Required argument: memoryBase");

        LefffMemoryLoader loader = new LefffMemoryLoader();
        File memoryBaseFile = new File(memoryBaseFilePath);
        LefffMemoryBase memoryBase = loader.deserializeMemoryBase(memoryBaseFile);

        String[] testWords = new String[] { "avoir" };
        if (word != null) {
            testWords = word.split(",");
        }

        for (String testWord : testWords) {
            Set<PosTag> possiblePosTags = memoryBase.findPossiblePosTags(testWord);
            LOG.debug("##### PosTags for '" + testWord + "': " + possiblePosTags.size());
            int i = 1;
            for (PosTag posTag : possiblePosTags) {
                LOG.debug("### PosTag " + (i++) + ":" + posTag);
            }

            List<? extends LexicalEntry> entriesForWord = memoryBase.getEntries(testWord);
            LOG.debug("##### Entries for '" + testWord + "': " + entriesForWord.size());
            i = 1;
            for (LexicalEntry entry : entriesForWord) {
                LOG.debug("### Entry " + (i++) + ":" + entry.getWord());
                LOG.debug("Category " + entry.getCategory());
                LOG.debug("Predicate " + entry.getPredicate());
                LOG.debug("Lemma " + entry.getLemma());
                LOG.debug("Morphology " + entry.getMorphology());
            }

            List<? extends LexicalEntry> entriesForLemma = memoryBase.getEntriesForLemma(testWord, "");
            LOG.debug("##### Entries for '" + testWord + "' lemma: " + entriesForLemma.size());
            for (LexicalEntry entry : entriesForLemma) {
                LOG.debug("### Entry " + entry.getWord());
                LOG.debug("Category " + entry.getCategory());
                LOG.debug("Predicate " + entry.getPredicate());
                LOG.debug("Lemma " + entry.getLemma());
                LOG.debug("Morphology " + entry.getMorphology());
                for (PredicateArgument argument : entry.getPredicateArguments()) {
                    LOG.debug("Argument: " + argument.getFunction() + ",Optional? " + argument.isOptional());
                    for (String realisation : argument.getRealisations()) {
                        LOG.debug("Realisation: " + realisation);
                    }
                }
            }
        }

    } else {
        System.out.println("Usage : Lefff load filepath");
    }
    long endTime = (new Date()).getTime() - startTime;
    LOG.debug("Total runtime: " + ((double) endTime / 1000) + " seconds");
}

From source file:de.meldanor.autothesis.Core.java

public static void main(String[] args) {
    try {//from   ww w.j a v a2s .co m
        AutoThesisCommandOption options = AutoThesisCommandOption.getInstance();
        CommandLine commandLine = new GnuParser().parse(options, args);

        // Missing commands
        if (!commandLine.hasOption(options.getUserCommand())
                || !commandLine.hasOption(options.getTokenCommand())
                || !commandLine.hasOption(options.getRepoCommand())) {
            new HelpFormatter().printHelp("autothesis", options);
            return;
        }

        String user = commandLine.getOptionValue(options.getUserCommand());
        String repo = commandLine.getOptionValue(options.getRepoCommand());
        String token = commandLine.getOptionValue(options.getTokenCommand());

        logger.info("Hello World, this is AutoThesis!");
        long intervalMinutes = Long.parseLong(commandLine.getOptionValue(options.getIntervalCommand(), "60"));
        logger.info("Check for update interval: " + intervalMinutes + " min");
        final AutoThesis autoThesis = new AutoThesis(user, repo, token);
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> {
            try {
                autoThesis.execute();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, 0, intervalMinutes, TimeUnit.MINUTES);

    } catch (Exception e) {
        logger.throwing(Level.ERROR, e);
    }
}

From source file:com.vmware.photon.controller.auth.Main.java

/**
 * Bootstrap the executor.//  w ww  . j  a va 2 s .  c  om
 * Usage: auth-tool [-h] {get-token,gt,register-client,rc} ...
 */
public static void main(String[] args) {

    try {
        AuthToolCmdLine authToolCmdLine = AuthToolCmdLine.parseCmdLineArguments(args);

        switch (authToolCmdLine.getCommand()) {
        case GET_ACCESS_TOKEN: {
            initializeLogging(AUTH_TOKEN_LOG_FILE_NAME);

            OIDCTokens tokens = getAuthTokens(authToolCmdLine);
            printAccessToken(tokens.getAccessToken());

            break;
        }
        case GET_REFRESH_TOKEN: {
            initializeLogging(AUTH_TOKEN_LOG_FILE_NAME);

            OIDCTokens tokens = getAuthTokens(authToolCmdLine);
            printRefreshToken(tokens.getRefreshToken());

            break;
        }
        case REGISTER_CLIENT: {
            initializeLogging(CLIENT_REGISTRATION_LOG_FILE_NAME);

            ClientRegistrationArguments arguments = (ClientRegistrationArguments) authToolCmdLine
                    .getArguments();

            AuthOIDCClient oidcClient = new AuthOIDCClient(arguments.getAuthServerAddress(),
                    arguments.getAuthServerPort(), arguments.getTenant());
            AuthClientHandler authClientHandler = oidcClient.getClientHandler(arguments.getUsername(),
                    arguments.getPassword());

            AuthClientHandler.ImplicitClient implicitClient = authClientHandler.registerImplicitClient(
                    new URI(arguments.getLoginRedirectEndpoint()),
                    new URI(arguments.getLogoutRedirectEndpoint()));

            printClientRegistrationInfo(implicitClient);

            break;
        }
        default:
            throw new RuntimeException("Not supported auth tool command.");
        }
    } catch (ArgumentParserException e) {
        System.err.println("Error: " + e.getMessage());
        System.err.println();
        AuthToolCmdLine.usage();
        System.exit(1);

    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        if (e.getCause() != null) {
            System.err.println(e.getCause().getMessage());
        }
        System.exit(1);
    }
}

From source file:net.opentsdb.ConfigReader.java

public static void main(String[] args) {
    System.setProperty("capsule.cache.dir", "/tmp");
    try {/* w  ww.  j  a v  a  2s.co m*/
        final Config config = new Config(false);
        String[] cmdLineArgs = load(config, new String[] { "--port", "3847" });
        System.out.println("CMD Line Args:" + Arrays.toString(cmdLineArgs));
        System.out.println("TSDB Config:" + config.dumpConfiguration());
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        throw new RuntimeException(ex);
    }
}

From source file:de.snertlab.xdccBee.ui.Application.java

public static void main(String args[]) {
    // INFO: Unter MacOsx muss jar wie folgt gestartet werden: java
    // -XstartOnFirstThread -jar
    try {//from  w  w w .  j a  v a 2  s . co  m
        if (!ArrayUtils.isEmpty(args) && !args[0].equals("-debug")) {
            BeeLogger.removeConsoleHandler();
        }
        logger.info("xdccBee start");
        window = new Application();
        window.setBlockOnOpen(true);
        window.open();
        if (Display.getCurrent() != null && !Display.getCurrent().isDisposed()) {
            Display.getCurrent().dispose();
        }
    } catch (Exception e) {
        BeeLogger.exception(e);
        throw new RuntimeException(e);
    }
    System.exit(0);
}