Example usage for org.w3c.dom Element getOwnerDocument

List of usage examples for org.w3c.dom Element getOwnerDocument

Introduction

In this page you can find the example usage for org.w3c.dom Element getOwnerDocument.

Prototype

public Document getOwnerDocument();

Source Link

Document

The Document object associated with this node.

Usage

From source file:cz.fi.muni.xkremser.editor.server.AuthenticationServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession(true);
    String url = (String) session.getAttribute(HttpCookies.TARGET_URL);
    String root = (URLS.LOCALHOST() ? "http://" : "https://") + req.getServerName() + (URLS.LOCALHOST()
            ? (req.getServerPort() == 80 || req.getServerPort() == 443 ? "" : (":" + req.getServerPort()))
            : "") + URLS.ROOT() + (URLS.LOCALHOST() ? "?gwt.codesvr=127.0.0.1:9997" : "");
    String authHeader = req.getHeader("Authorization");
    if (authHeader != null) {
        String decodedHeader = decode(req, authHeader);
        String pass = configuration.getHttpBasicPass();
        if (pass == null || "".equals(pass.trim()) || pass.length() < 4) {
            requrireAuthentication(resp);
        }/* www.j  a  va  2 s  . c o m*/
        if (decodedHeader.equals(ALLOWED_PREFIX + pass)) {
            session.setAttribute(HttpCookies.TARGET_URL, null);
            session.setAttribute(HttpCookies.SESSION_ID_KEY,
                    "https://www.google.com/profiles/109255519115168093543");
            session.setAttribute(HttpCookies.NAME_KEY, "admin");
            session.setAttribute(HttpCookies.ADMIN, HttpCookies.ADMIN_YES);
            ACCESS_LOGGER.info("LOG IN: [" + FORMATTER.format(new Date()) + "] User "
                    + decodedHeader.substring(0, decodedHeader.indexOf(":")) + " with openID BASIC_AUTH and IP "
                    + req.getRemoteAddr());
            URLS.redirect(resp, url == null ? root : url);
            return;
        } else {
            requrireAuthentication(resp);
            return;
        }
    }
    session.setAttribute(HttpCookies.TARGET_URL, null);
    String token = req.getParameter("token");

    String appID = configuration.getOpenIDApiKey();
    String openIdurl = configuration.getOpenIDApiURL();
    RPX rpx = new RPX(appID, openIdurl);
    Element e = null;
    try {
        e = rpx.authInfo(token);
    } catch (ConnectionException connEx) {
        requrireAuthentication(resp);
        return;
    }
    String idXPath = "//identifier";
    String nameXPath = "//displayName";
    XPathFactory xpfactory = XPathFactory.newInstance();
    XPath xpath = xpfactory.newXPath();
    String identifier = null;
    String name = null;
    try {
        XPathExpression expr1 = xpath.compile(idXPath);
        XPathExpression expr2 = xpath.compile(nameXPath);
        NodeList nodes1 = (NodeList) expr1.evaluate(e.getOwnerDocument(), XPathConstants.NODESET);
        NodeList nodes2 = (NodeList) expr2.evaluate(e.getOwnerDocument(), XPathConstants.NODESET);
        Element el = null;
        if (nodes1.getLength() != 0) {
            el = (Element) nodes1.item(0);
        }
        if (el != null) {
            identifier = el.getTextContent();
        }
        if (nodes2.getLength() != 0) {
            el = (Element) nodes2.item(0);
        }
        if (el != null) {
            name = el.getTextContent();
        }
    } catch (XPathExpressionException e1) {
        e1.printStackTrace();
    }
    if (identifier != null && !"".equals(identifier)) {
        ACCESS_LOGGER.info("LOG IN: [" + FORMATTER.format(new Date()) + "] User " + name + " with openID "
                + identifier + " and IP " + req.getRemoteAddr());
        int userStatus = UserDAO.UNKNOWN;
        try {
            userStatus = userDAO.isSupported(identifier);
        } catch (DatabaseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        switch (userStatus) {
        case UserDAO.UNKNOWN:
            // TODO handle DB error (inform user)
            break;
        case UserDAO.USER:
            // HttpCookies.setCookie(req, resp, HttpCookies.SESSION_ID_KEY,
            // identifier);
            session.setAttribute(HttpCookies.SESSION_ID_KEY, identifier);
            session.setAttribute(HttpCookies.NAME_KEY, name);
            URLS.redirect(resp, url == null ? root : url);
            break;
        case UserDAO.ADMIN:
            // HttpCookies.setCookie(req, resp, HttpCookies.SESSION_ID_KEY,
            // identifier);
            // HttpCookies.setCookie(req, resp, HttpCookies.ADMIN,
            // HttpCookies.ADMIN_YES);
            session.setAttribute(HttpCookies.SESSION_ID_KEY, identifier);
            session.setAttribute(HttpCookies.NAME_KEY, name);
            session.setAttribute(HttpCookies.ADMIN, HttpCookies.ADMIN_YES);
            URLS.redirect(resp, url == null ? root : url);
            break;
        case UserDAO.NOT_PRESENT:
        default:
            session.setAttribute(HttpCookies.UNKNOWN_ID_KEY, identifier);
            session.setAttribute(HttpCookies.NAME_KEY, name);
            URLS.redirect(resp, root + URLS.INFO_PAGE);
            break;
        }
    } else {
        URLS.redirect(resp, root + (URLS.LOCALHOST() ? URLS.LOGIN_LOCAL_PAGE : URLS.LOGIN_PAGE));
    }

    // System.out.println("ID:" + identifier);

    // if user is supported redirect to homepage else show him a page that he
    // has to be added to system first by admin

}

