Example usage for org.dom4j.io SAXReader read

List of usage examples for org.dom4j.io SAXReader read

Introduction

In this page you can find the example usage for org.dom4j.io SAXReader read.

Prototype

public Document read(InputSource in) throws DocumentException 

Source Link

Document

Reads a Document from the given InputSource using SAX

Usage

From source file:com.haulmont.cuba.core.sys.AppComponents.java

License:Apache License

private Document getDescriptorDoc(AppComponent component) throws IOException, DocumentException {
    String descriptorPath = component.getDescriptorPath();
    InputStream descrStream = getClass().getClassLoader().getResourceAsStream(descriptorPath);
    if (descrStream == null)
        throw new RuntimeException("App component descriptor was not found in '" + descriptorPath + "'");
    try {//from ww w .jav  a 2  s. c  o  m
        SAXReader reader = new SAXReader();
        return reader.read(new InputStreamReader(descrStream, StandardCharsets.UTF_8));
    } catch (DocumentException e) {
        throw new RuntimeException("Error reading app component descriptor '" + descriptorPath + "'", e);
    } finally {
        IOUtils.closeQuietly(descrStream);
    }
}

From source file:com.haulmont.cuba.core.sys.MetadataLoader.java

License:Apache License

protected void loadDatatypesFromClasspathResource() {
    SAXReader reader = new SAXReader();
    URL resource = Datatypes.class.getResource(getGetDatatypesResourcePath());
    if (resource != null) {
        log.info("Loading datatypes from " + resource);
        try {//  w w w.ja  v a2s .  c o  m
            Document document = reader.read(resource);
            Element element = document.getRootElement();

            List<Element> datatypeElements = Dom4j.elements(element, "datatype");
            for (Element datatypeElement : datatypeElements) {
                String datatypeClassName = datatypeElement.attributeValue("class");
                try {
                    Datatype datatype;
                    Class<Datatype> datatypeClass = ReflectionHelper.getClass(datatypeClassName);
                    try {
                        final Constructor<Datatype> constructor = datatypeClass.getConstructor(Element.class);
                        datatype = constructor.newInstance(datatypeElement);
                    } catch (Throwable e) {
                        datatype = datatypeClass.newInstance();
                    }

                    String id = datatypeElement.attributeValue("id");
                    if (Strings.isNullOrEmpty(id))
                        id = guessDatatypeId(datatype);
                    datatypeRegistry.register(datatype, id, true);
                } catch (Throwable e) {
                    log.error(String.format("Fail to load datatype '%s'", datatypeClassName), e);
                }
            }
        } catch (DocumentException e) {
            log.error("Fail to load datatype settings", e);
        }
    }
}

From source file:com.haulmont.cuba.desktop.theme.impl.DesktopThemeLoaderImpl.java

License:Apache License

private Document readXmlDocument(Resource resource) throws IOException {
    Document doc;//from   www. j  a v a 2s  .  c  o m
    InputStream stream = null;
    try {
        stream = resource.getInputStream();
        try {
            SAXReader reader = new SAXReader();
            doc = reader.read(stream);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    } finally {
        IOUtils.closeQuietly(stream);
    }
    return doc;
}

From source file:com.haulmont.yarg.structure.xml.impl.DefaultXmlReader.java

License:Apache License

@Override
public Report parseXml(String xml) throws IOException {
    try {/*w ww.  j  av  a  2s .c o m*/
        SAXReader reader = null;
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();

            SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

            factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource(
                    Thread.currentThread().getContextClassLoader().getResourceAsStream("reporting.xsd")) }));

            SAXParser parser = factory.newSAXParser();

            reader = new SAXReader(parser.getXMLReader());
        } catch (SAXException e) {
            throw new ReportingXmlException(
                    String.format("An error occurred during loading reporting xsd. \\n[%s]", xml), e);
        } catch (ParserConfigurationException e) {
            throw new ReportingXmlException(
                    String.format("An error occurred during loading reporting xsd. \\n[%s]", xml), e);
        }

        Document document = reader.read(new StringReader(xml));
        Element rootElement = document.getRootElement();
        Map<String, ReportTemplate> templateMap = parseTemplates(rootElement);
        List<ReportParameter> reportParameters = parseInputParameters(rootElement);
        List<ReportFieldFormat> reportFieldFormats = parseValueFormats(rootElement);
        BandBuilder rootBandDefinitionBuilder = new BandBuilder().name(BandData.ROOT_BAND_NAME);
        parseQueries(rootElement.element("rootBand"), rootBandDefinitionBuilder);
        parseChildBandDefinitions(rootElement.element("rootBand"), rootBandDefinitionBuilder);
        ReportBand rootBandDefinition = rootBandDefinitionBuilder.build();
        String reportName = rootElement.attribute("name").getText();
        ReportImpl report = new ReportImpl(reportName, templateMap, rootBandDefinition, reportParameters,
                reportFieldFormats);
        return report;
    } catch (DocumentException e) {
        throw new ReportingXmlException(
                String.format("An error occurred while parsing report xml. \\n[%s]", xml), e);
    } catch (FileNotFoundException e) {
        throw new ReportingXmlException(String.format("Could not find report template. \\n[%s]", xml), e);
    } catch (ClassNotFoundException e) {
        throw new ReportingXmlException(String.format("Report parameter class not found. \\n[%s]", xml), e);
    }
}

