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(String message, Throwable cause) 

Source Link

Document

Constructs a new runtime exception with the specified detail message and cause.

Usage

From source file:org.echocat.nodoodle.server.Main.java

public static void main(String[] args) {
    final File log4jConfig = new File(System.getProperty("log4j.configuration", "../config/log4j.xml"));
    if (log4jConfig.isFile()) {
        try {/*from   w w  w .j a  v  a  2s  .c  o  m*/
            final FileReader reader = new FileReader(log4jConfig);
            try {
                final DOMConfigurator domConfigurator = new DOMConfigurator();
                domConfigurator.doConfigure(reader, getLoggerRepository());
            } finally {
                IOUtils.closeQuietly(reader);
            }
        } catch (Exception e) {
            throw new RuntimeException("Could not configure log4j with " + log4jConfig + ".", e);
        }
    }

    final String applicationName = getApplicationName();
    //System.setSecurityManager(new ServerSecurityManager());
    LOG.info("Starting " + applicationName + "...");

    final File config = new File(
            System.getProperty(Main.class.getPackage().getName() + ".config", "../config/nodoodleServer.xml"));
    final AbstractApplicationContext applicationContext = new FileSystemXmlApplicationContext(config.getPath());
    LOG.info("Starting " + applicationName + "... DONE!");
    Runtime.getRuntime().addShutdownHook(new Thread("destroyer") {
        @Override
        public void run() {
            LOG.info("Stopping " + applicationName + "...");
            applicationContext.stop();
            LOG.info("Stopping " + applicationName + "... DONE!");
        }
    });
}

From source file:com.github.xbn.examples.regexutil.non_xbn.MatchEachWordInEveryLine.java

public static final void main(String[] as_1RqdTxtFilePath) {
    Iterator<String> lineItr = null;
    try {//from www  .  j  a v a  2  s  .c  o m
        lineItr = FileUtils.lineIterator(new File(as_1RqdTxtFilePath[0])); //Throws npx if null
    } catch (IOException iox) {
        throw new RuntimeException("Attempting to open \"" + as_1RqdTxtFilePath[0] + "\"", iox);
    } catch (RuntimeException rx) {
        throw new RuntimeException("One required parameter: The path to the text file.", rx);
    }

    //Dummy search string (""), so it can be reused (reset)
    Matcher mWord = Pattern.compile("\\b\\w+\\b").matcher("");
    while (lineItr.hasNext()) {
        String sLine = lineItr.next();
        mWord.reset(sLine);
        while (mWord.find()) {
            System.out.println(mWord.group());
        }
    }

}

From source file:com.util.finalProy.java

/**
 * @param args the command line arguments
 *///from www.j a  v  a  2 s  . c om
