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:Main.java

/**
   Return the first children of a node with a given name.
   @throws Exception if no child is found
 *///  ww w. jav a 2s.  com
static public Node assertChild(Node node, String child_name) throws Exception {
    Node ret = findChild(node, child_name);
    if (ret == null)
        throw new Exception("Cannot find " + child_name + " node");
    return ret;
}

From source file:Main.java

public static String httpGet(String url) throws Exception {
    ensureHttpClient();//www.  jav a2 s.  c  o m

    HttpGet request = new HttpGet(url);
    HttpResponse response = httpClient.execute(request);
    if (response != null) {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200)
            return stringFromInputStream(response.getEntity().getContent());
        else
            throw new Exception("Got error code " + statusCode + " from server");
    }

    throw new Exception("Unable to connect to server");
}

From source file:Main.java

/**
 * Convert xml to string./*w ww. ja  v a  2s. c  om*/
 *
 * @param pDocument
 *            the p document
 * @param encoding
 *            the encoding
 * @return the string
 * @throws Exception
 *             the exception
 */
public static String convertXML2String(Document pDocument, String encoding) throws Exception {
    TransformerFactory transformerFactory = null;
    Transformer transformer = null;
    DOMSource domSource = null;
    StringWriter writer = new java.io.StringWriter();
    StreamResult result = null;

    try {
        transformerFactory = TransformerFactory.newInstance();
        if (transformerFactory == null) {
            throw new Exception("TransformerFactory error");
        }

        transformer = transformerFactory.newTransformer();
        if (transformer == null) {
            throw new Exception("Transformer error");
        }

        if (encoding != null) {
            transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
        } else {
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        }

        domSource = new DOMSource(pDocument);
        result = new StreamResult(writer);

        transformer.transform(domSource, result);

        return writer.toString();
    } catch (TransformerFactoryConfigurationError e) {
        throw new Exception("TransformerFactoryConfigurationError", e);
    } catch (TransformerConfigurationException e) {
        throw new Exception("TransformerConfigurationException", e);
    } catch (TransformerException e) {
        throw new Exception("TransformerException", e);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException ex) {
            throw new Exception("IO error", ex);
        }
    }
}

From source file:Main.java

public static String getElementValue(String elementName, Element element) throws Exception {
    String value = null;//from  ww  w .  j a v a 2 s  .com
    NodeList childNodes = element.getElementsByTagName(elementName);
    Element cn = (Element) childNodes.item(0);
    value = cn.getFirstChild().getNodeValue().trim();
    //value = childNodes.item(0).getNodeValue().trim();
    if (value == null) {
        throw new Exception("No element found with given name:" + elementName);
    }
    return value;
}

From source file:com.likya.tlos.utils.PasswordService.java

public static synchronized String encrypt(String plaintext) throws Exception {
    MessageDigest md = null;//from www.  ja v  a 2s.  c  om
    try {
        md = MessageDigest.getInstance("SHA"); // step 2 //$NON-NLS-1$
    } catch (NoSuchAlgorithmException e) {
        throw new Exception(e.getMessage());
    }
    try {
        md.update(plaintext.getBytes("UTF-8")); // step 3 //$NON-NLS-1$
    } catch (UnsupportedEncodingException e) {
        throw new Exception(e.getMessage());
    }
    byte raw[] = md.digest(); // step 4

    /**
     * Sun uygulamasndan vazgeilip apache uygulamas kullanld
     * 16.03.2011 
     * 
     */
    // String hash = (new BASE64Encoder()).encode(raw); // step 5

    String hash = Base64.encodeBase64String(raw);

    return hash; // step 6
}

From source file:edu.msu.cme.rdp.classifier.comparison.ComparisonCmd.java

