Example usage for org.w3c.dom Element getNextSibling

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

Introduction

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

Prototype

public Node getNextSibling();

Source Link

Document

The node immediately following this node.

Usage

From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

private List<Element> getPlaceHolderContent(Element placeHolderElement, TemplateContext tempalteContext)
        throws Exception {
    String contentId = placeHolderElement.getAttribute(XmlConstants.ATTRIBUTE_ID);
    List<Element> concreteContent = null;
    Document document = tempalteContext.getSourceDocument();

    Element groupStartElement = getGroupStartElement(document, contentId, tempalteContext);
    if (groupStartElement != null) {
        concreteContent = new ArrayList<Element>();
        String nodeName = groupStartElement.getNodeName();
        if (nodeName.equals(XmlConstants.GROUP_START)) {
            boolean groupEndFound = false;
            Node node = groupStartElement.getNextSibling();
            while (true) {
                node = node.getNextSibling();
                if (node == null) {
                    break;
                }/*www .  j a  v a 2 s  .  com*/
                if (node instanceof Element) {
                    Element element = (Element) node;
                    nodeName = element.getNodeName();
                    if (nodeName.equals(XmlConstants.GROUP_END)) {
                        groupEndFound = true;
                        break;
                    } else if (nodeName.equals(XmlConstants.GROUP_START)) {
                        throw new IllegalArgumentException("Nesting <GroupStart> not supported.");
                    } else {
                        concreteContent.add(element);
                    }
                }
            }
            if (!groupEndFound) {
                throw new IllegalArgumentException("<GroupEnd> not found for [" + contentId + "].");
            }
        } else if (nodeName.equals(XmlConstants.GROUP_END)) {
            // do nothing
        } else {
            concreteContent.add(groupStartElement);
        }
    }
    return concreteContent;
}

From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

private List<Element> getImportContent(Element importElement, PreparseContext context) throws Exception {
    String src = importElement.getAttribute("src");

    if (StringUtils.isNotEmpty(src)) {
        Expression expression = expressionHandler.compile(src);
        if (expression != null) {
            src = (String) expression.evaluate();
        }/*from w ww .j a v a2 s  . co  m*/
    }

    if (StringUtils.isEmpty(src)) {
        throw new IllegalArgumentException("Import src undefined");
    }

    int i = src.lastIndexOf('#');
    if (i < 0) {
        throw new IllegalArgumentException("[groupId/componentId] missed");
    }

    String viewName = src.substring(0, i);
    String groupId = src.substring(i + 1);
    Assert.notEmpty(viewName, "Import viewName undefined.");
    Assert.notEmpty(groupId, "Import groupId/componentId undefined.");

    ViewConfigInfo viewConfigInfo = getViewConfigModelInfo(viewName);
    if (viewConfigInfo == null) {
        throw new XmlParseException("Import view not found [" + src + "].", context);
    }

    Document document = (Document) viewConfigInfo.getConfigModel();
    List<Element> importContent = null;
    Element groupStartElement = getGroupStartElement(document, groupId, context);
    if (groupStartElement != null) {
        importContent = new ArrayList<Element>();
        String nodeName = groupStartElement.getNodeName();
        if (nodeName.equals(XmlConstants.GROUP_START)) {
            boolean groupEndFound = false;
            Node node = groupStartElement.getNextSibling();
            while (true) {
                node = node.getNextSibling();
                if (node == null)
                    break;
                if (node instanceof Element) {
                    Element element = (Element) node;
                    nodeName = element.getNodeName();
                    if (nodeName.equals(XmlConstants.GROUP_END)) {
                        groupEndFound = true;
                        break;
                    } else if (nodeName.equals(XmlConstants.GROUP_START)) {
                        throw new IllegalArgumentException("Nesting <GroupStart> not supported.");
                    } else {
                        importContent.add(element);
                    }
                }
            }
            if (!groupEndFound) {
                throw new IllegalArgumentException("<GroupEnd> not found for [" + groupId + "].");
            }
        } else if (nodeName.equals(XmlConstants.GROUP_END) || nodeName.equals(XmlConstants.PLACE_HOLDER)
                || nodeName.equals(XmlConstants.PLACE_HOLDER_START)
                || nodeName.equals(XmlConstants.PLACE_HOLDER_END)) {
            // do nothing
        } else {
            importContent.add(groupStartElement);
        }
    }

    Resource dependentResource = viewConfigInfo.getResource();
    if (dependentResource != null) {
        context.getDependentResources().add(dependentResource);
    }
    return importContent;
}

