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:org.prettyx.DistributeServer.Network.ActionHandler.java

License:Open Source License

/**
 * Action when user send message to generate the sim file
 *
 * @param connection, data/*from ww  w.  j  a v  a2  s  . c  o m*/
 *                    data is composed of model description xml
 *
 */
public static void compileModel(WebSocket connection, String data)
        throws DocumentException, SQLException, IOException {

    SimFile simFile = new SimFile();
    Sim sim = new Sim();
    Model model = new Model();
    Map newComponentName = new HashMap<String, String>(); // package.class -> new name
    Set components = new HashSet<String>();
    Map parameter = new HashMap<String, String>(); //class.var -> value

    Map idToOwnerName = new ConcurrentHashMap<String, String>(); //model id -> owner name
    Map idToModelName = new ConcurrentHashMap<String, String>(); //model id -> model name
    Map partIdToModelId = new ConcurrentHashMap<String, String>(); // part id -> model id
    List<String> sourceToTarget = new ArrayList<String>(); //source port name + target port name
    List<SimFile> simFiles = new ArrayList<SimFile>(); //collect all the sim files which the new component use

    Document document = DocumentHelper.parseText(data);
    Element root = document.getRootElement();
    String componentName = root.element("name").getText();
    String currentUserName = "";
    LogUtility.logUtility().log2out("component name = " + componentName);
    List parts = root.element("parts").elements("part");

    DBOP dbop = new DBOP();
    Connection connectionToSql = dbop.getConnection();

    PreparedStatement prep = connectionToSql.prepareStatement("select nickname from Users where sid= ?;");
    prep.setString(1, (String) DistributeServerHearken.currentUsers.get(connection));
    ResultSet resultSet = prep.executeQuery();
    if (resultSet.next()) {
        currentUserName = resultSet.getString("nickname");
        LogUtility.logUtility().log2out("current user name:" + currentUserName);
    }
    resultSet.close();
    prep.close();

    prep = connectionToSql.prepareStatement("select owner,modelname from Models where id= ?;");

    for (Iterator it = parts.iterator(); it.hasNext();) {
        Element component = (Element) it.next();
        String modeId = component.attributeValue("componentId");
        String partId = component.attributeValue("id");
        partIdToModelId.put(partId, modeId);

        prep.setString(1, modeId);
        resultSet = prep.executeQuery();
        if (resultSet.next()) {
            String owner = resultSet.getString("owner");
            String modelName = resultSet.getString("modelname");
            idToModelName.put(modeId, modelName);
            PreparedStatement preparedStatement = connectionToSql
                    .prepareStatement("select nickname from Users where sid= ?;");
            preparedStatement.setString(1, owner);
            ResultSet resultSet1 = preparedStatement.executeQuery();
            if (resultSet1.next()) {
                String userName = resultSet1.getString("nickname");
                idToOwnerName.put(modeId, userName);
                LogUtility.logUtility().log2out("partId : userName = " + modeId + ":" + userName);
            }
            resultSet1.close();
            preparedStatement.close();
        }
    }
    prep.close();
    connectionToSql.close();

    if (!idToOwnerName.isEmpty()) {
        //copy files
        String newModelPath = DistributeServer.absolutePathOfRuntimeUsers + "/" + currentUserName + "/"
                + componentName;
        DEPFS.createDirectory(newModelPath);
        DEPFS.createDirectory(newModelPath + "/" + "dist");
        DEPFS.createDirectory(newModelPath + "/" + "input");
        DEPFS.createDirectory(newModelPath + "/" + "output");

        Iterator ita = null;
        ita = idToOwnerName.entrySet().iterator();
        while (ita.hasNext()) {
            Map.Entry entry = (Map.Entry) ita.next();
            String modelname = (String) idToModelName.get((String) entry.getKey());
            String owername = (String) entry.getValue();
            String sourcePath = DistributeServer.absolutePathOfRuntimeUsers + "/" + owername + "/" + modelname
                    + "/" + "dist/";
            String targetPath = newModelPath + "/" + "dist/";
            DEPFS.copyDirectory(sourcePath, targetPath);
            File oldSimFile = new File(DistributeServer.absolutePathOfRuntimeUsers + "/" + owername + "/"
                    + modelname + "/" + "simulation.sim");
            if (oldSimFile.exists()) {
                simFiles.add(new SimFile(DEPFS.readFile(oldSimFile)));
            }
        }

        //create sim file

        //only single model to run
        if (parts.size() == 1 && simFiles.size() == 1) {
            simFile = simFiles.get(0);
            for (Iterator it = parts.iterator(); it.hasNext();) {
                Element component = (Element) it.next();
                String partName = (String) idToModelName
                        .get(partIdToModelId.get(component.attributeValue("id")));

                //get parameter values
                List inPorts = component.elements("input");
                for (Iterator ot = inPorts.iterator(); ot.hasNext();) {
                    Element inPort = (Element) ot.next();
                    String portName = inPort.attributeValue("portName");
                    String portValue = inPort.attributeValue("value");
                    String inputFileName = inPort.attributeValue("fileName");

                    //                        components.add(partName + "." + portName.split("\\.")[0]);
                    if (portValue != "") {

                        if (inputFileName != "") {
                            File inputFile = new File(newModelPath + "/" + "input" + "/" + inputFileName);
                            DEPFS.writeFile(inputFile, portValue.replace("<br>", "\n"));
                            String source = partName + "." + portName;
                            parameter.put(source, "\"$oms_prj/input/" + inputFileName + "\"");

                        } else {
                            String source = partName + "." + portName;
                            parameter.put(source, portValue);
                        }
                        String originalComponentName = portName.substring(0, portName.lastIndexOf("."));
                        String originalComponentKey = simFile.getSim().getModel()
                                .getComponentKey(originalComponentName);
                        if (originalComponentKey != null) {
                            String originalComponentName1 = originalComponentKey + "."
                                    + portName.substring(portName.lastIndexOf(".") + 1, portName.length());
                            simFile.getSim().getModel().setParameter(originalComponentName1,
                                    (String) parameter.get(partName + "." + portName));
                            System.out.println(originalComponentName1);
                        }

                    }
                }
            }
            //using simFile to generate sim file

            File simulation = new File(DistributeServer.absolutePathOfRuntimeUsers + "/" + currentUserName + "/"
                    + componentName + "/simulation.sim");
            DEPFS.writeFile(simulation, simFile.toString());
            runModel(connection, data);

        } else {
            // get connected port
            for (Iterator it = parts.iterator(); it.hasNext();) {
                Element component = (Element) it.next();
                String partName = (String) idToModelName
                        .get(partIdToModelId.get(component.attributeValue("id")));
                List outPorts = component.elements("output");
                for (Iterator ot = outPorts.iterator(); ot.hasNext();) {
                    Element outPort = (Element) ot.next();
                    String portName = outPort.attributeValue("portName");
                    String targetPortName = outPort.attributeValue("targetPortName");
                    String targetModelId = outPort.attributeValue("targetPortId");
                    String targetModelName = (String) idToModelName.get(partIdToModelId.get(targetModelId));
                    String source = portName;
                    String target = targetPortName;
                    components.add(portName.split("\\.")[0] + "." + portName.split("\\.")[1]);
                    components.add(targetPortName.split("\\.")[0] + "." + targetPortName.split("\\.")[1]);
                    sourceToTarget.add(source + "+" + target);

                    //                        System.out.println("partName + \".\" + portName.split(\"\\\\.\")[0]"+portName.split("\\.")[0] + "." + portName.split("\\.")[1]);
                    //                        System.out.println("targetModelName + \".\" + targetPortName.split(\"\\\\.\")[0]" + targetPortName.split("\\.")[0] + "." + targetPortName.split("\\.")[1]);
                    //                        System.out.println("source + \"+\" + target"+source + "+" + target);

                }

                //get parameter values
                List inPorts = component.elements("input");
                for (Iterator ot = inPorts.iterator(); ot.hasNext();) {
                    Element inPort = (Element) ot.next();
                    String portName = inPort.attributeValue("portName");
                    String portValue = inPort.attributeValue("value");
                    String inputFileName = inPort.attributeValue("fileName");
                    components.add(portName.split("\\.")[0] + "." + portName.split("\\.")[1]);

                    if (inputFileName != "") {
                        File inputFile = new File(newModelPath + "/" + "input" + "/" + inputFileName);
                        DEPFS.writeFile(inputFile, portValue);
                        String source = portName;
                        parameter.put(source, "$oms_prj/input/" + portValue);

                    } else if (portValue != "") {
                        String source = portName;
                        parameter.put(source, portValue);
                    }

                }
            }

            //use components to component element
            ita = components.iterator();
            for (int i = 1; ita.hasNext(); i++) {
                String value = (String) ita.next();
                String newName = "c" + i;
                newComponentName.put(value, newName);
                model.setComponent(newName, value);
                //                    System.out.println("newName, value" + newName + value);

            }

            //use sourceToTarget to connect component
            for (int i = 0; i < sourceToTarget.size(); i++) {
                String[] componentInfo = sourceToTarget.get(i).split("\\+");
                String preSourceName = componentInfo[0].split("\\.")[0] + "."
                        + componentInfo[0].split("\\.")[1];
                String laterTargetName = componentInfo[1].split("\\.")[0] + "."
                        + componentInfo[1].split("\\.")[1];
                model.setConnect(
                        componentInfo[0].replace(preSourceName, (String) newComponentName.get(preSourceName)),
                        componentInfo[1].replace(laterTargetName,
                                (String) newComponentName.get(laterTargetName)));
                //                    System.out.println("componentInfo[0].replace(preSourceName, (String) newComponentName.get(preSourceName)),\n" +
                //                            "                            componentInfo[1].replace(laterTargetName, (String) newComponentName.get(laterTargetName))"
                //                    +componentInfo[0].replace(preSourceName ,(String) newComponentName.get(preSourceName))+
                //                            componentInfo[1].replace(laterTargetName, (String) newComponentName.get(laterTargetName)));
            }

            //user parameter to set parameter value
            if (!parameter.isEmpty()) {
                ita = parameter.entrySet().iterator();
                while (ita.hasNext()) {
                    Map.Entry entry = (Map.Entry) ita.next();
                    String key = (String) entry.getKey();
                    String[] pots = key.split("\\.");
                    String preName = key.replace(pots[0] + "." + pots[1],
                            (String) newComponentName.get(pots[0] + "." + pots[1]));
                    String value = "\"" + (String) entry.getValue() + "\"";
                    model.setParameter(preName, value);
                }
            }

            sim.setModel(model);
            simFile.setSim(sim);
            simFile.setImport("import static oms3.SimBuilder.instance as OMS3");

            //using simFile to generate sim file

            File simulation = new File(DistributeServer.absolutePathOfRuntimeUsers + "/" + currentUserName + "/"
                    + componentName + "/simulation.sim");
            DEPFS.writeFile(simulation, simFile.toString());
            System.out.println(simFile.toString());
            runModel(connection, data);

            //                JSONObject jsonObject = JSONObject.fromObject("{action:'compile',StatusCode:1,message:'success'}");
            //                connection.send(jsonObject.toString());
        }
    }
}

