Example usage for javax.xml.parsers DocumentBuilderFactory setValidating

List of usage examples for javax.xml.parsers DocumentBuilderFactory setValidating

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setValidating.

Prototype


public void setValidating(boolean validating) 

Source Link

Document

Specifies that the parser produced by this code will validate documents as they are parsed.

Usage

From source file:com.meidusa.amoeba.context.ProxyRuntimeContext.java

private ProxyServerConfig loadConfig(String configFileName) {
    DocumentBuilder db;//from  ww  w .  ja va 2  s  . c  o m

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(true);
        dbf.setNamespaceAware(false);

        db = dbf.newDocumentBuilder();
        db.setEntityResolver(new EntityResolver() {

            public InputSource resolveEntity(String publicId, String systemId) {
                if (systemId.endsWith("amoeba.dtd")) {
                    InputStream in = ProxyRuntimeContext.class
                            .getResourceAsStream("/com/meidusa/amoeba/xml/amoeba.dtd");
                    if (in == null) {
                        LogLog.error("Could not find [amoeba.dtd]. Used ["
                                + ProxyRuntimeContext.class.getClassLoader() + "] class loader in the search.");
                        return null;
                    } else {
                        return new InputSource(in);
                    }
                } else {
                    return null;
                }
            }
        });

        db.setErrorHandler(new ErrorHandler() {

            public void warning(SAXParseException exception) {
            }

            public void error(SAXParseException exception) throws SAXException {
                logger.error(exception.getMessage() + " at (" + exception.getLineNumber() + ":"
                        + exception.getColumnNumber() + ")");
                throw exception;
            }

            public void fatalError(SAXParseException exception) throws SAXException {
                logger.fatal(exception.getMessage() + " at (" + exception.getLineNumber() + ":"
                        + exception.getColumnNumber() + ")");
                throw exception;
            }
        });
        return loadConfigurationFile(configFileName, db);
    } catch (Exception e) {
        logger.fatal("Could not load configuration file, failing", e);
        throw new ConfigurationException("Error loading configuration file " + configFileName, e);
    }
}

From source file:com.evolveum.midpoint.prism.schema.SchemaToDomProcessor.java

/**
 * Create schema XSD DOM document.//from   w  w w  .j a  va2s. c  o  m
 */
private void init() throws ParserConfigurationException {

    if (namespacePrefixMapper == null) {
        // TODO: clone?
        namespacePrefixMapper = prismContext.getSchemaRegistry().getNamespacePrefixMapper();
    }

    // We don't want the "tns" prefix to be kept in the mapper
    namespacePrefixMapper = namespacePrefixMapper.clone();
    namespacePrefixMapper.registerPrefixLocal(getNamespace(), "tns");

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Using namespace prefix mapper to serialize schema:\n{}",
                DebugUtil.dump(namespacePrefixMapper));
    }

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    DocumentBuilder db = dbf.newDocumentBuilder();

    document = db.newDocument();
    Element root = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "schema"));
    document.appendChild(root);

    rootXsdElement = document.getDocumentElement();
    setAttribute(rootXsdElement, "targetNamespace", getNamespace());
    setAttribute(rootXsdElement, "elementFormDefault", "qualified");

    DOMUtil.setNamespaceDeclaration(rootXsdElement, "tns", getNamespace());

    if (attributeQualified) {
        setAttribute(rootXsdElement, "attributeFormDefault", "qualified");
    }
}

From source file:be.docarch.odt2braille.PEF.java

/**
 * Converts the flat .odt filt to a .pef file according to the braille settings.
 *
 * This function/*from  w ww .  ja  v  a 2s . co m*/
 * <ul>
 * <li>uses {@link ODT} to convert the .odt file to multiple DAISY-like xml files,</li>
 * <li>uses {@link LiblouisXML} to translate these files into braille, and</li>
 * <li>recombines these braille files into one single .pef file.</li>
 * </ul>
 *
 * First, the document <i>body</i> is processed and split in volumes, then the <i>page ranges</i> are calculated
 * and finally the <i>preliminary pages</i> of each volume are processed and inserted at the right places.
 * The checker checks the DAISY-like files and the volume lengths.
 *
 */