From source file:com.twinsoft.convertigo.engine.util.WsReference.java

private static void extractSoapVariables(XmlSchema xmlSchema, List<RequestableHttpVariable> variables,
        Node node, String longName, boolean isMulti, QName variableType) throws EngineException {
    if (node == null)
        return;/*from www .jav  a  2 s .co  m*/
    int type = node.getNodeType();

    if (type == Node.ELEMENT_NODE) {
        Element element = (Element) node;
        if (element != null) {
            String elementName = element.getLocalName();
            if (longName != null)
                elementName = longName + "_" + elementName;

            if (!element.getAttribute("soapenc:arrayType").equals("") && !element.hasChildNodes()) {
                String avalue = element.getAttribute("soapenc:arrayType");
                element.setAttribute("soapenc:arrayType", avalue.replaceAll("\\[\\]", "[1]"));

                Element child = element.getOwnerDocument().createElement("item");
                String atype = avalue.replaceAll("\\[\\]", "");
                child.setAttribute("xsi:type", atype);
                if (atype.startsWith("xsd:")) {
                    String variableName = elementName + "_item";
                    child.appendChild(
                            element.getOwnerDocument().createTextNode("$(" + variableName.toUpperCase() + ")"));
                    RequestableHttpVariable httpVariable = createHttpVariable(true, variableName,
                            new QName(Constants.URI_2001_SCHEMA_XSD, atype.split(":")[1]));
                    variables.add(httpVariable);
                }
                element.appendChild(child);
            }

            // extract from attributes
            NamedNodeMap map = element.getAttributes();
            for (int i = 0; i < map.getLength(); i++) {
                Node child = map.item(i);
                if (child.getNodeName().equals("soapenc:arrayType"))
                    continue;
                if (child.getNodeName().equals("xsi:type"))
                    continue;
                if (child.getNodeName().equals("soapenv:encodingStyle"))
                    continue;

                String variableName = getVariableName(variables, elementName + "_" + child.getLocalName());

                child.setNodeValue("$(" + variableName.toUpperCase() + ")");

                RequestableHttpVariable httpVariable = createHttpVariable(false, variableName,
                        Constants.XSD_STRING);
                variables.add(httpVariable);
            }

            // extract from children nodes
            boolean multi = false;
            QName qname = Constants.XSD_STRING;
            NodeList children = element.getChildNodes();
            if (children.getLength() > 0) {
                Node child = element.getFirstChild();
                while (child != null) {
                    if (child.getNodeType() == Node.COMMENT_NODE) {
                        String value = child.getNodeValue();
                        if (value.startsWith("type:")) {
                            String schemaType = child.getNodeValue().substring("type:".length()).trim();
                            qname = getVariableSchemaType(xmlSchema, schemaType);
                        }
                        if (value.indexOf("repetitions:") != -1) {
                            multi = true;
                        }
                    } else if (child.getNodeType() == Node.TEXT_NODE) {
                        String value = child.getNodeValue().trim();
                        if (value.equals("?") || !value.equals("")) {
                            String variableName = getVariableName(variables, elementName);

                            child.setNodeValue("$(" + variableName.toUpperCase() + ")");

                            RequestableHttpVariable httpVariable = createHttpVariable(isMulti, variableName,
                                    variableType);
                            variables.add(httpVariable);
                        }
                    } else if (child.getNodeType() == Node.ELEMENT_NODE) {
                        extractSoapVariables(xmlSchema, variables, child, elementName, multi, qname);
                        multi = false;
                        qname = Constants.XSD_STRING;
                    }

                    child = child.getNextSibling();
                }
            }

        }
    }
}

