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.amalto.workbench.utils.Util.java

License:Open Source License

public static String formatXsdSource(String xsdSource, boolean suppressDeclaration) {
    try {//from w w  w.ja  v a  2s. c o m
        SAXReader reader = new SAXReader();
        org.dom4j.Document document = reader.read(new StringReader(xsdSource));
        StringWriter writer = new StringWriter();
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");//$NON-NLS-1$
        format.setSuppressDeclaration(suppressDeclaration);
        XMLWriter xmlwriter = new XMLWriter(writer, format);
        xmlwriter.write(document);
        String str = writer.toString();
        writer.close();
        xmlwriter.close();
        return str;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return xsdSource;

}

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

License:Open Source License

public static Document parse(URL url) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(url);
    return document;
}

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

License:Open Source License

public static Document parse(File file) throws MalformedURLException, DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(file);
    return document;
}

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

License:Open Source License

public static Document parse(InputStream in) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(in);
    return document;
}

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

License:Open Source License

public static String formatXmlSource(String xmlSource) {

    SAXReader reader = new SAXReader();
    StringReader stringReader = new StringReader(xmlSource);
    StringWriter writer = null;//  w  w w.ja  v  a2 s  . c  om
    XMLWriter xmlwriter = null;
    String result = xmlSource;

    try {
        Document document = reader.read(stringReader);
        writer = new StringWriter();
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");//$NON-NLS-1$
        format.setIndentSize(4);
        format.setSuppressDeclaration(true);
        xmlwriter = new XMLWriter(writer, format);
        xmlwriter.write(document);
        result = writer.toString();
    } catch (Exception e) {

    } finally {

        try {
            if (stringReader != null)
                stringReader.close();

            if (xmlwriter != null)
                xmlwriter.close();

            if (writer != null)
                writer.close();

        } catch (Exception e) {

        }

    }
    return result;

}

From source file:com.android.uiautomator.tree.UiHierarchyXmlLoader.java

License:Apache License

public Document getDocument(String filePath) {
    Document document = null;// ww  w  . j  a v  a2 s .c o  m
    File file = new File(filePath);
    if (file.exists()) {
        SAXReader saxReader = new SAXReader();
        try {
            document = saxReader.read(file);
        } catch (DocumentException e) {
            System.out.println("" + filePath);
            e.printStackTrace();
        }
    } else {
        System.out.println("? : " + filePath);
    }
    return document;
}

From source file:com.anite.zebra.ext.xmlloader.XMLLoadProcess.java

License:Apache License

/**
 * Read in a file of XML, strip out the pretty printing via some juggling of objects and then return a
 * org.w3.document DOM object.//from  w w  w. j  a v a2 s.c o  m
 * 
 * @param xmlFile
 *            The file to be read in.
 * @return A ready to use org.w3.Document with pretty printing stripped out.
 * @throws DocumentException
 * @throws MalformedURLException
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
private Document readDocument(File xmlFile)
        throws DocumentException, MalformedURLException, UnsupportedEncodingException, IOException {
    SAXReader xmlReader = new SAXReader();
    xmlReader.setStripWhitespaceText(true);

    org.dom4j.Document dom4jDocument = xmlReader.read(xmlFile);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputFormat format = OutputFormat.createCompactFormat();
    XMLWriter writer = new XMLWriter(baos, format);

    writer.write(dom4jDocument);

    dom4jDocument = DocumentHelper.parseText(baos.toString());

    DOMWriter domWriter = new DOMWriter();
    Document doc = domWriter.write(dom4jDocument);
    return doc;
}

From source file:com.aoyun.serviceOld.GetValForYKPOne.java

/**
 * ?XMLoracle?/*from  www.  ja  v  a 2  s .  co m*/
 *
 * @param xmlFileList
 * @throws Exception
 */
