Example usage for org.w3c.dom Attr getOwnerElement

List of usage examples for org.w3c.dom Attr getOwnerElement

Introduction

In this page you can find the example usage for org.w3c.dom Attr getOwnerElement.

Prototype

public Element getOwnerElement();

Source Link

Document

The Element node this attribute is attached to or null if this attribute is not in use.

Usage

From source file:com.cloudseal.spring.client.namespace.Utility.java

public static void removeNode(final Element rootElement, final String xPathLocation)
        throws XPathExpressionException {
    final XPath xPath = XPathFactory.newInstance().newXPath();
    xPath.setNamespaceContext(new CloudSealNamespaceContext());
    final Node node = (Node) xPath.evaluate(xPathLocation, rootElement, XPathConstants.NODE);
    final short nodeType = node.getNodeType();

    switch (nodeType) {
    case Node.ELEMENT_NODE:
        final Node parent = node.getParentNode();
        parent.removeChild(node);/*from   www . j  ava 2s  .com*/
        break;

    case Node.ATTRIBUTE_NODE:
        final Attr attribute = (Attr) node;
        final Element element = attribute.getOwnerElement();
        element.removeAttributeNode(attribute);
        break;

    default:
        throw new IllegalArgumentException("Not supported node type: " + nodeType);
    }
}

From source file:Main.java

public static String getXPathForElement(Node e, NamespaceContext ctx) {
    StringBuffer sb = new StringBuffer();
    List<Node> path = new ArrayList<Node>();

    Node currentNode = e;/*from w  ww  .jav a  2s.  c  o  m*/
    while (currentNode.getParentNode() != currentNode.getOwnerDocument()) {
        path.add(0, currentNode);
        if (currentNode instanceof Attr) {
            Attr a = (Attr) currentNode;
            currentNode = a.getOwnerElement();
        } else {
            currentNode = currentNode.getParentNode();
        }
    }
    path.add(0, currentNode); // We need the root element

    for (Node n : path) {
        sb.append("/");

        if (n.getNodeType() == Node.ATTRIBUTE_NODE) {
            sb.append("@");
        }

        String namespaceURI = n.getNamespaceURI();
        if (namespaceURI != null && !namespaceURI.equals("")) {
            sb.append(ctx.getPrefix(namespaceURI)).append(":");
        }
        sb.append(n.getLocalName());

        if (n.getNodeType() == Node.ELEMENT_NODE) {
            appendElementQualifier(sb, (Element) n);
        }
    }

    return sb.toString();
}

From source file:Main.java

/**
 * Builds an XPointer that refers to the given node. If a shorthand pointer
 * (using a schema-determined identifier) cannot be constructed, then a
 * scheme-based pointer is derived that indicates the absolute location path
 * of a node in a DOM document. The location is specified as a scheme-based
 * XPointer having two parts://  w  ww  . ja  v a 2 s. c om
 * <ul>
 * <li>an xmlns() part that declares a namespace binding context;</li>
 * <li>an xpointer() part that includes an XPath expression using the
 * abbreviated '//' syntax for selecting a descendant node.</li>
 * </ul>
 * 
 * @param node
 *            A node in a DOM document.
 * @return A String containing either a shorthand or a scheme-based pointer
 *         that refers to the node.
 * 
 * @see <a href="http://www.w3.org/TR/xptr-framework/"target="_blank">
 *      XPointer Framework</a>
 * @see <a href="http://www.w3.org/TR/xptr-xmlns/" target="_blank">XPointer
 *      xmlns() Scheme</a>
 * @see <a href="http://www.w3.org/TR/xptr-xpointer/"
 *      target="_blank">XPointer xpointer() Scheme</a>
 */
public static String buildXPointer(Node node) {
    if (null == node) {
        return "";
    }
    StringBuilder xpointer = new StringBuilder();
    if (null != node.getAttributes() && null != node.getAttributes().getNamedItem("id")) {
        String id = node.getAttributes().getNamedItem("id").getNodeValue();
        xpointer.append(node.getLocalName()).append("[@id='").append(id).append("']");
        return xpointer.toString();
    }
    String nsURI = node.getNamespaceURI();
    String nsPrefix = node.getPrefix();
    if (null == nsPrefix)
        nsPrefix = "tns";
    // WARNING: Escaping rules are currently ignored.
    xpointer.append("xmlns(").append(nsPrefix).append("=").append(nsURI).append(")");
    xpointer.append("xpointer((");
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        // Find the element in the list of all similarly named descendants
        // of the document root.
        NodeList elementsByName = node.getOwnerDocument().getElementsByTagNameNS(nsURI, node.getLocalName());
        for (int i = 0; i < elementsByName.getLength(); i++) {
            if (elementsByName.item(i).isSameNode(node)) {
                xpointer.append("//");
                xpointer.append(nsPrefix).append(':').append(node.getLocalName()).append(")[").append(i + 1)
                        .append("])");
                break;
            }
        }
        break;
    case Node.DOCUMENT_NODE:
        xpointer.append("/");
        break;
    case Node.ATTRIBUTE_NODE:
        Attr attrNode = (Attr) node;
        xpointer = new StringBuilder(buildXPointer(attrNode.getOwnerElement()));
        xpointer.insert(xpointer.lastIndexOf(")"), "/@" + attrNode.getName());
        break;
    default:
        xpointer.setLength(0);
        break;
    }
    return xpointer.toString();
}