From source file:com.fota.Link.sdpApi.java

public SDPInfoVO getSpecificSubscpnInfo(String CTN) {
    //String resultStr = null;
    SDPInfoVO resVO = new SDPInfoVO();
    String strIMEI = null;/*  ww  w. ja  va2 s.  c om*/
    String Model_Name = null;
    String return_cd = null;
    try {
        String endPointUrl = PropUtil.getPropValue("sdp.oif114.url");

        String strRequest = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' "
                + "xmlns:oas='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'"
                + " xmlns:sdp='http://kt.com/sdp'>" + "     <soapenv:Header>" + "         <oas:Security>"
                + "             <oas:UsernameToken>" + "                 <oas:Username>"
                + PropUtil.getPropValue("sdp.id") + "</oas:Username>" + "                 <oas:Password>"
                + PropUtil.getPropValue("sdp.pw") + "</oas:Password>" + "             </oas:UsernameToken>"
                + "         </oas:Security>" + "     </soapenv:Header>"

                + "     <soapenv:Body>" + "         <sdp:getSpecificSubscpnInfoRequest>"
                + "         <!--You may enterthe following 6 items in any order-->"

                // + "             <sdp:Credt_Id></sdp:Credt_Id>"
                + "             <sdp:User_Name>" + CTN + "</sdp:User_Name>" + "<sdp:Credt_Type_Cd>" + "05"

                + "</sdp:Credt_Type_Cd>"

                + "         </sdp:getSpecificSubscpnInfoRequest>\n" + "     </soapenv:Body>\n"
                + "</soapenv:Envelope>";

        // connection
        URL url = new URL(endPointUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Content-type", "text/xml;charset=utf-8");
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        // output
        OutputStream os = connection.getOutputStream();
        // os.write(strRequest.getBytes(), 0, strRequest.length());
        os.write(strRequest.getBytes("utf-8"));
        os.flush();
        os.close();

        // input
        InputStream is = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
        String line = null;
        String parseStr = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            parseStr = line;
        }
        //resultStr = line;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource temp = new InputSource();
        temp.setCharacterStream(new StringReader(parseStr));
        Document doc = builder.parse(temp); //xml?

        NodeList list = doc.getElementsByTagName("*");

        int i = 0;
        Element element;
        String contents;
        // sdp:returnCode
        while (list.item(i) != null) {
            element = (Element) list.item(i);
            //System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            //System.out.println(element.getNodeName());
            if (element.hasChildNodes()) {
                contents = element.getFirstChild().getNodeValue();
                //System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55");
                //System.out.println(element.getNodeName());
                //System.out.println(element.getFirstChild().getNodeName());
                if (element.getNodeName().equals("n1:Resource_Unique_Id")) {
                    if (element.getNextSibling().getFirstChild().getNodeValue().equals(("06"))) {
                        //System.out.println("%%%%%%%%%%%%%%%%% FINDFIND!!! %%%%%%%%%%%%%%%%%%%%%%%%%%%55");
                        strIMEI = element.getFirstChild().getNodeValue();

                        //System.out.println("%%%%%%%%%%%%%%%%% FINDFIND!!!  " + strIMEI + "%%%%%%%%%%%%%%%%%%%%%%%%%%%55");
                    }
                    //resultStr = element.getFirstChild().getNodeName();
                }
                if (element.getNodeName().equals("n1:Resource_Model_Name")) {
                    Model_Name = element.getFirstChild().getNodeValue();
                }
                if (element.getNodeName().equals("sdp:returnCode")) {
                    return_cd = element.getFirstChild().getNodeValue();
                }
                //n1:Resource_Model_Name
                System.out.println(contents);
            }
            i++;
        }
        connection.disconnect();

    } catch (Exception e) {
        e.printStackTrace();
    }

    resVO.setModem_model_nm(Model_Name);
    resVO.setImei(strIMEI);
    resVO.setReturn_cd(return_cd);
    return resVO;
}