public static void main(String[] args) throws Exception {

    String queryFile1 = null;//from www  .jav a  2  s.  c  o m
    String queryFile2 = null;
    String class_outputFile = null;
    String compare_outputFile = null;
    String propFile = null;
    ClassificationResultFormatter.FORMAT format = CmdOptions.DEFAULT_FORMAT;
    float conf_cutoff = CmdOptions.DEFAULT_CONF;
    String gene = null;

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption(QUERYFILE1_SHORT_OPT)) {
            queryFile1 = line.getOptionValue(QUERYFILE1_SHORT_OPT);
        } else {
            throw new Exception("queryFile1 must be specified");
        }
        if (line.hasOption(QUERYFILE2_SHORT_OPT)) {
            queryFile2 = line.getOptionValue(QUERYFILE2_SHORT_OPT);
        } else {
            throw new Exception("queryFile2 must be specified");
        }

        if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) {
            class_outputFile = line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT);
        } else {
            throw new Exception("outputFile for classification results must be specified");
        }

        if (line.hasOption(COMPARE_OUTFILE_SHORT_OPT)) {
            compare_outputFile = line.getOptionValue(COMPARE_OUTFILE_SHORT_OPT);
        } else {
            throw new Exception("outputFile for comparsion results must be specified");
        }

        if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) {
            if (gene != null) {
                throw new IllegalArgumentException(
                        "Already specified the gene from the default location. Can not specify train_propfile");
            } else {
                propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT);
            }
        }
        if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) {
            conf_cutoff = Float.parseFloat(line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT));
        }
        if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) {
            String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT);
            if (f.equalsIgnoreCase("allrank")) {
                format = ClassificationResultFormatter.FORMAT.allRank;
            } else if (f.equalsIgnoreCase("fixrank")) {
                format = ClassificationResultFormatter.FORMAT.fixRank;
            } else if (f.equalsIgnoreCase("filterbyconf")) {
                format = ClassificationResultFormatter.FORMAT.filterbyconf;
            } else if (f.equalsIgnoreCase("db")) {
                format = ClassificationResultFormatter.FORMAT.dbformat;
            } else {
                throw new IllegalArgumentException(
                        "Not valid output format, only allrank, fixrank, filterbyconf and db allowed");
            }

        }
        if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) {
            if (propFile != null) {
                throw new IllegalArgumentException(
                        "Already specified train_propfile. Can not specify gene any more");
            }
            gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase();

            if (!gene.equals(ClassifierFactory.RRNA_16S_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALLSU_GENE)) {
                throw new IllegalArgumentException(gene + " is NOT valid, only allows "
                        + ClassifierFactory.RRNA_16S_GENE + " and " + ClassifierFactory.FUNGALLSU_GENE);
            }
        }
    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(120, "ComparisonCmd", "", options, "", true);
        return;
    }

    if (propFile == null && gene == null) {
        gene = ClassifierFactory.RRNA_16S_GENE;
    }

    ComparisonCmd cmd = new ComparisonCmd(propFile, gene);
    cmd.setConfidenceCutoff(conf_cutoff);
    printLicense();

    cmd.doClassify(queryFile1, queryFile2, class_outputFile, compare_outputFile, format);

}

From source file:eu.riscoss.RemoteRiskAnalyserMain.java

static void loadJSmile() throws Exception {
    File dir = new File(FileUtils.getTempDirectory(), "jnativelibs-" + RandomStringUtils.randomAlphabetic(30));
    if (!dir.mkdir()) {
        throw new Exception("failed to make dir");
    }//from  w ww  .j a v a2s. c o  m
    File jsmile = new File(dir, "libjsmile.so");
    URL jsmURL = Thread.currentThread().getContextClassLoader().getResource("libjsmile.so");
    FileUtils.copyURLToFile(jsmURL, jsmile);
    System.setProperty("java.library.path",
            System.getProperty("java.library.path") + ":" + dir.getAbsolutePath());

    // flush the library paths
    Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
    sysPathsField.setAccessible(true);
    sysPathsField.set(null, null);

    // Check that it works...
    System.loadLibrary("jsmile");

    dir.deleteOnExit();
    jsmile.deleteOnExit();
}

From source file:io.cloudslang.content.database.services.SQLQueryService.java

public static void executeSqlQuery(@NotNull final SQLInputs sqlInputs) throws Exception {
    if (StringUtils.isEmpty(sqlInputs.getSqlCommand())) {
        throw new Exception("command input is empty.");
    }/* w w  w.ja  v a2s  .  c  o  m*/
    ConnectionService connectionService = new ConnectionService();
    try (final Connection connection = connectionService.setUpConnection(sqlInputs)) {

        connection.setReadOnly(true);
        Statement statement = connection.createStatement(sqlInputs.getResultSetType(),
                sqlInputs.getResultSetConcurrency());
        statement.setQueryTimeout(sqlInputs.getTimeout());
        final ResultSet results = statement.executeQuery(sqlInputs.getSqlCommand());

        final ResultSetMetaData mtd = results.getMetaData();

        int iNumCols = mtd.getColumnCount();

        final StringBuilder strColumns = new StringBuilder(sqlInputs.getStrColumns());

        for (int i = 1; i <= iNumCols; i++) {
            if (i > 1) {
                strColumns.append(sqlInputs.getStrDelim());
            }
            strColumns.append(mtd.getColumnLabel(i));
        }
        sqlInputs.setStrColumns(strColumns.toString());

        while (results.next()) {
            final StringBuilder strRowHolder = new StringBuilder();
            for (int i = 1; i <= iNumCols; i++) {
                if (i > 1)
                    strRowHolder.append(sqlInputs.getStrDelim());
                if (results.getString(i) != null) {
                    String value = results.getString(i).trim();
                    if (sqlInputs.isNetcool())
                        value = SQLUtils.processNullTerminatedString(value);

                    strRowHolder.append(value);
                }
            }
            sqlInputs.getLRows().add(strRowHolder.toString());
        }
    }
}

