Example usage for org.xml.sax SAXException getMessage

List of usage examples for org.xml.sax SAXException getMessage

Introduction

In this page you can find the example usage for org.xml.sax SAXException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Return a detail message for this exception.

Usage

From source file:de.zib.scalaris.examples.wikipedia.data.xml.Main.java

/**
 * The main function of the application. Some articles are blacklisted and
 * will not be processed (see implementation for a list of them).
 * /*from w w  w . j  a v a2  s  .  com*/
 * @param args
 *            first argument should be the xml file to convert.
 */
public static void main(String[] args) {
    try {
        String filename = args[0];

        if (args.length > 1) {
            if (args[1].equals("filter")) {
                doFilter(filename, Arrays.copyOfRange(args, 2, args.length));
            } else if (args[1].equals("import-xml")) {
                doImport(filename, Arrays.copyOfRange(args, 2, args.length), ImportType.IMPORT_XML);
            } else if (args[1].equals("import-db")) {
                doImport(filename, Arrays.copyOfRange(args, 2, args.length), ImportType.IMPORT_DB);
            } else if (args[1].equals("prepare")) {
                doImport(filename, Arrays.copyOfRange(args, 2, args.length), ImportType.PREPARE_DB);
            } else if (args[1].equals("xml2db")) {
                doImport(filename, Arrays.copyOfRange(args, 2, args.length), ImportType.XML_2_DB);
            } else if (args[1].equals("convert")) {
                doConvert(filename, Arrays.copyOfRange(args, 2, args.length));
            } else if (args[1].equals("dumpdb-addlinks")) {
                doDumpdbAddlinks(filename, Arrays.copyOfRange(args, 2, args.length));
            } else if (args[1].equals("dumpdb-filter")) {
                doDumpdbFilter(filename, Arrays.copyOfRange(args, 2, args.length));
            }
        }
    } catch (SAXException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:tuit.java

@SuppressWarnings("ConstantConditions")
public static void main(String[] args) {
    System.out.println(licence);//  ww  w  . j  a  va  2s  .  com
    //Declare variables
    File inputFile;
    File outputFile;
    File tmpDir;
    File blastnExecutable;
    File properties;
    File blastOutputFile = null;
    //
    TUITPropertiesLoader tuitPropertiesLoader;
    TUITProperties tuitProperties;
    //
    String[] parameters = null;
    //
    Connection connection = null;
    MySQL_Connector mySQL_connector;
    //
    Map<Ranks, TUITCutoffSet> cutoffMap;
    //
    BLASTIdentifier blastIdentifier = null;
    //
    RamDb ramDb = null;

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption(tuit.IN, "input<file>", true, "Input file (currently fasta-formatted only)");
    options.addOption(tuit.OUT, "output<file>", true, "Output file (in " + tuit.TUIT_EXT + " format)");
    options.addOption(tuit.P, "prop<file>", true, "Properties file (XML formatted)");
    options.addOption(tuit.V, "verbose", false, "Enable verbose output");
    options.addOption(tuit.B, "blast_output<file>", true, "Perform on a pre-BLASTed output");
    options.addOption(tuit.DEPLOY, "deploy", false, "Deploy the taxonomic databases");
    options.addOption(tuit.UPDATE, "update", false, "Update the taxonomic databases");
    options.addOption(tuit.USE_DB, "usedb", false, "Use RDBMS instead of RAM-based taxonomy");

    Option option = new Option(tuit.REDUCE, "reduce", true,
            "Pack identical (100% similar sequences) records in the given sample file");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    option = new Option(tuit.COMBINE, "combine", true,
            "Combine a set of given reduction files into an HMP Tree-compatible taxonomy");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    options.addOption(tuit.NORMALIZE, "normalize", false,
            "If used in combination with -combine ensures that the values are normalized by the root value");

    HelpFormatter formatter = new HelpFormatter();

    try {

        //Get TUIT directory
        final File tuitDir = new File(
                new File(tuit.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())
                        .getParent());
        final File ramDbFile = new File(tuitDir, tuit.RAM_DB);

        //Setup logger
        Log.getInstance().setLogName("tuit.log");

        //Read command line
        final CommandLine commandLine = parser.parse(options, args, true);

        //Check if the REDUCE option is on
        if (commandLine.hasOption(tuit.REDUCE)) {

            final String[] fileList = commandLine.getOptionValues(tuit.REDUCE);
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Processing " + path.toString() + "...");
                final NucleotideFastaSequenceReductor nucleotideFastaSequenceReductor = NucleotideFastaSequenceReductor
                        .fromPath(path);
                ReductorFileOperator.save(nucleotideFastaSequenceReductor,
                        path.resolveSibling(path.getFileName().toString() + ".rdc"));
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Check if COMBINE is on
        if (commandLine.hasOption(tuit.COMBINE)) {
            final boolean normalize = commandLine.hasOption(tuit.NORMALIZE);
            final String[] fileList = commandLine.getOptionValues(tuit.COMBINE);
            //TODO: implement a test for format here

            final List<TreeFormatter.TreeFormatterFormat.HMPTreesOutput> hmpTreesOutputs = new ArrayList<>();
            final TreeFormatter treeFormatter = TreeFormatter
                    .newInstance(new TreeFormatter.TuitLineTreeFormatterFormat());
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Merging " + path.toString() + "...");
                treeFormatter.loadFromPath(path);
                final TreeFormatter.TreeFormatterFormat.HMPTreesOutput output = TreeFormatter.TreeFormatterFormat.HMPTreesOutput
                        .newInstance(treeFormatter.toHMPTree(normalize), s.substring(0, s.indexOf(".")));
                hmpTreesOutputs.add(output);
                treeFormatter.erase();
            }
            final Path destination;
            if (commandLine.hasOption(OUT)) {
                destination = Paths.get(commandLine.getOptionValue(tuit.OUT));
            } else {
                destination = Paths.get("merge.tcf");
            }
            CombinatorFileOperator.save(hmpTreesOutputs, treeFormatter, destination);
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        if (!commandLine.hasOption(tuit.P)) {
            throw new ParseException("No properties file option found, exiting.");
        } else {
            properties = new File(commandLine.getOptionValue(tuit.P));
        }

        //Load properties
        tuitPropertiesLoader = TUITPropertiesLoader.newInstanceFromFile(properties);
        tuitProperties = tuitPropertiesLoader.getTuitProperties();

        //Create tmp directory and blastn executable
        tmpDir = new File(tuitProperties.getTMPDir().getPath());
        blastnExecutable = new File(tuitProperties.getBLASTNPath().getPath());

        //Check for deploy
        if (commandLine.hasOption(tuit.DEPLOY)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.fastDeployNCBIDatabasesFromNCBI(connection, tmpDir);
            } else {
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }
        //Check for update
        if (commandLine.hasOption(tuit.UPDATE)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.updateDatabasesFromNCBI(connection, tmpDir);
            } else {
                //No need to specify a different way to update the database other than just deploy in case of the RAM database
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Connect to the database
        if (commandLine.hasOption(tuit.USE_DB)) {
            mySQL_connector = MySQL_Connector.newDefaultInstance(
                    "jdbc:mysql://" + tuitProperties.getDBConnection().getUrl().trim() + "/",
                    tuitProperties.getDBConnection().getLogin().trim(),
                    tuitProperties.getDBConnection().getPassword().trim());
            mySQL_connector.connectToDatabase();
            connection = mySQL_connector.getConnection();
        } else {
            //Probe for ram database

            if (ramDbFile.exists() && ramDbFile.canRead()) {
                Log.getInstance().log(Level.INFO, "Loading RAM taxonomic map...");
                try {
                    ramDb = RamDb.loadSelfFromFile(ramDbFile);
                } catch (IOException ie) {
                    if (ie instanceof java.io.InvalidClassException)
                        throw new IOException("The RAM-based taxonomic database needs to be updated.");
                }

            } else {
                Log.getInstance().log(Level.SEVERE,
                        "The RAM database either has not been deployed, or is not accessible."
                                + "Please use the --deploy option and check permissions on the TUIT directory. "
                                + "If you were looking to use the RDBMS as a taxonomic reference, plese use the -usedb option.");
                return;
            }
        }

        if (commandLine.hasOption(tuit.B)) {
            blastOutputFile = new File(commandLine.getOptionValue(tuit.B));
            if (!blastOutputFile.exists() || !blastOutputFile.canRead()) {
                throw new Exception("BLAST output file either does not exist, or is not readable.");
            } else if (blastOutputFile.isDirectory()) {
                throw new Exception("BLAST output file points to a directory.");
            }
        }
        //Check vital parameters
        if (!commandLine.hasOption(tuit.IN)) {
            throw new ParseException("No input file option found, exiting.");
        } else {
            inputFile = new File(commandLine.getOptionValue(tuit.IN));
            Log.getInstance().setLogName(inputFile.getName().split("\\.")[0] + ".tuit.log");
        }
        //Correct the output file option if needed
        if (!commandLine.hasOption(tuit.OUT)) {
            outputFile = new File((inputFile.getPath()).split("\\.")[0] + tuit.TUIT_EXT);
        } else {
            outputFile = new File(commandLine.getOptionValue(tuit.OUT));
        }

        //Adjust the output level
        if (commandLine.hasOption(tuit.V)) {
            Log.getInstance().setLevel(Level.FINE);
            Log.getInstance().log(Level.INFO, "Using verbose output for the log");
        } else {
            Log.getInstance().setLevel(Level.INFO);
        }
        //Try all files
        if (inputFile != null) {
            if (!inputFile.exists() || !inputFile.canRead()) {
                throw new Exception("Input file either does not exist, or is not readable.");
            } else if (inputFile.isDirectory()) {
                throw new Exception("Input file points to a directory.");
            }
        }

        if (!properties.exists() || !properties.canRead()) {
            throw new Exception("Properties file either does not exist, or is not readable.");
        } else if (properties.isDirectory()) {
            throw new Exception("Properties file points to a directory.");
        }

        //Create blast parameters
        final StringBuilder stringBuilder = new StringBuilder();
        for (Database database : tuitProperties.getBLASTNParameters().getDatabase()) {
            stringBuilder.append(database.getUse());
            stringBuilder.append(" ");//Gonna insert an extra space for the last database
        }
        String remote;
        String entrez_query;
        if (tuitProperties.getBLASTNParameters().getRemote().getDelegate().equals("yes")) {
            remote = "-remote";
            entrez_query = "-entrez_query";
            parameters = new String[] { "-db", stringBuilder.toString(), remote, entrez_query,
                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue(), "-evalue",
                    tuitProperties.getBLASTNParameters().getExpect().getValue() };
        } else {
            if (!commandLine.hasOption(tuit.B)) {
                if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .startsWith("NOT")
                        || tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                                .startsWith("ALL")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-negative_gilist",
                            TUITFileOperatorHelper.restrictToEntrez(tmpDir,
                                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()
                                            .toUpperCase().replace("NOT", "OR"))
                                    .getAbsolutePath(),
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .equals("")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-num_threads",
                            tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(),
                            /*"-gilist", TUITFileOperatorHelper.restrictToEntrez(
                            tmpDir, tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()).getAbsolutePath(),*/ //TODO remove comment!!!!!
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                }
            }
        }
        //Prepare a cutoff Map
        if (tuitProperties.getSpecificationParameters() != null
                && tuitProperties.getSpecificationParameters().size() > 0) {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>(tuitProperties.getSpecificationParameters().size());
            for (SpecificationParameters specificationParameters : tuitProperties
                    .getSpecificationParameters()) {
                cutoffMap.put(Ranks.valueOf(specificationParameters.getCutoffSet().getRank()),
                        TUITCutoffSet.newDefaultInstance(
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getPIdentCutoff().getValue()),
                                Double.parseDouble(specificationParameters.getCutoffSet()
                                        .getQueryCoverageCutoff().getValue()),
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getAlpha().getValue())));
            }
        } else {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>();
        }
        final TUITFileOperatorHelper.OutputFormat format;
        if (tuitProperties.getBLASTNParameters().getOutputFormat().getFormat().equals("rdp")) {
            format = TUITFileOperatorHelper.OutputFormat.RDP_FIXRANK;
        } else {
            format = TUITFileOperatorHelper.OutputFormat.TUIT;
        }

        try (TUITFileOperator<NucleotideFasta> nucleotideFastaTUITFileOperator = NucleotideFastaTUITFileOperator
                .newInstance(format, cutoffMap);) {
            nucleotideFastaTUITFileOperator.setInputFile(inputFile);
            nucleotideFastaTUITFileOperator.setOutputFile(outputFile);
            final String cleanupString = tuitProperties.getBLASTNParameters().getKeepBLASTOuts().getKeep();
            final boolean cleanup;
            if (cleanupString.equals("no")) {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be deleted.");
                cleanup = true;
            } else {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be kept.");
                cleanup = false;
            }
            //Create blast identifier
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            if (commandLine.hasOption(tuit.USE_DB)) {

                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, connection,
                            cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, connection, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else {
                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup, ramDb);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup, ramDb);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            Future<?> runnableFuture = executorService.submit(blastIdentifier);
            runnableFuture.get();
            executorService.shutdown();
        }
    } catch (ParseException pe) {
        Log.getInstance().log(Level.SEVERE, (pe.getMessage()));
        formatter.printHelp("tuit", options);
    } catch (SAXException saxe) {
        Log.getInstance().log(Level.SEVERE, saxe.getMessage());
    } catch (FileNotFoundException fnfe) {
        Log.getInstance().log(Level.SEVERE, fnfe.getMessage());
    } catch (TUITPropertyBadFormatException tpbfe) {
        Log.getInstance().log(Level.SEVERE, tpbfe.getMessage());
    } catch (ClassCastException cce) {
        Log.getInstance().log(Level.SEVERE, cce.getMessage());
    } catch (JAXBException jaxbee) {
        Log.getInstance().log(Level.SEVERE,
                "The properties file is not well formatted. Please ensure that the XML is consistent with the io.properties.dtd schema.");
    } catch (ClassNotFoundException cnfe) {
        //Probably won't happen unless the library deleted from the .jar
        Log.getInstance().log(Level.SEVERE, cnfe.getMessage());
        //cnfe.printStackTrace();
    } catch (SQLException sqle) {
        Log.getInstance().log(Level.SEVERE,
                "A database communication error occurred with the following message:\n" + sqle.getMessage());
        //sqle.printStackTrace();
        if (sqle.getMessage().contains("Access denied for user")) {
            Log.getInstance().log(Level.SEVERE, "Please use standard database login: "
                    + NCBITablesDeployer.login + " and password: " + NCBITablesDeployer.password);
        }
    } catch (Exception e) {
        Log.getInstance().log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException sqle) {
                Log.getInstance().log(Level.SEVERE, "Problem closing the database connection: " + sqle);
            }
        }
        Log.getInstance().log(Level.FINE, "Task done, exiting...");
    }
}