From source file:it.cnr.icar.eric.common.security.wss4j.WSS4JSignatureSAML.java

/**
 * Compute the Signature over the references.
 * /* w w w .  j  av a  2 s  .co m*/
 * After references are set this method computes the Signature for them.
 * This method can be called any time after the references were set. See
 * <code>addReferencesToSign()</code>.
 * 
 * @throws WSSecurityException
 */
public void computeSignature(List<javax.xml.crypto.dsig.Reference> referenceList, WSSecHeader secHeader,
        Element siblingElement) throws WSSecurityException {
    try {
        java.security.Key key;
        if (senderVouches) {
            key = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPW);
        } else if (secretKey != null) {
            key = WSSecurityUtil.prepareSecretKey(sigAlgo, secretKey);
        } else {
            key = userCrypto.getPrivateKey(user, password);
        }
        SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(sigAlgo, null);
        SignedInfo signedInfo = signatureFactory.newSignedInfo(c14nMethod, signatureMethod, referenceList);

        sig = signatureFactory.newXMLSignature(signedInfo, keyInfo, null,
                getWsConfig().getIdAllocator().createId("SIG-", null), null);

        org.w3c.dom.Element securityHeaderElement = secHeader.getSecurityHeader();
        //
        // Prepend the signature element to the security header (after the assertion)
        //
        XMLSignContext signContext = null;
        if (siblingElement != null && siblingElement.getNextSibling() != null) {
            signContext = new DOMSignContext(key, securityHeaderElement, siblingElement.getNextSibling());
        } else {
            signContext = new DOMSignContext(key, securityHeaderElement);
        }
        signContext.putNamespacePrefix(WSConstants.SIG_NS, WSConstants.SIG_PREFIX);
        if (WSConstants.C14N_EXCL_OMIT_COMMENTS.equals(canonAlgo)) {
            signContext.putNamespacePrefix(WSConstants.C14N_EXCL_OMIT_COMMENTS,
                    WSConstants.C14N_EXCL_OMIT_COMMENTS_PREFIX);
        }
        signContext.setProperty(STRTransform.TRANSFORM_WS_DOC_INFO, wsDocInfo);
        wsDocInfo.setCallbackLookup(callbackLookup);

        // Add the elements to sign to the Signature Context
        wsDocInfo.setTokensOnContext((DOMSignContext) signContext);

        if (secRefSaml != null && secRefSaml.getElement() != null) {
            WSSecurityUtil.storeElementInContext((DOMSignContext) signContext, secRefSaml.getElement());
        }
        if (secRef != null && secRef.getElement() != null) {
            WSSecurityUtil.storeElementInContext((DOMSignContext) signContext, secRef.getElement());
        }
        sig.sign(signContext);

        signatureValue = sig.getSignatureValue().getValue();
    } catch (Exception ex) {
        log.error(ex);
        throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, null, null, ex);
    }
}

From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.general.GeneralConfigConverter.java

/**
 * This method sifts through server.xml to find the AprLifecycleListener. If it exists, but is not defined in the
 * locally cached copy of GeneralConfig, it is stripped out when pushing a new copy of server.xml. If it exists,
 * then the className is forced to the correct fully qualified class name. If it doesn't exist, and IS defined in
 * GeneralConfig, it is added to server.xml.
 *//*from  w  w w. j  a  v a  2  s . c  o  m*/