public boolean makePEF() throws IOException, ParserConfigurationException, TransformerException,
        InterruptedException, SAXException, ConversionException, LiblouisXMLException, Exception {

    logger.entering("PEF", "makePEF");

    Configuration settings = odt.getConfiguration();

    Element[] volumeElements;
    Element sectionElement;
    File bodyFile = null;
    File brailleFile = null;
    File preliminaryFile = null;

    List<Volume> volumes = manager.getVolumes();

    String volumeInfo = capitalizeFirstLetter(
            ResourceBundle.getBundle(L10N, settings.mainLocale).getString("in")) + " " + volumes.size() + " "
            + ResourceBundle.getBundle(L10N, settings.mainLocale)
                    .getString((volumes.size() > 1) ? "volumes" : "volume")
            + "\n@title\n@pages";

    volumeElements = new Element[volumes.size()];

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setValidating(false);
    docFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    DOMImplementation impl = docBuilder.getDOMImplementation();

    Document document = impl.createDocument(pefNS, "pef", null);
    Element root = document.getDocumentElement();
    root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", pefNS);
    root.setAttributeNS(null, "version", "2008-1");

    Element headElement = document.createElementNS(pefNS, "head");
    Element metaElement = document.createElementNS(pefNS, "meta");
    metaElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dc", "http://purl.org/dc/elements/1.1/");
    Element dcElement = document.createElementNS("http://purl.org/dc/elements/1.1/", "dc:identifier");
    dcElement.appendChild(document.createTextNode(Integer.toHexString((int) (Math.random() * 1000000)) + " "
            + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format((new Date()))));
    metaElement.appendChild(dcElement);
    dcElement = document.createElementNS("http://purl.org/dc/elements/1.1/", "dc:format");
    dcElement.appendChild(document.createTextNode("application/x-pef+xml"));
    metaElement.appendChild(dcElement);
    headElement.appendChild(metaElement);

    root.appendChild(headElement);

    int columns = pefSettings.getColumns();
    int rows = pefSettings.getRows();
    boolean duplex = pefSettings.getDuplex();
    int rowgap = pefSettings.getEightDots() ? 1 : 0;
    int beginPage = settings.getBeginningBraillePageNumber();

    if (statusIndicator != null) {
        statusIndicator.start();
        statusIndicator.setSteps(volumes.size());
        statusIndicator.setStatus(ResourceBundle.getBundle(L10N, statusIndicator.getPreferredLocale())
                .getString("statusIndicatorStep"));
    }

    for (int volumeCount = 0; volumeCount < volumes.size(); volumeCount++) {

        volumeElements[volumeCount] = document.createElementNS(pefNS, "volume");
        volumeElements[volumeCount].setAttributeNS(null, "cols", String.valueOf(columns));
        volumeElements[volumeCount].setAttributeNS(null, "rows",
                String.valueOf(rows + (int) Math.ceil(((rows - 1) * rowgap) / 4d)));
        volumeElements[volumeCount].setAttributeNS(null, "rowgap", String.valueOf(rowgap));
        volumeElements[volumeCount].setAttributeNS(null, "duplex", duplex ? "true" : "false");

        Volume volume = volumes.get(volumeCount);

        // Body section

        logger.info("Processing volume " + (volumeCount + 1) + " : " + volume.getTitle());

        if (!(volume instanceof PreliminaryVolume)) {

            bodyFile = File.createTempFile(TMP_NAME, ".daisy.body." + (volumeCount + 1) + ".xml", TMP_DIR);
            bodyFile.deleteOnExit();
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();

            odt.getBodyMatter(bodyFile, volume);
            liblouisXML.configure(bodyFile, brailleFile, false, beginPage);
            liblouisXML.run();

            // Read pages
            sectionElement = document.createElementNS(pefNS, "section");
            int pageCount = addPagesToSection(document, sectionElement, brailleFile, rows, columns, -1);
            volumeElements[volumeCount].appendChild(sectionElement);

            // Checker
            if (checker != null) {
                checker.checkDaisyFile(bodyFile);
            }

            // Braille page range
            volume.setBraillePagesStart(beginPage);
            volume.setNumberOfBraillePages(pageCount);
            beginPage += pageCount;

            // Print page range
            if (volume.getFrontMatter() && settings.getVolumeInfoEnabled()) {
                extractPrintPageRange(bodyFile, volume, settings);
            }
        }

        // Special symbols list
        if (volume.getSpecialSymbolListEnabled()) {
            extractSpecialSymbols(bodyFile, volume, volumeCount, settings);
        }

        // Preliminary section

        if (volume.getFrontMatter() || volume.getTableOfContent() || volume.getTranscribersNotesPageEnabled()
                || volume.getSpecialSymbolListEnabled()) {

            preliminaryFile = File.createTempFile(TMP_NAME, ".daisy.front." + (volumeCount + 1) + ".xml",
                    TMP_DIR);
            preliminaryFile.deleteOnExit();
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();

            odt.getFrontMatter(preliminaryFile, volume, volumeInfo);
            liblouisXML.configure(preliminaryFile, brailleFile, true,
                    volume.getTableOfContent() ? volume.getFirstBraillePage() : 1);
            liblouisXML.run();

            // Page range
            int pageCount = countPages(brailleFile, volume);
            volume.setNumberOfPreliminaryPages(pageCount);

            // Translate again with updated volume info and without volume separator marks
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();
            odt.getFrontMatter(preliminaryFile, volume, volumeInfo);
            liblouisXML.configure(preliminaryFile, brailleFile, false,
                    volume.getTableOfContent() ? volume.getFirstBraillePage() : 1);
            liblouisXML.run();

            // Read pages
            sectionElement = document.createElementNS(pefNS, "section");
            addPagesToSection(document, sectionElement, brailleFile, rows, columns, pageCount);
            volumeElements[volumeCount].insertBefore(sectionElement,
                    volumeElements[volumeCount].getFirstChild());

            // Checker
            if (checker != null) {
                checker.checkDaisyFile(preliminaryFile);
            }
        }

        if (statusIndicator != null) {
            statusIndicator.increment();
        }
    }

    if (checker != null) {
        checker.checkVolumes(volumes);
    }

    Element bodyElement = document.createElementNS(pefNS, "body");

    for (int volumeCount = 0; volumeCount < volumes.size(); volumeCount++) {
        bodyElement.appendChild(volumeElements[volumeCount]);
    }

    root.appendChild(bodyElement);

    document.insertBefore((ProcessingInstruction) document.createProcessingInstruction("xml-stylesheet",
            "type='text/css' href='pef.css'"), document.getFirstChild());

    OdtUtils.saveDOM(document, pefFile);

    logger.exiting("PEF", "makePEF");

    if (!validatePEF(pefFile)) {
        return false;
    }

    return true;
}

