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.iih5.smartorm.kit.SqlXmlKit.java

License:Apache License

private void init(File dataDir) {
    try {//from   w  ww. j  av  a  2  s  .  c  om
        List<File> files = new ArrayList<File>();
        listDirectory(dataDir, files);
        for (File file : files) {
            if (file.getName().contains(".xml")) {
                SAXReader reader = new SAXReader();
                Document document = reader.read(file);
                Element xmlRoot = document.getRootElement();
                for (Object e : xmlRoot.elements("class")) {
                    Map<String, String> methods = new HashMap<String, String>();
                    Element clasz = (Element) e;
                    for (Object ebj : clasz.elements("sql")) {
                        Element sql = (Element) ebj;
                        methods.put(sql.attribute("method").getValue(), sql.getText());
                    }
                    resourcesMap.put(clasz.attributeValue("name"), methods);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.infinities.skyport.util.XMLUtil.java

License:Apache License

public static Document parse(File file)
        throws DocumentException, UnsupportedEncodingException, FileNotFoundException {
    final SAXReader reader = new SAXReader();
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
    final Document document = reader.read(br);

    return document;
}

From source file:com.ischool.weixin.tool.MessageUtil.java

License:Open Source License

public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
    // ?HashMap/*ww  w .ja  va  2  s  . co m*/
    Map<String, String> map = new HashMap<String, String>();

    // request??
    InputStream inputStream = request.getInputStream();
    // ??
    SAXReader reader = new SAXReader();
    Document document = reader.read(inputStream);
    // xml
    Element root = document.getRootElement();
    // ?
    @SuppressWarnings("unchecked")
    List<Element> elementList = root.elements();

    // ???
    for (Element e : elementList) {
        map.put(e.getName(), e.getText());
    }
    // ?
    inputStream.close();
    inputStream = null;

    return map;
}

From source file:com.itextpdf.rups.model.XfaFile.java

License:Open Source License

/**
 * Constructs an XFA file from an OutputStreamResource.
 * This resource can be an XML file or a node in a RUPS application.
 * @param   resource   the XFA resource/*  ww w  .java 2  s. c  om*/
 * @throws IOException 
 * @throws DocumentException 
 */
public XfaFile(OutputStreamResource resource) throws IOException, DocumentException {
    // Is there a way to avoid loading everything in memory?
    // Can we somehow get the XML from the PDF as an InputSource, Reader or InputStream?
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    resource.writeTo(baos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    SAXReader reader = new SAXReader();
    xfaDocument = reader.read(bais);
}

From source file:com.jaspersoft.jasperserver.export.ImporterImpl.java

License:Open Source License

protected Document readIndexDocument() {
    InputStream indexInput = getIndexInput();
    boolean close = true;
    try {/*w w  w  .  j  av  a  2 s . c  o m*/
        SAXReader reader = new SAXReader();
        reader.setEncoding(getCharacterEncoding());
        Document document = reader.read(indexInput);

        close = false;
        indexInput.close();

        return document;
    } catch (IOException e) {
        log.error(e);
        throw new JSExceptionWrapper(e);
    } catch (DocumentException e) {
        log.error(e);
        throw new JSExceptionWrapper(e);
    } finally {
        if (close) {
            try {
                indexInput.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
}

From source file:com.jeeframework.util.xml.XMLProperties.java

License:Open Source License

/**
 * Builds the document XML model up based the given reader of XML data.
 *
 * @param in the input stream used to build the xml document
 * @throws IOException thrown when an error occurs reading the input stream.
 *///from  w w w. ja  v a  2s .c o  m
private void buildDoc(Reader in) throws IOException {
    try {
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        document = xmlReader.read(in);
    } catch (Exception e) {
        Log.error("Error reading XML properties", e);
        throw new IOException(e.getMessage());
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.jga.view.seguridad.RolManagedBean.java

protected List<Rol> getSecurityRoles() {

    HttpServletRequest origRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();/*from  w w w.j  a v  a 2 s .c  o m*/
    ServletContext sc = origRequest.getServletContext();
    InputStream is = sc.getResourceAsStream("/WEB-INF/web.xml");

    try {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(is);

        Element webApp = doc.getRootElement();

        // Type safety warning:  dom4j doesn't use generics
        List<Element> roleElements = webApp.elements("security-role");
        for (Element roleEl : roleElements) {
            roles.add(new Rol(roleEl.element("role-name").getText()));
        }
    } catch (EJBException ex) {
        Exception ne = (Exception) ex.getCause();
        Logger.getLogger(UsuarioManagedBean.class.getName()).log(Level.SEVERE, null, ne);
    } catch (Exception ex) {
        Logger.getLogger(UsuarioManagedBean.class.getName()).log(Level.SEVERE, null, ex);
    }

    return roles;
}

From source file:com.jmstoolkit.pipeline.Pipeline.java

License:Open Source License

/**
 * Determine what action the received message contains, validate that and
 * perform it. Validation is done using the JDK's Xerces implementation
 * against a DTD. The DTD should be in the user.dir location!
 *
 * @param xml The XML from the <code>Message</code>
 * @return A dom4j <code>Document</code> for further processing.
 * @throws DocumentException If the XML can not be parsed and validated.
 * @throws PipelineException If the XML contains an invalid action.
 *///  w  w w  .  j  a  va2 s. co m
private Document getAction(final String xml) throws DocumentException, PipelineException {
    System.out.println("############################################");
    System.out.println("Action message received:");
    System.out.println(xml);
    System.out.println("############################################");

    // Below will all bomb with DocumentException
    // enable validation
    final SAXReader saxReader = new SAXReader(isValidated());
    // Validation is done using the JDK's bundled xerces implementation
    // against a DTD. The DTD should be in the user.dir location!
    final Document doc = saxReader.read(new StringReader(xml));
    final String name = trim(doc.valueOf("//plugin/name"));
    final String action = trim(doc.valueOf("//plugin/action"));
    final String type = trim(doc.valueOf("//plugin/type"));
    final String xversion = trim(doc.valueOf("//plugin/version"));

    LOG.log(Level.INFO, "Action message received: {0}, for service name: {1} and service type: {2}",
            new Object[] { action, name, type });

    if (!VERSION.equalsIgnoreCase(xversion)) {
        throw new PipelineException(
                "Action version: " + xversion + " does not match Pipeline version: " + VERSION);
    }

    if ("new".equalsIgnoreCase(action)) {
        if (getPlugins().containsKey(name)) {
            throw new PipelineException(
                    "Can't create new Plugin name: " + name + ". Plugin with same name already exists.");
        }
    } else if ("update".equalsIgnoreCase(action)) {
        if (!getPlugins().containsKey(name)) {
            throw new PipelineException("Can't update Plugin: " + name + ". No Plugin with that name found.");
        }
    } else if ("update".equalsIgnoreCase(action)) {
        if (!getPlugins().containsKey(name)) {
            throw new PipelineException("Can't stop Plugin: " + name + ". No Plugin with that name found.");
        }
    }
    return doc;
}

From source file:com.jmstoolkit.pipeline.plugin.XMLValueTransform.java

License:Open Source License

/**
 * Method to parse and validate the <code>work</code> XML String.
 *
 * @param work The XML to be validated.//from w  ww  .  j av  a 2  s  . c  o  m
 * @return The validated XML.
 * @throws DocumentException When the XML fails to validation.
 * @throws XMLValueTransformException When additional validation fails.
 */
private Document getWork(final String work) throws DocumentException, XMLValueTransformException {
    // validate vs. DTD: enrich.dtd
    final SAXReader saxReader = new SAXReader(true);
    final Document doc = saxReader.read(new StringReader(work));
    // additional validation...
    try {
        Class.forName(trim(doc.valueOf("//enrich/defaultDatabase/driver")));
    } catch (ClassNotFoundException ex) {
        throw new XMLValueTransformException("Default database driver not found in classpath: " + ex);
    }
    return doc;
}

From source file:com.jmstoolkit.pipeline.plugin.XMLValueTransform.java

License:Open Source License

/**
 * Implementation of JMS <code>MessageListener</code> interface. Performs
 * the work when a message is received.//from www.j  av  a 2s.c o  m
 *
 * @param message The JMS Message received.
 */
@Override
public final void onMessage(final Message message) {
    String messageId = "";
    try {
        messageId = message.getJMSMessageID();
    } catch (JMSException ex) {
        LOGGER.log(Level.SEVERE, "Failed to get message id", ex);
    }
    if (message instanceof TextMessage) {
        try {
            final String body = ((TextMessage) message).getText();

            System.out.println("############################################");
            System.out.println("Transform input message received by " + getName() + ":");
            System.out.println(body.substring(0, 78));
            System.out.println("############################################");

            try {
                // do NOT validate vs. DTD
                final SAXReader saxReader = new SAXReader();
                Document doc = saxReader.read(new StringReader(body));
                int count = 0;
                for (XMLValueTransformer xvt : this.getXforms()) {
                    try {
                        doc = xvt.transform(doc);
                        count++;
                    } catch (DataAccessException ex) {
                        LOGGER.log(Level.WARNING, messageId + " JDBC failed: " + xvt.toString(), ex);
                    }
                }
                LOGGER.log(Level.INFO, "{0} {1} of {2} XMLValueTransformers succeeded",
                        new Object[] { messageId, count, getXforms().size() });
                LOGGER.log(Level.INFO, "{0} Transform performed by service: {1}",
                        new Object[] { messageId, getName() });

                getJmsTemplate().convertAndSend(doc.asXML());

                this.operationCount++;
            } catch (DocumentException ex) {
                LOGGER.log(Level.SEVERE, messageId + " Unable to parse XML message: " + body + ". ", ex);
            }
        } catch (JMSException ex) {
            LOGGER.log(Level.SEVERE, messageId + " Failed to get message text: ", ex);
        }
    } else {
        LOGGER.log(Level.WARNING, "{0} Message is not a TextMessage. TextMessages only please.",
                new Object[] { messageId });
    }
}