private void convertAprLifecycleListener(Document document, Element server,
        AprLifecycleListener configuredAprLifecycleListener) {
    Element aprLifecycleListenerXmlElementInServerXml = null;
    Element lastListener = null;
    boolean foundAprLifecycleXmlElementInServerXml = false;

    List<Element> listeners = DomUtils.getChildElementsByTagName(server, TAG_NAME_LISTENER);

    for (Element listener : listeners) {
        lastListener = listener; // We need to catch the last listener, so we can insert before its nextSibling.
        if (isAprLifecycleListener(listener)) {
            foundAprLifecycleXmlElementInServerXml = true;
            aprLifecycleListenerXmlElementInServerXml = listener;
            if (configuredAprLifecycleListener == null) {
                server.removeChild(aprLifecycleListenerXmlElementInServerXml);
            }
        }
    }

    if (configuredAprLifecycleListener != null) {
        if (!foundAprLifecycleXmlElementInServerXml) {
            aprLifecycleListenerXmlElementInServerXml = document.createElement(TAG_NAME_LISTENER);
        }
        aprLifecycleListenerXmlElementInServerXml.setAttribute(ATTRIBUTE_CLASS_NAME,
                CLASS_NAME_APR_LIFECYCLE_LISTENER);
        if (!foundAprLifecycleXmlElementInServerXml) {
            if (lastListener != null) {
                // Strangely, there doesn't appear to be any sort of insertAfter() call, so we have to fetch the
                // next sibling.
                server.insertBefore(aprLifecycleListenerXmlElementInServerXml, lastListener.getNextSibling());
            } else {
                Element globalNamingResources = DomUtils.getChildElementByTagName(server,
                        "GlobalNamingResources");
                server.insertBefore(aprLifecycleListenerXmlElementInServerXml, globalNamingResources);
            }

        }
    }
}

From source file:com.enonic.vertical.adminweb.MenuHandlerServlet.java

private void moveMenuItemDown(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        ExtendedMap formItems) throws VerticalAdminException {

    String menuXML = (String) session.getAttribute("menuxml");
    Document doc = XMLTool.domparse(menuXML);

    String xpath = "/model/menuitems-to-list//menuitem[@key = '" + formItems.getString("key") + "']";
    Element movingMenuItemElement = (Element) XMLTool.selectNode(doc, xpath);

    Element parentElement = (Element) movingMenuItemElement.getParentNode();
    Node nextSiblingElement = movingMenuItemElement.getNextSibling();

    movingMenuItemElement = (Element) parentElement.removeChild(movingMenuItemElement);
    doc.importNode(movingMenuItemElement, true);

    if (nextSiblingElement != null) {
        // spool forward...
        for (nextSiblingElement = nextSiblingElement.getNextSibling(); (nextSiblingElement != null
                && nextSiblingElement
                        .getNodeType() != Node.ELEMENT_NODE); nextSiblingElement = nextSiblingElement
                                .getNextSibling()) {

        }// www .j a va 2 s .c  o m

        if (nextSiblingElement != null) {
            parentElement.insertBefore(movingMenuItemElement, nextSiblingElement);
        } else {
            parentElement.appendChild(movingMenuItemElement);
        }
    } else {
        // This is the bottom element, move it to the top
        parentElement.insertBefore(movingMenuItemElement, parentElement.getFirstChild());
    }

    session.setAttribute("menuxml", XMLTool.documentToString(doc));

    MultiValueMap queryParams = new MultiValueMap();
    queryParams.put("page", formItems.get("page"));
    queryParams.put("op", "browse");
    queryParams.put("keepxml", "yes");
    queryParams.put("highlight", formItems.get("key"));
    queryParams.put("menukey", formItems.get("menukey"));
    queryParams.put("parentmi", formItems.get("parentmi"));
    queryParams.put("subop", "shiftmenuitems");

    queryParams.put("move_menuitem", formItems.getString("move_menuitem", ""));
    queryParams.put("move_from_parent", formItems.getString("move_from_parent", ""));
    queryParams.put("move_to_parent", formItems.getString("move_to_parent", ""));

    redirectClientToAdminPath("adminpage", queryParams, request, response);
}

From source file:com.enonic.vertical.adminweb.AdminHandlerBaseServlet.java