From source file:org.prettyx.DistributeServer.Network.ActionHandler.java

License:Open Source License

/**
 * @TODO//  w w  w. j  a v  a2s . c  o  m
 */

public static void runModel(final WebSocket connection, String data) throws SQLException, DocumentException {

    Document document = DocumentHelper.parseText(data);
    Element root = document.getRootElement();
    String componentName = root.element("name").getText();

    DBOP dbop = new DBOP();
    String currentUserName = "";
    Connection connectionToSql = dbop.getConnection();

    PreparedStatement prep = connectionToSql.prepareStatement("select nickname from Users where sid= ?;");
    prep.setString(1, (String) DistributeServerHearken.currentUsers.get(connection));
    ResultSet resultSet = prep.executeQuery();
    if (resultSet.next()) {
        currentUserName = resultSet.getString("nickname");
        LogUtility.logUtility().log2out("current user name:" + currentUserName);
    }
    resultSet.close();
    prep.close();

    String path = DistributeServer.absolutePathOfRuntimeUsers + "/" + currentUserName + "/" + componentName;

    final String zipFileName = "/tmp/" + UUID.randomUUID() + ".zip";
    try {
        File file = new File(path);
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
        DEPFS.zip(file.getPath(), file.getPath().length(), out);
        out.closeEntry();
        out.close();

        try {
            WebSocketClient webSocketClient = new WebSocketClient(new URI(
                    "ws://" + DistributeServer.settingsCenter.getSetting("Network", "ComputeServerAddress"))) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    try {
                        send(JSONObject
                                .fromObject("{action:" + Message.D_C_RUN + ", sid:'', data:\""
                                        + DEPFS.encodeBase64File(zipFileName).replace("\n", "") + "\"}")
                                .toString());
                        DEPFS.removeFile(zipFileName);
                    } catch (Exception e) {
                        LogUtility.logUtility().log2err(e.getMessage());
                    }
                }

                @Override
                public void onMessage(String s) {
                    // TODO Process Returned Data
                    JSONObject jsonObject = JSONObject.fromObject(s);
                    if (jsonObject.size() == 2) {
                        LogUtility.logUtility().log2out(jsonObject.toString());
                        int action = (Integer) jsonObject.get("action");
                        String data = (String) jsonObject.get("data");

                        try {
                            switch (action) {
                            case Message.D_C_RESULT: {
                                jsonObject = JSONObject
                                        .fromObject("{action:'run',StatusCode:1,message:'" + data + "'}");
                                System.out.println(jsonObject.toString());
                                connection.send(jsonObject.toString());
                            }
                            case Message.D_C_ANALYSIS: {
                                jsonObject = JSONObject
                                        .fromObject("{action:'analysis',StatusCode:1,message:'" + data + "'}");
                                System.out.println(jsonObject.toString());
                                connection.send(jsonObject.toString());
                            }
                            default:
                                LogUtility.logUtility().log2err("action type error:" + s);
                            }
                        } catch (Exception e) {
                            LogUtility.logUtility().log2err(e.getMessage());
                        }

                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {

                }

                @Override
                public void onError(Exception e) {

                }
            };
            webSocketClient.connect();
        } catch (Exception e) {
            LogUtility.logUtility().log2err(e.getMessage());
        }

    } catch (Exception e) {
        LogUtility.logUtility().log2err(e.getMessage());
    }
}