From source file:Main.java

public static boolean xmlStringValidate(String xmlStr, String xsdPath) {
    boolean flag = false;
    try {//from  w w  w.j  a  v  a 2 s . co m
        SchemaFactory factory = SchemaFactory.newInstance(SCHEMALANG);
        File schemaLocation = new File(xsdPath);
        Schema schema = factory.newSchema(schemaLocation);
        Validator validator = schema.newValidator();
        InputStream is = new ByteArrayInputStream(xmlStr.getBytes());
        Source source = new StreamSource(is);
        try {
            validator.validate(source);
            flag = true;
        } catch (SAXException ex) {
            System.out.println(ex.getMessage());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return flag;
}

From source file:Main.java

public static Document loadXMLFrom(InputStream inputStream) throws Exception {
    Document doc = null;// ww w.j a  v  a2  s  . co  m
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    javax.xml.parsers.DocumentBuilder builder = null;
    try {
        builder = factory.newDocumentBuilder();
        doc = builder.parse(inputStream);
    } catch (ParserConfigurationException pce) {
        throw new Exception(pce.getMessage());
    } catch (SAXException se) {
        throw new Exception(se.getMessage());
    } catch (IOException ioe) {
        throw new Exception(ioe.getMessage());
    } finally {
        inputStream.close();
    }
    return doc;
}

From source file:Main.java

/**
 * Create a map based on a xml file and a xpath expression and an attribute.
 * Treat attribute's value as map's key, treat xpath expression represented node's text content as map's value.
 * //  w  w w.  j a  v  a 2  s  . co m
 * @param xmlFile handled xml file
 * @param xpathExp xpath express, such as "//var"
 * @param arrtibute attribute, such as "name"
 * @return created Map object
 * @throws Exception
 */
public static Map<String, String> readXmlToMap(String xmlFile, String xpathExp, String arrtibute)
        throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setIgnoringElementContentWhitespace(true);

    DocumentBuilder db = factory.newDocumentBuilder();
    Document xmlDoc = null;
    try {
        xmlDoc = db.parse(new File(xmlFile));
    } catch (SAXException e) {
        if ("Premature end of file.".equals(e.getMessage()))
            System.out.println("Maybe your local data file has no content.");
        //e.printStackTrace();
        return new HashMap<String, String>();
    }
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    NodeList varList = (NodeList) xpath.evaluate(xpathExp, xmlDoc, XPathConstants.NODESET);
    Map<String, String> dataMap = new HashMap<String, String>();
    for (int i = 0; i < varList.getLength(); i++)
        dataMap.put(varList.item(i).getAttributes().getNamedItem(arrtibute).getNodeValue(),
                varList.item(i).getTextContent());

    return dataMap;
}

From source file:Main.java

public static Document parseFile(String fileName) {
    System.out.println("Parsing XML file... " + fileName);

    if (documentBuilder == null) {
        refreshDocumentBuilder();//ww w  .  ja v a 2s.c  om
    }

    File sourceFile = new File(fileName);

    try {
        return documentBuilder.parse(sourceFile);
    } catch (SAXException e) {
        System.out.println("Wrong XML file structure: " + e.getMessage());
        return null;
    } catch (IOException e) {
        System.out.println("Could not read source file: " + e.getMessage());
    }

    return null;
}

From source file:com.wso2telco.identity.application.authentication.endpoint.util.ReadMobileConnectConfig.java

public static Map<String, String> query(String XpathExpression) {

    Map<String, String> ConfigfileAttributes = new Hashtable<String, String>();

    // standard for reading an XML file
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*w w  w . j  a v  a2s.  c  om*/
    DocumentBuilder builder;
    Document doc = null;
    XPathExpression expr = null;
    try {
        builder = factory.newDocumentBuilder();
        doc = builder.parse(CarbonUtils.getCarbonConfigDirPath() + File.separator + "mobile-connect.xml");

        // create an XPathFactory
        XPathFactory xFactory = XPathFactory.newInstance();

        // create an XPath object
        XPath xpath = xFactory.newXPath();

        // compile the XPath expression
        expr = xpath.compile("//" + XpathExpression + "/*");
        // run the query and get a nodeset
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        //        // cast the result to a DOM NodeList
        NodeList nodes = (NodeList) result;

        for (int i = 0; i < nodes.getLength(); i++) {
            ConfigfileAttributes.put(nodes.item(i).getNodeName(), nodes.item(i).getTextContent());
        }
    } catch (SAXException e) {
        log.error(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage());
    } catch (ParserConfigurationException e) {
        log.error(e.getMessage());
    } catch (XPathExpressionException e) {
        log.error(e.getMessage());
    }

    return ConfigfileAttributes;
}

From source file:com.adito.httpunit.HttpTestParser.java

static HttpTestContainer generateTests(String path) throws IOException {
    try {//from w  ww. j  av  a2 s.c  o m
        Digester digester = new Digester();
        digester.setValidating(false);

        digester.addObjectCreate(MATCH_TESTS, HttpTestContainer.class);
        digester.addSetProperties(MATCH_TESTS, "rootUrl", "rootUrl");
        digester.addSetProperties(MATCH_TESTS, "port", "port");
        digester.addSetProperties(MATCH_TESTS, "defaultUsername", "defaultUsername");
        digester.addSetProperties(MATCH_TESTS, "defaultPassword", "defaultPassword");

        digester.addObjectCreate(MATCH_TEST, HttpTestEntry.class);
        digester.addSetProperties(MATCH_TEST, "name", "name");
        digester.addSetProperties(MATCH_TEST, "authenticated", "authenticated");
        digester.addSetProperties(MATCH_TEST, "username", "username");
        digester.addSetProperties(MATCH_TEST, "password", "password");

        digester.addObjectCreate(MATCH_TEST_STEP, HttpTestEntryStep.class);
        digester.addSetProperties(MATCH_TEST_STEP, "name", "name");
        digester.addSetProperties(MATCH_TEST_STEP, "method", "method");
        digester.addSetProperties(MATCH_TEST_STEP, "url", "url");
        digester.addSetProperties(MATCH_TEST_STEP, "expectedCode", "expectedCode");
        digester.addSetProperties(MATCH_TEST_STEP, "redirectUrl", "redirectUrl");

        digester.addObjectCreate(MATCH_PARAMETER, HttpTestEntryStep.Parameter.class);
        digester.addSetProperties(MATCH_PARAMETER, "key", "key");
        digester.addSetProperties(MATCH_PARAMETER, "value", "value");
        digester.addSetNext(MATCH_PARAMETER, "addParameter");

        digester.addObjectCreate(MATCH_MESSAGE, HttpTestEntryStep.Value.class);
        digester.addSetProperties(MATCH_MESSAGE, "value", "value");
        digester.addSetNext(MATCH_MESSAGE, "addMessage");

        digester.addObjectCreate(MATCH_ERROR, HttpTestEntryStep.Value.class);
        digester.addSetProperties(MATCH_ERROR, "value", "value");
        digester.addSetNext(MATCH_ERROR, "addError");

        digester.addSetNext(MATCH_TEST_STEP, "addStep");
        digester.addSetNext(MATCH_TEST, "addEntry");

        InputStream input = new FileInputStream(path);
        return (HttpTestContainer) digester.parse(input);
    } catch (SAXException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:net.oneandone.sushi.fs.webdav.MultiStatus.java

public static List<MultiStatus> fromResponse(Xml xml, HttpResponse response) throws IOException {
    Builder builder;//from   www  .j av a  2s.c  o m
    InputStream in;
    Element root;
    List<MultiStatus> result;
    ChildElements iter;

    in = response.getEntity().getContent();
    try {
        builder = xml.getBuilder();
        synchronized (builder) {
            root = builder.parse(in).getDocumentElement();
        }
    } catch (SAXException e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        in.close();
    }
    Dom.require(root, "multistatus", Method.DAV);
    result = new ArrayList<MultiStatus>();
    iter = Method.DAV.childElements(root, Method.XML_RESPONSE);
    while (iter.hasNext()) {
        fromXml(iter.next(), result);
    }
    return result;
}

From source file:Main.java

private static org.w3c.dom.Document getXMLDocument(String url) {

    Document document = null;//from  w  w  w. j av a  2 s  . c om

    DocumentBuilderFactory builderFactory;
    DocumentBuilder parser;

    // Try to load the document at the specified filepath into a DOM structure.
    //
    try {

        builderFactory = DocumentBuilderFactory.newInstance();

        parser = builderFactory.newDocumentBuilder();

        document = parser.parse(url);

    } catch (ParserConfigurationException p) {

        System.out.println("Error creating DOM parser.");
        System.out.println("   " + p.getMessage());

    } catch (SAXException s) {

        System.out.println("XML document returned is not well-formed.");
        System.out.println("   URL : " + url);
        System.out.println("   " + s.getMessage());

    } catch (IOException i) {

        System.out.println("Error accessing the stream.");
        System.out.println("   URL : " + url);
        System.out.println("   " + i.getMessage());
        document = null;

    }

    return document;

}