Example usage for org.dom4j DocumentHelper createElement

List of usage examples for org.dom4j DocumentHelper createElement

Introduction

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

Prototype

public static Element createElement(String name) 

Source Link

Usage

From source file:com.pureinfo.srm.config.notice.domain.NoticeMgrImpl.java

License:Open Source License

public void store() throws PureException {
    if (!isLoaded())
        return;/*from w  w w  .  jav a  2 s .c o m*/
    synchronized (this) {
        Element root = DocumentHelper.createElement(ELEMENT_NOTICES);
        for (Iterator iter = m_notices.values().iterator(); iter.hasNext();) {
            Notice notice = (Notice) iter.next();
            notice.toXMLElement(root.addElement(ELEMENT_NOTICE));
        }
        String sFileName = ClassResourceUtil.mapFullPath(DATA_FILENAME, true);
        try {
            new XMLWriter(new FileOutputStream(sFileName), OutputFormat.createPrettyPrint())
                    .write(DocumentHelper.createDocument(root));
        } catch (Exception ex) {
            throw new PureException(PureException.UNKNOWN, "", ex);
        }
    }
}

From source file:com.servoy.j2db.documentation.QualifiedDocumentationName.java

License:Open Source License

public Element toXML(String elementName) {
    Element root = DocumentHelper.createElement(elementName);
    if (memberName != null) {
        root.addAttribute(ATTR_MEMBER, memberName);
        String argsAsString = argumentsArray2String(argumentsTypes);
        //         if (argsAsString != null) root.addAttribute(ATTR_ARGUMENTSTYPES, argsAsString);
    }/*from   w  ww .  j av a  2 s.c  om*/
    if (className != null)
        root.addAttribute(ATTR_OBJECT, className);
    return root;
}

From source file:com.tedi.engine.XMLOutput.java

License:Open Source License

