Example usage for org.dom4j DocumentHelper parseText

List of usage examples for org.dom4j DocumentHelper parseText

Introduction

In this page you can find the example usage for org.dom4j DocumentHelper parseText.

Prototype

public static Document parseText(String text) throws DocumentException 

Source Link

Document

parseText parses the given text as an XML document and returns the newly created Document.

Usage

From source file:de.decoit.siemgui.service.converter.NeustaCorrelationRuleConverter.java

License:Open Source License

@Override
public CorrelationRule convertLocalCorrelationRule(RuleEntity rule) throws ConversionException {
    if (rule == null) {
        throw new ConversionException("Received null pointer for RuleEntity conversion");
    }/*from   w  w w.  j av a 2  s  .c o m*/

    Document doc;
    try {
        doc = DocumentHelper.parseText(rule.getRule());
    } catch (DocumentException ex) {
        throw new ConversionException("Exception during XML conversion", ex);
    }

    CorrelationRule domRule = new CorrelationRule();
    domRule.setEntityId(rule.getId());
    domRule.setName(rule.getName());
    domRule.setDescription(parseRuleDescriptionFromXml(doc));
    domRule.setCondition(parseRuleConditionFromXml(doc));
    domRule.setAction(parseRuleActionFromXml(doc));

    if (rule.getServerRuldId() != null) {
        domRule.setDtoId(rule.getServerRuldId());
    } else {
        domRule.setDtoId(0L);
    }

    return domRule;
}

From source file:de.decoit.siemgui.service.converter.NeustaCorrelationRuleConverter.java

License:Open Source License

@Override
public CorrelationRule convertRemoteCorrelationRule(RuleDTO rule) throws ConversionException {
    if (rule == null) {
        throw new ConversionException("Received null pointer for RuleDTO conversion");
    }//from ww  w  .  j  av a  2 s  . c o  m

    Document doc;
    try {
        doc = DocumentHelper.parseText(rule.getXml());
    } catch (DocumentException ex) {
        throw new ConversionException("Exception during XML conversion", ex);
    }

    CorrelationRule domRule = new CorrelationRule();

    domRule.setDtoId(rule.getId());
    domRule.setName(rule.getName());
    domRule.setDescription(parseRuleDescriptionFromXml(doc));
    domRule.setCondition(parseRuleConditionFromXml(doc));
    domRule.setAction(parseRuleActionFromXml(doc));

    return domRule;
}

From source file:de.ingrid.mdek.servlets.HelpServlet.java

License:EUPL

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    HttpSession session = request.getSession();
    Enumeration<String> enumeration = request.getParameterNames();

    while (enumeration.hasMoreElements()) {
        String parameterName = enumeration.nextElement();
        String parameter = (String) request.getParameter(parameterName);
        log.debug("parameter name: " + parameterName);
        log.debug("parameter value: " + parameter);
    }//w  w w . ja  v  a  2 s .  c  o  m

    String fileName = baseHelpFileName.substring(0, baseHelpFileName.lastIndexOf(".xml")) + "_"
            + request.getSession().getAttribute("currLang") + ".xml";

    response.setContentType("text/html");
    response.setCharacterEncoding("UTF8");

    PrintWriter out = null;
    try {
        out = response.getWriter();

    } catch (IOException e) {
        log.error("Could not open PrintWriter.", e);
        throw new ServletException(e);
    }

    // read help resource
    SAXReader xmlReader = new SAXReader();
    Document doc = null;
    try {
        doc = xmlReader.read(getServletContext().getResourceAsStream(fileName));

    } catch (Exception e) {
        //            log.error("Error reading help source file!", e);
    }

    // If the doc could not be found, use the base help filename
    if (doc == null) {
        try {
            doc = xmlReader.read(getServletContext().getResourceAsStream(baseHelpFileName));

        } catch (Exception e) {
            log.error("Error reading help source file!", e);
            throw new ServletException(e);
        }
    }

    // get the help chapter
    String helpKey = request.getParameter("hkey");
    if (helpKey == null) {
        helpKey = "index";
    }
    Object chapterObj = doc.selectSingleNode("//section[@help-key='" + helpKey + "']/ancestor::chapter");

    // transform the xml content to valid html using xslt
    if (chapterObj == null) {
        //           context.put("help_content", "<p>help key (" + helpKey + ") not found!</p>");
        out.print("<p>help key (" + helpKey + ") not found!</p>");

    } else {
        TransformerFactory factory;
        try {
            factory = TransformerFactory.newInstance();
        } catch (Throwable t) {
            System.setProperty("javax.xml.transform.TransformerFactory",
                    "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
            factory = TransformerFactory.newInstance();
        }

        try {
            StreamSource stylesheet = new StreamSource(getServletContext().getResourceAsStream(xslFileName));
            Transformer transformer = factory.newTransformer(stylesheet);
            DocumentResult result = new DocumentResult();
            String subtree = ((DefaultElement) chapterObj).asXML();
            DocumentSource source = new DocumentSource(DocumentHelper.parseText(subtree));

            transformer.transform(source, result);
            String helpContent = result.getDocument().asXML();
            //                context.put("help_content", helpContent);
            out.print(helpContent);

        } catch (Exception e) {
            log.error("Error processing help entry!", e);
        }
    }
}