public static void main(String[] args) throws JSONException {
    // TODO code application logic her
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println(sb.toString());
    System.out.println(
            "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
    JSONObject objJason = new JSONObject(jsonResult);
    JSONArray dataJson = new JSONArray();
    dataJson = objJason.getJSONArray("data");

    System.out.println("objeto normal 1 " + dataJson.toString());
    //
    //
    System.out.println(
            "\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n");
    String jsonString2 = dataJson.toString();
    String temp = dataJson.toString();
    temp = jsonString2.replace("[", "");
    jsonString2 = temp.replace("]", "");
    System.out.println("new json string" + jsonString2);

    JSONObject objJson2 = new JSONObject(jsonString2);
    System.out.println("el objeto simple json es " + objJson2.toString());

    System.out.println(
            "\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n");

    String account1 = objJson2.optString("account");
    System.out.println(account1);
    JSONObject objJson3 = new JSONObject(account1);
    System.out.println("el ULTIMO OBJETO SIMPLE ES  " + objJson3.toString());
    System.out.println(
            "\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n");
    String firstName = objJson3.getString("first_name");
    System.out.println(firstName);
    System.out.println(objJson3.get("id"));
    System.out.println(
            "\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n");
    Gson gson = new Gson();
    Account account = gson.fromJson(objJson3.toString(), Account.class);
    System.out.println(account.getFirst_name());
    System.out.println(account.getCreation());
}

From source file:com.github.xbn.examples.regexutil.non_xbn.BetweenLineMarkersButSkipFirstXmpl.java

public static final void main(String[] as_1RqdTxtFilePath) {
    Iterator<String> lineItr = null;
    try {/*w w w. j a v  a2s .c  o  m*/
        lineItr = FileUtils.lineIterator(new File(as_1RqdTxtFilePath[0])); //Throws npx if null
    } catch (IOException iox) {
        throw new RuntimeException("Attempting to open \"" + as_1RqdTxtFilePath[0] + "\"", iox);
    } catch (RuntimeException rx) {
        throw new RuntimeException("One required parameter: The path to the text file.", rx);
    }

    String LINE_SEP = System.getProperty("line.separator", "\n");

    ArrayList<String> alsItems = new ArrayList<String>();
    boolean bStartMark = false;
    boolean bLine1Skipped = false;
    StringBuilder sdCurrentItem = new StringBuilder();
    while (lineItr.hasNext()) {
        String sLine = lineItr.next().trim();
        if (!bStartMark) {
            if (sLine.startsWith(".START_SEQUENCE")) {
                bStartMark = true;
                continue;
            }
            throw new IllegalStateException("Start mark not found.");
        }
        if (!bLine1Skipped) {
            bLine1Skipped = true;
            continue;
        } else if (!sLine.equals(".END_SEQUENCE")) {
            sdCurrentItem.append(sLine).append(LINE_SEP);
        } else {
            alsItems.add(sdCurrentItem.toString());
            sdCurrentItem.setLength(0);
            bStartMark = false;
            bLine1Skipped = false;
            continue;
        }
    }

    for (String s : alsItems) {
        System.out.println("----------");
        System.out.print(s);
    }
}

From source file:com.blockhaus2000.csvviewer.CsvViewerMain.java

public static void main(final String[] args) {
    try (final CSVParser parser = new CSVParser(new InputStreamReader(System.in), CSVFormat.DEFAULT)) {
        final Table table = new Table();

        final Map<String, Integer> headerMap = parser.getHeaderMap();
        if (headerMap != null) {
            final TableRow headerRow = new TableRow();
            headerMap.keySet().forEach(headerData -> headerRow.addCell(new TableRowCell(headerData)));
            table.setHeaderRow(headerRow);
        }//from   w w  w.ja v a 2s. co  m

        final AtomicBoolean asHeader = new AtomicBoolean(headerMap == null);
        parser.getRecords().forEach(record -> {
            final TableRow row = new TableRow();
            record.forEach(rowData -> row.addCell(new TableRowCell(rowData)));
            if (asHeader.getAndSet(false)) {
                table.setHeaderRow(row);
            } else {
                table.addRow(row);
            }
        });

        System.out.println(table.getFormattedString());
    } catch (final IOException cause) {
        throw new RuntimeException("An error occurred whilst parsing stdin!", cause);
    }
}

From source file:edu.wpi.checksims.ChecksimsRunner.java

/**
 * CLI entrypoint of Checksims.//from  w  ww.ja v a  2s.  c  o  m
 *
 * @param args CLI arguments
 */
public static void main(String[] args) {
    ChecksimsConfig config;

    try {
        config = ChecksimsCommandLine.parseCLI(args);
    } catch (ParseException e) {
        throw new RuntimeException("Error parsing command-line options", e);
    } catch (ChecksimsException e) {
        throw new RuntimeException("Error interpreting command-line options", e);
    } catch (IOException e) {
        throw new RuntimeException("Error building submissions", e);
    }

    logs = LoggerFactory.getLogger(ChecksimsRunner.class);

    runChecksims(config);

    System.exit(0);
}

From source file:com.aliyun.odps.mapred.cli.Cli.java

public static void main(String[] args) {
    SessionState ss = SessionState.get();
    OptionParser parser = new OptionParser(ss);
    try {//from  w  w  w  .ja va  2 s.c o  m
        parser.parse(args);
    } catch (FileNotFoundException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    } catch (ClassNotFoundException e) {
        System.err.println("Class not found:" + e.getMessage());
        System.exit(-1);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        parser.usage();
        System.exit(-1);
    } catch (OdpsException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    }

    try {
        Method main = parser.getMainClass().getMethod("main", String[].class);
        main.invoke(null, (Object) parser.getArguments());
    } catch (InvocationTargetException e) {
        Throwable t = e.getCause();
        if (t != null && t instanceof OdpsException) {
            OdpsException ex = (OdpsException) t;
            System.err.println(ex.getErrorCode() + ":" + ex.getMessage());
            System.exit(-1);
        } else {
            throw new RuntimeException("Unknown error", e);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.usc.goffish.gofs.tools.GoFSFormat.java

public static void main(String[] args) throws IOException {
    if (args.length < REQUIRED_ARGS) {
        PrintUsageAndQuit(null);/*from w ww .j a va  2 s . c  o  m*/
    }

    if (args.length == 1 && args[0].equals("-help")) {
        PrintUsageAndQuit(null);
    }

    Path executableDirectory;
    try {
        executableDirectory = Paths
                .get(GoFSFormat.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();
    } catch (URISyntaxException e) {
        throw new RuntimeException("Unexpected error retrieving executable location", e);
    }
    Path configPath = executableDirectory.resolve(DEFAULT_CONFIG).normalize();

    boolean copyBinaries = false;

    // parse optional arguments
    int i = 0;
    OptArgLoop: for (i = 0; i < args.length - REQUIRED_ARGS; i++) {
        switch (args[i]) {
        case "-config":
            i++;

            try {
                configPath = Paths.get(args[i]);
            } catch (InvalidPathException e) {
                PrintUsageAndQuit("Config file - " + e.getMessage());
            }

            break;
        case "-copyBinaries":
            copyBinaries = true;
            break;
        default:
            break OptArgLoop;
        }
    }

    if (args.length - i < REQUIRED_ARGS) {
        PrintUsageAndQuit(null);
    }

    // finished parsing args
    if (i < args.length) {
        PrintUsageAndQuit("Unrecognized argument \"" + args[i] + "\"");
    }

    // parse config

    System.out.println("Parsing config...");

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setDelimiterParsingDisabled(true);
    try {
        config.load(Files.newInputStream(configPath));
    } catch (ConfigurationException e) {
        throw new IOException(e);
    }

    // retrieve data nodes
    ArrayList<URI> dataNodes;
    {
        String[] dataNodesArray = config.getStringArray(GOFS_DATANODES_KEY);
        if (dataNodesArray.length == 0) {
            throw new ConversionException("Config must contain key " + GOFS_DATANODES_KEY);
        }

        dataNodes = new ArrayList<>(dataNodesArray.length);

        if (dataNodesArray.length == 0) {
            throw new ConversionException("Config key " + GOFS_DATANODES_KEY
                    + " has invalid format - must define at least one data node");
        }

        try {
            for (String node : dataNodesArray) {
                URI dataNodeURI = new URI(node);

                if (!"file".equalsIgnoreCase(dataNodeURI.getScheme())) {
                    throw new ConversionException("config key " + GOFS_DATANODES_KEY + " value \"" + dataNodeURI
                            + "\" has invalid format - data node urls must have 'file' scheme");
                } else if (dataNodeURI.getPath() == null || dataNodeURI.getPath().isEmpty()) {
                    throw new ConversionException("config key " + GOFS_DATANODES_KEY + " value \"" + dataNodeURI
                            + "\" has invalid format - data node urls must have an absolute path specified");
                }

                // ensure uri ends with a slash, so we know it is a directory
                if (!dataNodeURI.getPath().endsWith("/")) {
                    dataNodeURI = dataNodeURI.resolve(dataNodeURI.getPath() + "/");
                }

                dataNodes.add(dataNodeURI);
            }
        } catch (URISyntaxException e) {
            throw new ConversionException(
                    "Config key " + GOFS_DATANODES_KEY + " has invalid format - " + e.getMessage());
        }
    }

    // validate serializer type
    Class<? extends ISliceSerializer> serializerType;
    {
        String serializerTypeName = config.getString(GOFS_SERIALIZER_KEY);
        if (serializerTypeName == null) {
            throw new ConversionException("Config must contain key " + GOFS_SERIALIZER_KEY);
        }

        try {
            serializerType = SliceSerializerProvider.loadSliceSerializerType(serializerTypeName);
        } catch (ReflectiveOperationException e) {
            throw new ConversionException(
                    "Config key " + GOFS_SERIALIZER_KEY + " has invalid format - " + e.getMessage());
        }
    }

    // retrieve name node
    IInternalNameNode nameNode;
    try {
        nameNode = NameNodeProvider.loadNameNodeFromConfig(config, GOFS_NAMENODE_TYPE_KEY,
                GOFS_NAMENODE_LOCATION_KEY);
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException("Unable to load name node", e);
    }

    System.out.println("Contacting name node...");

    // validate name node
    if (!nameNode.isAvailable()) {
        throw new IOException("Name node at " + nameNode.getURI() + " is not available");
    }

    System.out.println("Contacting data nodes...");

    // validate data nodes
    for (URI dataNode : dataNodes) {
        // only attempt ssh if host exists
        if (dataNode.getHost() != null) {
            try {
                SSHHelper.SSH(dataNode, "true");
            } catch (IOException e) {
                throw new IOException("Data node at " + dataNode + " is not available", e);
            }
        }
    }

    // create temporary directory
    Path workingDir = Files.createTempDirectory("gofs_format");
    try {
        // create deploy directory
        Path deployDirectory = Files.createDirectory(workingDir.resolve(DATANODE_DIR_NAME));

        // create empty slice directory
        Files.createDirectory(deployDirectory.resolve(DataNode.DATANODE_SLICE_DIR));

        // copy binaries
        if (copyBinaries) {
            System.out.println("Copying binaries...");
            FileUtils.copyDirectory(executableDirectory.toFile(),
                    deployDirectory.resolve(executableDirectory.getFileName()).toFile());
        }

        // write config file
        Path dataNodeConfigFile = deployDirectory.resolve(DataNode.DATANODE_CONFIG);
        try {
            // create config for every data node and scp deploy folder into place
            for (URI dataNodeParent : dataNodes) {
                URI dataNode = dataNodeParent.resolve(DATANODE_DIR_NAME);

                PropertiesConfiguration datanode_config = new PropertiesConfiguration();
                datanode_config.setDelimiterParsingDisabled(true);
                datanode_config.setProperty(DataNode.DATANODE_INSTALLED_KEY, true);
                datanode_config.setProperty(DataNode.DATANODE_NAMENODE_TYPE_KEY,
                        config.getString(GOFS_NAMENODE_TYPE_KEY));
                datanode_config.setProperty(DataNode.DATANODE_NAMENODE_LOCATION_KEY,
                        config.getString(GOFS_NAMENODE_LOCATION_KEY));
                datanode_config.setProperty(DataNode.DATANODE_LOCALHOSTURI_KEY, dataNode.toString());

                try {
                    datanode_config.save(Files.newOutputStream(dataNodeConfigFile));
                } catch (ConfigurationException e) {
                    throw new IOException(e);
                }

                System.out.println("Formatting data node " + dataNode.toString() + "...");

                // scp everything into place on the data node
                SCPHelper.SCP(deployDirectory, dataNodeParent);

                // update name node
                nameNode.addDataNode(dataNode);
            }

            // update name node
            nameNode.setSerializer(serializerType);
        } catch (Exception e) {
            System.out.println(
                    "ERROR: data node formatting interrupted - name node and data nodes are in an inconsistent state and require clean up");
            throw e;
        }

        System.out.println("GoFS format complete");

    } finally {
        FileUtils.deleteQuietly(workingDir.toFile());
    }
}

From source file:examples.mail.IMAPMail.java

public static void main(String[] args) {
    if (args.length < 3) {
        System.err.println("Usage: IMAPMail <imap server hostname> <username> <password> [TLS]");
        System.exit(1);/* ww  w .ja v  a2 s.  c  om*/
    }

    String server = args[0];
    String username = args[1];
    String password = args[2];

    String proto = (args.length > 3) ? args[3] : null;

    IMAPClient imap;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        imap = new IMAPSClient(proto, true); // implicit
        // enable the next line to only check if the server certificate has expired (does not check chain):
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        // OR enable the next line if the server uses a self-signed certificate (no checks)
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
    } else {
        imap = new IMAPClient();
    }
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

    // We want to timeout if a response takes longer than 60 seconds
    imap.setDefaultTimeout(60000);

    // suppress login details
    imap.addProtocolCommandListener(new PrintCommandListener(System.out, true));

    try {
        imap.connect(server);
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    try {
        if (!imap.login(username, password)) {
            System.err.println("Could not login to server. Check password.");
            imap.disconnect();
            System.exit(3);
        }

        imap.setSoTimeout(6000);

        imap.capability();

        imap.select("inbox");

        imap.examine("inbox");

        imap.status("inbox", new String[] { "MESSAGES" });

        imap.logout();
        imap.disconnect();
    } catch (IOException e) {
        System.out.println(imap.getReplyString());
        e.printStackTrace();
        System.exit(10);
        return;
    }
}

From source file:ch.tatool.app.service.export.DataImportTest.java

public static void main(String[] args) {
    // get the httpentity containing the data
    HttpEntity httpEntity = getHttpEntity();
    // Create a httpclient instance
    DefaultHttpClient httpclient = new DefaultHttpClient();
    // setup a POST call
    HttpGet httpGet = new HttpGet(serverUrl);

    try {/*from   www. j ava2  s. c o m*/
        HttpResponse response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            System.out.println("Unable to download data: " + response.getStatusLine().getReasonPhrase());
            System.out.println(response.getStatusLine().getStatusCode());
        } else {
            // all ok
            HttpEntity enty = response.getEntity();
            InputStream is = enty.getContent();

            XmlBeanFactory beanFactory = null;
            try {

                beanFactory = new XmlBeanFactory(new InputStreamResource(is));

            } catch (BeansException be) {
                // TODO: inform user that training configuration is broken
                throw new RuntimeException("Unable to load module configuration", be);
            }

            // check whether we have the mandatory beans (rootElement)
            if (!beanFactory.containsBean("rootElement")) {
                // TODO: inform user that training configuration is broken
                throw new RuntimeException("No rootElement bean found in the module configuration file");
            }

            // fetch the rootElement
            Node rootElement = (Node) beanFactory.getBean("rootElement");

            System.out.println(rootElement.getId());

        }
    } catch (IOException ioe) {

    }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}