Example usage for org.jdom2.input SAXBuilder SAXBuilder

List of usage examples for org.jdom2.input SAXBuilder SAXBuilder

Introduction

In this page you can find the example usage for org.jdom2.input SAXBuilder SAXBuilder.

Prototype

public SAXBuilder(final XMLReaderJDOMFactory readersouce) 

Source Link

Document

Creates a new SAXBuilder with the specified XMLReaderJDOMFactory.

Usage

From source file:AL_gui.java

License:Apache License

public void loadFile(String pathname, String filename) {

    try {//from   w w  w  .jav  a2 s. co m
        // Build & creat the document with SAX, use XML schema validation
        URL path = ClassLoader.getSystemResource("ANNeML.xsd");
        if (path.getFile() == null) {
            jLabel2.setForeground(Color.RED);
            jLabel2.setText("error loading XML schema");
        } else {
            //File argylexsd = new File(path.toURI());
            //XMLReaderJDOMFactory schemafac = new XMLReaderXSDFactory(argylexsd);
            XMLReaderJDOMFactory schemafac = new XMLReaderXSDFactory("ANNeML.xsd"); //***for .jar deployment
            SAXBuilder builder = new SAXBuilder(schemafac);
            AL_gui.NNetMap = builder.build(pathname);
            java.util.List subnets = XPath.newInstance("//SUBNET").selectNodes(AL_gui.NNetMap);
            java.util.List layers = XPath.newInstance("//LAYER").selectNodes(AL_gui.NNetMap);
            java.util.List inputNeurodes = XPath.newInstance("//NEURODE[SYNAPSE/@ORG_NEURODE='INPUT']")
                    .selectNodes(AL_gui.NNetMap);
            java.util.List hiddenNeurodes = XPath.newInstance("//LAYER[@LAYER_NAME='HIDDEN']/NEURODE")
                    .selectNodes(AL_gui.NNetMap);
            java.util.List outputNeurodes = XPath.newInstance("//LAYER[@LAYER_NAME='OUTPUT']/NEURODE")
                    .selectNodes(AL_gui.NNetMap);
            jLabel2.setForeground(Color.GREEN);
            jLabel2.setText("Valid ANNeML file.");
        }
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(AL_gui.this, "There was an error parsing the file.\n" + e.toString(),
                "Warning", JOptionPane.WARNING_MESSAGE);
    }

}

From source file:Erudite_gui.java

License:Apache License