From source file:de.ingrid.portal.interfaces.impl.WMSInterfaceImpl.java

License:EUPL

public String getWMCDocument(String sessionId) {
    String response = null;/* w w w .  j a  v  a 2s.c o m*/

    try {
        String urlStr = config.getString("interface_url",
                "http://localhost/mapbender/php/mod_portalCommunication_gt.php");
        if (urlStr.indexOf("?") > 0) {
            urlStr = urlStr.concat("&PREQUEST=getWMC").concat("&PHPSESSID=" + sessionId);
        } else {
            urlStr = urlStr.concat("?PREQUEST=getWMC").concat("&PHPSESSID=" + sessionId);
        }

        if (log.isDebugEnabled()) {
            log.debug("MapBender Server Request: " + urlStr);
        }

        //          Create an instance of HttpClient.
        HttpClient client = new HttpClient();

        // Create a method instance.
        GetMethod method = new GetMethod(urlStr);

        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(2, false));

        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                log.error("Requesting WMC faild for URL: " + urlStr);
            }

            // Read the response body.
            byte[] responseBody = method.getResponseBody();

            response = new String(responseBody);

        } catch (HttpException e) {
            log.error("Fatal protocol violation: " + e.getMessage(), e);
        } catch (IOException e) {
            log.error("Fatal transport error: " + e.getMessage(), e);
        } finally {
            // Release the connection.
            method.releaseConnection();
        }

        if (log.isDebugEnabled()) {
            log.debug("MapBender Server Response: " + response);
        }

        Document document = DocumentHelper.parseText(response);
        // check for valid server response
        String error = document.valueOf("//portal_communication/error");
        if (error != null && error.length() > 0) {
            throw new Exception("MapBender Server Error: " + error);
        }

        String sessionMapBender = document.valueOf("//portal_communication/session");
        if (sessionMapBender != null && !sessionMapBender.equals(sessionId)) {
            throw new Exception(
                    "MapBender Server Error: session Id (" + sessionId + ") from request and session Id ("
                            + sessionMapBender + ") from MapBender are not the same.");
        }

        String urlEncodedWmc = document.valueOf("//portal_communication/wmc");
        return urlEncodedWmc;

    } catch (Exception e) {
        log.error(e.toString());
    }
    return null;
}

From source file:de.ingrid.portal.interfaces.impl.WMSInterfaceImpl.java

License:EUPL