From source file:com.netspective.sparx.form.DialogContext.java

public void exportToXml(Element parent) {
    ServletRequest request = getRequest();
    Element dcElem = parent.getOwnerDocument().createElement("dialog-context");
    dcElem.setAttribute("name", dialog.getName());
    dcElem.setAttribute("transaction", state.getIdentifier());
    fieldStates.exportToXml(dcElem);/* w  w  w  .ja  v a 2s .c om*/

    Set retainedParams = null;
    if (retainReqParams != null) {
        retainedParams = new HashSet();
        for (int i = 0; i < retainReqParams.length; i++) {
            String paramName = retainReqParams[i];
            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues != null)
                exportParamToXml(dcElem, paramName, paramValues);
            retainedParams.add(paramName);
        }
    }
    boolean retainedAnyParams = retainedParams != null;

    if (dialog.retainRequestParams()) {
        if (dialog.getDialogFlags().flagIsSet(DialogFlags.RETAIN_ALL_REQUEST_PARAMS)) {
            for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
                String paramName = (String) e.nextElement();
                if (paramName.startsWith(Dialog.PARAMNAME_DIALOGPREFIX)
                        || paramName.startsWith(Dialog.PARAMNAME_CONTROLPREFIX)
                        || (retainedAnyParams && retainedParams.contains(paramName)))
                    continue;

                exportParamToXml(dcElem, paramName, request.getParameterValues(paramName));
            }
        } else {
            String[] retainParams = dialog.getRetainParams();
            int retainParamsCount = retainParams.length;

            for (int i = 0; i < retainParamsCount; i++) {
                String paramName = retainParams[i];
                if (retainedAnyParams && retainedParams.contains(paramName))
                    continue;

                exportParamToXml(dcElem, paramName, request.getParameterValues(paramName));
            }
        }
    }

    parent.appendChild(dcElem);
}

From source file:com.twinsoft.convertigo.beans.core.RequestableStep.java

protected String getWsdlBackupDir(Element element) throws Exception {
    Element rootElement = element.getOwnerDocument().getDocumentElement();
    Element projectNode = (Element) XMLUtils.findChildNode(rootElement, Node.ELEMENT_NODE);
    NodeList properties = projectNode.getElementsByTagName("property");
    Element pName = (Element) XMLUtils.findNodeByAttributeValue(properties, "name", "name");
    String projectName = (String) XMLUtils
            .readObjectFromXml((Element) XMLUtils.findChildNode(pName, Node.ELEMENT_NODE));
    return Engine.PROJECTS_PATH + "/" + projectName + "/backup-wsdl";
}