From source file:org.projectforge.framework.xstream.XmlHelper.java

License:Open Source License

public static Element fromString(final String str) {
    if (StringUtils.isBlank(str) == true) {
        return null;
    }/*from   ww w. j a  va 2 s.  c  om*/
    try {
        final Document document = DocumentHelper.parseText(str);
        return document.getRootElement();
    } catch (final DocumentException ex) {
        log.error("Exception encountered " + ex.getMessage());
    }
    return null;
}

From source file:org.projectforge.web.FavoritesMenu.java

License:Open Source License

public void readFromXml(final String menuAsXml) {
    if (menu == null) {
        log.error("User's menu is null, can't get FavoritesMenu!");
        return;/* w w  w  . j  a va2s. co m*/
    }
    if (log.isDebugEnabled() == true) {
        log.debug("readFromXml: " + menuAsXml);
    }
    Document document = null;
    try {
        document = DocumentHelper.parseText(menuAsXml);
    } catch (final DocumentException ex) {
        log.error("Exception encountered " + ex, ex);
        return;
    }
    final MenuBuilderContext context = new MenuBuilderContext(menu, accessChecker, PFUserContext.getUser(),
            false);
    final Element root = document.getRootElement();
    menuEntries = new ArrayList<MenuEntry>();
    for (final Iterator<?> it = root.elementIterator("item"); it.hasNext();) {
        final Element item = (Element) it.next();
        final MenuEntry menuEntry = readFromXml(item, context);
        menuEntries.add(menuEntry);
    }
}

