Example usage for org.xml.sax SAXParseException getException

List of usage examples for org.xml.sax SAXParseException getException

Introduction

In this page you can find the example usage for org.xml.sax SAXParseException getException.

Prototype

public Exception getException() 

Source Link

Document

Return the embedded exception, if any.

Usage

From source file:Main.java

/**
 * Parse the XML file and create Document
 * @param fileName/*from  w w  w  . ja  v a  2  s.  c  om*/
 * @return Document
 */
public static Document parse(InputStream fs) {
    Document document = null;
    // Initiate DocumentBuilderFactory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // To get a validating parser
    factory.setValidating(false);

    // To get one that understands namespaces
    factory.setNamespaceAware(true);
    try {
        // Get DocumentBuilder
        DocumentBuilder builder = factory.newDocumentBuilder();

        // Parse and load into memory the Document
        //document = builder.parse( new File(fileName));
        document = builder.parse(fs);
        return document;
    } catch (SAXParseException spe) {
        // Error generated by the parser
        System.err.println("\n** Parsing error , line " + spe.getLineNumber() + ", uri " + spe.getSystemId());
        System.err.println(" " + spe.getMessage());
        // Use the contained exception, if any
        Exception x = spe;
        if (spe.getException() != null)
            x = spe.getException();
        x.printStackTrace();
    } catch (SAXException sxe) {
        // Error generated during parsing
        Exception x = sxe;
        if (sxe.getException() != null)
            x = sxe.getException();
        x.printStackTrace();
    } catch (ParserConfigurationException pce) {
        // Parser with specified options can't be built
        pce.printStackTrace();
    } catch (IOException ioe) {
        // I/O error
        ioe.printStackTrace();
    }

    return null;
}

From source file:gov.nih.nci.caadapter.ws.AddNewScenario.java

/**
* Parse a XML document into DOM Tree//from w  w w. j a va  2s  . co m
*
* @param file The input File handler
* @return XML DOM Tree
*/
private Document readFile(File file) throws Exception {
    org.w3c.dom.Document doc;

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //dbf.setValidating(true);
        DocumentBuilder db = dbf.newDocumentBuilder();

        doc = db.parse(file);

        return doc;
    } catch (SAXParseException ex) {
        throw (ex);
    } catch (SAXException ex) {
        Exception x = ex.getException();
        throw ((x == null) ? ex : x);
    }
}

From source file:com.cyberway.issue.crawler.settings.XMLSettingsHandler.java

/** Read the CrawlerSettings object from a specific file.
 *
 * @param settings the settings object to be updated with data from the
 *                 persistent storage./*from   ww  w  .  ja  v  a2s.com*/
 * @param f the file to read from.
 * @return the updated settings object or null if there was no data for this
 *         in the persistent storage.
 */