From source file:com.amalto.workbench.utils.XSDParser.java

/**
 * Read the markup from the .xml input./* w w  w. jav a  2 s. c o m*/
 * 
 * @param fileName the name of an XML file.
 */
public void readMarkup(String markup) {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setValidating(false);
    try {
        InputSource source = new InputSource(new StringReader(markup));
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(source);
        for (Node child = document.getDocumentElement().getFirstChild(); child != null; child = child
                .getNextSibling()) {
            if ("elementAnnotation".equals(child.getLocalName())) { //$NON-NLS-1$
                handleMarkup(elementDeclarationMarkupMap, (Element) child);
            } else if ("attributeAnnotation".equals(child.getLocalName())) { //$NON-NLS-1$
                handleMarkup(attributeDeclarationMarkupMap, (Element) child);
            } else if ("content".equals(child.getLocalName())) { //$NON-NLS-1$
                handleMarkup(contentDocumentationMap, (Element) child);
            } else if ("typeMap".equals(child.getLocalName())) { //$NON-NLS-1$
                Element markupElement = (Element) child;
                String schemaType = markupElement.getAttribute("schemaType"); //$NON-NLS-1$
                String javaClass = markupElement.getAttribute("javaClass"); //$NON-NLS-1$
                schemaTypeToJavaClassMap.put(schemaType, javaClass);
            }
        }
    } catch (Exception exception) {
        exception.printStackTrace(System.err);
    }
}

From source file:de.betterform.xml.xforms.model.Instance.java

/**
 * Returns a new created instance document.
 * <p/>// w  w  w . j av a 2 s.  c om
 * If this instance has an original instance, it will be imported into this
 * new document. Otherwise the new document is left empty.
 *
 * @return a new created instance document.
 * @throws de.betterform.xml.xforms.exception.XFormsException
 */
private Document createInstanceDocument() throws XFormsException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false);
        factory.setValidating(false);
        Document document = factory.newDocumentBuilder().newDocument();

        if (this.initialInstance != null) {
            Node imported = document.importNode(this.initialInstance.cloneNode(true), true);
            document.appendChild(imported);

            if (getXFormsAttribute(SRC_ATTRIBUTE) == null && getXFormsAttribute(RESOURCE_ATTRIBUTE) == null) {
                NamespaceResolver.applyNamespaces(this.element, document.getDocumentElement());
            }
        }

        return document;
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:com.amalto.workbench.utils.XSDParser.java