protected Document applyChangesInAccessRights(Document docExistingAccessRights,
        Map<String, ExtendedMap> removedAccessRights, Map<String, ExtendedMap> modifiedAccessRights,
        Map<String, ExtendedMap> addedAccessRights) {

    // We have to make a clone of this hashtable, because we may have to remove some elements
    // and we don't want to affect this on the original hashtable.
    addedAccessRights = new HashMap<String, ExtendedMap>(addedAccessRights);

    //("removedAccessRights = " + removedAccessRights);
    //("modifiedAccessRights = " + modifiedAccessRights);
    //("addedAccessRights = " + addedAccessRights);

    Element elExistingAccessRights = docExistingAccessRights.getDocumentElement();

    //("antall accessrights: " + elExistingAccessRights.getChildNodes().getLength());
    // Loop thru existing accessrights and check if there is anyone to remove or modify
    Element curAccessRight = (Element) elExistingAccessRights.getFirstChild();
    while (curAccessRight != null) {

        String groupKey = curAccessRight.getAttribute("groupkey");
        //("checking accessright, groupkey = " + groupKey);

        boolean remove = removedAccessRights.containsKey(groupKey);
        boolean modify = modifiedAccessRights.containsKey(groupKey);
        boolean add = addedAccessRights.containsKey(groupKey);
        boolean overwrite = (modify || add);

        // Remove accessright
        if (remove) {

            //("removing accessright, groupkey = " + groupKey);
            curAccessRight = XMLTool.removeChildFromParent(elExistingAccessRights, curAccessRight);
        }/*from   www  .  j  a va2 s.  co  m*/
        // Overwrite accessright
        else if (overwrite) {

            ExtendedMap params;
            if (modify) {
                params = modifiedAccessRights.get(groupKey);
                //("modifying/overwriting accessright, groupkey = " + groupKey);
            } else // add == true:
            {
                params = addedAccessRights.get(groupKey);
                //("adding/overwriting accessright, groupkey = " + groupKey);
            }

            Document docNewAccessRight = XMLTool.createDocument("foo");
            Element elNewAccessRight = buildAccessRightElement(docNewAccessRight,
                    docNewAccessRight.getDocumentElement(), groupKey, params);

            Element imported = (Element) docExistingAccessRights.importNode(elNewAccessRight, true);
            elExistingAccessRights.replaceChild(imported, curAccessRight);
            curAccessRight = imported;

            // Hvis vi overskriver eksisterende rettighet i stedet for  legge til, fordi den finnes fra fr
            // m vi fjerne rettigheten fra addedAccessRights, slik at vi ikke legger til den to ganger.
            if (add) {
                //("Found an accessright that we wanted to add, that existed - we overwrite it
                // inseated, and removes the groupkey ("+groupKey+")from the addAccessRights hashtable so that it
                // want be added later");
                addedAccessRights.remove(groupKey);
            }

            //
            curAccessRight = (Element) curAccessRight.getNextSibling();
        } else {
            curAccessRight = (Element) curAccessRight.getNextSibling();
        }
    }
    // Add new accessrights
    for (Object addedAccessRightKey : addedAccessRights.keySet()) {
        String currentGroupKey = (String) addedAccessRightKey;

        //("adding new accessright, groupkey = " + currentGroupKey);

        ExtendedMap params = addedAccessRights.get(currentGroupKey);
        Document docNewAccessRight = XMLTool.createDocument("foo");
        Element elNewAccessRight = buildAccessRightElement(docNewAccessRight,
                docNewAccessRight.getDocumentElement(), currentGroupKey, params);

        elExistingAccessRights.appendChild(docExistingAccessRights.importNode(elNewAccessRight, true));
    }

    return docExistingAccessRights;
}

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;//  w w  w .  j  a v  a  2s .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.enonic.vertical.engine.handlers.MenuHandler.java