public String process(Vector structureV, Vector dataV) {
    doc = DocumentHelper.createDocument();
    Element root = null;/*from   w  ww.j av a2  s. c  om*/
    String suppress = null;
    String result = "";

    if (logger.isDebugEnabled()) {
        logger.debug("Processing XML output.");
    }

    if (structureV != null && structureV.size() > 0 && structureV != null) {
        try {
            // main loop for creating the XML document
            for (int i = 0; i < structureV.size(); i++) {
                String value = (String) dataV.elementAt(i);
                Vector fieldV = (Vector) structureV.elementAt(i);
                String path = (String) fieldV.elementAt(0);
                String endpoint = (String) fieldV.elementAt(1);
                String datatype = (String) fieldV.elementAt(4);
                // deal with suppression criteria
                // --------------------------------------------------------------
                if (suppress != null) {
                    if (path.indexOf(suppress) > -1)
                        continue;
                    else
                        suppress = null;
                }
                // if printing of this part of the tree was supressed, skip
                // ahead
                if (value.equals(TEDI_SUPRESS)) {
                    if (suppress == null)
                        suppress = path;
                    continue;
                }
                // ---------------------------------------------------------------------------------------------
                Vector currentRowVector = (Vector) structureV.elementAt(i);
                // Only non-calc fields make it to output
                if (!currentRowVector.elementAt(4).toString().equals(CALC)) {
                    StringTokenizer st = new StringTokenizer(path, "/");
                    int count = st.countTokens();
                    // factor out the root
                    String firstToken = st.nextToken();
                    count--;
                    // Set root if required
                    if (root == null) {
                        this.setSystemID(firstToken);
                        root = DocumentHelper.createElement(firstToken);
                        doc.setRootElement(root);
                        if (count == 0 && endpoint.length() == 0)
                            continue;
                    } else if (endpoint.length() == 0)
                        count--;
                    // Handle error condition of no root
                    if (root == null) {
                        execResults.addMessage(ExecutionResults.M_ERROR, ExecutionResults.J2EE_TARGET_ERR,
                                "Mapping defintion error locating root element declaration.");
                        execResults.setReturnCode(ExecutionResults.RESULT_ERROR);
                        break;
                    }
                    if (endpoint.length() > 0) {
                        if (mapFile.isSuppressAttribIfEmpty() && value.length() == 0)
                            continue;
                        else if (mapFile.isSuppressAttribIfHasOnlyWhitespace() && value.trim().length() == 0)
                            continue;
                    }
                    // this is the main loop for a path
                    Element elem = root;
                    for (int j = 0; j < count; j++) {
                        String item = st.nextToken();
                        List childList = elem.elements(item);
                        if (childList.size() > 0) {
                            elem = (Element) childList.get(childList.size() - 1);
                        } else {
                            elem = elem.addElement(item);
                        }
                    }
                    if (endpoint.length() == 0) {
                        elem = elem.addElement(st.nextToken());
                        if (datatype.equals(TEXT_CDATA))
                            elem.addCDATA(value);
                        else if (!datatype.equals(NOT_MAPPABLE))
                            elem.addText(value);
                    } else {
                        elem.addAttribute(endpoint, value);
                    }
                }
            } // end for() main loop

            // "isSuppressDocType" indicator re-used to suppress NS prefixes
            if (!isSuppressDocType) {
                addNSPrefixesToDocument();
            }

            result = cleanDocument(doc);
        } catch (Exception e) {
            execResults.addMessage(ExecutionResults.M_ERROR, ExecutionResults.J2EE_TARGET_ERR,
                    "Error creating XML document: " + e.getMessage());
            execResults.setReturnCode(ExecutionResults.RESULT_ERROR);
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Processing of XML output completed.");
    }
    return result;
}

From source file:com.test.android.push.xmpp.handler.IQRegisterHandler.java

License:Open Source License

/**
 * Constructor./* w ww  .  j a  v  a 2  s  . com*/
 */
public IQRegisterHandler() {
    androidService = ServiceLocator.getUserService();
    probeResponse = DocumentHelper.createElement(QName.get("query", NAMESPACE));
    probeResponse.addElement("username");
    probeResponse.addElement("password");
    probeResponse.addElement("userId");
}

From source file:com.vmware.o11n.plugin.powershell.remote.impl.winrm.Action.java

License:Open Source License

public Element getElement() {
    return DocumentHelper.createElement(QName.get("Action", Namespaces.NS_ADDRESSING))
            .addAttribute("mustUnderstand", "true").addText(uri);
}

From source file:com.vmware.o11n.plugin.powershell.remote.impl.winrm.OptionSet.java

License:Open Source License

public Element getElement() {
    final Element optionSet = DocumentHelper.createElement(QName.get("OptionSet", Namespaces.NS_WSMAN_DMTF));
    for (KeyValuePair p : keyValuePairs) {
        optionSet.addElement(QName.get("Option", Namespaces.NS_WSMAN_DMTF)).addAttribute("Name", p.getKey())
                .addText(p.getValue());//  w w w .ja v  a 2  s  .c  o  m
    }
    return optionSet;
}

From source file:com.vmware.o11n.plugin.powershell.remote.impl.winrm.ClientState.java

License:Open Source License

private void cleanUp() {
    if (commandId == null)
        return;/*from www  .  ja  v a  2  s.  co m*/
    log.debug("cleanUp shellId {} commandId {} ", shellId, commandId);
    final Element bodyContent = DocumentHelper.createElement(QName.get("Signal", Namespaces.NS_WIN_SHELL))
            .addAttribute("CommandId", commandId);
    bodyContent.addElement(QName.get("Code", Namespaces.NS_WIN_SHELL))
            .addText("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminate");
    final Document requestDocument = getRequestDocument(Action.WS_SIGNAL, ResourceURI.RESOURCE_URI_CMD, null,
            shellId, bodyContent);
    @SuppressWarnings("unused")
    Document responseDocument = sendMessage(requestDocument, SoapAction.SIGNAL);

}

From source file:com.vmware.o11n.plugin.powershell.remote.impl.winrm.ClientState.java

License:Open Source License

/**
 * Loops endlessly and provides output stream content to the OverthereProcessOutputHandler instance 
 * @param handler - instance of OverthereProcessOutputHandler that will collect the output
 *///from  w  w w .j  a v a  2  s. co m
synchronized public void getCommandOutput(WinRmCapturingOverthereProcessOutputHandler handler) {
    log.debug("getCommandOutput shellId {} commandId {} ", shellId, commandId);
    final Element bodyContent = DocumentHelper.createElement(QName.get("Receive", Namespaces.NS_WIN_SHELL));
    bodyContent.addElement(QName.get("DesiredStream", Namespaces.NS_WIN_SHELL))
            .addAttribute("CommandId", commandId).addText("stdout stderr");
    final Document requestDocument = getRequestDocument(Action.WS_RECEIVE, ResourceURI.RESOURCE_URI_CMD, null,
            shellId, bodyContent);

    for (;;) {
        Document responseDocument = sendMessage(requestDocument, SoapAction.RECEIVE);

        //  If no output is available before the wsman:OperationTimeout expires, 
        //  the server MUST return a WSManFault with the Code attribute equal to "2150858793". 
        //  When the client receives this fault, it SHOULD issue another Receive request. 
        //  The client SHOULD continue to issue Receive messages as soon as the previous ReceiveResponse has been received.
        final List<?> faults = FaultExtractor.FAULT_CODE.getXPath().selectNodes(responseDocument);
        if (!faults.isEmpty()) {
            String faultCode = ((Attribute) faults.get(0)).getText();
            final List<?> faultMessages = FaultExtractor.FAULT_MESSAGE.getXPath().selectNodes(responseDocument);
            String faultMessage = ((Element) faultMessages.get(0)).getText();
            log.debug("fault code {} message", faultCode);
            if (faultCode.equalsIgnoreCase("2150858793")) {
                continue;
            } else {
                log.debug("fault code {}", faultCode);
                throw new WinRMRuntimeIOException(faultMessage);
            }
        }

        String stdout = handleStream(responseDocument, ResponseExtractor.STDOUT);
        handler.handleOutputChunk(stdout);

        String stderr = handleStream(responseDocument, ResponseExtractor.STDERR);
        BufferedReader stderrReader = new BufferedReader(new StringReader(stderr));
        try {
            for (;;) {
                String line = stderrReader.readLine();
                if (line == null) {
                    break;
                }
                handler.handleErrorLine(line);
            }
        } catch (IOException exc) {
            throw new RuntimeIOException("Unexpected I/O exception while reading stderr", exc);
        }

        if (chunk == 0) {
            try {
                exitCode = getFirstElement(responseDocument, ResponseExtractor.EXIT_CODE);
                log.debug("exit code {}", exitCode);
            } catch (Exception e) {
                log.debug("not found");
            }
        }
        chunk++;

        /* We may need to get additional output if the stream has not finished.
                                The CommandState will change from Running to Done like so:
                                @example
                
                                 from...
                                 <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Running"/>
                                 to...
                                 <rsp:CommandState CommandId="..." State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done">
                                     <rsp:ExitCode>0</rsp:ExitCode>
                                 </rsp:CommandState>
                             */
        final List<?> list = ResponseExtractor.STREAM_DONE.getXPath().selectNodes(responseDocument);
        if (!list.isEmpty()) {
            exitCode = getFirstElement(responseDocument, ResponseExtractor.EXIT_CODE);
            log.debug("exit code {}", exitCode);
            break;
        }

        if (handler.isDone() == true) {
            break;
        }
    }
    //logger.debug("all the command output has been fetched (chunk={})", chunk);
}

From source file:com.vmware.o11n.plugin.powershell.remote.impl.winrm.ClientState.java

License:Open Source License

private String runCommand(String command) {
    log.debug("runCommand shellId {} command {}", shellId, command);
    final Element bodyContent = DocumentHelper.createElement(QName.get("CommandLine", Namespaces.NS_WIN_SHELL));

    String encoded = command;//  w ww.  ja  va  2 s .  com
    if (!command.startsWith("\""))
        encoded = "\"" + encoded;
    if (!command.endsWith("\""))
        encoded = encoded + "\"";

    log.debug("Encoded command is {}", encoded);

    bodyContent.addElement(QName.get("Command", Namespaces.NS_WIN_SHELL)).addText(encoded);

    final Document requestDocument = getRequestDocument(Action.WS_COMMAND, ResourceURI.RESOURCE_URI_CMD,
            OptionSet.RUN_COMMAND, shellId, bodyContent);
    Document responseDocument = sendMessage(requestDocument, SoapAction.COMMAND_LINE);

    return getFirstElement(responseDocument, ResponseExtractor.COMMAND_ID);
}

From source file:com.vmware.o11n.plugin.powershell.remote.impl.winrm.ClientState.java

License:Open Source License

synchronized public void sendCmdToInputStream(String command, boolean shouldEncode) {
    log.debug("runCommand shellId {} command {}", shellId, command);
    final Element bodyContent = DocumentHelper.createElement(QName.get("Send", Namespaces.NS_WIN_SHELL));
    String encoded = null;/*from  ww  w. ja  v  a2  s .c  o  m*/
    if (shouldEncode) {
        try {
            encoded = new String(Base64.encodeBase64(command.getBytes()), CHARSET_UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    String cmdToSent = shouldEncode ? encoded : command;
    log.debug("Encoded command is {}", cmdToSent);

    bodyContent.addElement(QName.get("Stream", Namespaces.NS_WIN_SHELL)).addText(cmdToSent)
            .addAttribute("Name", "stdin").addAttribute("CommandId", commandId);

    final Document requestDocument = getRequestDocument(Action.WS_SEND, ResourceURI.RESOURCE_URI_CMD,
            OptionSet.RUN_COMMAND, shellId, bodyContent);
    sendMessage(requestDocument, SoapAction.COMMAND_LINE);
}