/**
 * Load the XML Schema file and print the documentation based on it.
 * //from w ww  .  j a v  a2 s .c om
 * @param xsdFile the name of an XML Schema file.
 */
public void loadAndPrint(String xsd) throws Exception {
    // XSDFactory xsdFactory = XSDFactory.eINSTANCE;

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setValidating(false);
    InputSource source = new InputSource(new StringReader(xsd));
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(source);
    XSDSchema xsdSchema = XSDSchemaImpl.createSchema(document.getDocumentElement());

    // Create a resource set and load the main schema file into it.
    //
    /*
     * ResourceSet resourceSet = new ResourceSetImpl(); XSDResourceImpl xsdResource = (XSDResourceImpl) resourceSet
     * .getResource(URI.createFileURI(xsdFile), true);
     * 
     * XSDResourceImpl res = new XSDResourceImpl();
     * 
     * XSDSchema xsdSchema = xsdResource.getSchema();
     */

    String elementContentHeaderDocumentation = getContentDocumentation("element-header"); //$NON-NLS-1$
    if (elementContentHeaderDocumentation != null) {
        System.out.println(elementContentHeaderDocumentation);
    }

    List all = new ArrayList(xsdSchema.getElementDeclarations());

    for (Iterator iter = all.iterator(); iter.hasNext();) {
        XSDElementDeclaration concept = (XSDElementDeclaration) iter.next();
        System.out
                .println("CONCEPT: " + concept.getName() + "-- " + concept.getContainer().getClass().getName()); //$NON-NLS-1$ //$NON-NLS-2$

        // name of the concept in English
        XSDAnnotation annotation = concept.getAnnotation();
        if (annotation != null) {
            EList list = annotation.getApplicationInformation();
            for (Iterator iterator = list.iterator(); iterator.hasNext();) {
                Element appinfo = (Element) iterator.next();
                String language = appinfo.getAttribute("source"); //$NON-NLS-1$
                if ("EN".equals(language.toUpperCase())) { //$NON-NLS-1$
                    if (appinfo.getFirstChild() != null)
                        System.out.println("     " + appinfo.getFirstChild().getNodeValue()); //$NON-NLS-1$
                }
            }
        }

        // children
        XSDTypeDefinition typedef = concept.getTypeDefinition();
        if (typedef instanceof XSDComplexTypeDefinition) {
            XSDComplexTypeContent xsdContent = ((XSDComplexTypeDefinition) typedef).getContent();
            XSDParticle xsdParticle = (XSDParticle) xsdContent;
            String ident = "    "; //$NON-NLS-1$
            processParticle(xsdParticle, ident);
        }

    } // for elements
}

From source file:org.opengeoportal.proxy.controllers.DynamicOgcController.java

/**
* An HTTP reverse proxy/gateway servlet. It is designed to be extended for customization
* if desired. Most of the work is handled by
* <a href="http://hc.apache.org/httpcomponents-client-ga/">Apache HttpClient</a>.
* <p>// www . j  av  a2 s  .  c o  m
* There are alternatives to a servlet based proxy such as Apache mod_proxy if that is available to you. However
* this servlet is easily customizable by Java, secure-able by your web application's security (e.g. spring-security),
* portable across servlet engines, and is embeddable into another web application.
* </p>
* <p>
* Inspiration: http://httpd.apache.org/docs/2.0/mod/mod_proxy.html
* </p>
*
* @author David Smiley dsmiley@mitre.org>
*/

private void createBuilder() throws ParserConfigurationException {
    // Create a factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //ignore validation, dtd
    factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    factory.setValidating(false);

    // Use document builder factory
    builder = factory.newDocumentBuilder();
}

From source file:de.betterform.xml.xforms.XFormsProcessorImpl.java

private DocumentBuilder getDocumentBuilder() throws XFormsException {
    // ensure xerces dom
    try {//from   w  w w. j  a  v a 2s. c o m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        // factory.setAttribute("http://apache.org/xml/properties/dom/document-class-name", "org.apache.xerces.dom.DocumentImpl");

        DocumentBuilder db = factory.newDocumentBuilder();
        // use an empty entity resolver to avoid that Xerces may try to
        // download the system DTD (can cause latency problems)
        db.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                return null;
            };
        });
        return db;
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:dip.world.variant.VariantManager.java

/** 
 *   Initiaize the VariantManager. //from   w  w w. ja v  a2  s  . com
 *   <p>
 *   An exception is thrown if no File paths are specified. A "." may be used
 *   to specify th ecurrent directory.
 *   <p>
 *   Loaded XML may be validated if the isValidating flag is set to true.
 *
 */