From source file:de.betterform.agent.web.servlet.ErrorServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    WebUtil.nonCachingResponse(response);
    //pick up the exception details
    String xpath = "unknown";
    String cause = "";
    String msg = (String) getSessionAttribute(request, "betterform.exception.message");
    if (msg != null) {
        int start = msg.indexOf("::");
        if (start > 3) {
            xpath = msg.substring(start + 2);
            msg = msg.substring(0, start);
        }/*from w w w.j  a  v  a  2 s.c  o  m*/
        //todo: don't we need an 'else' here?
    }
    Exception ex = (Exception) getSessionAttribute(request, "betterform.exception");
    if (ex != null && ex.getCause() != null && ex.getCause().getMessage() != null) {
        cause = ex.getCause().getMessage();
    }

    //create XML structure for exception details
    Element rootNode = DOMUtil.createRootElement("error");
    DOMUtil.appendElement(rootNode, "context", request.getContextPath());
    DOMUtil.appendElement(rootNode, "url", request.getSession().getAttribute("betterform.referer").toString());
    DOMUtil.appendElement(rootNode, "xpath", xpath);
    DOMUtil.appendElement(rootNode, "message", msg);
    DOMUtil.appendElement(rootNode, "cause", cause);

    //transform is different depending on exception type
    if (ex instanceof XFormsErrorIndication) {
        Object o = ((XFormsErrorIndication) ex).getContextInfo();
        if (o instanceof HashMap) {
            HashMap<String, Object> map = (HashMap) ((XFormsErrorIndication) ex).getContextInfo();
            if (map.size() != 0) {
                Element contextinfo = rootNode.getOwnerDocument().createElement("contextInfo");
                rootNode.appendChild(contextinfo);
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    DOMUtil.appendElement(rootNode, entry.getKey(), entry.getValue().toString());
                }
            }
        }
        //todo: check -> there are contextInfos containing a simple string but seems to be integrated within above error message already - skip for now
        /*
                    else{
                    }
        */
        Document hostDoc = (Document) getSessionAttribute(request, "betterform.hostDoc");
        String serializedDoc = DOMUtil.serializeToString(hostDoc);
        //reparse
        try {
            byte bytes[] = serializedDoc.getBytes("UTF-8");
            Document newDoc = PositionalXMLReader.readXML(new ByteArrayInputStream(bytes));
            DOMUtil.prettyPrintDOM(newDoc);
            //eval xpath
            Node n = XPathUtil.evaluateAsSingleNode(newDoc, xpath);
            String linenumber = (String) n.getUserData("lineNumber");
            DOMUtil.appendElement(rootNode, "lineNumber", linenumber);

            DOMUtil.prettyPrintDOM(rootNode);

            WebUtil.doTransform(getServletContext(), response, newDoc, "highlightError.xsl", rootNode);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        WebUtil.doTransform(getServletContext(), response, rootNode.getOwnerDocument(), "error.xsl", null);
    }
}

From source file:com.enonic.vertical.userservices.ContentHandlerBaseController.java

protected void buildContentTypeXML(UserServicesService userServices, Element contentdataElem,
        ExtendedMap formItems, boolean skipEmptyElements)
        throws VerticalUserServicesException, RemoteException {
    Document doc = contentdataElem.getOwnerDocument();
    Element moduleElement = (Element) formItems.get("__module_element");

    contentdataElem.setAttribute("version", "1.0");

    // Date conversion objects
    NodeList blockElements;/*from w  w  w .  j  a  v a  2s.  com*/
    try {
        blockElements = XMLTool.selectNodes(moduleElement, "form/block");

        for (int k = 0; k < blockElements.getLength(); ++k) {
            Element blockElement = (Element) blockElements.item(k);
            NodeList inputElements = XMLTool.selectNodes(blockElement, "input");

            boolean groupBlock = false;
            String groupXPath = blockElement.getAttribute("group");
            if (groupXPath != null && groupXPath.length() > 0) {
                groupBlock = true;
            }

            if (!groupBlock) {
                createNormalBlock(formItems, doc, contentdataElem, inputElements, skipEmptyElements);
            } else {
                createGroupBlock(formItems, doc, contentdataElem, inputElements, groupXPath, k + 1);
            }
        }
    } catch (ParseException pe) {
        String message = "Failed to parse a date: %t";
        VerticalUserServicesLogger.warnUserServices(this.getClass(), 3, message, pe);
    }
}