protected final CrawlerSettings readSettingsObject(CrawlerSettings settings, File f) {
    CrawlerSettings result = null;
    try {
        InputStream is = null;
        if (!f.exists()) {
            // Perhaps the file we're looking for is on the CLASSPATH.
            // DON'T look on the CLASSPATH for 'settings.xml' files.  The
            // look for 'settings.xml' files happens frequently. Not looking
            // on classpath for 'settings.xml' is an optimization based on
            // ASSUMPTION that there will never be a 'settings.xml' saved
            // on classpath.
            if (!f.getName().startsWith(settingsFilename)) {
                is = XMLSettingsHandler.class.getResourceAsStream(f.getPath());
            }
        } else {
            is = new FileInputStream(f);
        }
        if (is != null) {
            XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
            InputStream file = new BufferedInputStream(is);
            parser.setContentHandler(new CrawlSettingsSAXHandler(settings));
            InputSource source = new InputSource(file);
            source.setSystemId(f.toURL().toExternalForm());
            parser.parse(source);
            result = settings;
        }
    } catch (SAXParseException e) {
        logger.warning(e.getMessage() + " in '" + e.getSystemId() + "', line: " + e.getLineNumber()
                + ", column: " + e.getColumnNumber());
    } catch (SAXException e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (ParserConfigurationException e) {
        logger.warning(e.getMessage() + ": " + e.getCause().getMessage());
    } catch (FactoryConfigurationError e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (IOException e) {
        logger.warning("Could not access file '" + f.getAbsolutePath() + "': " + e.getMessage());
    }
    return result;
}

From source file:org.archive.crawler.settings.XMLSettingsHandler.java

/** Read the CrawlerSettings object from a specific file.
 *
 * @param settings the settings object to be updated with data from the
 *                 persistent storage.//from www  .  ja  v  a2s.c  om
 * @param f the file to read from.
 * @return the updated settings object or null if there was no data for this
 *         in the persistent storage.
 */
protected final CrawlerSettings readSettingsObject(CrawlerSettings settings, File f) {
    CrawlerSettings result = null;
    try {
        InputStream is = null;
        if (!f.exists()) {
            // Perhaps the file we're looking for is on the CLASSPATH.
            // DON'T look on the CLASSPATH for 'settings.xml' files.  The
            // look for 'settings.xml' files happens frequently. Not looking
            // on classpath for 'settings.xml' is an optimization based on
            // ASSUMPTION that there will never be a 'settings.xml' saved
            // on classpath.
            if (!f.getName().startsWith(settingsFilename)) {
                is = XMLSettingsHandler.class.getResourceAsStream(toResourcePath(f));
            }
        } else {
            is = new FileInputStream(f);
        }
        if (is != null) {
            XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
            InputStream file = new BufferedInputStream(is);
            parser.setContentHandler(new CrawlSettingsSAXHandler(settings));
            InputSource source = new InputSource(file);
            source.setSystemId(f.toURL().toExternalForm());
            parser.parse(source);
            result = settings;
        }
    } catch (SAXParseException e) {
        logger.warning(e.getMessage() + " in '" + e.getSystemId() + "', line: " + e.getLineNumber()
                + ", column: " + e.getColumnNumber());
    } catch (SAXException e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (ParserConfigurationException e) {
        logger.warning(e.getMessage() + ": " + e.getCause().getMessage());
    } catch (FactoryConfigurationError e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (IOException e) {
        logger.warning("Could not access file '" + f.getAbsolutePath() + "': " + e.getMessage());
    }
    return result;
}

From source file:org.dita.dost.module.GenMapAndTopicListModule.java

/**
 * Read a file and process it for list information.
 * //from w ww.ja  v  a 2 s .c  o m
 * @param ref system path of the file to process
 * @throws DITAOTException if processing failed
 */
private void processFile(final Reference ref) throws DITAOTException {
    currentFile = ref.filename;
    assert currentFile.isAbsolute();
    logger.info("Processing " + currentFile);
    final String[] params = { currentFile.toString() };

    try {
        XMLReader xmlSource = getXmlReader(ref.format);
        for (final XMLFilter f : getProcessingPipe(currentFile)) {
            f.setParent(xmlSource);
            f.setEntityResolver(CatalogUtils.getCatalogResolver());
            xmlSource = f;
        }
        xmlSource.setContentHandler(nullHandler);

        xmlSource.parse(currentFile.toString());

        if (listFilter.isValidInput()) {
            processParseResult(currentFile);
            categorizeCurrentFile(ref);
        } else if (!currentFile.equals(rootFile)) {
            logger.warn(MessageUtils.getInstance().getMessage("DOTJ021W", params).toString());
            failureList.add(currentFile);
        }
    } catch (final RuntimeException e) {
        throw e;
    } catch (final SAXParseException sax) {
        final Exception inner = sax.getException();
        if (inner != null && inner instanceof DITAOTException) {
            throw (DITAOTException) inner;
        }
        if (currentFile.equals(rootFile)) {
            throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ012F", params).toString()
                    + ": " + sax.getMessage(), sax);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ013E", params).toString()
                    + ": " + sax.getMessage(), sax);
        } else {
            logger.error(MessageUtils.getInstance().getMessage("DOTJ013E", params).toString() + ": "
                    + sax.getMessage(), sax);
        }
        failureList.add(currentFile);
    } catch (final FileNotFoundException e) {
        if (currentFile.equals(rootFile)) {
            throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTA069F", params).toString(), e);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTX008E", params).toString()
                    + ": " + e.getMessage(), e);
        } else {
            logger.error(MessageUtils.getInstance().getMessage("DOTX008E", params).toString());
        }
        failureList.add(currentFile);
    } catch (final Exception e) {
        if (currentFile.equals(rootFile)) {
            throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ012F", params).toString()
                    + ": " + e.getMessage(), e);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ013E", params).toString()
                    + ": " + e.getMessage(), e);
        } else {
            logger.error(MessageUtils.getInstance().getMessage("DOTJ013E", params).toString() + ": "
                    + e.getMessage(), e);
        }
        failureList.add(currentFile);
    }

    if (!listFilter.isValidInput() && currentFile.equals(rootFile)) {
        if (xmlValidate) {
            // stop the build if all content in the input file was filtered out.
            throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ022F", params).toString());
        } else {
            // stop the build if the content of the file is not valid.
            throw new DITAOTException(MessageUtils.getInstance().getMessage("DOTJ034F", params).toString());
        }
    }

    doneList.add(currentFile);
    listFilter.reset();
    keydefFilter.reset();

}

From source file:org.dita.dost.module.reader.AbstractReaderModule.java