From source file:Main.java

/**
 * This method is a tree-search to help prevent against wrapping attacks. It checks that no
 * two Elements have ID Attributes that match the "value" argument, if this is the case then
 * "false" is returned. Note that a return value of "true" does not necessarily mean that
 * a matching Element has been found, just that no wrapping attack has been detected.
 *//*from   w w w . jav a  2s  . c o  m*/
public static boolean protectAgainstWrappingAttack(Node startNode, String value) {
    Node startParent = startNode.getParentNode();
    Node processedNode = null;
    Element foundElement = null;

    String id = value.trim();
    if (id.charAt(0) == '#') {
        id = id.substring(1);
    }

    while (startNode != null) {
        if (startNode.getNodeType() == Node.ELEMENT_NODE) {
            Element se = (Element) startNode;

            NamedNodeMap attributes = se.getAttributes();
            if (attributes != null) {
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr attr = (Attr) attributes.item(i);
                    if (attr.isId() && id.equals(attr.getValue())) {
                        if (foundElement == null) {
                            // Continue searching to find duplicates
                            foundElement = attr.getOwnerElement();
                        } else {
                            //log.debug("Multiple elements with the same 'Id' attribute value!");
                            return false;
                        }
                    }
                }
            }
        }

        processedNode = startNode;
        startNode = startNode.getFirstChild();

        // no child, this node is done.
        if (startNode == null) {
            // close node processing, get sibling
            startNode = processedNode.getNextSibling();
        }

        // no more siblings, get parent, all children
        // of parent are processed.
        while (startNode == null) {
            processedNode = processedNode.getParentNode();
            if (processedNode == startParent) {
                return true;
            }
            // close parent node processing (processed node now)
            startNode = processedNode.getNextSibling();
        }
    }
    return true;
}

From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivityXmlParser.java

/**
 * Resolves DOM node contained textual data and formats it using provided locator.
 *
 * @param locator/*w w  w. j  ava2 s  .c  om*/
 *            locator instance to alter using XML attributes contained data type, format and units used to format
 *            resolved value
 * @param node
 *            DOM node to collect textual data
 * @return resolved textual value formatted based on the locator's formatting properties
 * @throws ParseException
 *             if exception occurs applying locator format properties to specified value
 */
protected static Object getTextContent(ActivityFieldLocator locator, Node node) throws ParseException {
    String strValue = node.getTextContent();
    Node attrsNode = node;

    if (node instanceof Attr) {
        Attr attr = (Attr) node;

        attrsNode = attr.getOwnerElement();
    }

    // Get list of attributes and their values for
    // current element
    NamedNodeMap attrsMap = attrsNode == null ? null : attrsNode.getAttributes();

    Node attr;
    String attrVal;
    ActivityFieldLocator locCopy = locator.clone();
    if (attrsMap != null && attrsMap.getLength() > 0) {
        attr = attrsMap.getNamedItem(DATA_TYPE_ATTR);
        attrVal = attr == null ? null : attr.getTextContent();
        if (StringUtils.isNotEmpty(attrVal)) {
            locCopy.setDataType(ActivityFieldDataType.valueOf(attrVal));
        }

        attr = attrsMap.getNamedItem(FORMAT_ATTR);
        attrVal = attr == null ? null : attr.getTextContent();
        if (StringUtils.isNotEmpty(attrVal)) {
            attr = attrsMap.getNamedItem(LOCALE_ATTR);
            String attrLVal = attr == null ? null : attr.getTextContent();

            locCopy.setFormat(attrVal, StringUtils.isEmpty(attrLVal) ? locator.getLocale() : attrLVal);
        }

        attr = attrsMap.getNamedItem(UNITS_ATTR);
        attrVal = attr == null ? null : attr.getTextContent();
        if (StringUtils.isNotEmpty(attrVal)) {
            locCopy.setUnits(attrVal);
        }
    }

    return locCopy.formatValue(strValue.trim());
}

From source file:org.dozer.eclipse.plugin.sourcepage.hyperlink.DozerClassHyperlinkDetector.java