From source file:org.saiku.adhoc.utils.XmlUtils.java

License:Open Source License

public static String prettyPrint(final String xml) {
    StringWriter sw = null;//from  ww  w.j  a v  a  2 s.  com

    try {
        final OutputFormat format = new OutputFormat("  ", true);
        //OutputFormat.createPrettyPrint();
        final org.dom4j.Document document = DocumentHelper.parseText(xml);
        sw = new StringWriter();
        final XMLWriter writer = new XMLWriter(sw, format);
        writer.write(document);
    } catch (Exception e) {
        System.out.println("creating beautified xml failed, refer to exc : " + e.getMessage());
    }
    return sw.toString();
}

From source file:org.saiku.plugin.resources.PluginResource.java

License:Apache License

@GET
@Produces({ "application/json" })
@Path("/cda/execute")
public Response execute(@QueryParam("query") String query, @QueryParam("type") String type) {
    try {/*from   w w  w  .j  a v a  2  s  .  c  o  m*/
        String cdaString = getCda(query);
        Document cda = DocumentHelper.parseText(cdaString);
        throw new UnsupportedOperationException("We dont support execution of CDA at this time");
        // final CdaSettings cdaSettings = new CdaSettings(cda, "cda1", null);
        //
        // log.debug("Doing query on Cda - Initializing CdaEngine");
        // final CdaEngine engine = CdaEngine.getInstance();
        // final QueryOptions queryOptions = new QueryOptions();
        // queryOptions.setDataAccessId("1");
        // queryOptions.setOutputType("json");
        // log.info("Doing query");
        // ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // PrintStream printstream = new PrintStream(outputStream);
        // engine.doQuery(printstream, cdaSettings, queryOptions);
        // byte[] doc = outputStream.toByteArray();
        //
        // return Response.ok(doc, MediaType.APPLICATION_JSON).header(
        // "content-length",doc.length).build();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Response.serverError().build();
}

From source file:org.saiku.plugin.resources.PluginResource.java

License:Apache License

private Document getCdaAsDocument(String driver, String url, String name, String query) throws Exception {
    String cda = getCdaAsString(driver, url, name, query);
    return DocumentHelper.parseText(cda);
}

From source file:org.seamless_ip.services.dao.ProjectDaoImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public Collection<VisualisationTO> getVisualisationsForProject(Long userId, Long projectId) {
    // check if user has valid permission for this action
    if (!userDao.canDoForProject(userId, projectId, Task.READ, Right.VISUALIZATION))
        throw new RuntimeException("Sorry, you are not allowed to view visualisations for this project!");

    // visualizations are encoded into the Project.Problem.properties field
    Project project = get(projectId);//  www .j a  v  a  2 s. co m
    if (project == null)
        throw new RuntimeException("Loading failed, project with id=" + projectId + " does not exist!");

    if (project.getProblem() == null)
        throw new RuntimeException(
                "Loading failed, project with id=" + projectId + " has no Problem instance!");

    // get the properties and decode the XML document
    ArrayList<VisualisationTO> result = new ArrayList<VisualisationTO>();
    String properties = project.getProblem().getProperties();
    if ((properties != null) && (properties.length() > 0)) {
        try {
            Document document = DocumentHelper.parseText(properties);
            if (document.getRootElement() != null) {
                // decode XML into visualisationTO's
                Iterator iter = document.getRootElement().elementIterator("visualisation");
                if (iter != null) {
                    while (iter.hasNext()) {
                        Element v = (Element) iter.next();
                        VisualisationTO item = new VisualisationTO(v);
                        result.add(item);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Loading of visualisations failed: " + e.getMessage(), e);
        }
    }

    return result;
}

From source file:org.sipfoundry.openfire.vcard.provider.RestInterface.java

License:Contributor Agreement License

public String buildXMLContactInfoXSLT(Element e) {
    try {//from   www  . ja va 2s.co  m
        String x = e.asXML().replace("xmlns=\"vcard-temp\"", ""); // xmlns causes dom4j xpath
        // not working somehow.
        Document vcardDoc = DocumentHelper.parseText(x);

        logger.debug("before XSLT " + vcardDoc.getRootElement().asXML());
        InputStream inStream = this.getClass().getResourceAsStream("/contactInfo.xsl");
        Document contactDoc = styleDocument(vcardDoc, inStream);

        logger.debug("After XSLT " + contactDoc.getRootElement().asXML());
        return contactDoc.getRootElement().asXML();
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        return null;
    }

}

From source file:org.sipfoundry.openfire.vcard.provider.RestInterface.java

License:Contributor Agreement License

public static String buildXMLContactInfo(Element e) {
    try {/*from   www . j  av a2s. c  o m*/
        String x = e.asXML().replace("xmlns=\"vcard-temp\"", ""); // xmlns causes dom4j xpath
        // not working somehow.

        logger.debug("In buildXMLContactInfo vcard string is " + x);
        Document vcardDoc = DocumentHelper.parseText(x);
        Element el = vcardDoc.getRootElement();

        StringBuilder xbuilder = new StringBuilder("<contact-information>");

        xbuilder.append("<firstName>");
        xbuilder.append(getNodeText(el, "N/GIVEN"));
        xbuilder.append("</firstName>");
        xbuilder.append("<lastName>");
        xbuilder.append(getNodeText(el, "N/FAMILY"));
        xbuilder.append("</lastName>");
        xbuilder.append("<jobTitle>");
        xbuilder.append(getNodeText(el, "TITLE"));
        xbuilder.append("</jobTitle>");
        xbuilder.append("<jobDept>");
        xbuilder.append(getNodeText(el, "ORG/ORGUNIT"));
        xbuilder.append("</jobDept>");
        xbuilder.append("<companyName>");
        xbuilder.append(getNodeText(el, "ORG/ORGNAME"));
        xbuilder.append("</companyName>");

        xbuilder.append("<officeAddress>");
        xbuilder.append("<street>");
        xbuilder.append(getNodeText(el, "ADR/STREET"));
        xbuilder.append("</street>");
        xbuilder.append("<city>");
        xbuilder.append(getNodeText(el, "ADR/LOCALITY"));
        xbuilder.append("</city>");
        xbuilder.append("<country>");
        xbuilder.append(getNodeText(el, "ADR/CTRY"));
        xbuilder.append("</country>");
        xbuilder.append("<state>");
        xbuilder.append(getNodeText(el, "ADR/REGION"));
        xbuilder.append("</state>");
        xbuilder.append("<zip>");
        xbuilder.append(getNodeText(el, "ADR/PCODE"));
        xbuilder.append("</zip>");
        xbuilder.append("</officeAddress>");

        /*
         * if (!(getNodeText(el, "JABBERID").equals("unknown"))) { xbuilder.append("<imId>");
         * xbuilder.append(getNodeText(el, "JABBERID"));xbuilder.append("</imId>"); }
         */
        xbuilder.append("<emailAddress>");
        xbuilder.append(getNodeText(el, "EMAIL/USERID"));
        xbuilder.append("</emailAddress>");
        xbuilder.append("</contact-information>");

        logger.debug("contact info generated by buildXMLContactInfo is " + xbuilder.toString());

        return xbuilder.toString();
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        return null;
    }

}