Example usage for org.dom4j.io SAXReader SAXReader

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

Introduction

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

Prototype

public SAXReader() 

Source Link

Usage

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;//from   w  ww.  j a  v a  2 s  . co m
    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;//w ww.  java 2s.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   ww w .j a  va  2  s  .c  om*/
 * 
 * @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  w ww  .  j  a  va 2s .  c o 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/*from  ww  w  .  j  a va2 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.app.util.SettingUtils.java

License:Open Source License

/**
 * ?//  w w  w  .  ja va 2s. c om
 * 
 * @return 
 */
public static Setting get() {
    Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
    net.sf.ehcache.Element cacheElement = cache.get(Setting.CACHE_KEY);
    Setting setting;
    if (cacheElement != null) {
        setting = (Setting) cacheElement.getObjectValue();
    } else {
        setting = new Setting();
        try {
            File appXmlFile = new ClassPathResource(CommonAttributes.APP_XML_PATH).getFile();
            Document document = new SAXReader().read(appXmlFile);
            List<Element> elements = document.selectNodes("/app/setting");
            for (Element element : elements) {
                String name = element.attributeValue("name");
                String value = element.attributeValue("value");
                try {
                    beanUtils.setProperty(setting, name, value);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    }
    return setting;
}

From source file:com.app.util.SettingUtils.java

License:Open Source License

/**
 * /*ww w  . j  av a  2 s .c  om*/
 * 
 * @param setting
 *            
 */
public static void set(Setting setting) {
    try {
        File appXmlFile = new ClassPathResource(CommonAttributes.APP_XML_PATH).getFile();
        Document document = new SAXReader().read(appXmlFile);
        List<Element> elements = document.selectNodes("/app/setting");
        for (Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = beanUtils.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fileOutputStream = null;
        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            fileOutputStream = new FileOutputStream(appXmlFile);
            xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                }
            }
            IOUtils.closeQuietly(fileOutputStream);
        }

        Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
        cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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// ww w . ja  v a2s . c o 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));
            }
        }
    }
}

From source file:com.appdynamics.monitors.hbase.HBaseMonitor.java

License:Apache License

private void getCredentials(final Map<String, String> args) {
    credentials = new ArrayList<Credential>();
    Credential cred = new Credential();

    cred.dbname = args.get("dbname");
    cred.host = args.get("host");
    cred.port = args.get("port");
    cred.username = args.get("user");
    cred.password = args.get("pass");

    if (!isNotEmpty(cred.dbname)) {
        cred.dbname = "DB 1";
    }//from  w  ww . j  a va  2  s.c o  m

    credentials.add(cred);

    String xmlPath = args.get("properties-path");
    if (isNotEmpty(xmlPath)) {
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(xmlPath);
            Element root = doc.getRootElement();

            for (Element credElem : (List<Element>) root.elements("credentials")) {
                cred = new Credential();
                cred.dbname = credElem.elementText("dbname");
                cred.host = credElem.elementText("host");
                cred.port = credElem.elementText("port");
                cred.username = credElem.elementText("user");
                cred.password = credElem.elementText("pass");

                if (isNotEmpty(cred.host) && isNotEmpty(cred.port)) {
                    if (!isNotEmpty(cred.dbname)) {
                        cred.dbname = "DB " + (credentials.size() + 1);
                    }
                    credentials.add(cred);
                }
            }
        } catch (DocumentException e) {
            logger.error("Cannot read '" + xmlPath + "'. Monitor is running without additional credentials");
        }
    }
}

From source file:com.appdynamics.snmp.SNMPTrapSender.java

License:Apache License

/**
 * Parses the config xml//from  w w w  .  j  ava  2s  . co m
 * @param    xml         Configuration file locations
 * @return            Map<String, String> - Map of config objects
 * @throws             DocumentException
 */
private static Map<String, String> parseXML(String xml) throws DocumentException {
    Map<String, String> map = new HashMap<String, String>();
    SAXReader reader = new SAXReader();
    Document document = reader.read(xml);
    Element root = document.getRootElement();

    for (Iterator<Element> i = root.elementIterator(); i.hasNext();) {
        Element element = (Element) i.next();
        if (element.getName().equals("snmp-v3")) {
            Iterator<Element> elementIterator = element.elementIterator();
            for (Iterator<Element> j = elementIterator; j.hasNext();) {
                element = (Element) j.next();
                map.put(element.getName(), element.getText());
            }
        } else {
            map.put(element.getName(), element.getText());
        }
    }

    return map;
}