/**
 * Read a file and process it for list information.
 *
 * @param ref system path of the file to process
 * @param parseFile file to parse, may be {@code null}
 * @throws DITAOTException if processing failed
 *//*from  w ww  .j a va 2 s  .  c  o  m*/
void readFile(final Reference ref, final URI parseFile) throws DITAOTException {
    currentFile = ref.filename;
    assert currentFile.isAbsolute();
    final URI src = parseFile != null ? parseFile : currentFile;
    assert src.isAbsolute();
    final URI rel = tempFileNameScheme.generateTempFileName(currentFile);
    outputFile = new File(job.tempDirURI.resolve(rel));
    final File outputDir = outputFile.getParentFile();
    if (!outputDir.exists() && !outputDir.mkdirs()) {
        logger.error("Failed to create output directory " + outputDir.getAbsolutePath());
        return;
    }
    validateMap = Collections.emptyMap();
    defaultValueMap = Collections.emptyMap();
    logger.info("Processing " + currentFile + " to " + outputFile.toURI());
    final String[] params = { currentFile.toString() };

    // Verify stub for current file is in Job
    final FileInfo fi = job.getFileInfo(currentFile);
    if (fi == null) {
        final FileInfo stub = new FileInfo.Builder().src(currentFile).uri(rel).result(currentFile)
                .isInput(currentFile.equals(rootFile)).build();
        job.add(stub);
    }

    //        InputSource in = null;
    Result out = null;
    try {
        final TransformerFactory tf = TransformerFactory.newInstance();
        final SAXTransformerFactory stf = (SAXTransformerFactory) tf;
        final TransformerHandler serializer = stf.newTransformerHandler();

        XMLReader parser = getXmlReader(ref.format);
        XMLReader xmlSource = parser;
        for (final XMLFilter f : getProcessingPipe(currentFile)) {
            f.setParent(xmlSource);
            f.setEntityResolver(CatalogUtils.getCatalogResolver());
            xmlSource = f;
        }

        try {
            final LexicalHandler lexicalHandler = new DTDForwardHandler(xmlSource);
            parser.setProperty("http://xml.org/sax/properties/lexical-handler", lexicalHandler);
            parser.setFeature("http://xml.org/sax/features/lexical-handler", true);
        } catch (final SAXNotRecognizedException e) {
        }

        //            in = new InputSource(src.toString());
        out = new StreamResult(new FileOutputStream(outputFile));
        serializer.setResult(out);
        xmlSource.setContentHandler(serializer);
        xmlSource.parse(src.toString());

        if (listFilter.isValidInput()) {
            processParseResult(currentFile);
            categorizeCurrentFile(ref);
        } else if (!currentFile.equals(rootFile)) {
            logger.warn(MessageUtils.getMessage("DOTJ021W", params).toString());
            failureList.add(currentFile);
        }
    } catch (final RuntimeException e) {
        throw e;
    } catch (final SAXParseException sax) {
        final Exception inner = sax.getException();
        if (inner != null && inner instanceof DITAOTException) {
            throw (DITAOTException) inner;
        }
        if (currentFile.equals(rootFile)) {
            throw new DITAOTException(
                    MessageUtils.getMessage("DOTJ012F", params).toString() + ": " + sax.getMessage(), sax);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(
                    MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + sax.getMessage(), sax);
        } else {
            logger.error(MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + sax.getMessage(), sax);
        }
        failureList.add(currentFile);
    } catch (final FileNotFoundException e) {
        if (!exists(currentFile)) {
            if (currentFile.equals(rootFile)) {
                throw new DITAOTException(MessageUtils.getMessage("DOTA069F", params).toString(), e);
            } else if (processingMode == Mode.STRICT) {
                throw new DITAOTException(MessageUtils.getMessage("DOTX008E", params).toString(), e);
            } else {
                logger.error(MessageUtils.getMessage("DOTX008E", params).toString());
            }
        } else if (currentFile.equals(rootFile)) {
            throw new DITAOTException(MessageUtils.getMessage("DOTJ078F", params).toString()
                    + " Cannot load file: " + e.getMessage(), e);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(MessageUtils.getMessage("DOTJ079E", params).toString()
                    + " Cannot load file: " + e.getMessage(), e);
        } else {
            logger.error(MessageUtils.getMessage("DOTJ079E", params).toString() + " Cannot load file: "
                    + e.getMessage());
        }
        failureList.add(currentFile);
    } catch (final Exception e) {
        if (currentFile.equals(rootFile)) {
            throw new DITAOTException(
                    MessageUtils.getMessage("DOTJ012F", params).toString() + ": " + e.getMessage(), e);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(
                    MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + e.getMessage(), e);
        } else {
            logger.error(MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + e.getMessage(), e);
        }
        failureList.add(currentFile);
    } finally {
        if (out != null) {
            try {
                close(out);
            } catch (final IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        if (failureList.contains(currentFile)) {
            FileUtils.deleteQuietly(outputFile);
        }
    }

    if (!listFilter.isValidInput() && currentFile.equals(rootFile)) {
        if (validate) {
            // stop the build if all content in the input file was filtered out.
            throw new DITAOTException(MessageUtils.getMessage("DOTJ022F", params).toString());
        } else {
            // stop the build if the content of the file is not valid.
            throw new DITAOTException(MessageUtils.getMessage("DOTJ034F", params).toString());
        }
    }

    doneList.add(currentFile);
    listFilter.reset();
    keydefFilter.reset();

}

From source file:org.eclipse.rdf4j.rio.trix.TriXParser.java

private void parse(InputSource inputStreamOrReader) throws IOException, RDFParseException, RDFHandlerException {
    clear();/*from   w w  w  .j  a  va  2 s.  com*/

    try {
        if (rdfHandler != null) {
            rdfHandler.startRDF();
        }

        XMLReader xmlReader;

        if (getParserConfig().isSet(XMLParserSettings.CUSTOM_XML_READER)) {
            xmlReader = getParserConfig().get(XMLParserSettings.CUSTOM_XML_READER);
        } else {
            xmlReader = XMLReaderFactory.createXMLReader();
        }

        xmlReader.setErrorHandler(this);

        saxParser = new SimpleSAXParser(xmlReader);
        saxParser.setPreserveWhitespace(true);
        saxParser.setListener(new TriXSAXHandler());

        saxParser.parse(inputStreamOrReader);
    } catch (SAXParseException e) {
        Exception wrappedExc = e.getException();

        if (wrappedExc == null) {
            reportFatalError(e, e.getLineNumber(), e.getColumnNumber());
        } else {
            reportFatalError(wrappedExc, e.getLineNumber(), e.getColumnNumber());
        }
    } catch (SAXException e) {
        Exception wrappedExc = e.getException();

        if (wrappedExc == null) {
            reportFatalError(e);
        } else if (wrappedExc instanceof RDFParseException) {
            throw (RDFParseException) wrappedExc;
        } else if (wrappedExc instanceof RDFHandlerException) {
            throw (RDFHandlerException) wrappedExc;
        } else {
            reportFatalError(wrappedExc);
        }
    } finally {
        clear();
    }

    if (rdfHandler != null) {
        rdfHandler.endRDF();
    }
}

From source file:org.eclipse.wb.internal.core.model.description.helpers.ComponentDescriptionHelper.java

/**
 * @param editor/*from  ww w  . jav a 2  s  .  c  om*/
 *          the {@link AstEditor} in context of which we work now.
 * @param key
 *          the {@link ComponentDescriptionKey} of requested {@link ComponentDescription}.
 * @param additionalDescriptionInfos
 *          additional {@link ClassResourceInfo}'s to parse after {@link ClassResourceInfo}'s
 *          collected for component {@link Class}. May be empty, but not <code>null</code>.
 * 
 * @return the {@link ComponentDescription} of component with given {@link Class}.
 * @throws Exception
 *           if no {@link ComponentDescription} can be found.
 */
private static ComponentDescription getDescription0(AstEditor editor, ComponentDescriptionKey key,
        List<ClassResourceInfo> additionalDescriptionInfos) throws Exception {
    EditorState state = EditorState.get(editor);
    ILoadingContext context = EditorStateLoadingContext.get(state);
    Class<?> componentClass = key.getComponentClass();
    //
    try {
        // prepare result description
        ComponentDescription componentDescription = new ComponentDescription(key);
        addConstructors(editor.getJavaProject(), componentDescription);
        componentDescription.setBeanInfo(ReflectionUtils.getBeanInfo(componentClass));
        componentDescription.setBeanDescriptor(new IntrospectionHelper(componentClass).getBeanDescriptor());
        // prepare list of description resources, from generic to specific
        LinkedList<ClassResourceInfo> descriptionInfos;
        {
            descriptionInfos = Lists.newLinkedList();
            DescriptionHelper.addDescriptionResources(descriptionInfos, context, componentClass);
            Assert.isTrueException(!descriptionInfos.isEmpty(),
                    ICoreExceptionConstants.DESCRIPTION_NO_DESCRIPTIONS, componentClass.getName());
            // at last append additional description resource
            descriptionInfos.addAll(additionalDescriptionInfos);
        }
        // prepare Digester
        Digester digester;
        {
            digester = new Digester();
            digester.setLogger(new NoOpLog());
            addRules(digester, editor, componentClass);
        }
        // read descriptions from generic to specific
        for (ClassResourceInfo descriptionInfo : descriptionInfos) {
            ResourceInfo resourceInfo = descriptionInfo.resource;
            // read next description
            {
                componentDescription.setCurrentClass(descriptionInfo.clazz);
                digester.push(componentDescription);
                // do parse
                InputStream is = resourceInfo.getURL().openStream();
                try {
                    digester.parse(is);
                } finally {
                    IOUtils.closeQuietly(is);
                }
            }
            // clear parts that can not be inherited
            if (descriptionInfo.clazz == componentClass) {
                setDescriptionWithInnerTags(componentDescription, resourceInfo);
            } else {
                componentDescription.clearCreations();
                componentDescription.setDescription(null);
            }
        }
        // set toolkit
        if (componentDescription.getToolkit() == null) {
            for (int i = descriptionInfos.size() - 1; i >= 0; i--) {
                ClassResourceInfo descriptionInfo = descriptionInfos.get(i);
                ToolkitDescription toolkit = descriptionInfo.resource.getToolkit();
                if (toolkit != null) {
                    componentDescription.setToolkit(toolkit);
                    break;
                }
            }
            Assert.isTrueException(componentDescription.getToolkit() != null,
                    ICoreExceptionConstants.DESCRIPTION_NO_TOOLKIT, componentClass.getName());
        }
        // icon, default creation
        setIcon(context, componentDescription, componentClass);
        configureDefaultCreation(componentDescription);
        // final operations
        {
            Assert.isNotNull(componentDescription.getModelClass());
            componentDescription.joinProperties();
        }
        // add to caches
        if (key.isPureComponent() && !"true".equals(componentDescription.getParameter("dontCacheDescription"))
                && shouldCacheDescriptions_inPackage(descriptionInfos.getLast(), componentClass)) {
            componentDescription.setCached(true);
        }
        // mark for caching presentation
        if (shouldCachePresentation(descriptionInfos.getLast(), componentClass)) {
            componentDescription.setPresentationCached(true);
        }
        // use processors
        for (IDescriptionProcessor processor : getDescriptionProcessors()) {
            processor.process(editor, componentDescription);
        }
        // well, we have result
        return componentDescription;
    } catch (SAXParseException e) {
        throw new DesignerException(ICoreExceptionConstants.DESCRIPTION_LOAD_ERROR, e.getException(),
                componentClass.getName());
    }
}

From source file:org.lnicholls.galleon.util.Configurator.java

private void loadDocument(AppManager appManager, File file) {
    ServerConfiguration serverConfiguration = Server.getServer().getServerConfiguration();
    // Need to handle previous version of configuration file
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //factory.setValidating(true);
    //factory.setNamespaceAware(true);
    try {/*from   w  w  w. j  a  v  a  2  s .  c  om*/
        FileInputStream in = null;
        DocumentBuilder builder = factory.newDocumentBuilder();
        in = new FileInputStream(file);
        Document document = builder.parse(in);
        in.close();
        in = null;

        // <configuration>
        Node domNode = document.getFirstChild();
        if (log.isDebugEnabled())
            log.debug("document:" + domNode.getNodeName());

        if (domNode.getNodeName().equalsIgnoreCase(TAG_CONFIGURATION)) {
            NamedNodeMap namedNodeMap = domNode.getAttributes();
            if (namedNodeMap != null) {
                // Check for required attributes
                Node attribute = namedNodeMap.getNamedItem(ATTRIBUTE_VERSION);
                if (log.isDebugEnabled())
                    log.debug(domNode.getNodeName() + ":" + attribute.getNodeName() + "="
                            + attribute.getNodeValue());
                loadDocument(domNode, appManager);
                if (!attribute.getNodeValue().equals(serverConfiguration.getVersion()))
                    save(appManager);
            }
        }
    } catch (SAXParseException spe) {
        // Error generated by the parser
        log.error("Parsing error, line " + spe.getLineNumber() + ", uri " + spe.getSystemId());
        log.error("   " + spe.getMessage());
        Tools.logException(Configurator.class, spe);

        // Use the contained exception, if any
        Exception x = spe;
        if (spe.getException() != null)
            x = spe.getException();
        Tools.logException(Configurator.class, x);

    } catch (SAXException sxe) {
        // Error generated during parsing)
        Exception x = sxe;
        if (sxe.getException() != null)
            x = sxe.getException();
        Tools.logException(Configurator.class, x);
    } catch (ParserConfigurationException pce) {
        // Parser with specified options can't be built
        log.error("Cannot get context" + file.getAbsolutePath());
        Tools.logException(Configurator.class, pce);
    } catch (IOException ioe) {
        // I/O error
        log.error("Cannot get context" + file.getAbsolutePath());
        Tools.logException(Configurator.class, ioe);
    } finally {
    }
}

From source file:org.lnicholls.galleon.util.Configurator.java

private void loadDocument(Node configurationNode, AppManager appManager) {
    ServerConfiguration serverConfiguration = Server.getServer().getServerConfiguration();
    try {//from ww w .ja  va  2  s . c om
        // <server>, <app>
        for (int i = 0; i < configurationNode.getChildNodes().getLength(); i++) {
            Node node = configurationNode.getChildNodes().item(i);
            if (log.isDebugEnabled())
                log.debug("node:" + node.getNodeName());

            if (node.getNodeType() == Node.ELEMENT_NODE) {
                if (node.getNodeName().equals(TAG_SERVER)) {
                    if (log.isDebugEnabled())
                        log.debug("Found server");
                    NamedNodeMap namedNodeMap = node.getAttributes();
                    if (namedNodeMap != null) {
                        Node attribute = namedNodeMap.getNamedItem(ATTRIBUTE_RELOAD);
                        // Required attributes
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            try {
                                int reload = Integer.parseInt(attribute.getNodeValue());
                                serverConfiguration.setReload(reload);
                            } catch (NumberFormatException ex) {
                                log.error("Invalid " + ATTRIBUTE_RELOAD + " for " + TAG_SERVER + ": "
                                        + attribute.getNodeValue());
                            }
                        }
                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_PORT);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            try {
                                int port = Integer.parseInt(attribute.getNodeValue());
                                serverConfiguration.setPort(port);
                            } catch (NumberFormatException ex) {
                                log.error("Invalid " + ATTRIBUTE_PORT + " for " + TAG_SERVER + ": "
                                        + attribute.getNodeValue());
                            }
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_HTTP_PORT);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            try {
                                int port = Integer.parseInt(attribute.getNodeValue());
                                serverConfiguration.setHttpPort(port);
                            } catch (NumberFormatException ex) {
                                log.error("Invalid " + ATTRIBUTE_HTTP_PORT + " for " + TAG_SERVER + ": "
                                        + attribute.getNodeValue());
                            }
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_TITLE);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            serverConfiguration.setName(attribute.getNodeValue());
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_IP_ADDRESS);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            String address = attribute.getNodeValue();
                            // Fix IP address if needed
                            if (!Tools.isLocalAddress(address)) {
                                log.error("Invalid server IP address: " + address);
                                address = Tools.getLocalIpAddress();
                                log.debug("Changing IP address to: " + address);
                            }

                            serverConfiguration.setIPAddress(address);
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_PUBLIC_IP_ADDRESS);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            serverConfiguration.setPublicIPAddress(attribute.getNodeValue());
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_PIN);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue().length());
                            serverConfiguration.setPin(attribute.getNodeValue());
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_PASSWORD);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue().length());
                            serverConfiguration.setPassword(attribute.getNodeValue());
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_SHUFFLE_ITEMS);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            serverConfiguration
                                    .setShuffleItems(Boolean.valueOf(attribute.getNodeValue()).booleanValue());
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_GENERATE_THUMBNAILS);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            serverConfiguration.setGenerateThumbnails(
                                    Boolean.valueOf(attribute.getNodeValue()).booleanValue());
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_RECORDINGS_PATH);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            serverConfiguration.setRecordingsPath(Tools
                                    .unEscapeXMLChars(URLDecoder.decode(attribute.getNodeValue(), ENCODING)));
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_MEDIA_ACCESS_KEY);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue().length());
                            serverConfiguration.setMediaAccessKey(attribute.getNodeValue());
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_SKIN);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue().length());
                            serverConfiguration.setSkin(attribute.getNodeValue());
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_DEBUG);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            serverConfiguration
                                    .setDebug(Boolean.valueOf(attribute.getNodeValue()).booleanValue());
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_TIMEOUT);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            serverConfiguration.setDisableTimeout(
                                    Boolean.valueOf(attribute.getNodeValue()).booleanValue());
                        }

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_MENU);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            serverConfiguration
                                    .setMenu(Boolean.valueOf(attribute.getNodeValue()).booleanValue());
                        }
                    }
                } else if (node.getNodeName().equals(TAG_APP)) {
                    if (log.isDebugEnabled())
                        log.debug("Found app");
                    NamedNodeMap namedNodeMap = node.getAttributes();
                    if (namedNodeMap != null) {
                        String title = null;
                        String className = null;
                        Node attribute = namedNodeMap.getNamedItem(ATTRIBUTE_NAME);
                        // Check for required attributes
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            title = attribute.getNodeValue();
                        } else
                            log.error("Missing required " + ATTRIBUTE_NAME + " attribute for " + TAG_APP);

                        attribute = namedNodeMap.getNamedItem(ATTRIBUTE_CLASS);
                        if (attribute != null) {
                            if (log.isDebugEnabled())
                                log.debug(node.getNodeName() + ":" + attribute.getNodeName() + "="
                                        + attribute.getNodeValue());
                            className = attribute.getNodeValue();
                        } else
                            log.error("Missing required " + ATTRIBUTE_CLASS + " attribute for " + TAG_APP);

                        if (className != null) {
                            if (className.indexOf('$') != -1)
                                className = className.substring(0, className.indexOf('$'));
                            else
                                className = className.substring(0,
                                        className.length() - "Configuration".length());
                            Object appConfiguration = null;
                            Iterator appDescriptorIterator = appManager.getAppDescriptors().iterator();
                            while (appDescriptorIterator.hasNext()) {
                                AppDescriptor appDescriptor = (AppDescriptor) appDescriptorIterator.next();
                                if (appDescriptor.getClassName().equals(className)) {
                                    AppContext appContext = new AppContext(appDescriptor);
                                    if (appContext.getConfiguration() != null) {
                                        try {
                                            BeanReader beanReader = new BeanReader();
                                            beanReader.getXMLIntrospector().setAttributesForPrimitives(true);
                                            beanReader.registerBeanClass("app",
                                                    appContext.getConfiguration().getClass());

                                            ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                            OutputFormat of = new OutputFormat("XML", ENCODING, true);
                                            XMLSerializer serializer = new XMLSerializer(bos, of);
                                            serializer.asDOMSerializer();
                                            serializer.serialize((Element) node);

                                            StringReader xmlReader = new StringReader(bos.toString());
                                            bos.close();

                                            appConfiguration = beanReader.parse(xmlReader);
                                            appContext.setConfiguration(appConfiguration);

                                            appManager.createApp(appContext);

                                            if (log.isDebugEnabled())
                                                log.debug("App=" + appContext);
                                        } catch (IntrospectionException ex) {
                                            log.error("Could not load app " + title + " (" + className + ")");
                                        }
                                    } else
                                        log.error("Could not find app " + title + " (" + className + ")");
                                }
                            }

                            if (appConfiguration == null) {
                                log.error("Could not find app " + title + " (" + className + ")");
                            }
                        }
                    }
                } else if (node.getNodeName().equals(TAG_TIVO)) {
                    if (log.isDebugEnabled())
                        log.debug("Found TiVo");
                    try {
                        BeanReader beanReader = new BeanReader();
                        beanReader.getXMLIntrospector().setAttributesForPrimitives(true);
                        beanReader.registerBeanClass("tivo", TiVo.class);

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        OutputFormat of = new OutputFormat("XML", ENCODING, true);
                        XMLSerializer serializer = new XMLSerializer(bos, of);
                        serializer.asDOMSerializer();
                        serializer.serialize((Element) node);

                        StringReader xmlReader = new StringReader(bos.toString());
                        bos.close();

                        TiVo tivo = (TiVo) beanReader.parse(xmlReader);

                        serverConfiguration.addTiVo(tivo);

                        if (log.isDebugEnabled())
                            log.debug("TiVo=" + tivo);
                    } catch (IntrospectionException ex) {
                        log.error("Could not load tivo");
                    }
                } else if (node.getNodeName().equals(TAG_RULE)) {
                    if (log.isDebugEnabled())
                        log.debug("Found Rule");
                    try {
                        BeanReader beanReader = new BeanReader();
                        beanReader.getXMLIntrospector().setAttributesForPrimitives(true);
                        beanReader.registerBeanClass("rule", Rule.class);

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        OutputFormat of = new OutputFormat("XML", ENCODING, true);
                        XMLSerializer serializer = new XMLSerializer(bos, of);
                        serializer.asDOMSerializer();
                        serializer.serialize((Element) node);

                        StringReader xmlReader = new StringReader(bos.toString());
                        bos.close();

                        Rule rule = (Rule) beanReader.parse(xmlReader);

                        serverConfiguration.addRule(rule);

                        if (log.isDebugEnabled())
                            log.debug("Rule=" + rule);
                    } catch (IntrospectionException ex) {
                        log.error("Could not load rule");
                    }
                } else if (node.getNodeName().equals(TAG_MUSIC_PLAYER_CONFIGURATION)) {
                    if (log.isDebugEnabled())
                        log.debug("Found Music Player Configuration");
                    try {
                        BeanReader beanReader = new BeanReader();
                        beanReader.getXMLIntrospector().setAttributesForPrimitives(true);
                        beanReader.registerBeanClass("musicPlayerConfiguration",
                                MusicPlayerConfiguration.class);

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        OutputFormat of = new OutputFormat("XML", ENCODING, true);
                        XMLSerializer serializer = new XMLSerializer(bos, of);
                        serializer.asDOMSerializer();
                        serializer.serialize((Element) node);

                        StringReader xmlReader = new StringReader(bos.toString());
                        bos.close();

                        MusicPlayerConfiguration musicPlayerConfiguration = (MusicPlayerConfiguration) beanReader
                                .parse(xmlReader);

                        serverConfiguration.setMusicPlayerConfiguration(musicPlayerConfiguration);

                        if (log.isDebugEnabled())
                            log.debug("MusicPlayerConfiguration=" + musicPlayerConfiguration);
                    } catch (IntrospectionException ex) {
                        log.error("Could not load Music Player Configuration");
                    }
                } else if (node.getNodeName().equals(TAG_DATA_CONFIGURATION)) {
                    if (log.isDebugEnabled())
                        log.debug("Found Data Configuration");
                    try {
                        BeanReader beanReader = new BeanReader();
                        beanReader.getXMLIntrospector().setAttributesForPrimitives(true);
                        beanReader.registerBeanClass("dataConfiguration", DataConfiguration.class);

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        OutputFormat of = new OutputFormat("XML", ENCODING, true);
                        XMLSerializer serializer = new XMLSerializer(bos, of);
                        serializer.asDOMSerializer();
                        serializer.serialize((Element) node);

                        StringReader xmlReader = new StringReader(bos.toString());
                        bos.close();

                        DataConfiguration dataConfiguration = (DataConfiguration) beanReader.parse(xmlReader);

                        serverConfiguration.setDataConfiguration(dataConfiguration);

                        if (log.isDebugEnabled())
                            log.debug("DataConfiguration=" + dataConfiguration);
                    } catch (IntrospectionException ex) {
                        log.error("Could not load Data Configuration");
                    }
                } else if (node.getNodeName().equals(TAG_GOBACK_CONFIGURATION)) {
                    if (log.isDebugEnabled())
                        log.debug("Found GoBack Configuration");
                    try {
                        BeanReader beanReader = new BeanReader();
                        beanReader.getXMLIntrospector().setAttributesForPrimitives(true);
                        beanReader.registerBeanClass("goBackConfiguration", GoBackConfiguration.class);

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        OutputFormat of = new OutputFormat("XML", ENCODING, true);
                        XMLSerializer serializer = new XMLSerializer(bos, of);
                        serializer.asDOMSerializer();
                        serializer.serialize((Element) node);

                        StringReader xmlReader = new StringReader(bos.toString());
                        bos.close();

                        GoBackConfiguration goBackConfiguration = (GoBackConfiguration) beanReader
                                .parse(xmlReader);

                        serverConfiguration.setGoBackConfiguration(goBackConfiguration);

                        if (log.isDebugEnabled())
                            log.debug("GoBackConfiguration=" + goBackConfiguration);
                    } catch (IntrospectionException ex) {
                        log.error("Could not load GoBack Configuration");
                    }
                } else if (node.getNodeName().equals(TAG_DOWNLOAD_CONFIGURATION)) {
                    if (log.isDebugEnabled())
                        log.debug("Found Download Configuration");
                    try {
                        BeanReader beanReader = new BeanReader();
                        beanReader.getXMLIntrospector().setAttributesForPrimitives(true);
                        beanReader.registerBeanClass("downloadConfiguration", DownloadConfiguration.class);

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        OutputFormat of = new OutputFormat("XML", ENCODING, true);
                        XMLSerializer serializer = new XMLSerializer(bos, of);
                        serializer.asDOMSerializer();
                        serializer.serialize((Element) node);

                        StringReader xmlReader = new StringReader(bos.toString());
                        bos.close();

                        DownloadConfiguration downloadConfiguration = (DownloadConfiguration) beanReader
                                .parse(xmlReader);

                        serverConfiguration.setDownloadConfiguration(downloadConfiguration);

                        if (log.isDebugEnabled())
                            log.debug("DownloadConfiguration=" + downloadConfiguration);
                    } catch (IntrospectionException ex) {
                        log.error("Could not load Download Configuration");
                    }
                }
            }
        }
    } catch (SAXParseException spe) {
        // Error generated by the parser
        log.error("Parsing error, line " + spe.getLineNumber() + ", uri " + spe.getSystemId());
        log.error("   " + spe.getMessage());
        Tools.logException(Configurator.class, spe);

        // Use the contained exception, if any
        Exception x = spe;
        if (spe.getException() != null)
            x = spe.getException();
        Tools.logException(Configurator.class, x);

    } catch (SAXException sxe) {
        // Error generated during parsing)
        Exception x = sxe;
        if (sxe.getException() != null)
            x = sxe.getException();
        Tools.logException(Configurator.class, x);
    } catch (IOException ioe) {
        // I/O error
        Tools.logException(Configurator.class, ioe, "Cannot get context");
    } catch (Exception ioe) {
        // I/O error
        Tools.logException(Configurator.class, ioe, "Cannot get context");
    } finally {
    }
}