From source file:com.hihframework.osplugins.dom4j.XmlParseUtil.java

License:Apache License

public Document readXml(File file) throws MalformedURLException, DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(file);
    //Document document=reader.read(InputStream);
    //Document document=reader.read(url);
    return document;
}

From source file:com.huateng.struts.system.action.LoginRedirectAction.java

License:Open Source License

@Override
protected String subExecute() throws Exception {
    Operator operator = (Operator) getSessionAttribute(Constants.OPERATOR_INFO);
    SAXReader reader = new SAXReader();
    org.dom4j.Document document = null;
    try {//from   w  ww . j  a  v a 2  s  .com
        document = reader.read(ServletActionContext.getRequest().getSession().getServletContext()
                .getResourceAsStream(Constants.MENU_CONFIG_CONTEXTPATH));
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    LinkedHashMap<String, Object> menuMap = MenuInfoUtil.setOperatorMenuWithDegree(operator.getOprDegree(),
            ServletActionContext.getRequest().getContextPath(), document);
    Iterator<String> iter = menuMap.keySet().iterator();
    LinkedList<Object> toolList = new LinkedList<Object>();
    List<String> menuList = new ArrayList<String>();
    while (iter.hasNext()) {
        toolList.add(menuMap.get(iter.next()));
    }
    String toolBarStr = JSONArray.fromObject(toolList).toString();
    //?JSON???

    toolBarStr = toolBarStr.replaceAll(Constants.MENU_LVL1_JSON_FUNC, Constants.MENU_LVL1_FUNC)
            .replaceAll(Constants.MENU_LVL3_JSON_FUNC, Constants.MENU_LVL3_FUNC);
    //?
    setSessionAttribute(Constants.OPERATOR_INFO, operator);
    //???
    removeTreeCls(menuMap);
    //??
    setSessionAttribute(Constants.TREE_MENU_MAP, menuMap);
    //?
    setSessionAttribute(Constants.TOOL_BAR_STR, toolBarStr);
    //TODO ??
    loadLastOperInfo(operator);
    String panelStr = menuMap.get(Constants.TREE_MENU_PANEL).toString();
    setSessionAttribute(Constants.TREE_MENU_PANEL, panelStr);
    return SUCCESS;
}

From source file:com.hyrt.cei.util.ColumnsUtil.java

public Table[] parsePDM_VO(InputStream ips) {
    Table[] tabs = new Table[] {};
    List<Table> voS = new ArrayList<Table>();
    Table vo = null;//from w w w .j  a  va2s . c  o  m
    Column[] cols = null;
    SAXReader sr = new SAXReader();
    Document doc = null;
    try {
        doc = sr.read(ips);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    Iterator itr = doc.selectNodes("//c:Tables//o:Table").iterator();
    while (itr.hasNext()) {
        vo = new Table();
        cols = new Column[] {};
        List<Column> list = new ArrayList<Column>();
        Column col = null;
        Element e_table = (Element) itr.next();
        vo.setTableName(e_table.elementTextTrim("Name"));
        vo.setTableCode(e_table.elementTextTrim("Code"));
        Iterator itr1 = e_table.element("Columns").elements("Column").iterator();
        while (itr1.hasNext()) {
            try {
                col = new Column();
                Element e_col = (Element) itr1.next();
                String pkID = e_col.attributeValue("Id");
                col.setDefaultValue(e_col.elementTextTrim("DefaultValue"));
                col.setName(e_col.elementTextTrim("Name"));
                if (e_col.elementTextTrim("DataType").indexOf("(") > 0) {
                    col.setType(e_col.elementTextTrim("DataType").substring(0,
                            e_col.elementTextTrim("DataType").indexOf("(")));
                } else {
                    col.setType(e_col.elementTextTrim("DataType"));
                }
                col.setCode(e_col.elementTextTrim("Code"));
                col.setLength(e_col.elementTextTrim("Length") == null ? 0
                        : Integer.parseInt(e_col.elementTextTrim("Length")));
                if (e_table.element("Keys") != null) {
                    String keys_key_id = e_table.element("Keys").element("Key").attributeValue("Id");
                    String keys_column_ref = e_table.element("Keys").element("Key").element("Key.Columns")
                            .element("Column").attributeValue("Ref");
                    String keys_primarykey_ref_id = e_table.element("PrimaryKey").element("Key")
                            .attributeValue("Ref");

                    if (keys_primarykey_ref_id.equals(keys_key_id) && keys_column_ref.equals(pkID)) {
                        col.setPkFlag(true);
                        vo.setPkField(col.getCode());
                    }

                }
                list.add(col);
                //System.out.println(col);
            } catch (Exception ex) {
                // col.setType(e_col.elementTextTrim("DataType"));
                ex.printStackTrace();
            }
        }
        vo.setCols(list.toArray(cols));
        voS.add(vo);
        //System.out.println(vo);
        //System.out.println("======================");
        //System.out.println();
    }
    return voS.toArray(tabs);
}

From source file:com.ibm.cognos.API.java

License:Open Source License

public API(String sReportSpec) {
    try {//  w  w w.j  a  va2s .  co m
        // when creating a dom document, temporarily remove the default
        // namespace from the XML otherwise selecting nodes will fail.
        String start = null;
        String end = null;
        int index = sReportSpec.indexOf("xmlns=", 0);
        if (index >= 0) {
            start = sReportSpec.substring(0, index);
            end = sReportSpec
                    .substring(sReportSpec.indexOf("http://developer.cognos.com/schemas/report/8.0/") + 48);
            sReportSpec = start + end;
        }
        // load the spec into the DOM
        SAXReader xmlReader = new SAXReader();
        ByteArrayInputStream bais = new ByteArrayInputStream(sReportSpec.getBytes("UTF-8"));
        oDocument = xmlReader.read(bais);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.ibm.cognos.ReportObject.java

License:Open Source License

public Document getMetadata(CRNConnect connection, String p_sModel) {
    Option[] options = new Option[2];
    AsynchOptionInt primaryThreshold = new AsynchOptionInt();
    AsynchOptionInt secondaryThreshold = new AsynchOptionInt();

    String sModel = p_sModel;/*  w  w w.jav  a2 s . c om*/

    String sXML = "<metadataRequest connection=\"" + sModel + "\">" + "<Metadata Depth='' "
            + "no_collections='1'>" + "<Properties>" + "<Property name='*/@name'/>"
            + "<Property name='*/@datatype'/>" + "<Property name='*/@_path'/>" + "<Property name='*/@_ref'/>"
            + "<Property name='*/@usage'/>" + "<Property name='./folder'/>"
            + "<Property name='./querySubject'/>" + "<Property name='./queryItem'/>" + "</Properties>"
            + "</Metadata>" + "</metadataRequest>";

    primaryThreshold.setName(AsynchOptionEnum.primaryWaitThreshold);
    primaryThreshold.setValue(0);
    secondaryThreshold.setName(AsynchOptionEnum.secondaryWaitThreshold);
    secondaryThreshold.setValue(0);

    options[0] = primaryThreshold;
    options[1] = secondaryThreshold;

    Document oDom = null;
    try {
        boolean foundMetadata = false;
        AsynchReply runResponse;
        String sMetaData = "";
        ReportServiceMetadataSpecification metadataSpec = new ReportServiceMetadataSpecification();
        AsynchDetailReportMetadata reportMetadata = new AsynchDetailReportMetadata();

        metadataSpec.setValue(new Specification(sXML));

        // Since both primary and secondary wait thresholds are 0,
        // this request will not return until it is complete.

        // sn_dg_sdk_method_reportService_runSpecification_metadata_start_1
        runResponse = connection.getReportService().runSpecification(metadataSpec, new ParameterValue[] {},
                options);

        for (int i = 0; i < runResponse.getDetails().length && !foundMetadata; i++) {
            if (runResponse.getDetails()[i] instanceof AsynchDetailReportMetadata) {
                foundMetadata = true;
                reportMetadata = (AsynchDetailReportMetadata) runResponse.getDetails()[i];
                sMetaData = reportMetadata.getMetadata().toString();
            }
        }
        // sn_dg_sdk_method_reportService_runSpecification_metadata_end_1

        // sn_dg_prm_smpl_modifyreport_P2_start_0
        // This strips out the leading XML declaration
        sMetaData = sMetaData.substring(sMetaData.indexOf("?>") + 2);
        SAXReader xmlReader = new SAXReader();
        ByteArrayInputStream bais = new ByteArrayInputStream(sMetaData.getBytes("UTF-8"));
        oDom = xmlReader.read((InputStream) bais);
        // sn_dg_prm_smpl_modifyreport_P2_end_0

    } catch (Exception e) {
        e.printStackTrace();
    }
    return oDom;
}

From source file:com.iflytek.edu.cloud.frame.utils.ErrorMsgParser.java

License:Apache License

public static String getErrorCode(MockHttpServletResponse response) {
    try {//from  w  ww  . java2 s  .c o  m
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new ByteArrayInputStream(response.getContentAsByteArray()));
        Element rootElement = document.getRootElement();
        return rootElement.element("code").getText();
    } catch (DocumentException e) {
        return null;
    }
}