private Hashtable<String, Element> appendMenuItemsBySettings(User user, Document doc,
        Hashtable<String, Element> hashtable_menus, MenuGetterSettings getterSettings) {

    Hashtable<String, Element> hashtable_MenuItems = new Hashtable<String, Element>();

    List<Integer> paramValues = new ArrayList<Integer>(2);
    StringBuffer sqlMenuItems = new StringBuffer(MENU_ITEM_SELECT);

    // menuKey/*  ww w . j ava2 s .  c o m*/
    MenuItemCriteria criteria = getterSettings.getMenuItemCriteria();
    if (getterSettings.hasMenuKeys() || criteria.hasMenuKey()) {
        if (getterSettings.hasMenuKeys()) {
            int[] menuKeys = getterSettings.getMenuKeys();
            sqlMenuItems.append(" AND men_lKey IN (");
            for (int i = 0; i < menuKeys.length; i++) {
                if (i > 0) {
                    sqlMenuItems.append(',');
                }
                sqlMenuItems.append(menuKeys[i]);
            }

            sqlMenuItems.append(')');
        } else {
            sqlMenuItems.append(" AND mei_men_lKey = ?");
            paramValues.add(criteria.getMenuKeyAsInteger());
        }
    }
    // only root menuitems
    if (getterSettings.getOnlyRootMenuItems()) {
        sqlMenuItems.append(" AND mei_lParent IS NULL");
    }

    if (user != null) {
        getSecurityHandler().appendMenuItemSQL(user, sqlMenuItems, criteria);
    }

    sqlMenuItems.append(ORDER_BY);

    Connection con = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;

    Element element_AdminReadMenuItems = doc.getDocumentElement();
    try {
        con = getConnection();

        statement = con.prepareStatement(sqlMenuItems.toString());

        int i = 1;
        for (Iterator<Integer> iter = paramValues.iterator(); iter.hasNext(); i++) {
            Object paramValue = iter.next();
            statement.setObject(i, paramValue);
        }

        try {
            // Hender ut menuitems
            resultSet = statement.executeQuery();
            while (resultSet.next()) {

                int curMenuItemKey = resultSet.getInt("mei_lKey");

                Element menuItem = buildMenuItemXML(doc, element_AdminReadMenuItems, resultSet, -1, false,
                        false, true, true, false, 1);
                Element accessRights = XMLTool.createElement(doc, menuItem, "accessrights");
                getSecurityHandler().appendAccessRightsOnMenuItem(user, curMenuItemKey, accessRights, true);

                XMLTool.createElement(doc, menuItem, "menuitems");
                // Lagrer referansen til kategori-elementet for raskt oppslag til senere bruk
                hashtable_MenuItems.put(String.valueOf(curMenuItemKey), menuItem);
            }
        } finally {
            close(resultSet);
            resultSet = null;
            close(statement);
            statement = null;
        }

        // Gr igjennom menuitems og bygger opp trestrukturen
        Element curAdminReadMenuItem = (Element) element_AdminReadMenuItems.getFirstChild();
        while (curAdminReadMenuItem != null) {

            String parentKey = curAdminReadMenuItem.getAttribute("parent");

            Element nextElement = (Element) curAdminReadMenuItem.getNextSibling();

            // Forelder node finnes ikke fra fr
            if ("menuitem".equals(curAdminReadMenuItem.getNodeName())) {
                insertParentMenuItem(user, MENU_ITEM_SELECT_BY_KEY, doc, element_AdminReadMenuItems,
                        hashtable_menus, hashtable_MenuItems, curAdminReadMenuItem, parentKey);
            }

            curAdminReadMenuItem = nextElement;
        }

    } catch (SQLException sqle) {
        String message = "Failed to get menuitems: %t";
        VerticalEngineLogger.error(this.getClass(), 0, message, sqle);
    } finally {
        close(resultSet);
        close(statement);
        close(con);
    }

    return hashtable_MenuItems;
}

From source file:org.apache.servicemix.jbi.deployer.descriptor.DescriptorFactory.java

/**
 * Get the next sibling element/*w w w .  j a  v a2  s .  c o  m*/
 *
 * @param el
 * @return
 */
public static Element getNextSiblingElement(Element el) {
    for (Node n = el.getNextSibling(); n != null; n = n.getNextSibling()) {
        if (n instanceof Element) {
            return (Element) n;
        }
    }
    return null;
}