From source file:org.gvnix.web.exception.handler.roo.addon.addon.WebModalDialogOperationsImpl.java

/**
 * Decides if write to disk is needed (ie updated or created)<br/>
 * Used for TAGx files TODO: candidato a ir al mdulo Support
 * //from  w  w  w  .  j  av a2  s.c om
 * @param filePath
 * @param body
 * @return
 */
private boolean writeToDiskIfNecessary(String filePath, Element body) {
    // Build a string representation of the JSP
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Transformer transformer = XmlUtils.createIndentingTransformer();
    XmlUtils.writeXml(transformer, byteArrayOutputStream, body.getOwnerDocument());
    String viewContent = byteArrayOutputStream.toString();

    // If mutableFile becomes non-null, it means we need to use it to write
    // out the contents of jspContent to the file
    MutableFile mutableFile = null;
    if (fileManager.exists(filePath)) {
        // First verify if the file has even changed
        File newFile = new File(filePath);
        String existing = null;
        try {
            existing = IOUtils.toString(new FileReader(newFile));
        } catch (IOException ignoreAndJustOverwriteIt) {
            LOGGER.finest("Problems writting ".concat(newFile.getAbsolutePath()));
        }

        if (!viewContent.equals(existing)) {
            mutableFile = fileManager.updateFile(filePath);
        }
    } else {
        mutableFile = fileManager.createFile(filePath);
        Validate.notNull(mutableFile, "Could not create '" + filePath + "'");
    }

    if (mutableFile != null) {
        try {
            // We need to write the file out (it's a new file, or the
            // existing file has different contents)
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                inputStream = IOUtils.toInputStream(viewContent);
                outputStream = mutableFile.getOutputStream();
                IOUtils.copy(inputStream, outputStream);
            } finally {
                IOUtils.closeQuietly(inputStream);
                IOUtils.closeQuietly(outputStream);
            }
            // Return and indicate we wrote out the file
            return true;
        } catch (IOException ioe) {
            throw new IllegalStateException("Could not output '" + mutableFile.getCanonicalPath() + "'", ioe);
        }
    }

    // A file existed, but it contained the same content, so we return false
    return false;
}

From source file:com.enonic.vertical.userservices.FormHandlerController.java

