Example usage for org.jdom2.input.sax XMLReaders NONVALIDATING

List of usage examples for org.jdom2.input.sax XMLReaders NONVALIDATING

Introduction

In this page you can find the example usage for org.jdom2.input.sax XMLReaders NONVALIDATING.

Prototype

XMLReaders NONVALIDATING

To view the source code for org.jdom2.input.sax XMLReaders NONVALIDATING.

Click Source Link

Document

The non-validating singleton

Usage

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 {/*from   w w  w.j av a2 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
 *///from w  w  w  . ja va2s .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
 *///from   www . j  ava  2s .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   www.jav  a 2 s.com*/
 *
 * @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:com.hp.application.automation.tools.octane.actions.UFTParameterFactory.java

License:Apache License

public static String convertResourceMtrAsJSON(InputStream resourceMtrInputStream) throws IOException {

    //TODO: Check is exists
    poiFS = new POIFSFileSystem(resourceMtrInputStream);
    DirectoryNode root = poiFS.getRoot();

    for (Entry entry : root) {
        String name = entry.getName();
        if (name.equals("ComponentInfo")) {
            if (entry instanceof DirectoryEntry) {
                System.out.println(entry);
            } else if (entry instanceof DocumentEntry) {
                byte[] content = new byte[((DocumentEntry) entry).getSize()];
                poiFS.createDocumentInputStream("ComponentInfo").read(content);
                String fromUnicodeLE = StringUtil.getFromUnicodeLE(content);
                xmlData = fromUnicodeLE.substring(fromUnicodeLE.indexOf('<')).replaceAll("\u0000", "");
                //                    System.out.println(xmlData);
            }//from  www  . j a  v a 2 s.c  o m
        }
    }
    try {
        SAXBuilder saxBuilder = new SAXBuilder(XMLReaders.NONVALIDATING, (SAXHandlerFactory) null,
                (JDOMFactory) null);
        Document document = null;
        document = saxBuilder.build(new StringReader(xmlData));
        Element classElement = document.getRootElement();
        List<Element> studentList = classElement.getChildren();
        ObjectMapper mapper = new ObjectMapper();
        ArrayList<UFTParameter> uftParameters = new ArrayList<UFTParameter>();
        UFTParameter uftParameter = new UFTParameter();
        for (int temp = 0; temp < studentList.size(); temp++) {
            Element tag = studentList.get(temp);
            if ("ArgumentsCollection".equalsIgnoreCase(tag.getName())) {
                List<Element> children = tag.getChildren();
                for (int i = 0; i < children.size(); i++) {
                    Element element = children.get(i);
                    List<Element> elements = element.getChildren();

                    for (int j = 0; j < elements.size(); j++) {

                        Element element1 = elements.get(j);
                        switch (element1.getName()) {
                        case "ArgName":
                            uftParameter.setArgName(element1.getValue());
                            break;
                        case "ArgDirection":
                            uftParameter.setArgDirection(Integer.parseInt(element1.getValue()));
                            break;
                        case "ArgDefaultValue":
                            uftParameter.setArgDefaultValue(element1.getValue());
                            break;
                        case "ArgType":
                            uftParameter.setArgType(element1.getValue());
                            break;
                        case "ArgIsExternal":
                            uftParameter.setArgIsExternal(Integer.parseInt(element1.getValue()));
                            break;
                        default:
                            logger.warning(
                                    String.format("Element name %s didn't match any case", element1.getName()));
                            break;
                        }
                    }
                    uftParameters.add(uftParameter);
                }
                return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(uftParameters);
            }
        }
    } catch (Exception e) {
        logger.severe(e.getMessage());
    }
    return null;
}

From source file:com.hpe.application.automation.tools.octane.actions.UFTParameterFactory.java

License:Open Source License

public static String convertResourceMtrAsJSON(InputStream resourceMtrInputStream) throws IOException {

    //String QTPFileParameterFileName = "resource.mtr";
    //InputStream is = paths.get(0).getParent().child("Action0").child(QTPFileParameterFileName).read();

    String xmlData = UFTTestUtil.decodeXmlContent(resourceMtrInputStream);

    try {/*from   w  w  w . j  a  va  2 s. c o  m*/
        SAXBuilder saxBuilder = new SAXBuilder(XMLReaders.NONVALIDATING, null, null);
        Document document = saxBuilder.build(new StringReader(xmlData));
        Element rootElement = document.getRootElement();
        List<Element> rootChildrenElements = rootElement.getChildren();
        ArrayList<UFTParameter> uftParameters = new ArrayList<>();
        for (int temp = 0; temp < rootChildrenElements.size(); temp++) {
            Element tag = rootChildrenElements.get(temp);
            if ("ArgumentsCollection".equalsIgnoreCase(tag.getName())) {
                List<Element> children = tag.getChildren();
                for (int i = 0; i < children.size(); i++) {
                    UFTParameter uftParameter = new UFTParameter();
                    Element element = children.get(i);
                    List<Element> elements = element.getChildren();

                    for (int j = 0; j < elements.size(); j++) {

                        Element element1 = elements.get(j);
                        switch (element1.getName()) {
                        case "ArgName":
                            uftParameter.setArgName(element1.getValue());
                            break;
                        case "ArgDirection":
                            uftParameter.setArgDirection(Integer.parseInt(element1.getValue()));
                            break;
                        case "ArgDefaultValue":
                            uftParameter.setArgDefaultValue(element1.getValue());
                            break;
                        case "ArgType":
                            uftParameter.setArgType(element1.getValue());
                            break;
                        case "ArgIsExternal":
                            uftParameter.setArgIsExternal(Integer.parseInt(element1.getValue()));
                            break;
                        default:
                            logger.warning(
                                    String.format("Element name %s didn't match any case", element1.getName()));
                            break;
                        }
                    }
                    uftParameters.add(uftParameter);
                }
                ObjectMapper mapper = new ObjectMapper();
                String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(uftParameters);
                return result;
            }
        }
    } catch (Exception e) {
        logger.severe(e.getMessage());
    }
    return null;
}

From source file:com.hpe.application.automation.tools.octane.actions.UFTParameterFactory.java

License:Open Source License

public static Collection<UFTParameter> convertApiTestXmlToArguments(File parametersFile,
        boolean isInputParameters) throws IOException {

    /*<TestParameters>
    <Schema>/* w  w  w  .j  a v  a  2s.co  m*/
        <xsd:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:types="http://hp.vtd.schemas/types/v1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <xs:import schemaLocation="../../../dat/schemas/Types.xsd" namespace="http://hp.vtd.schemas/types/v1.0" />
            <xs:element types:displayName="Parameters" name="Arguments">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element types:masked="false" name="StartParam1" type="xs:long">
                            <xs:annotation>
                                <xs:documentation />
                            </xs:annotation>
                        </xs:element>
                        <xs:element types:masked="false" name="endParam1" type="xs:string">
                            <xs:annotation>
                                <xs:documentation />
                            </xs:annotation>
                        </xs:element>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xsd:schema>
    </Schema>
    <Values>
        <Arguments>
            <StartParam1>1</StartParam1>
            <endParam1>f</endParam1>
        </Arguments>
    </Values>
    </TestParameters>*/

    try {
        SAXBuilder saxBuilder = new SAXBuilder(XMLReaders.NONVALIDATING, null, null);
        Document document = saxBuilder.build(parametersFile);
        Element rootElement = document.getRootElement();

        Map<String, UFTParameter> uftParametersMap = new HashMap<>();
        List<Element> argElements = getHierarchyChildElement(rootElement, "Schema", "schema", "element",
                "complexType", "sequence").getChildren();
        for (Element argElement : argElements) {
            String name = argElement.getAttributeValue("name");
            String type = argElement.getAttributeValue("type").replace("xs:", "");
            int direction = isInputParameters ? 0 : 1;

            UFTParameter parameter = new UFTParameter();
            parameter.setArgName(name);
            parameter.setArgType(type);
            parameter.setArgDirection(direction);
            uftParametersMap.put(parameter.getArgName(), parameter);
        }

        //getArg default values
        List<Element> argDefValuesElements = getHierarchyChildElement(rootElement, "Values", "Arguments")
                .getChildren();
        for (Element argElement : argDefValuesElements) {
            UFTParameter parameter = uftParametersMap.get(argElement.getName());
            if (parameter != null) {
                parameter.setArgDefaultValue(argElement.getValue());
            }
        }

        return uftParametersMap.values();
    } catch (Exception e) {
        logger.severe(e.getMessage());
    }
    return Collections.emptySet();
}

From source file:com.hpe.application.automation.tools.octane.actions.UFTTestUtil.java

License:Open Source License

/**
 * Extract test description from UFT GUI test.
 * Note : UFT API test doesn't contain description
 * @param dirPath path of UFT test/*ww  w  .  j  ava  2 s  . com*/
 * @return test description
 */
public static String getTestDescription(FilePath dirPath) {
    String desc;

    try {
        if (!dirPath.exists()) {
            return null;
        }

        FilePath tspTestFile = new FilePath(dirPath, "Test.tsp");
        InputStream is = new FileInputStream(tspTestFile.getRemote());
        String xmlContent = decodeXmlContent(is);

        SAXBuilder saxBuilder = new SAXBuilder(XMLReaders.NONVALIDATING, null, null);
        Document document = saxBuilder.build(new StringReader(xmlContent));
        Element rootElement = document.getRootElement();
        Element descElement = rootElement.getChild("Description");
        desc = descElement.getValue();
    } catch (Exception e) {
        return null;
    }

    return desc;
}

From source file:com.izforge.izpack.util.xmlmerge.merge.DefaultXmlMerge.java

License:Open Source License

@Override
public InputStream merge(InputStream[] sources) throws AbstractXmlMergeException {
    SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);
    // Xerces-specific - see: http://xerces.apache.org/xerces-j/features.html
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    Document[] docs = new Document[sources.length];

    for (int i = 0; i < sources.length; i++) {
        try {/*ww  w.j a  v  a  2  s.  co m*/
            docs[i] = builder.build(sources[i]);
        } catch (Exception e) {
            throw new ParseException(e);
        }
    }

    Document result = doMerge(docs);

    Format prettyFormatter = Format.getPrettyFormat();
    // Use system line seperator to avoid problems
    // with carriage return under linux
    prettyFormatter.setLineSeparator(System.getProperty("line.separator"));
    XMLOutputter sortie = new XMLOutputter(prettyFormatter);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    try {
        sortie.output(result, buffer);
    } catch (IOException ex) {
        throw new DocumentException(result, ex);
    }

    return new ByteArrayInputStream(buffer.toByteArray());
}

From source file:com.izforge.izpack.util.xmlmerge.merge.DefaultXmlMerge.java

License:Open Source License

@Override
public void merge(File[] sources, File target) throws AbstractXmlMergeException {
    SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);
    // Xerces-specific - see: http://xerces.apache.org/xerces-j/features.html
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    Document[] docs = new Document[sources.length];

    for (int i = 0; i < sources.length; i++) {
        try {/* w  ww  .j ava2  s. c o m*/
            docs[i] = builder.build(sources[i]);
        } catch (Exception e) {
            throw new ParseException(e);
        }
    }

    Document result = doMerge(docs);

    Format prettyFormatter = Format.getPrettyFormat();
    // Use system line separator to avoid problems
    // with carriage return under linux
    prettyFormatter.setLineSeparator(System.getProperty("line.separator"));
    XMLOutputter sortie = new XMLOutputter(prettyFormatter);

    try {
        sortie.output(result, new FileOutputStream(target));
    } catch (IOException ex) {
        throw new DocumentException(result, ex);
    }
}