public void loadFile(String pathname, String filename) {
    jLabel6.setEnabled(true);//from  ww w.ja v  a  2  s .co m
    jLabel7.setEnabled(true);
    jButton3.setEnabled(true);
    jButton4.setEnabled(true);
    jCheckBox1.setSelected(false);
    jCheckBox1.setEnabled(true);
    jEditorPane1.setEnabled(true);
    DefaultTableModel tblmodel = (DefaultTableModel) jTable2.getModel();
    tblmodel.setRowCount(0);

    try {
        // Build & creat the document with SAX, use XML schema validation
        URL path = ClassLoader.getSystemResource("ANNeML.xsd");
        if (path.getFile() == null) {
            jLabel2.setForeground(Color.RED);
            jLabel2.setText("error loading XML schema");
        } else {
            //File argylexsd = new File(path.toURI());
            //XMLReaderJDOMFactory schemafac = new XMLReaderXSDFactory(argylexsd);
            XMLReaderJDOMFactory schemafac = new XMLReaderXSDFactory("ANNeML.xsd"); //***for .jar deployment
            SAXBuilder builder = new SAXBuilder(schemafac);
            Erudite_gui.NNetMap = builder.build(pathname);
            JDOMToTreeModelAdapter model = new JDOMToTreeModelAdapter(Erudite_gui.NNetMap);
            XMLTreeCellRenderer renderer = new XMLTreeCellRenderer();
            jTree1.setCellRenderer(renderer);
            jTree1.setModel(model);
            java.util.List subnets = XPath.newInstance("//SUBNET").selectNodes(Erudite_gui.NNetMap);
            java.util.List layers = XPath.newInstance("//LAYER").selectNodes(Erudite_gui.NNetMap);
            java.util.List inputNeurodes = XPath.newInstance("//NEURODE[SYNAPSE/@ORG_NEURODE='INPUT']")
                    .selectNodes(Erudite_gui.NNetMap);
            java.util.List hiddenNeurodes = XPath.newInstance("//LAYER[@LAYER_NAME='HIDDEN']/NEURODE")
                    .selectNodes(Erudite_gui.NNetMap);
            java.util.List outputNeurodes = XPath.newInstance("//LAYER[@LAYER_NAME='OUTPUT']/NEURODE")
                    .selectNodes(Erudite_gui.NNetMap);
            Color colr = new Color(0, 153, 255);
            jLabel2.setForeground(colr);
            jLabel2.setText("Valid ANNeML file.");
            HTMLEditorKit kit = (HTMLEditorKit) jEditorPane1.getEditorKit();
            HTMLDocument doc = (HTMLDocument) jEditorPane1.getDocument();
            kit.insertHTML(doc, jEditorPane1.getCaretPosition(), "<b>" + filename + " loaded...</b>", 0, 0,
                    null);
            jLabel3.setText("Subnet(s): " + subnets.size() + "  Layers: " + layers.size() + "  Inputs: "
                    + inputNeurodes.size() + "  Hidden: " + hiddenNeurodes.size() + "  Outputs: "
                    + outputNeurodes.size());
            jLabel7.setText(java.lang.String.valueOf(inputNeurodes.size()));
            Erudite_gui.inputNID = new String[inputNeurodes.size()];
            Erudite_gui.inputCNAME = new String[inputNeurodes.size()];
            Erudite_gui.outputNID = new String[outputNeurodes.size()];
            Erudite_gui.outputCNAME = new String[outputNeurodes.size()];
            int i = 0;
            for (Iterator it = inputNeurodes.iterator(); it.hasNext();) {
                Element InputNode = (Element) it.next();
                Erudite_gui.inputNID[i] = InputNode.getAttributeValue("N_ID");
                Erudite_gui.inputCNAME[i] = InputNode.getAttributeValue("CNAME");
                tblmodel.addRow(
                        new String[] { null, Erudite_gui.inputNID[i] + " '" + inputCNAME[i] + "' ", null });
                kit.insertHTML(doc, jEditorPane1.getCaretPosition(),
                        "<b>" + inputNID[i] + "</b> " + inputCNAME[i] + "<br>", 0, 0, null);
                i++;
            }
            int y = 0;
            for (Iterator it = outputNeurodes.iterator(); it.hasNext();) {
                Element OutputNode = (Element) it.next();
                Erudite_gui.outputCNAME[y] = OutputNode.getAttributeValue("CNAME");
                Erudite_gui.outputNID[y] = OutputNode.getAttributeValue("N_ID");
                kit.insertHTML(doc, jEditorPane1.getCaretPosition(),
                        "<b>" + outputNID[y] + "</b> " + outputCNAME[y] + "<br>", 0, 0, null);
                y++;
            }
            kit.insertHTML(doc, jEditorPane1.getCaretPosition(),
                    "Ready for input processing or training...<br><br>", 0, 0, null);
        }
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(jPanel1, "There was an error parsing the file.\n" + e.toString(),
                "Warning", JOptionPane.WARNING_MESSAGE);
    }

}

From source file:at.newmedialab.ldpath.model.functions.XPathFunction.java

License:Apache License

private LinkedList<String> doFilter(String in, Set<String> xpaths) throws IOException {
    LinkedList<String> result = new LinkedList<String>();
    try {//  w w  w . jav  a  2  s .  co m
        Document doc = new SAXBuilder(XMLReaders.NONVALIDATING).build(new StringReader(in));
        XMLOutputter out = new XMLOutputter();

        for (String xp : xpaths) {
            XPathExpression<Content> xpath = XPathFactory.instance().compile(xp, Filters.content());
            for (Content node : xpath.evaluate(doc)) {
                if (node instanceof Element)
                    result.add(out.outputString((Element) node));
                else if (node instanceof Text)
                    result.add(out.outputString((Text) node));
            }
        }
        return result;
    } catch (JDOMException xpe) {
        throw new IllegalArgumentException("error while processing xpath expressions: '" + xpaths + "'", xpe);
    }
}