public boolean isLinkableAttr(Attr attr) {
    String attrName = attr.getName();
    String ownerName = attr.getOwnerElement().getNodeName();
    String parentName = attr.getOwnerElement().getParentNode().getNodeName();

    if ("bean-factory".equals(attrName))
        return true;
    else if ("field".equals(ownerName)) {
        if ("custom-converter".equals(attrName) || "custom-converter-id".equals(attrName))
            return true;
    } else if ("field".equals(parentName)) {
        if ("set-method".equals(attrName) || "get-method".equals(attrName) || "map-set-method".equals(attrName)
                || "map-get-method".equals(attrName))
            return true;
    }//from w  ww.j av a 2s .  com

    return false;
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

private static Node getParentNode(Node node) {
    if (node instanceof Attr) {
        Attr attr = (Attr) node;
        return attr.getOwnerElement();
    } else {/*from w  w w .j a  v  a2  s.c om*/
        return node.getParentNode();
    }
}

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

/**
 * Compute the xpath of a node relative to an anchor.
 * // w  w w  . j ava  2 s  . c  o  m
 * @param node
 *            node to find the xpath from.
 * @param anchor
 *            the relative point to fid from.
 * @return the computed xpath.
 */
public static String calcXpath(Node node, Node anchor) {
    String xpath = "";
    Node current = null;

    if (node == null || node.equals(anchor))
        return "";

    // add attribute to xpath
    if (node instanceof Attr) {
        Attr attr = (Attr) node;
        node = attr.getOwnerElement();
        xpath = '@' + attr.getName() + '/';
    }

    while ((current = node.getParentNode()) != anchor) {
        Engine.logEngine.trace("Calc Xpath : current node : " + current.getNodeName());
        NodeList childs = current.getChildNodes();
        int index = 0;
        for (int i = 0; i < childs.getLength(); i++) {
            if (childs.item(i).getNodeType() != Node.ELEMENT_NODE
                    && !childs.item(i).getNodeName().equalsIgnoreCase("#text"))
                continue;

            Engine.logEngine.trace("Calc Xpath : ==== > Child node : " + childs.item(i).getNodeName());

            // Bump the index if we have the same tag names..
            if (childs.item(i).getNodeName().equalsIgnoreCase(node.getNodeName())) {
                // tag names are equal ==> bump the index.
                index++;
                // is our node the one that is listed ?
                if (childs.item(i).equals(node))
                    // We found our node in the parent node list
                    break;
            }
        }
        // count the number of elements having the same tag
        int nbElements = 0;
        for (int i = 0; i < childs.getLength(); i++) {
            if (childs.item(i).getNodeName().equalsIgnoreCase(node.getNodeName())) {
                nbElements++;
            }
        }

        String name = node.getNodeName();
        if (name.equalsIgnoreCase("#text"))
            name = "text()";
        name = xpathEscapeColon(name);

        if (nbElements > 1) {
            xpath = name + "[" + index + "]/" + xpath;
        } else {
            // only one element had the same tag ==> do not compute the [xx]
            // syntax..
            xpath = name + "/" + xpath;
        }
        node = current;
    }
    if (xpath.length() > 0)
        // remove the trailing '/'
        xpath = xpath.substring(0, xpath.length() - 1);

    return xpath;
}

From source file:de.betterform.xml.xforms.model.Instance.java

/**
 * Deletes the specified node./*from   ww w . ja  v  a2  s. c  om*/
 *
 * @param path the path pointing to the node to be deleted.
 */
public boolean deleteNode(Node node, String path) throws XFormsException {
    String canonicalPath = DOMUtil.getCanonicalPath(node);
    if (node == null) {
        LOGGER.warn("Node is null - delete is terminated with no effect.");
        return false;
    }

    //don't delete readonly nodes
    if (isReadonly(node)) {
        LOGGER.warn("Node or one of it's parents is readonly - delete is terminated with no effect.");
        return false;
    }

    //don't delete content of a xmlns Attribute - not clear what Spec means by not allowing to delete a namespace node
    if (node.getNodeName().startsWith("xmlns")) {
        LOGGER.warn("Node is Namespace declaration - delete is terminated with no effect.");
        return false;
    }

    //don't delete root nodes
    if (node.getNodeType() != Node.ATTRIBUTE_NODE && node.getParentNode().getNodeType() == Node.DOCUMENT_NODE) {
        LOGGER.warn("Node is a root Node - delete is terminated with no effect.");
        return false;
    }

    //don't delete document nodes
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        LOGGER.warn("Node is a Document Node - delete is terminated with no effect.");
        return false;
    }

    Node canonNode = node;

    if (node.getNodeType() != Node.ATTRIBUTE_NODE) {
        node.getParentNode().removeChild(node);
    } else {
        Attr attr = (Attr) node;
        attr.getOwnerElement().removeAttributeNode(attr);
    }

    // dispatch internal betterform event (for instant repeat updating)
    String[] canonicalParts = XPathUtil.getNodesetAndPredicates(path);
    HashMap map = new HashMap();
    map.put("nodeset", canonicalParts[0]);
    map.put("position", canonicalParts[canonicalParts.length - 1]);
    map.put("canonPath", canonicalPath);
    this.container.dispatch(this.target, BetterFormEventNames.NODE_DELETED, map);

    if (getLogger().isDebugEnabled()) {
        getLogger().debug(
                this + " delete node: instance data after manipulation" + toString(this.instanceDocument));
    }
    return true;
}