From source file:Main.java

/**
 * Convert xml to byte array./*from  ww  w  .  j ava 2  s .  c o  m*/
 *
 * @param pDocument
 *            the p document
 * @param encoding
 *            the encoding
 * @return the byte[]
 * @throws Exception
 *             the exception
 */
public static byte[] convertXML2ByteArray(Node pDocument, String encoding) throws Exception {
    TransformerFactory transformerFactory = null;
    Transformer transformer = null;
    DOMSource domSource = null;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    StreamResult result = null;

    try {
        transformerFactory = TransformerFactory.newInstance();
        if (transformerFactory == null) {
            throw new Exception("TransformerFactory error");
        }

        transformer = transformerFactory.newTransformer();
        if (transformer == null) {
            throw new Exception("Transformer error");
        }

        if (encoding != null) {
            transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
        } else {
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        }

        domSource = new DOMSource(pDocument);
        result = new StreamResult(outputStream);

        transformer.transform(domSource, result);

        return outputStream.toByteArray();
    } catch (TransformerFactoryConfigurationError e) {
        throw new Exception("TransformerFactoryConfigurationError", e);
    } catch (TransformerConfigurationException e) {
        throw new Exception("TransformerConfigurationException", e);
    } catch (TransformerException e) {
        throw new Exception("TransformerException", e);
    } finally {
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ex) {
            throw new Exception("IO error", ex);
        }
    }
}

From source file:Main.java

/**
 * Gets the encoding of xml byte array./*ww w  .  ja v a  2 s  .c o  m*/
 *
 * @param xmlData
 *            the xml data
 * @return the encoding of xml byte array
 * @throws Exception
 *             the exception
 */
public static String getEncodingOfXmlByteArray(byte[] xmlData) throws Exception {
    String encodingAttributeName = "ENCODING";
    try {
        String first50CharactersInUtf8UpperCase = new String(xmlData, "UTF-8").substring(0, 50).toUpperCase();
        if (first50CharactersInUtf8UpperCase.contains(encodingAttributeName)) {
            int encodingstart = first50CharactersInUtf8UpperCase.indexOf(encodingAttributeName)
                    + encodingAttributeName.length();

            int contentStartEinfach = first50CharactersInUtf8UpperCase.indexOf("'", encodingstart);
            int contentStartDoppelt = first50CharactersInUtf8UpperCase.indexOf("\"", encodingstart);
            int contentStart = Math.min(contentStartEinfach, contentStartDoppelt);
            if (contentStartEinfach < 0) {
                contentStart = contentStartDoppelt;
            }
            if (contentStart < 0) {
                throw new Exception("XmlByteArray-Encoding nicht ermittelbar");
            }
            contentStart = contentStart + 1;

            int contentEndSingle = first50CharactersInUtf8UpperCase.indexOf("'", contentStart);
            int contentEndDouble = first50CharactersInUtf8UpperCase.indexOf("\"", contentStart);
            int contentEnd = Math.min(contentEndSingle, contentEndDouble);
            if (contentEndSingle < 0) {
                contentEnd = contentEndDouble;
            }
            if (contentEnd < 0) {
                throw new Exception("XmlByteArray-Encoding nicht ermittelbar");
            }

            String encodingString = first50CharactersInUtf8UpperCase.substring(contentStart, contentEnd);
            return encodingString;
        } else {
            throw new Exception("XmlByteArray-Encoding nicht ermittelbar");
        }
    } catch (UnsupportedEncodingException e) {
        throw new Exception("XmlByteArray-Encoding nicht ermittelbar");
    }
}