From source file:at.newmedialab.lmf.search.services.cores.SolrCoreServiceImpl.java

License:Apache License

/**
 * Create/update the schema.xml file for the given core according to the core definition.
 *
 * @param engine the engine configuration
 *//*  w w w . j  a  v a2s.c  o m*/
private void createSchemaXml(SolrCoreConfiguration engine) throws MarmottaException {
    log.info("generating schema.xml for search program {}", engine.getName());

    SAXBuilder parser = new SAXBuilder(XMLReaders.NONVALIDATING);
    File schemaTemplate = new File(getCoreDirectory(engine.getName()),
            "conf" + File.separator + "schema-template.xml");
    File schemaFile = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "schema.xml");
    try {
        Document doc = parser.build(schemaTemplate);

        Element schemaNode = doc.getRootElement();
        Element fieldsNode = schemaNode.getChild("fields");
        if (!schemaNode.getName().equals("schema") || fieldsNode == null)
            throw new MarmottaException(schemaTemplate + " is an invalid SOLR schema file");

        schemaNode.setAttribute("name", engine.getName());

        Program<Value> program = engine.getProgram();

        for (FieldMapping<?, Value> fieldMapping : program.getFields()) {
            String fieldName = fieldMapping.getFieldName();
            String solrType = null;
            try {
                solrType = solrProgramService.getSolrFieldType(fieldMapping.getFieldType().toString());
            } catch (MarmottaException e) {
                solrType = null;
            }
            if (solrType == null) {
                log.error("field {} has an invalid field type; ignoring field definition", fieldName);
                continue;
            }

            Element fieldElement = new Element("field");
            fieldElement.setAttribute("name", fieldName);
            fieldElement.setAttribute("type", solrType);
            // Set the default properties
            fieldElement.setAttribute("stored", "true");
            fieldElement.setAttribute("indexed", "true");
            fieldElement.setAttribute("multiValued", "true");

            // FIXME: Hardcoded Stuff!
            if (solrType.equals("location")) {
                fieldElement.setAttribute("indexed", "true");
                fieldElement.setAttribute("multiValued", "false");
            }

            // Handle extra field configuration
            final Map<String, String> fieldConfig = fieldMapping.getFieldConfig();
            if (fieldConfig != null) {
                for (Map.Entry<String, String> attr : fieldConfig.entrySet()) {
                    if (SOLR_FIELD_OPTIONS.contains(attr.getKey())) {
                        fieldElement.setAttribute(attr.getKey(), attr.getValue());
                    }
                }
            }
            fieldsNode.addContent(fieldElement);

            if (fieldConfig != null && fieldConfig.keySet().contains(SOLR_COPY_FIELD_OPTION)) {
                String[] copyFields = fieldConfig.get(SOLR_COPY_FIELD_OPTION).split("\\s*,\\s*");
                for (String copyField : copyFields) {
                    if (copyField.trim().length() > 0) { // ignore 'empty' fields
                        Element copyElement = new Element("copyField");
                        copyElement.setAttribute("source", fieldName);
                        copyElement.setAttribute("dest", copyField.trim());
                        schemaNode.addContent(copyElement);
                    }
                }
            } else {
                Element copyElement = new Element("copyField");
                copyElement.setAttribute("source", fieldName);
                copyElement.setAttribute("dest", "lmf.text_all");
                schemaNode.addContent(copyElement);
            }

            //for suggestions, copy all fields to lmf.spellcheck (used for spellcheck and querying);
            //only facet is a supported type at the moment
            if (fieldConfig != null && fieldConfig.keySet().contains(SOLR_SUGGESTION_FIELD_OPTION)) {
                String suggestionType = fieldConfig.get(SOLR_SUGGESTION_FIELD_OPTION);
                if (suggestionType.equals("facet")) {
                    Element copyElement = new Element("copyField");
                    copyElement.setAttribute("source", fieldName);
                    copyElement.setAttribute("dest", "lmf.spellcheck");
                    schemaNode.addContent(copyElement);
                } else {
                    log.error("suggestionType " + suggestionType + " not supported");
                }
            }
        }

        if (!schemaFile.exists() || schemaFile.canWrite()) {
            FileOutputStream out = new FileOutputStream(schemaFile);

            XMLOutputter xo = new XMLOutputter(Format.getPrettyFormat().setIndent("    "));
            xo.output(doc, out);
            out.close();
        } else {
            log.error("schema file {} is not writable", schemaFile);
        }

    } catch (JDOMException e) {
        throw new MarmottaException("parse error while parsing SOLR schema template file " + schemaTemplate, e);
    } catch (IOException e) {
        throw new MarmottaException("I/O error while parsing SOLR schema template file " + schemaTemplate, e);
    }

}