public static synchronized void init(final List<File> searchPaths, boolean isValidating)
        throws javax.xml.parsers.ParserConfigurationException, NoVariantsException {
    long ttime = System.currentTimeMillis();
    long vptime = ttime;
    Log.println("VariantManager.init()");

    if (searchPaths == null || searchPaths.isEmpty()) {
        throw new IllegalArgumentException();
    }

    if (vm != null) {
        // perform cleanup
        vm.variantMap.clear();
        vm.variants = new ArrayList<Variant>();
        vm.currentUCL = null;
        vm.currentPackageURL = null;

        vm.symbolPacks = new ArrayList<SymbolPack>();
        vm.symbolMap.clear();
    }

    vm = new VariantManager();

    // find plugins, create plugin loader
    final List<URL> pluginURLs = vm.searchForFiles(searchPaths, VARIANT_EXTENSIONS);

    // setup document builder
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {
        // this may improve performance, and really only apply to Xerces
        dbf.setAttribute("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.FALSE);
        dbf.setAttribute("http://apache.org/xml/properties/input-buffer-size", new Integer(4096));
        dbf.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
    } catch (Exception e) {
        Log.println("VM: Could not set XML feature.", e);
    }

    dbf.setValidating(isValidating);
    dbf.setCoalescing(false);
    dbf.setIgnoringComments(true);

    // setup variant parser
    XMLVariantParser variantParser = new XMLVariantParser(dbf);

    // for each plugin, attempt to find the "variants.xml" file inside. 
    // if it does not exist, we will not load the file. If it does, we will parse it,
    // and associate the variant with the URL in a hashtable.
    for (final URL pluginURL : pluginURLs) {
        URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL });
        URL variantXMLURL = urlCL.findResource(VARIANT_FILE_NAME);
        if (variantXMLURL != null) {
            String pluginName = getFile(pluginURL);

            // parse variant description file, and create hash entry of variant object -> URL
            InputStream is = null;
            try {
                is = new BufferedInputStream(variantXMLURL.openStream());
                variantParser.parse(is, pluginURL);
                final List<Variant> variants = variantParser.getVariants();

                // add variants; variants with same name (but older versions) are
                // replaced with same-name newer versioned variants
                for (final Variant variant : variants) {
                    addVariant(variant, pluginName, pluginURL);
                }
            } catch (IOException e) {
                // display error dialog
                ErrorDialog.displayFileIO(null, e, pluginURL.toString());
            } catch (org.xml.sax.SAXException e) {
                // display error dialog
                ErrorDialog.displayGeneral(null, e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    // if we are in webstart, search for variants within webstart jars
    Enumeration<URL> enum2 = null;
    ClassLoader cl = null;

    if (vm.isInWebstart) {
        cl = vm.getClass().getClassLoader();

        try {
            enum2 = cl.getResources(VARIANT_FILE_NAME);
        } catch (IOException e) {
            enum2 = null;
        }

        if (enum2 != null) {
            while (enum2.hasMoreElements()) {
                URL variantURL = enum2.nextElement();

                // parse variant description file, and create hash entry of variant object -> URL
                InputStream is = null;
                String pluginName = getWSPluginName(variantURL);

                try {
                    is = new BufferedInputStream(variantURL.openStream());

                    variantParser.parse(is, variantURL);
                    final List<Variant> variants = variantParser.getVariants();

                    // add variants; variants with same name (but older versions) are
                    // replaced with same-name newer versioned variants
                    for (final Variant variant : variants) {
                        addVariant(variant, pluginName, variantURL);
                    }
                } catch (IOException e) {
                    // display error dialog
                    ErrorDialog.displayFileIO(null, e, variantURL.toString());
                } catch (org.xml.sax.SAXException e) {
                    // display error dialog
                    ErrorDialog.displayGeneral(null, e);
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        } // if(enum2 != null)
    }

    // check: did we find *any* variants? Throw an exception.
    if (vm.variantMap.isEmpty()) {
        StringBuffer msg = new StringBuffer(256);
        msg.append("No variants found on path: ");
        for (final File searchPath : searchPaths) {
            msg.append(searchPath);
            msg.append("; ");
        }

        throw new NoVariantsException(msg.toString());
    }

    Log.printTimed(vptime, "VariantManager: variant parsing time: ");

    ///////////////// SYMBOLS /////////////////////////

    // now, parse symbol packs
    XMLSymbolParser symbolParser = new XMLSymbolParser(dbf);

    // find plugins, create plugin loader
    final List<URL> pluginURLs2 = vm.searchForFiles(searchPaths, SYMBOL_EXTENSIONS);

    // for each plugin, attempt to find the "variants.xml" file inside. 
    // if it does not exist, we will not load the file. If it does, we will parse it,
    // and associate the variant with the URL in a hashtable.
    for (final URL pluginURL : pluginURLs2) {
        URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL });
        URL symbolXMLURL = urlCL.findResource(SYMBOL_FILE_NAME);
        if (symbolXMLURL != null) {
            String pluginName = getFile(pluginURL);

            // parse variant description file, and create hash entry of variant object -> URL
            InputStream is = null;
            try {
                is = new BufferedInputStream(symbolXMLURL.openStream());
                symbolParser.parse(is, pluginURL);
                addSymbolPack(symbolParser.getSymbolPack(), pluginName, pluginURL);
            } catch (IOException e) {
                // display error dialog
                ErrorDialog.displayFileIO(null, e, pluginURL.toString());
            } catch (org.xml.sax.SAXException e) {
                // display error dialog
                ErrorDialog.displayGeneral(null, e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    // if we are in webstart, search for variants within webstart jars      
    enum2 = null;
    cl = null;

    if (vm.isInWebstart) {
        cl = vm.getClass().getClassLoader();

        try {
            enum2 = cl.getResources(SYMBOL_FILE_NAME);
        } catch (IOException e) {
            enum2 = null;
        }

        if (enum2 != null) {
            while (enum2.hasMoreElements()) {
                URL symbolURL = enum2.nextElement();

                // parse variant description file, and create hash entry of variant object -> URL
                InputStream is = null;
                String pluginName = getWSPluginName(symbolURL);

                try {
                    is = new BufferedInputStream(symbolURL.openStream());
                    symbolParser.parse(is, symbolURL);
                    addSymbolPack(symbolParser.getSymbolPack(), pluginName, symbolURL);
                } catch (IOException e) {
                    // display error dialog
                    ErrorDialog.displayFileIO(null, e, symbolURL.toString());
                } catch (org.xml.sax.SAXException e) {
                    // display error dialog
                    ErrorDialog.displayGeneral(null, e);
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        } // if(enum2 != null)
    } // if(isInWebStart)      

    // check: did we find *any* symbol packs? Throw an exception.
    if (vm.symbolMap.isEmpty()) {
        StringBuffer msg = new StringBuffer(256);
        msg.append("No SymbolPacks found on path: ");
        for (final File searchPath : searchPaths) {
            msg.append(searchPath);
            msg.append("; ");
        }

        throw new NoVariantsException(msg.toString());
    }
    Log.printTimed(ttime, "VariantManager: total parsing time: ");
}

From source file:org.eclipse.winery.repository.client.WineryRepositoryClient.java

/**
 * @param useProxy if a debugging proxy should be used
 *
 * @throws IllegalStateException if DOM parser could not be created
 *///from w ww  . j a  v  a  2s  . c  o  m
public WineryRepositoryClient(boolean useProxy) {
    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getClasses().add(JacksonJsonProvider.class);
    if (useProxy) {
        URLConnectionClientHandler ch = new URLConnectionClientHandler(new ConnectionFactory());
        this.client = new Client(ch, clientConfig);
    } else {
        this.client = Client.create(clientConfig);
    }

    this.entityTypeDataCache = new HashMap<>();
    this.nameCache = new HashMap<>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    if (WineryRepositoryClient.VALIDATING) {
        factory.setValidating(true);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema;
        URL resource = this.getClass().getResource("/TOSCA-v1.0.xsd");
        try {
            schema = schemaFactory.newSchema(resource);
        } catch (SAXException e) {
            throw new IllegalStateException("Schema could not be initalized", e);
        }
        factory.setSchema(schema);
    }
    try {
        this.toscaDocumentBuilder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException("document builder could not be initalized", e);
    }
    /*
     TODO: include this somehow - in the case of VALIDATING
            
     Does not work with TTopolgoyTemplate as this is not allowed in the root of an XML document
    this.toscaDocumentBuilder.setErrorHandler(new ErrorHandler() {
            
       @Override
       public void warning(SAXParseException arg0) throws SAXException {
    throw arg0;
       }
            
       @Override
       public void fatalError(SAXParseException arg0) throws SAXException {
    throw arg0;
       }
            
       @Override
       public void error(SAXParseException arg0) throws SAXException {
    throw arg0;
       }
    });
    */
}