public void getValueForXml(List<File> xmlFileList, JdbcOperate jdbcOperate) throws Exception {

    ArrayList<JSONObject> parkingLPRJSONList = new ArrayList<JSONObject>();

    List<ParkingLPRBean> parkingLPRList = new ArrayList<ParkingLPRBean>();//ParkingLPR(?)?

    ParkingLPRBean parkingLPR = null;//

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    for (File file : xmlFileList) {
        try {

            parkingLPR = new ParkingLPRBean();

            SAXReader reader = new SAXReader();
            Document document = reader.read(file);
            Element root = document.getRootElement();

            String code = getCode();
            parkingLPR.setId(code);

            if (root.element("device_id") == null) {
                parkingLPR.setDeviceId("");
            } else {
                parkingLPR.setDeviceId(root.element("device_id").getText());
            }
            parkingLPR.setVersion("10000001");

            if (root.element("plate_license") == null) {
                parkingLPR.setPlateNumber("");
            } else {
                parkingLPR.setPlateNumber(root.element("plate_license").getText());
            }
            if (root.element("plate_color") == null) {
                parkingLPR.setPlateColor("");
            } else {
                String plateColor = getPlateColor(root.element("plate_color").getText());
                parkingLPR.setPlateColor(plateColor);
            }
            if (root.element("capture_time") == null) {
                parkingLPR.setPassTime("");
            } else {
                parkingLPR.setPassTime(root.element("capture_time").getText());
            }
            if (root.element("camera_ipaddr") == null) {
                parkingLPR.setDeviceIp("");
            } else {
                parkingLPR.setDeviceIp(root.element("camera_ipaddr").getText());
            }
            if (root.element("longitude") == null) {
                parkingLPR.setLongitude("");
            } else {
                parkingLPR.setLongitude(root.element("longitude").getText());
            }
            if (root.element("latitude") == null) {
                parkingLPR.setLatitude("");
            } else {
                parkingLPR.setLatitude(root.element("latitude").getText());
            }
            if (root.element("site_code") == null) {
                parkingLPR.setParkingId("");
            } else {
                String siteCode = root.element("site_code").getText();
                String substring = siteCode.substring(0, 4);
                parkingLPR.setParkingId(substring);
            }
            if (root.element("direction") == null) {
                parkingLPR.setInOut("");
            } else {
                parkingLPR.setInOut(root.element("direction").getText());
            }

            String date = dateFormat.format(new Date());
            parkingLPR.setCreateTime(date);

            parkingLPR.setSource("1");

            if (root.element("plate_type") == null) {
                parkingLPR.setPlateType("");
            } else {
                parkingLPR.setPlateType(root.element("plate_type").getText());
            }
            if (root.element("car_color") == null) {
                parkingLPR.setCarColor("");
            } else {
                parkingLPR.setCarColor(root.element("car_color").getText());
            }
            if (root.element("car_type") == null) {
                parkingLPR.setCarType("");
            } else {
                parkingLPR.setCarType(root.element("car_type").getText());
            }
            if (root.element("lane") == null) {
                parkingLPR.setLane("");
            } else {
                parkingLPR.setLane(root.element("lane").getText());
            }
            if (root.element("cs") == null) {
                parkingLPR.setCs(0);
            } else {
                parkingLPR.setCs(Integer.parseInt(root.element("cs").getText()));
            }

            //list?
            parkingLPRList.add(parkingLPR);

            //????ID????IP????ID?ID
            String carNo = root.element("plate_license").getText();
            String parkcode = root.element("site_code").getText();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String ctStr = root.element("capture_time").getText();
            String inOut = root.element("direction").getText();
            String num = "";
            if (inOut.equals("0")) {
                num = "-1";
            } else {
                num = "1";
            }
            long capture_time = format.parse(ctStr).getTime();//?
            List<NameValuePair> list = new ArrayList<NameValuePair>();//???
            list.add(new BasicNameValuePair("parkcode", parkcode));
            list.add(new BasicNameValuePair("qty", num));
            YKPMain.elementList.add(root);
            YKPMain.list.add(list);

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();//?
            nvps.add(new BasicNameValuePair("parkcode", parkcode));
            nvps.add(new BasicNameValuePair("carnumber", carNo));
            nvps.add(new BasicNameValuePair("regtime", capture_time + ""));
            nvps.add(new BasicNameValuePair("direction", inOut));
            YKPMain.carList.add(nvps);//

        } catch (DocumentException e) {
            logger.error("?XML:" + file.getPath());
        }
    }

    //beanjsonJSON list
    try {
        for (ParkingLPRBean parkingLPRs : parkingLPRList) {
            JSONObject parkingLPRJSON = beanUtil.convertBeanToJson(parkingLPRs);
            parkingLPRJSONList.add(parkingLPRJSON);
        }
    } catch (Exception e) {
        logger.error("?JSON" + e.getMessage());
    }

    //keys
    String keys[] = { "id", "deviceId", "version", "plateNumber", "plateColor", "passTime", "deviceIp",
            "longitude", "latitude", "parkingId", "inOut", "source", "plateType", "carColor", "carType",
            "lane" };

    //?sql?
    String sql = "insert into parking_lpr(id,device_id,version,plate_number,plate_color,pass_time,device_ip,longitude,latitude,"
            + "parking_id,in_out,create_time,source,plate_type,car_color,car_type,lane)"
            + "values(?,?,?,?,?,to_date(?,'yyyy-mm-dd hh24:mi:ss'),?,?,?,?,?,sysdate,?,?,?,?,?)";

    //???array
    JSONArray array = jdbcOperate.executeBatchPre(sql, parkingLPRJSONList, keys);
    JSONObject jsonObject = null;

    //????
    if (array.size() == 0) {
        logger.info(":" + array.size() + "???");
        //0oraclexml
        for (File file : xmlFileList) {
            file.delete();
        }
        xmlFileList.clear();
    } else {
        int begin = 0;
        int end = 0;

        for (int i = 0; i < array.size(); i++) {
            jsonObject = array.getJSONObject(i);
            System.out.println(jsonObject);

            Set<Map.Entry<String, Object>> entrySet = jsonObject.entrySet();
            for (Map.Entry<String, Object> entry : entrySet) {
                String key = entry.getKey();
                if (key.equals("begin")) {
                    begin = Integer.parseInt(entry.getValue().toString());
                } else if (key.equals("end")) {
                    end = Integer.parseInt(entry.getValue().toString());
                }
            }
            logger.error(":" + array.size() + "?" + "" + begin + "-" + end
                    + "??");
            //?XML
            getXMLForError(begin, end, xmlFileList);
            for (int j = 0; j < XMLListForError.size(); j++) {
                logger.error(begin + "---" + end + " :?"
                        + XMLListForError.get(j).getPath());
            }
        }

        //??XML(??)?
        for (int i = 0; i < xmlFileList.size(); i++) {
            for (int j = i; j < XMLListForError.size(); j++) {
                if (xmlFileList.get(i).getName().equals(XMLListForError.get(j).getName())) {
                    break;
                }
            }
            if (i > XMLListForError.size()) {
                xmlFileList.get(i).delete();
            }
        }
        System.out.println(XMLListForError.size());
        XMLListForError.clear();
        xmlFileList.clear();
    }
}