From source file:at.newmedialab.lmf.search.services.cores.SolrCoreServiceImpl.java

License:Apache License

/**
 * Create/update the solrconfig.xml file for the given core according to the core configuration.
 *
 * @param engine the solr core configuration
 *//* ww w. j a  va 2  s.  c o  m*/
private void createSolrConfigXml(SolrCoreConfiguration engine) throws MarmottaException {
    File configTemplate = new File(getCoreDirectory(engine.getName()),
            "conf" + File.separator + "solrconfig-template.xml");
    File configFile = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "solrconfig.xml");

    try {
        SAXBuilder parser = new SAXBuilder(XMLReaders.NONVALIDATING);
        Document solrConfig = parser.build(configTemplate);

        FileOutputStream out = new FileOutputStream(configFile);

        // Configure suggestion service: add fields to suggestion handler
        Program<Value> program = engine.getProgram();
        for (Element handler : solrConfig.getRootElement().getChildren("requestHandler")) {
            if (handler.getAttribute("class").getValue().equals(SuggestionRequestHandler.class.getName())) {
                for (Element lst : handler.getChildren("lst")) {
                    if (lst.getAttribute("name").getValue().equals("defaults")) {
                        //set suggestion fields
                        for (FieldMapping<?, Value> fieldMapping : program.getFields()) {

                            String fieldName = fieldMapping.getFieldName();
                            final Map<String, String> fieldConfig = fieldMapping.getFieldConfig();

                            if (fieldConfig != null
                                    && fieldConfig.keySet().contains(SOLR_SUGGESTION_FIELD_OPTION)) {
                                String suggestionType = fieldConfig.get(SOLR_SUGGESTION_FIELD_OPTION);
                                if (suggestionType.equals("facet")) {
                                    Element field_elem = new Element("str");
                                    field_elem.setAttribute("name", SuggestionRequestParams.SUGGESTION_FIELD);
                                    field_elem.setText(fieldName);
                                    lst.addContent(field_elem);
                                } else {
                                    log.error("suggestionType " + suggestionType + " not supported");
                                }
                            }
                        }
                    }
                }
            }
        }

        XMLOutputter xo = new XMLOutputter(Format.getPrettyFormat().setIndent("    "));
        xo.output(solrConfig, out);
        out.close();
    } catch (JDOMException e) {
        throw new MarmottaException("parse error while parsing SOLR schema template file " + configTemplate, e);
    } catch (IOException e) {
        throw new MarmottaException("I/O error while parsing SOLR schema template file " + configTemplate, e);
    }
}

From source file:ataraxis.passwordmanager.XMLHandler.java

License:Open Source License

/**
 * Load the Passwords from a XML File./*from w  w w  .  j a va 2 s.c  o m*/
 *
 * @throws StorageException if an error occurs
 */
public void loadPasswords() throws StorageException {
    try {
        // Build document with on-the-fly decryption
        SAXBuilder xmlReader = new SAXBuilder(XMLReaders.NONVALIDATING);

        InputStream inStream = getAccountFileInputStream();
        s_doc = xmlReader.build(inStream);
        inStream.close();

        // set root Element of Document
        s_rootElement = s_doc.getRootElement();
    } catch (JDOMException e) {
        logger.fatal(e);
        throw new StorageException(e);
    } catch (IOException e) {
        logger.fatal(e);
        throw new StorageException(e);
    }
}

From source file:ca.nrc.cadc.dali.tables.votable.VOTableReader.java

License:Open Source License

/**
 * Create a XML parser using the schemaMap schemas for validation.
 * @param schemaMap Map of schema namespace to location.
 * @return XML parser./*  w w w  . j a  v  a2 s. c  o m*/
 */