public void setWMCDocument(String wmc, String sessionId) {
    String urlStr = config.getString("interface_url",
            "http://localhost/mapbender/php/mod_portalCommunication_gt.php");
    if (urlStr.indexOf("?") > 0) {
        urlStr = urlStr.concat("&PREQUEST=setWMC").concat("&PHPSESSID=" + sessionId);
    } else {// w  w  w. ja va  2s  . c o m
        urlStr = urlStr.concat("?PREQUEST=setWMC").concat("&PHPSESSID=" + sessionId);
    }
    //      Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    PostMethod method = new PostMethod(urlStr);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(2, false));

    NameValuePair[] data = { new NameValuePair("wmc", wmc) };
    method.setRequestBody(data);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Sending WMC faild for URL: " + urlStr);
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        if (log.isDebugEnabled()) {
            log.debug("MapBender Server Response: " + new String(responseBody));
        }

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        Document document = DocumentHelper.parseText(new String(responseBody));

        // check for valid server response
        String error = document.valueOf("//portal_communication/error");
        if (error != null && error.length() > 0) {
            throw new Exception("WMS Server Error: " + error);
        }

        String success = document.valueOf("//portal_communication/success");
        if (error == null || success.length() == 0) {
            throw new Exception("WMS Server Error: Cannot find success message from server. message was: "
                    + new String(responseBody));
        }

    } catch (HttpException e) {
        log.error("Fatal protocol violation: " + e.getMessage(), e);
    } catch (IOException e) {
        log.error("Fatal transport error: " + e.getMessage(), e);
    } catch (Exception e) {
        log.error("Fatal error: " + e.getMessage(), e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:de.ingrid.portal.portlets.HelpPortlet.java

License:EUPL

/**
 * @see org.apache.portals.bridges.velocity.GenericVelocityPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
 *///from  w w w  . j  av  a 2 s . c  o  m
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    Context context = getContext(request);

    IngridResourceBundle messages = new IngridResourceBundle(
            getPortletConfig().getResourceBundle(request.getLocale()), request.getLocale());
    context.put("MESSAGES", messages);

    // find help file according to the language
    String lang = Utils.checkSupportedLanguage(request.getLocale().getLanguage());
    String fileName = "ingrid-portal-help_" + lang + ".xml";
    String filePath = null;
    try {
        filePath = Utils.getResourceAsStream(fileName);
    } catch (Exception e1) {
        log.warn(fileName + " not found!");
    }
    if (filePath == null) {
        try {
            filePath = Utils.getResourceAsStream("ingrid-portal-help.xml");
        } catch (Exception e) {
            log.error("ingrid-portal-help.xml not found!");
        }
    }

    // read help resource
    SAXReader xmlReader = new SAXReader();
    Document doc = null;
    try {
        doc = xmlReader.read(filePath);
    } catch (Exception e) {
        log.error("Error reading help source file: " + filePath, e);
    }

    // get the help chapter
    String helpKey = request.getParameter("hkey");
    if (helpKey == null) {
        helpKey = "index";
    }

    // read help chapter
    Object chapterObj = null;
    String myPath = "//section[@help-key='" + helpKey + "']/ancestor::chapter";
    try {
        chapterObj = doc.selectSingleNode(myPath);
    } catch (Throwable t) {
        log.error("Error reading '" + myPath + "' from help source file: " + filePath, t);
    }

    // transform the xml content to valid html using xslt
    if (chapterObj == null) {
        context.put("help_content", "<p>help key (" + helpKey + ") not found!</p>");
    } else {
        TransformerFactory factory;
        try {
            factory = TransformerFactory.newInstance();
        } catch (Throwable t) {
            System.setProperty("javax.xml.transform.TransformerFactory",
                    "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
            factory = TransformerFactory.newInstance();
        }

        try {
            StreamSource stylesheet = new StreamSource(Utils.getResourceAsStream("ingrid-portal-help.xsl"));
            Transformer transformer = factory.newTransformer(stylesheet);
            DocumentResult result = new DocumentResult();
            String subtree = ((DefaultElement) chapterObj).asXML();
            DocumentSource source = new DocumentSource(DocumentHelper.parseText(subtree));

            transformer.transform(source, result);
            String helpContent = result.getDocument().asXML();
            context.put("help_content", helpContent);
        } catch (Exception e) {
            log.error("Error processing help entry!", e);
        }
    }

    super.doView(request, response);
}

From source file:de.innovationgate.webgate.api.jdbc.WGDocumentImpl.java

License:Open Source License

protected static Object readItemValue(WGDatabaseImpl db, WGDocumentImpl doc, Item item) throws WGAPIException {
    switch (item.getType()) {

    case ITEMTYPE_SERIALIZED_XSTREAM:
        try {//from   w  ww . jav a  2  s .c om

            DeserialisationCache cache = item.getDeserialisationCache();
            int serializedHashCode = item.getText().hashCode();
            if (cache != null && cache.getSerializedHashCode() == serializedHashCode) {
                return cache.getDeserializedObject();
            }

            Object obj = XSTREAM_SERIALIZER.fromXML(item.getText());
            cache = new DeserialisationCache(serializedHashCode, obj);
            item.setDeserialisationCache(cache);
            return obj;

        } catch (Exception e) {
            throw new WGIllegalDataException(
                    "Error deserializing itemvalue of type 'ITEMTYPE_SERIALIZED_XSTREAM'.", e);
        }

    case ITEMTYPE_SERIALIZED_CASTOR:
        Unmarshaller unmarshaller = new Unmarshaller();
        try {

            // Workaround for castor bug. Primitive wrappers for
            // boolean, character, long do not contain xsi:type
            Document domDoc = DocumentHelper.parseText(item.getText());
            Element root = domDoc.getRootElement();
            if (root.getName().equals("boolean")) {
                root.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                root.addAttribute("xsi:type", "java:java.lang.Boolean");
            } else if (root.getName().equals("character")) {
                root.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                root.addAttribute("xsi:type", "java:java.lang.Boolean");
            } else if (root.getName().equals("long")) {
                root.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                root.addAttribute("xsi:type", "java:java.lang.Long");
            } else if (root.getName().equals("array-list")) {
                root.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                root.addAttribute("xsi:type", "java:java.util.ArrayList");
            }

            DOMWriter domWriter = new DOMWriter();
            return unmarshaller.unmarshal(domWriter.write(domDoc));
            // return unmarshaller.unmarshal(new
            // StringReader(item.getText()));
        } catch (MarshalException e) {
            throw new WGIllegalDataException("Error unmarshaling serialized object", e);
        } catch (ValidationException e) {
            throw new WGIllegalDataException("Error unmarshaling serialized object", e);
        } catch (DocumentException e) {
            throw new WGIllegalDataException("Error unmarshaling serialized object", e);
        }

    case ITEMTYPE_JSON:
        return new JsonParser().parse(item.getText());

    case ITEMTYPE_STRING:
        return item.getText();

    case ITEMTYPE_NUMBER:
        return item.getNumber();

    case ITEMTYPE_DATE:
        return new Date(item.getDate().getTime());

    case ITEMTYPE_BOOLEAN:
        return new Boolean(item.getNumber().doubleValue() == 1);

    case ITEMTYPE_BINARY:
        if (item instanceof ExtensionData) {
            return db.getFileHandling().readBinaryExtensionData(doc, (ExtensionData) item);
        } else {
            throw new WGSystemException("Unsupported itemtype '" + item.getType() + "' for the current entity");
        }

    default:
        throw new WGSystemException("Unsupported itemtype '" + item.getType() + "'.");

    }
}

From source file:de.innovationgate.webgate.api.WGCSSJSModule.java

License:Open Source License

/**
 * If codetype is XML, returns the contained XML-code as dom Document.
 * @throws DocumentException/*from  w  w  w  .j ava2 s. c  o m*/
 * @throws WGAPIException 
 */
public Document getDOMDocument() throws DocumentException, WGAPIException {

    if (!getCodeType().equals(CODETYPE_XML)) {
        return DocumentHelper.createDocument();
    }

    return DocumentHelper.parseText(getCode());

}

From source file:de.innovationgate.wga.server.api.Xml.java

License:Open Source License

/**
 * Parses XML text and returns a DOM document object for it
 * @param xml The xml//from ww w.  j a va2 s  .co  m
 * @param systemId An URL which should be used to resolve relative references in the XML text, like a DOCTYPE reference.
 * @return DOM document of parsed XML data 
 * @throws DocumentException
 */
public Document parse(String xml, String systemId) throws WGException, DocumentException {
    // Cutoff eventual content in prolog which may be a problem for the parser (like BOMs, see B00005006)
    int beginTagIndex = xml.indexOf("<");
    if (beginTagIndex != -1) {
        xml = xml.substring(beginTagIndex);
    }

    if (systemId != null) {
        SAXReader reader = new SAXReader();
        return reader.read(new StringReader(xml), systemId);
    } else {
        return DocumentHelper.parseText(xml);
    }
}

From source file:de.innovationgate.wga.server.api.Xml.java

License:Open Source License

private Branch retrieveBranch(Object object) throws DocumentException {
    Branch branch;// w  w w .jav  a  2 s  .  co  m
    if (object instanceof String) {
        branch = DocumentHelper.parseText((String) object);
    } else {
        branch = (Branch) object;
    }
    return branch;
}