From source file:com.app.buzz.weixin.util.XmlUtils.java

License:Open Source License

/**
 * ??xml ?map/*w  w  w. j av a  2 s . c o  m*/
 * */
public static Map<String, String> xml2Map(InputStream in) {
    Map<String, String> map = new HashMap<String, String>();
    SAXReader reader = new SAXReader();
    try {
        Document document = reader.read(in);
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        for (Element e : elements) {
            map.put(e.getName(), e.getText());
        }
        return map;

    } catch (DocumentException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.appdynamics.monitors.hadoop.parser.Parser.java

License:Apache License

/**
 * Parses XML file at <code>xml</code> and collect filtering rules.
 *
 * @param xml/*from  www  .j  a va2 s .  co m*/
 * @throws DocumentException
 */
public void parseXML(String xml) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document doc = reader.read(xml);
    Element root = doc.getRootElement();
    String text;

    Iterator<Element> hrmIter = root.element("hadoop-resource-manager").elementIterator();
    Iterator<Element> ambariIter = root.element("ambari").elementIterator();

    while (hrmIter.hasNext()) {
        Element element = hrmIter.next();
        if (element.getName().equals("aggregate-app-period")) {
            if (!(text = element.getText()).equals("")) {
                try {
                    aggrAppPeriod = Integer.parseInt(text);
                } catch (NumberFormatException e) {
                    logger.error("Error parsing aggregate-app-period: " + e + "\n"
                            + "Using default value instead: " + DEFAULT_THREAD_LIMIT);
                    aggrAppPeriod = DEFAULT_AGGR_APP_PERIOD;
                }
            }
        } else if (element.getName().equals("exclude-nodeid")) {
            if (!(text = element.getText()).equals("")) {
                String[] nodeId = text.split(",");
                excludeNodeid.addAll(Arrays.asList(nodeId));
            }
        } else {
            logger.error("Unknown element '" + element.getName() + "' in properties file");
        }
    }

    while (ambariIter.hasNext()) {
        Element element = ambariIter.next();

        if (element.getName().equals("thread-limit")) {
            if (!(text = element.getText()).equals("")) {
                try {
                    threadLimit = Integer.parseInt(text);
                } catch (NumberFormatException e) {
                    logger.error("Error parsing thread-limit " + e + "\n" + "Using default value instead: "
                            + DEFAULT_THREAD_LIMIT);
                    threadLimit = DEFAULT_THREAD_LIMIT;
                }
            }
        } else if (element.getName().equals("include-cluster")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.split(",");
                includeAmbariCluster.addAll(Arrays.asList(appId));
            }
        } else if (element.getName().equals("include-host")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.split(",");
                includeAmbariHost.addAll(Arrays.asList(appId));
            }
        } else if (element.getName().equals("exclude-host")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.split(",");
                excludeAmbariHost.addAll(Arrays.asList(appId));
            }
        } else if (element.getName().equals("exclude-service")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.toLowerCase().split(",");
                excludeAmbariService.addAll(Arrays.asList(appId));
            }
        } else if (element.getName().equals("exclude-service-component")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.toLowerCase().split(",");
                excludeAmbariServiceComponent.addAll(Arrays.asList(appId));
            }
        } else if (element.getName().equals("include-host-metrics")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.toLowerCase().split(",");
                includeAmbariHostMetrics.addAll(Arrays.asList(appId));
            }
        } else if (element.getName().equals("include-component-metrics")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.toLowerCase().split(",");
                includeAmbariComponentMetrics.addAll(Arrays.asList(appId));
            }
        }
    }
}