protected SAXBuilder createBuilder(Map<String, String> schemaMap) {
    long start = System.currentTimeMillis();
    boolean schemaVal = (schemaMap != null);
    String schemaResource;
    String space = " ";
    StringBuilder sbSchemaLocations = new StringBuilder();
    if (schemaVal) {
        log.debug("schemaMap.size(): " + schemaMap.size());
        for (String schemaNSKey : schemaMap.keySet()) {
            schemaResource = (String) schemaMap.get(schemaNSKey);
            sbSchemaLocations.append(schemaNSKey).append(space).append(schemaResource).append(space);
        }
        // enable xerces grammar caching
        System.setProperty("org.apache.xerces.xni.parser.XMLParserConfiguration", GRAMMAR_POOL);
    }

    XMLReaderSAX2Factory factory = new XMLReaderSAX2Factory(schemaVal, PARSER);
    SAXBuilder builder = new SAXBuilder(factory);
    if (schemaVal) {
        builder.setFeature("http://xml.org/sax/features/validation", true);
        builder.setFeature("http://apache.org/xml/features/validation/schema", true);
        if (schemaMap.size() > 0) {
            builder.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
                    sbSchemaLocations.toString());
        }
    }
    long finish = System.currentTimeMillis();
    log.debug("SAXBuilder in " + (finish - start) + "ms");
    return builder;
}

From source file:ca.nrc.cadc.uws.util.XmlUtil.java

License:Open Source License

public static SAXBuilder createBuilder(Map<String, String> schemaMap) {
    long start = System.currentTimeMillis();
    boolean schemaVal = (schemaMap != null);
    String schemaResource;// w w  w. j av  a2s.c om
    String space = " ";
    StringBuilder sbSchemaLocations = new StringBuilder();
    if (schemaVal) {
        log.debug("schemaMap.size(): " + schemaMap.size());
        for (String schemaNSKey : schemaMap.keySet()) {
            schemaResource = (String) schemaMap.get(schemaNSKey);
            sbSchemaLocations.append(schemaNSKey).append(space).append(schemaResource).append(space);
        }
        // enable xerces grammar caching
        System.setProperty("org.apache.xerces.xni.parser.XMLParserConfiguration", GRAMMAR_POOL);
    }

    XMLReaderSAX2Factory factory = new XMLReaderSAX2Factory(schemaVal, PARSER);
    SAXBuilder builder = new SAXBuilder(factory);
    if (schemaVal) {
        builder.setFeature("http://xml.org/sax/features/validation", true);
        builder.setFeature("http://apache.org/xml/features/validation/schema", true);
        if (schemaMap.size() > 0) {
            builder.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
                    sbSchemaLocations.toString());
        }
    }
    long finish = System.currentTimeMillis();
    log.debug("SAXBuilder in " + (finish - start) + "ms");
    return builder;
}

From source file:com.archimatetool.jdom.JDOMUtils.java

License:Open Source License

/**
 * Reads and returns a JDOM Document from file with Schema validation
 * @param xmlFile The XML File/*from   w ww .  j av  a2 s.  c  o m*/
 * @param schemaFile One or more Schema files
 * @return The JDOM Document or null if not found
 * @throws JDOMException
 * @throws IOException
 */
public static Document readXMLFile(File xmlFile, File... schemaFiles) throws IOException, JDOMException {
    XMLReaderJDOMFactory factory = new XMLReaderXSDFactory(schemaFiles);
    SAXBuilder builder = new SAXBuilder(factory);

    // This allows UNC mapped locations to load
    return builder.build(new FileInputStream(xmlFile));
}

From source file:com.hack23.cia.service.external.common.impl.XmlAgentImpl.java

License:Apache License

/**
 * Sets the name space on xml stream./*from w w  w. java2 s .  com*/
 *
 * @param in
 *            the in
 * @param nameSpace
 *            the name space
 * @return the source
 * @throws Exception
 *             the exception
 */
private static Source setNameSpaceOnXmlStream(final InputStream in, final String nameSpace) throws Exception {
    final SAXBuilder sb = new SAXBuilder(new XMLReaderSAX2Factory(false));
    final Document doc = sb.build(in);
    doc.getRootElement().setNamespace(Namespace.getNamespace(nameSpace));
    return new JDOMSource(doc);
}