@Override
protected void buildContentTypeXML(UserServicesService userServices, Element contentdataElem,
        ExtendedMap formItems, boolean skipElements) throws VerticalUserServicesException {

    int menuItemKey = formItems.getInt("_form_id");

    // Elements in the old form XML are prefixed with an underscore
    Element _formElement = (Element) formItems.get("__form");

    Document doc = contentdataElem.getOwnerDocument();
    Element formElement = XMLTool.createElement(doc, contentdataElem, "form");
    formElement.setAttribute("categorykey", _formElement.getAttribute("categorykey"));

    // Set title element:
    Element _titleElement = XMLTool.getElement(_formElement, "title");
    XMLTool.createElement(doc, formElement, "title", XMLTool.getElementText(_titleElement));

    // There may be multiple error states/codes, so we have to keep track of them.
    // When errors occurr, XML is inserted into the resulting document, and sent
    // back to the user client.
    // TIntArrayList errorCodes = new TIntArrayList(5);
    List<Integer> errorCodes = new ArrayList<Integer>(5);

    // The people that will recieve the form mail:
    Element recipientsElem = XMLTool.getElement(_formElement, "recipients");
    if (recipientsElem != null) {
        formElement.appendChild(doc.importNode(recipientsElem, true));
    }//  ww w  .j  a  va  2  s.c o  m

    // Loop all form items and insert the data from the form:
    int fileattachmentCount = 0;
    Element[] _formItems = XMLTool.getElements(_formElement, "item");
    for (int i = 0; i < _formItems.length; i++) {
        String formName = menuItemKey + "_form_" + (i + 1);

        Element itemElement = (Element) doc.importNode(_formItems[i], true);
        formElement.appendChild(itemElement);

        String type = itemElement.getAttribute("type");

        if ("text".equals(type)) {
            // Remove default data:
            Element tmpElement = XMLTool.getElement(itemElement, "data");
            if (tmpElement != null) {
                itemElement.removeChild(tmpElement);
            }
        }

        if ("text".equals(type) || "textarea".equals(type) || "checkbox".equals(type)) {
            String value = formItems.getString(formName, "");

            // If a regular expression is specified, it should be verified that
            // the data entered in the form conforms to this:
            String regexp = itemElement.getAttribute("validation");
            if ("text".equals(type) && regexp != null && regexp.length() > 0) {
                final boolean valueIsNonEmpty = value.length() > 0;
                if (!value.matches(regexp) && valueIsNonEmpty) {
                    XMLTool.createElement(doc, itemElement, "error", ERR_MSG_VALIDATION_FAILED)
                            .setAttribute("id", String.valueOf(ERR_VALIDATION_FAILED));

                    if (!errorCodes.contains(ERR_VALIDATION_FAILED)) {
                        errorCodes.add(ERR_VALIDATION_FAILED);
                    }
                }
            }

            // If the form element is required, we must test that the user actually
            // entered data:
            if (itemElement.getAttribute("required").equals("true") && value.length() == 0) {
                XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id",
                        String.valueOf(ERR_MISSING_REQ));

                if (!errorCodes.contains(ERR_MISSING_REQ)) {
                    errorCodes.add(ERR_MISSING_REQ);
                }
            }

            XMLTool.createElement(doc, itemElement, "data", value);
        } else if ("checkbox".equals(type)) {
            String value;
            if (formItems.getString(formName, "").equals("on")) {
                value = "1";
            } else {
                value = "0";
            }

            XMLTool.createElement(doc, itemElement, "data", value);
        } else if ("radiobuttons".equals(type) || "dropdown".equals(type)) {
            String value = formItems.getString(formName, null);

            boolean selected = false;
            Element tmpElement = XMLTool.getElement(itemElement, "data");
            Element[] options = XMLTool.getElements(tmpElement, "option");
            for (Element option : options) {
                tmpElement = option;
                if (tmpElement.getAttribute("value").equals(value)) {
                    tmpElement.setAttribute("selected", "true");
                    selected = true;
                    break;
                }
            }

            // If the form element is required, we must test that the user actually
            // checked on of the radiobuttons:
            if (itemElement.getAttribute("required").equals("true") && !selected) {
                XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id",
                        String.valueOf(ERR_MISSING_REQ));

                if (!errorCodes.contains(ERR_MISSING_REQ)) {
                    errorCodes.add(ERR_MISSING_REQ);
                }
            }
        } else if ("checkboxes".equals(type)) {
            String[] values = formItems.getStringArray(formName);

            Element tmpElement = XMLTool.getElement(itemElement, "data");
            Element[] options = XMLTool.getElements(tmpElement, "option");
            for (Element option : options) {
                tmpElement = option;

                for (String currentValue : values) {
                    if (tmpElement.getAttribute("value").equals(currentValue)) {
                        tmpElement.setAttribute("selected", "true");
                        break;
                    }
                }
            }
        } else if ("fileattachment".equals(type)) {
            FileItem fileItem = formItems.getFileItem(formName, null);

            // If the form element is required, we must test that the user actually
            // entered data:
            if ("true".equals(itemElement.getAttribute("required")) && fileItem == null) {
                XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id",
                        String.valueOf(ERR_MISSING_REQ));

                if (!errorCodes.contains(ERR_MISSING_REQ)) {
                    errorCodes.add(ERR_MISSING_REQ);
                }
            } else if (fileItem != null) {
                String fileName = FileUtil.getFileName(fileItem);
                Element binaryDataElem = XMLTool.createElement(doc, itemElement, "binarydata", fileName);
                binaryDataElem.setAttribute("key", "%" + fileattachmentCount++);
            }
        }

    }

    HttpServletRequest request = ServletRequestAccessor.getRequest();

    try {
        Boolean captchaOk = captchaService.validateCaptcha(formItems, request, "form", "create");
        if ((captchaOk != null) && (!captchaOk)) {
            errorCodes.add(ERR_INVALID_CAPTCHA);
        }
    } catch (CaptchaServiceException e) {
        String message = "Failed during captcha validation: %t";
        VerticalUserServicesLogger.error(this.getClass(), 0, message, e);
        errorCodes.add(ERR_OPERATION_BACKEND);
    }

    // If one or more errors occurred, an exception is thrown, containing the errorcodes
    // and the resulting document (that now should include error XML):
    if (errorCodes.size() > 0) {
        throw new FormException(doc, errorCodes.toArray(new Integer[errorCodes.size()]));
    }

    VerticalUserServicesLogger.debug(this.getClass(), 10, doc);
}