From source file:com.rapid.server.Designer.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    RapidRequest rapidRequest = new RapidRequest(this, request);

    try {//from  w ww.  ja  v a2  s. co m

        String output = "";

        // read bytes from request body into our own byte array (this means we can deal with images) 
        InputStream input = request.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        for (int length = 0; (length = input.read(_byteBuffer)) > -1;)
            outputStream.write(_byteBuffer, 0, length);
        byte[] bodyBytes = outputStream.toByteArray();

        // get the rapid application
        Application rapidApplication = getApplications().get("rapid");

        // check we got one
        if (rapidApplication != null) {

            // get rapid security
            SecurityAdapter rapidSecurity = rapidApplication.getSecurityAdapter();

            // check we got some
            if (rapidSecurity != null) {

                // get user name
                String userName = rapidRequest.getUserName();
                if (userName == null)
                    userName = "";

                // check permission
                if (rapidSecurity.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)) {

                    Application application = rapidRequest.getApplication();

                    if (application != null) {

                        if ("savePage".equals(rapidRequest.getActionName())) {

                            String bodyString = new String(bodyBytes, "UTF-8");

                            getLogger().debug("Designer POST request : " + request.getQueryString() + " body : "
                                    + bodyString);

                            JSONObject jsonPage = new JSONObject(bodyString);

                            // instantiate a new blank page
                            Page newPage = new Page();

                            // set page properties
                            newPage.setId(jsonPage.optString("id"));
                            newPage.setName(jsonPage.optString("name"));
                            newPage.setTitle(jsonPage.optString("title"));
                            newPage.setFormPageType(jsonPage.optInt("formPageType"));
                            newPage.setLabel(jsonPage.optString("label"));
                            newPage.setDescription(jsonPage.optString("description"));
                            newPage.setSimple(jsonPage.optBoolean("simple"));

                            // look in the JSON for an event array
                            JSONArray jsonEvents = jsonPage.optJSONArray("events");
                            // add the events if we found one
                            if (jsonEvents != null)
                                newPage.setEvents(Control.getEvents(this, jsonEvents));

                            // look in the JSON for a styles array
                            JSONArray jsonStyles = jsonPage.optJSONArray("styles");
                            // if there were styles
                            if (jsonStyles != null)
                                newPage.setStyles(Control.getStyles(this, jsonStyles));

                            // if there are child controls from the page loop them and add to the pages control collection
                            JSONArray jsonControls = jsonPage.optJSONArray("childControls");
                            if (jsonControls != null) {
                                for (int i = 0; i < jsonControls.length(); i++) {
                                    // get the JSON control
                                    JSONObject jsonControl = jsonControls.getJSONObject(i);
                                    // call our function so it can go iterative
                                    newPage.addControl(createControl(jsonControl));
                                }
                            }

                            // if there are roles specified for this page
                            JSONArray jsonUserRoles = jsonPage.optJSONArray("roles");
                            if (jsonUserRoles != null) {
                                List<String> userRoles = new ArrayList<String>();
                                for (int i = 0; i < jsonUserRoles.length(); i++) {
                                    // get the JSON role
                                    String jsonUserRole = jsonUserRoles.getString(i);
                                    // add to collection
                                    userRoles.add(jsonUserRole);
                                }
                                // assign to page
                                newPage.setRoles(userRoles);
                            }

                            // look in the JSON for a sessionVariables array
                            JSONArray jsonSessionVariables = jsonPage.optJSONArray("sessionVariables");
                            // if we found one
                            if (jsonSessionVariables != null) {
                                List<String> sessionVariables = new ArrayList<String>();
                                for (int i = 0; i < jsonSessionVariables.length(); i++) {
                                    sessionVariables.add(jsonSessionVariables.getString(i));
                                }
                                newPage.setSessionVariables(sessionVariables);
                            }

                            // look in the JSON for a pageVisibilityRules array
                            JSONArray jsonVisibilityConditions = jsonPage.optJSONArray("visibilityConditions");
                            // if we found one
                            if (jsonVisibilityConditions != null) {
                                List<Condition> visibilityConditions = new ArrayList<Condition>();
                                for (int i = 0; i < jsonVisibilityConditions.length(); i++) {
                                    visibilityConditions
                                            .add(new Condition(jsonVisibilityConditions.getJSONObject(i)));
                                }
                                newPage.setVisibilityConditions(visibilityConditions);
                            }

                            // look in the JSON for a pageVisibilityRules array is an and or or (default to and)
                            String jsonConditionsType = jsonPage.optString("conditionsType", "and");
                            // set what we got
                            newPage.setConditionsType(jsonConditionsType);

                            // retrieve the html body
                            String htmlBody = jsonPage.optString("htmlBody");
                            // if we got one trim it and retain in page
                            if (htmlBody != null)
                                newPage.setHtmlBody(htmlBody.trim());

                            // look in the JSON for rolehtml
                            JSONArray jsonRolesHtml = jsonPage.optJSONArray("rolesHtml");
                            // if we found some
                            if (jsonRolesHtml != null) {
                                // instantiate the roles html collection
                                ArrayList<Page.RoleHtml> rolesHtml = new ArrayList<Page.RoleHtml>();
                                // loop the entries
                                for (int i = 0; i < jsonRolesHtml.length(); i++) {
                                    // get the entry
                                    JSONObject jsonRoleHtml = jsonRolesHtml.getJSONObject(i);
                                    // retain the html
                                    String html = jsonRoleHtml.optString("html");
                                    // trim it if there is one
                                    if (html != null)
                                        html = html.trim();
                                    // create an array to hold the roles
                                    ArrayList<String> roles = new ArrayList<String>();
                                    // get the roles
                                    JSONArray jsonRoles = jsonRoleHtml.optJSONArray("roles");
                                    // if we got some
                                    if (jsonRoles != null) {
                                        // loop them
                                        for (int j = 0; j < jsonRoles.length(); j++) {
                                            // get the role
                                            String role = jsonRoles.getString(j);
                                            // add it to the roles collections
                                            roles.add(role);
                                        }
                                    }
                                    // create and add a new roleHtml  object
                                    rolesHtml.add(new Page.RoleHtml(roles, html));
                                }
                                // add it to the page
                                newPage.setRolesHtml(rolesHtml);
                            }

                            // fetch a copy of the old page (if there is one)
                            Page oldPage = application.getPages().getPage(getServletContext(), newPage.getId());
                            // if the page's name changed we need to remove it
                            if (oldPage != null) {
                                if (!oldPage.getName().equals(newPage.getName())) {
                                    oldPage.delete(this, rapidRequest, application);
                                }
                            }

                            // save the new page to file
                            newPage.save(this, rapidRequest, application, true);

                            // get any pages collection (we're only sent it if it's been changed)
                            JSONArray jsonPages = jsonPage.optJSONArray("pages");
                            // if we got some
                            if (jsonPages != null) {
                                // make a new map for the page orders
                                Map<String, Integer> pageOrders = new HashMap<String, Integer>();
                                // loop the page orders
                                for (int i = 0; i < jsonPages.length(); i++) {
                                    // add the order to the map
                                    pageOrders.put(jsonPages.getJSONObject(i).getString("id"), i);
                                }
                                // replace the application pageOrders map
                                application.setPageOrders(pageOrders);
                                // save the application and the new orders
                                application.save(this, rapidRequest, true);
                            }
                            boolean jsonPageOrderReset = jsonPage.optBoolean("pageOrderReset");
                            if (jsonPageOrderReset) {
                                // empty the application pageOrders map so everything goes alphabetical
                                application.setPageOrders(null);
                            }

                            // send a positive message
                            output = "{\"message\":\"Saved!\"}";

                            // set the response type to json
                            response.setContentType("application/json");

                        } else if ("testSQL".equals(rapidRequest.getActionName())) {

                            // turn the body bytes into a string
                            String bodyString = new String(bodyBytes, "UTF-8");

                            JSONObject jsonQuery = new JSONObject(bodyString);

                            JSONArray jsonInputs = jsonQuery.optJSONArray("inputs");

                            JSONArray jsonOutputs = jsonQuery.optJSONArray("outputs");

                            Parameters parameters = new Parameters();

                            if (jsonInputs != null) {

                                for (int i = 0; i < jsonInputs.length(); i++)
                                    parameters.addNull();

                            }

                            DatabaseConnection databaseConnection = application.getDatabaseConnections()
                                    .get(jsonQuery.optInt("databaseConnectionIndex", 0));

                            ConnectionAdapter ca = databaseConnection.getConnectionAdapter(getServletContext(),
                                    application);

                            DataFactory df = new DataFactory(ca);

                            int outputs = 0;

                            if (jsonOutputs != null)
                                outputs = jsonOutputs.length();

                            String sql = jsonQuery.getString("SQL");
                            // some jdbc drivers need the line breaks removing before they'll work properly - here's looking at you MS SQL Server!
                            sql = sql.replace("\n", " ");

                            if (outputs == 0) {

                                df.getPreparedStatement(rapidRequest, sql, parameters);

                            } else {

                                ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters);

                                ResultSetMetaData rsmd = rs.getMetaData();

                                int cols = rsmd.getColumnCount();

                                if (outputs > cols)
                                    throw new Exception(outputs + " outputs, but only " + cols + " column"
                                            + (cols > 1 ? "s" : "") + " selected");

                                for (int i = 0; i < outputs; i++) {

                                    JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                                    String field = jsonOutput.optString("field", "");

                                    if (!"".equals(field)) {

                                        field = field.toLowerCase();

                                        boolean gotOutput = false;

                                        for (int j = 0; j < cols; j++) {

                                            String sqlField = rsmd.getColumnLabel(j + 1).toLowerCase();

                                            if (field.equals(sqlField)) {
                                                gotOutput = true;
                                                break;
                                            }

                                        }

                                        if (!gotOutput) {
                                            rs.close();
                                            df.close();
                                            throw new Exception("Field \"" + field + "\" from output " + (i + 1)
                                                    + " is not present in selected columns");
                                        }

                                    }

                                }

                                // close the recordset
                                rs.close();
                                // close the data factory
                                df.close();

                            }

                            // send a positive message
                            output = "{\"message\":\"OK\"}";

                            // set the response type to json
                            response.setContentType("application/json");

                        } else if ("uploadImage".equals(rapidRequest.getActionName())
                                || "import".equals(rapidRequest.getActionName())) {

                            // get the content type from the request
                            String contentType = request.getContentType();
                            // get the position of the boundary from the content type
                            int boundaryPosition = contentType.indexOf("boundary=");
                            // derive the start of the meaning data by finding the boundary
                            String boundary = contentType.substring(boundaryPosition + 10);
                            // this is the double line break after which the data occurs
                            byte[] pattern = { 0x0D, 0x0A, 0x0D, 0x0A };
                            // find the position of the double line break
                            int dataPosition = Bytes.findPattern(bodyBytes, pattern);
                            // the body header is everything up to the data
                            String header = new String(bodyBytes, 0, dataPosition, "UTF-8");
                            // find the position of the filename in the data header
                            int filenamePosition = header.indexOf("filename=\"");
                            // extract the file name
                            String filename = header.substring(filenamePosition + 10,
                                    header.indexOf("\"", filenamePosition + 10));
                            // find the position of the file type in the data header
                            int fileTypePosition = header.toLowerCase().indexOf("type:");
                            // extract the file type
                            String fileType = header.substring(fileTypePosition + 6);

                            if ("uploadImage".equals(rapidRequest.getActionName())) {

                                // check the file type
                                if (!fileType.equals("image/jpeg") && !fileType.equals("image/gif")
                                        && !fileType.equals("image/png"))
                                    throw new Exception("Unsupported file type");

                                // get the web folder from the application
                                String path = rapidRequest.getApplication().getWebFolder(getServletContext());
                                // create a file output stream to save the data to
                                FileOutputStream fos = new FileOutputStream(path + "/" + filename);
                                // write the file data to the stream
                                fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length
                                        - dataPosition - pattern.length - boundary.length() - 9);
                                // close the stream
                                fos.close();

                                // log the file creation
                                getLogger().debug("Saved image file " + path + filename);

                                // create the response with the file name and upload type
                                output = "{\"file\":\"" + filename + "\",\"type\":\""
                                        + rapidRequest.getActionName() + "\"}";

                            } else if ("import".equals(rapidRequest.getActionName())) {

                                // check the file type
                                if (!"application/x-zip-compressed".equals(fileType)
                                        && !"application/zip".equals(fileType))
                                    throw new Exception("Unsupported file type");

                                // get the name
                                String appName = request.getParameter("name");

                                // check we were given one
                                if (appName == null)
                                    throw new Exception("Name must be provided");

                                // get the version
                                String appVersion = request.getParameter("version");

                                // check we were given one
                                if (appVersion == null)
                                    throw new Exception("Version must be provided");

                                // make the id from the safe and lower case name
                                String appId = Files.safeName(appName).toLowerCase();

                                // make the version from the safe and lower case name
                                appVersion = Files.safeName(appVersion);

                                // get application destination folder
                                File appFolderDest = new File(
                                        Application.getConfigFolder(getServletContext(), appId, appVersion));
                                // get web contents destination folder
                                File webFolderDest = new File(
                                        Application.getWebFolder(getServletContext(), appId, appVersion));

                                // look for an existing application of this name and version
                                Application existingApplication = getApplications().get(appId, appVersion);
                                // if we have an existing application 
                                if (existingApplication != null) {
                                    // back it up first
                                    existingApplication.backup(this, rapidRequest, false);
                                }

                                // get a file for the temp directory
                                File tempDir = new File(getServletContext().getRealPath("/WEB-INF/temp"));
                                // create it if not there
                                if (!tempDir.exists())
                                    tempDir.mkdir();

                                // the path we're saving to is the temp folder
                                String path = getServletContext()
                                        .getRealPath("/WEB-INF/temp/" + appId + ".zip");
                                // create a file output stream to save the data to
                                FileOutputStream fos = new FileOutputStream(path);
                                // write the file data to the stream
                                fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length
                                        - dataPosition - pattern.length - boundary.length() - 9);
                                // close the stream
                                fos.close();

                                // log the file creation
                                getLogger().debug("Saved import file " + path);

                                // get a file object for the zip file
                                File zipFile = new File(path);
                                // load it into a zip file object
                                ZipFile zip = new ZipFile(zipFile);
                                // unzip the file
                                zip.unZip();
                                // delete the zip file
                                zipFile.delete();

                                // unzip folder (for deletion)
                                File unZipFolder = new File(
                                        getServletContext().getRealPath("/WEB-INF/temp/" + appId));
                                // get application folders
                                File appFolderSource = new File(
                                        getServletContext().getRealPath("/WEB-INF/temp/" + appId + "/WEB-INF"));
                                // get web content folders
                                File webFolderSource = new File(getServletContext()
                                        .getRealPath("/WEB-INF/temp/" + appId + "/WebContent"));

                                // check we have the right source folders
                                if (webFolderSource.exists() && appFolderSource.exists()) {

                                    // get application.xml file
                                    File appFileSource = new File(appFolderSource + "/application.xml");

                                    if (appFileSource.exists()) {

                                        // delete the appFolder if it exists
                                        if (appFolderDest.exists())
                                            Files.deleteRecurring(appFolderDest);
                                        // delete the webFolder if it exists
                                        if (webFolderDest.exists())
                                            Files.deleteRecurring(webFolderDest);

                                        // copy application content
                                        Files.copyFolder(appFolderSource, appFolderDest);

                                        // copy web content
                                        Files.copyFolder(webFolderSource, webFolderDest);

                                        try {

                                            // load the new application (but don't initialise, nor load pages)
                                            Application appNew = Application.load(getServletContext(),
                                                    new File(appFolderDest + "/application.xml"), false);

                                            // update application name
                                            appNew.setName(appName);

                                            // get the old id
                                            String appOldId = appNew.getId();

                                            // make the new id
                                            appId = Files.safeName(appName).toLowerCase();

                                            // update the id
                                            appNew.setId(appId);

                                            // get the old version
                                            String appOldVersion = appNew.getVersion();

                                            // make the new version
                                            appVersion = Files.safeName(appVersion);

                                            // update the version
                                            appNew.setVersion(appVersion);

                                            // update the created date
                                            appNew.setCreatedDate(new Date());

                                            // set the status to In development
                                            appNew.setStatus(Application.STATUS_DEVELOPMENT);

                                            // a map of actions that might be removed from any of the pages
                                            Map<String, Integer> removedActions = new HashMap<String, Integer>();

                                            // look for page files
                                            File pagesFolder = new File(
                                                    appFolderDest.getAbsolutePath() + "/pages");
                                            // if the folder is there
                                            if (pagesFolder.exists()) {

                                                // create a filter for finding .page.xml files
                                                FilenameFilter xmlFilenameFilter = new FilenameFilter() {
                                                    public boolean accept(File dir, String name) {
                                                        return name.toLowerCase().endsWith(".page.xml");
                                                    }
                                                };

                                                // loop the .page.xml files 
                                                for (File pageFile : pagesFolder.listFiles(xmlFilenameFilter)) {

                                                    BufferedReader reader = new BufferedReader(
                                                            new InputStreamReader(new FileInputStream(pageFile),
                                                                    "UTF-8"));
                                                    String line = null;
                                                    StringBuilder stringBuilder = new StringBuilder();

                                                    while ((line = reader.readLine()) != null) {
                                                        stringBuilder.append(line);
                                                        stringBuilder.append("\n");
                                                    }
                                                    reader.close();

                                                    // retrieve the xml into a string
                                                    String fileString = stringBuilder.toString();

                                                    // prepare a new file string which will update into
                                                    String newFileString = null;

                                                    // if the old app did not have a version (for backwards compatibility)
                                                    if (appOldVersion == null) {

                                                        // replace all properties that appear to have a url, and all created links - note the fix for cleaning up the double encoding
                                                        newFileString = fileString
                                                                .replace("applications/" + appOldId + "/",
                                                                        "applications/" + appId + "/"
                                                                                + appVersion + "/")
                                                                .replace("~?a=" + appOldId + "&amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;")
                                                                .replace("~?a=" + appOldId + "&amp;amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;");

                                                    } else {

                                                        // replace all properties that appear to have a url, and all created links - note the fix for double encoding 
                                                        newFileString = fileString
                                                                .replace(
                                                                        "applications/" + appOldId + "/"
                                                                                + appOldVersion + "/",
                                                                        "applications/" + appId + "/"
                                                                                + appVersion + "/")
                                                                .replace(
                                                                        "~?a=" + appOldId + "&amp;v="
                                                                                + appOldVersion + "&amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;")
                                                                .replace(
                                                                        "~?a=" + appOldId + "&amp;amp;v="
                                                                                + appOldVersion + "&amp;amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;");
                                                    }

                                                    // now open the string into a document
                                                    Document pageDocument = XML.openDocument(newFileString);
                                                    // get an xpath factory
                                                    XPathFactory xPathfactory = XPathFactory.newInstance();
                                                    XPath xpath = xPathfactory.newXPath();
                                                    // an expression for any attributes with a local name of "type"
                                                    XPathExpression expr = xpath
                                                            .compile("//@*[local-name()='type']");
                                                    // get them
                                                    NodeList nl = (NodeList) expr.evaluate(pageDocument,
                                                            XPathConstants.NODESET);
                                                    // get out system actions
                                                    JSONArray jsonActions = getJsonActions();
                                                    // if we found any elements with a type attribute and we have system actions
                                                    if (nl.getLength() > 0 && jsonActions.length() > 0) {
                                                        // a list of action types
                                                        List<String> types = new ArrayList<String>();
                                                        // loop the json actions
                                                        for (int i = 0; i < jsonActions.length(); i++)
                                                            types.add(jsonActions.getJSONObject(i)
                                                                    .optString("type").toLowerCase());
                                                        // loop the action attributes we found
                                                        for (int i = 0; i < nl.getLength(); i++) {
                                                            // get this attribute
                                                            Attr a = (Attr) nl.item(i);
                                                            // get the value of the type 
                                                            String type = a.getTextContent().toLowerCase();
                                                            // get the element the attribute is in
                                                            Node n = a.getOwnerElement();
                                                            // if we don't know about this action type
                                                            if (!types.contains(type)) {
                                                                // get the parent node
                                                                Node p = n.getParentNode();
                                                                // remove this node
                                                                p.removeChild(n);
                                                                // if we have removed this type already
                                                                if (removedActions.containsKey(type)) {
                                                                    // increment the entry for this type
                                                                    removedActions.put(type,
                                                                            removedActions.get(type) + 1);
                                                                } else {
                                                                    // add an entry for this type
                                                                    removedActions.put(type, 1);
                                                                }
                                                            } // got type check                                                                                                                                             
                                                        } // attribute loop

                                                    } // attribute and system action check

                                                    // use the transformer to write to disk
                                                    TransformerFactory transformerFactory = TransformerFactory
                                                            .newInstance();
                                                    Transformer transformer = transformerFactory
                                                            .newTransformer();
                                                    DOMSource source = new DOMSource(pageDocument);
                                                    StreamResult result = new StreamResult(pageFile);
                                                    transformer.transform(source, result);

                                                } // page xml file loop

                                            } // pages folder check

                                            // now initialise with the new id but don't make the resource files (this reloads the pages and sets up the security adapter)
                                            appNew.initialise(getServletContext(), false);

                                            // get the security for this application
                                            SecurityAdapter security = appNew.getSecurityAdapter();

                                            // if we have one
                                            if (security != null) {

                                                // assume we don't have the user
                                                boolean gotUser = false;
                                                // get the current users record from the adapter
                                                User user = security.getUser(rapidRequest);
                                                // check the current user is present in the app's security adapter
                                                if (user != null) {
                                                    // now check the current user password is correct too
                                                    if (security.checkUserPassword(rapidRequest, userName,
                                                            rapidRequest.getUserPassword())) {
                                                        // we have the right user with the right password
                                                        gotUser = true;
                                                    } else {
                                                        // remove this user as the password does not match
                                                        security.deleteUser(rapidRequest);
                                                    }
                                                }

                                                // if we don't have the user
                                                if (!gotUser) {
                                                    // get the current user from the Rapid application
                                                    User rapidUser = rapidSecurity.getUser(rapidRequest);
                                                    // create a new user based on the Rapid user
                                                    user = new User(userName, rapidUser.getDescription(),
                                                            rapidUser.getPassword());
                                                    // add the new user 
                                                    security.addUser(rapidRequest, user);
                                                }

                                                // add Admin and Design roles for the new user if required
                                                if (!security.checkUserRole(rapidRequest,
                                                        com.rapid.server.Rapid.ADMIN_ROLE))
                                                    security.addUserRole(rapidRequest,
                                                            com.rapid.server.Rapid.ADMIN_ROLE);

                                                if (!security.checkUserRole(rapidRequest,
                                                        com.rapid.server.Rapid.DESIGN_ROLE))
                                                    security.addUserRole(rapidRequest,
                                                            com.rapid.server.Rapid.DESIGN_ROLE);
                                            }

                                            // if any items were removed
                                            if (removedActions.keySet().size() > 0) {
                                                // a description of what was removed
                                                String removed = "";
                                                // loop the entries
                                                for (String type : removedActions.keySet()) {
                                                    int count = removedActions.get(type);
                                                    removed += "removed " + count + " " + type + " action"
                                                            + (count == 1 ? "" : "s") + " on import\n";
                                                }
                                                // get the current description
                                                String description = appNew.getDescription();
                                                // if null set to empty string
                                                if (description == null)
                                                    description = "";
                                                // add a line break if need be
                                                if (description.length() > 0)
                                                    description += "\n";
                                                // add the removed
                                                description += removed;
                                                // set it back
                                                appNew.setDescription(description);
                                            }

                                            // reload the pages (actually clears down the pages collection and reloads the headers)
                                            appNew.getPages().loadpages(getServletContext());

                                            // save application (this will also initialise and rebuild the resources)
                                            appNew.save(this, rapidRequest, false);

                                            // add application to the collection
                                            getApplications().put(appNew);

                                            // delete unzip folder
                                            Files.deleteRecurring(unZipFolder);

                                            // send a positive message
                                            output = "{\"id\":\"" + appNew.getId() + "\",\"version\":\""
                                                    + appNew.getVersion() + "\"}";

                                        } catch (Exception ex) {

                                            // delete the appFolder if it exists
                                            if (appFolderDest.exists())
                                                Files.deleteRecurring(appFolderDest);
                                            // if the parent is empty delete it too
                                            if (appFolderDest.getParentFile().list().length <= 1)
                                                Files.deleteRecurring(appFolderDest.getParentFile());

                                            // delete the webFolder if it exists
                                            if (webFolderDest.exists())
                                                Files.deleteRecurring(webFolderDest);
                                            // if the parent is empty delete it too
                                            if (webFolderDest.getParentFile().list().length <= 1)
                                                Files.deleteRecurring(webFolderDest.getParentFile());

                                            // rethrow exception
                                            throw ex;

                                        }

                                    } else {

                                        // delete unzip folder
                                        Files.deleteRecurring(unZipFolder);

                                        // throw excpetion
                                        throw new Exception("Must be a valid Rapid " + Rapid.VERSION + " file");

                                    }

                                } else {

                                    // delete unzip folder
                                    Files.deleteRecurring(unZipFolder);

                                    // throw excpetion
                                    throw new Exception("Must be a valid Rapid file");

                                }

                            }

                        }

                        getLogger().debug("Designer POST response : " + output);

                        PrintWriter out = response.getWriter();
                        out.print(output);
                        out.close();

                    } // got an application

                } // got rapid design role

            } // got rapid security

        } // got rapid application

    } catch (Exception ex) {

        getLogger().error("Designer POST error : ", ex);

        sendException(rapidRequest, response, ex);

    }

}