From source file:com.enonic.cms.web.portal.services.FormServicesProcessor.java

@Override
protected void buildContentTypeXML(UserServicesService userServices, Element contentdataElem,
        ExtendedMap formItems, boolean skipElements) throws VerticalUserServicesException {

    int menuItemKey = formItems.getInt("_form_id");

    // Elements in the old form XML are prefixed with an underscore
    Element _formElement = (Element) formItems.get("__form");

    Document doc = contentdataElem.getOwnerDocument();
    Element formElement = XMLTool.createElement(doc, contentdataElem, "form");
    formElement.setAttribute("categorykey", _formElement.getAttribute("categorykey"));

    // Set title element:
    Element _titleElement = XMLTool.getElement(_formElement, "title");
    XMLTool.createElement(doc, formElement, "title", XMLTool.getElementText(_titleElement));

    // There may be multiple error states/codes, so we have to keep track of them.
    // When errors occurr, XML is inserted into the resulting document, and sent
    // back to the user client.
    // TIntArrayList errorCodes = new TIntArrayList(5);
    List<Integer> errorCodes = new ArrayList<Integer>(5);

    // The people that will recieve the form mail:
    Element recipientsElem = XMLTool.getElement(_formElement, "recipients");
    if (recipientsElem != null) {
        formElement.appendChild(doc.importNode(recipientsElem, true));
    }/*from  ww  w.  j av  a  2 s  . c o m*/

    // Loop all form items and insert the data from the form:
    int fileattachmentCount = 0;
    Element[] _formItems = XMLTool.getElements(_formElement, "item");
    for (int i = 0; i < _formItems.length; i++) {
        String formName = menuItemKey + "_form_" + (i + 1);

        Element itemElement = (Element) doc.importNode(_formItems[i], true);
        formElement.appendChild(itemElement);

        String type = itemElement.getAttribute("type");

        if ("text".equals(type)) {
            // Remove default data:
            Element tmpElement = XMLTool.getElement(itemElement, "data");
            if (tmpElement != null) {
                itemElement.removeChild(tmpElement);
            }
        }

        if ("text".equals(type) || "textarea".equals(type) || "checkbox".equals(type)) {
            String value = formItems.getString(formName, "");

            // If a regular expression is specified, it should be verified that
            // the data entered in the form conforms to this:
            String regexp = itemElement.getAttribute("validation");
            if ("text".equals(type) && regexp != null && regexp.length() > 0) {
                final boolean valueIsNonEmpty = value.length() > 0;
                if (!value.matches(regexp) && valueIsNonEmpty) {
                    XMLTool.createElement(doc, itemElement, "error", ERR_MSG_VALIDATION_FAILED)
                            .setAttribute("id", String.valueOf(ERR_VALIDATION_FAILED));

                    if (!errorCodes.contains(ERR_VALIDATION_FAILED)) {
                        errorCodes.add(ERR_VALIDATION_FAILED);
                    }
                }
            }

            // If the form element is required, we must test that the user actually
            // entered data:
            if (itemElement.getAttribute("required").equals("true") && value.length() == 0) {
                XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id",
                        String.valueOf(ERR_MISSING_REQ));

                if (!errorCodes.contains(ERR_MISSING_REQ)) {
                    errorCodes.add(ERR_MISSING_REQ);
                }
            }

            XMLTool.createElement(doc, itemElement, "data", value);
        } else if ("checkbox".equals(type)) {
            String value;
            if (formItems.getString(formName, "").equals("on")) {
                value = "1";
            } else {
                value = "0";
            }

            XMLTool.createElement(doc, itemElement, "data", value);
        } else if ("radiobuttons".equals(type) || "dropdown".equals(type)) {
            String value = formItems.getString(formName, null);

            boolean selected = false;
            Element tmpElement = XMLTool.getElement(itemElement, "data");
            Element[] options = XMLTool.getElements(tmpElement, "option");
            for (Element option : options) {
                tmpElement = option;
                if (tmpElement.getAttribute("value").equals(value)) {
                    tmpElement.setAttribute("selected", "true");
                    selected = true;
                    break;
                }
            }

            // If the form element is required, we must test that the user actually
            // checked on of the radiobuttons:
            if (itemElement.getAttribute("required").equals("true") && !selected) {
                XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id",
                        String.valueOf(ERR_MISSING_REQ));

                if (!errorCodes.contains(ERR_MISSING_REQ)) {
                    errorCodes.add(ERR_MISSING_REQ);
                }
            }
        } else if ("checkboxes".equals(type)) {
            String[] values = formItems.getStringArray(formName);

            Element tmpElement = XMLTool.getElement(itemElement, "data");
            Element[] options = XMLTool.getElements(tmpElement, "option");
            for (Element option : options) {
                tmpElement = option;

                for (String currentValue : values) {
                    if (tmpElement.getAttribute("value").equals(currentValue)) {
                        tmpElement.setAttribute("selected", "true");
                        break;
                    }
                }
            }
        } else if ("fileattachment".equals(type)) {
            FileItem fileItem = formItems.getFileItem(formName, null);

            // If the form element is required, we must test that the user actually
            // entered data:
            if ("true".equals(itemElement.getAttribute("required")) && fileItem == null) {
                XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id",
                        String.valueOf(ERR_MISSING_REQ));

                if (!errorCodes.contains(ERR_MISSING_REQ)) {
                    errorCodes.add(ERR_MISSING_REQ);
                }
            } else if (fileItem != null) {
                String fileName = FileUtil.getFileName(fileItem);
                Element binaryDataElem = XMLTool.createElement(doc, itemElement, "binarydata", fileName);
                binaryDataElem.setAttribute("key", "%" + fileattachmentCount++);
            }
        }

    }

    HttpServletRequest request = ServletRequestAccessor.getRequest();

    Boolean captchaOk = captchaService.validateCaptcha(formItems, request, "form", "create");
    if ((captchaOk != null) && (!captchaOk)) {
        errorCodes.add(ERR_INVALID_CAPTCHA);
    }

    // If one or more errors occurred, an exception is thrown, containing the errorcodes
    // and the resulting document (that now should include error XML):
    if (errorCodes.size() > 0) {
        throw new FormException(doc, errorCodes.toArray(new Integer[errorCodes.size()]));
    }
}

From source file:org.gvnix.dynamic.configuration.roo.addon.ConfigurationsImpl.java

/**
 * {@inheritDoc}//  w  w  w. ja  v  a  2s.  c  o  m
 */
public DynProperty updateProperty(String configuration, String property, String value) {

    // Get the required property element to update
    Element prop = getProperty(configuration, property);
    if (prop == null) {
        return null;
    }

    // Get the property value element
    Node valueElem = getValueElement(prop);

    if (value == null) {
        if (valueElem != null) {

            // Undefined property value: remove property value element
            prop.removeChild(valueElem);
        }

    } else {

        if (valueElem == null) {

            // Undo undefined property value: Create property value element
            valueElem = prop.getOwnerDocument().createElement(VALUE_ELEMENT_NAME);
            prop.appendChild(valueElem);
        }

        // Set property value
        valueElem.setTextContent(value);
    }

    saveConfiguration(prop);

    return parseProperty(prop);
}