List of usage examples for org.w3c.dom Node getNextSibling
public Node getNextSibling();
From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java
/** * Find the next sibling at DOM level of the given XAdES DOM element. * /* w w w. j av a2 s . c om*/ * @param xadesElement * @param namespace * @param localName * @param jaxbType * @return * @throws XAdESValidationException */ public static <T> T findNextSibling(Element xadesElement, String namespace, String localName, Class<T> jaxbType) throws XAdESValidationException { Node siblingNode = xadesElement.getNextSibling(); while (siblingNode != null && siblingNode.getNodeType() != Node.ELEMENT_NODE) { /* * Can happen as shown during latest ETSI XAdES plugtests. */ LOG.debug("skipping a non-Element sibling: " + siblingNode.getNodeType()); if (Node.TEXT_NODE == siblingNode.getNodeType()) { LOG.debug("TEXT node sibling: \"" + siblingNode.getNodeValue() + "\""); } siblingNode = siblingNode.getNextSibling(); } if (null == siblingNode) { return null; } Element element = (Element) siblingNode; if (false == namespace.equals(element.getNamespaceURI())) { return null; } if (false == localName.equals(element.getLocalName())) { return null; } return unmarshall(element, jaxbType); }
From source file:com.l2jfree.gameserver.document.DocumentBase.java
final void parseTemplate(Node n, Object template) { n = n.getFirstChild();//from w w w .java 2 s . co m for (; n != null; n = n.getNextSibling()) { parseTemplateNode(n, template); } }
From source file:Main.java
/** * This method is a tree-search to help prevent against wrapping attacks. It checks that no other * Element than the given "knownElement" argument has an ID attribute that matches the "value" * argument, which is the ID value of "knownElement". If this is the case then "false" is returned. *///from ww w .j a v a 2 s. c o m public static boolean protectAgainstWrappingAttack(Node startNode, Element knownElement, String value) { Node startParent = startNode.getParentNode(); Node processedNode = 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()) && se != knownElement) { //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.jereksel.rommanager.XMLParser.java
/** * Getting node value/*w w w .jav a 2s . com*/ * * @param elem element */ public final String getElementValue(Node elem) { Node child; if (elem != null) { if (elem.hasChildNodes()) { for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.getNodeType() == Node.TEXT_NODE) { return child.getNodeValue(); } } } } return ""; }
From source file:cz.incad.cdk.cdkharvester.PidsRetriever.java
private void getDocs() throws Exception { String urlStr = harvestUrl + URIUtil.encodeQuery(actual_date); logger.log(Level.INFO, "urlStr: {0}", urlStr); org.w3c.dom.Document solrDom = solrResults(urlStr); String xPathStr = "/response/result/@numFound"; expr = xpath.compile(xPathStr);/*ww w .j a v a 2 s . co m*/ int numDocs = Integer.parseInt((String) expr.evaluate(solrDom, XPathConstants.STRING)); logger.log(Level.INFO, "numDocs: {0}", numDocs); if (numDocs > 0) { xPathStr = "/response/result/doc/str[@name='PID']"; expr = xpath.compile(xPathStr); NodeList nodes = (NodeList) expr.evaluate(solrDom, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String pid = node.getFirstChild().getNodeValue(); String to = node.getNextSibling().getFirstChild().getNodeValue(); qe.add(new DocEntry(pid, to)); } } }
From source file:cn.edu.bit.whitesail.parser.HtmlParser.java
private void getLinks(Node node, List<URL> URLsToFill, String anchor) { URL u = null;// w ww .ja va 2 s. c o m if (node.getNodeName().equalsIgnoreCase("a") || node.getNodeName().equalsIgnoreCase("link")) { NamedNodeMap map = node.getAttributes(); int length = map.getLength(); for (int i = 0; i < length; i++) { Node item = map.item(i); if (item.getNodeName().equalsIgnoreCase("href")) { u = URLFormat(item.getNodeValue(), anchor); if (null != u) { URLsToFill.add(u); } } } } Node child = node.getFirstChild(); while (child != null) { getLinks(child, URLsToFill, anchor); child = child.getNextSibling(); } }
From source file:org.apache.solr.kelvin.responseanalyzers.XmlDoclistExtractorResponseAnalyzer.java
public void decode(Map<String, Object> previousResponses) throws Exception { ObjectMapper mapper = new ObjectMapper(); ArrayNode response = mapper.createArrayNode(); if (!previousResponses.containsKey(XmlResponseAnalyzer.XML_DOM)) { previousResponses.put(DOC_LIST, response); //empty return;//www .jav a 2 s.c om } NodeList nodeList = (NodeList) expr.evaluate((Document) previousResponses.get(XmlResponseAnalyzer.XML_DOM), XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node doc = nodeList.item(i); ObjectNode oDoc = mapper.createObjectNode(); Node subel = doc.getFirstChild(); while (subel != null) { if (subel.getNodeType() != Node.TEXT_NODE) { String fieldName = subel.getAttributes().getNamedItem("name").getNodeValue(); String elementName = subel.getNodeName(); if ("arr".equals(elementName)) { ArrayNode multivaluedField = mapper.createArrayNode(); Node mvItem = subel.getFirstChild(); while (mvItem != null) { multivaluedField.add(mvItem.getTextContent()); mvItem = mvItem.getNextSibling(); } oDoc.put(fieldName, multivaluedField); } else { String value = subel.getTextContent(); oDoc.put(fieldName, value); } } subel = subel.getNextSibling(); } response.add(oDoc); } previousResponses.put(DOC_LIST, response); }
From source file:com.qwazr.extractor.parser.ImageParser.java
private void browseNodes(String path, final Node root, final ParserFieldsBuilder result) { if (root == null) return;/*from w ww. j a v a 2 s .co m*/ switch (root.getNodeType()) { case Node.TEXT_NODE: result.add(ParserField.newString(path, null), root.getNodeValue()); break; case Node.ELEMENT_NODE: final NamedNodeMap nnm = root.getAttributes(); if (nnm != null) for (int i = 0; i < nnm.getLength(); i++) browseNodes(path, nnm.item(i), result); Node child = root.getFirstChild(); while (child != null) { browseNodes(path + "/" + child.getNodeName(), child, result); child = child.getNextSibling(); } break; case Node.ATTRIBUTE_NODE: path = path + "#" + root.getNodeName(); result.add(ParserField.newString(path, null), root.getNodeValue()); break; default: throw new NotImplementedException("Unknown attribute: " + root.getNodeType()); } }
From source file:net.d53dev.dslfy.web.service.GifService.java
private void configureGIFFrame(IIOMetadata meta, String delayTime, int imageIndex, String disposalMethod, int loopCount) { String metaFormat = meta.getNativeMetadataFormatName(); if (!"javax_imageio_gif_image_1.0".equals(metaFormat)) { throw new IllegalArgumentException("Unfamiliar gif metadata format: " + metaFormat); }//from w w w.j a v a2s .c om Node root = meta.getAsTree(metaFormat); Node child = root.getFirstChild(); while (child != null) { if ("GraphicControlExtension".equals(child.getNodeName())) break; child = child.getNextSibling(); } IIOMetadataNode gce = (IIOMetadataNode) child; gce.setAttribute("userDelay", "FALSE"); gce.setAttribute("delayTime", delayTime); gce.setAttribute("disposalMethod", disposalMethod); if (imageIndex == 0) { IIOMetadataNode aes = new IIOMetadataNode("ApplicationExtensions"); IIOMetadataNode ae = new IIOMetadataNode("ApplicationExtension"); ae.setAttribute("applicationID", "NETSCAPE"); ae.setAttribute("authenticationCode", "2.0"); byte[] uo = new byte[] { 0x1, (byte) (loopCount & 0xFF), (byte) ((loopCount >> 8) & 0xFF) }; ae.setUserObject(uo); aes.appendChild(ae); root.appendChild(aes); } try { meta.setFromTree(metaFormat, root); } catch (IIOInvalidTreeException e) { throw new Error(e); } }
From source file:edu.stanford.muse.webapp.Accounts.java
/** does account setup and login (and look up default folder if well-known account) from the given request. * request params are loginName<N>, password<N>, etc (see loginForm for details). * returns an object with {status: 0} if success, or {status: <non-zero>, errorMessage: '... '} if failure. * if success and account has a well-known sent mail folder, the returned object also has something like: * {defaultFolder: '[Gmail]/Sent Mail', defaultFolderCount: 1033} * accounts on the login page are numbered 0 upwards. */ public static JSONObject login(HttpServletRequest request, int accountNum) throws IOException, JSONException { JSONObject result = new JSONObject(); HttpSession session = request.getSession(); // allocate the fetcher if it doesn't already exist MuseEmailFetcher m = null;/*from w w w. j ava2s . c o m*/ synchronized (session) // synchronize, otherwise may lose the fetcher when multiple accounts are specified and are logged in to simult. { m = (MuseEmailFetcher) JSPHelper.getSessionAttribute(session, "museEmailFetcher"); boolean doIncremental = request.getParameter("incremental") != null; if (m == null || !doIncremental) { m = new MuseEmailFetcher(); session.setAttribute("museEmailFetcher", m); } } // note: the same params get posted with every accountNum // we'll update for all account nums, because sometimes account #0 may not be used, only #1 onwards. This should be harmless. // we used to do only altemailaddrs, but now also include the name. updateUserInfo(request); String accountType = request.getParameter("accountType" + accountNum); if (Util.nullOrEmpty(accountType)) { result.put("status", 1); result.put("errorMessage", "No information for account #" + accountNum); return result; } String loginName = request.getParameter("loginName" + accountNum); String password = request.getParameter("password" + accountNum); String protocol = request.getParameter("protocol" + accountNum); // String port = request.getParameter("protocol" + accountNum); // we don't support pop/imap on custom ports currently. can support server.com:port syntax some day String server = request.getParameter("server" + accountNum); String defaultFolder = request.getParameter("defaultFolder" + accountNum); if (server != null) server = server.trim(); if (loginName != null) loginName = loginName.trim(); // for these ESPs, the user may have typed in the whole address or just his/her login name if (accountType.equals("gmail") && loginName.indexOf("@") < 0) loginName = loginName + "@gmail.com"; if (accountType.equals("yahoo") && loginName.indexOf("@") < 0) loginName = loginName + "@yahoo.com"; if (accountType.equals("live") && loginName.indexOf("@") < 0) loginName = loginName + "@live.com"; if (accountType.equals("stanford") && loginName.indexOf("@") < 0) loginName = loginName + "@stanford.edu"; if (accountType.equals("gmail")) server = "imap.gmail.com"; // add imapdb stuff here. boolean imapDBLookupFailed = false; String errorMessage = ""; int errorStatus = 0; if (accountType.equals("email") && Util.nullOrEmpty(server)) { log.info("accountType = email"); defaultFolder = "Sent"; { // ISPDB from Mozilla imapDBLookupFailed = true; String emailDomain = loginName.substring(loginName.indexOf("@") + 1); log.info("Domain: " + emailDomain); // from http://suhothayan.blogspot.in/2012/05/how-to-install-java-cryptography.html // to get around the need for installingthe unlimited strength encryption policy files. try { Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted"); field.setAccessible(true); field.set(null, java.lang.Boolean.FALSE); } catch (Exception ex) { ex.printStackTrace(); } // URL url = new URL("https://live.mozillamessaging.com/autoconfig/v1.1/" + emailDomain); URL url = new URL("https://autoconfig.thunderbird.net/v1.1/" + emailDomain); try { URLConnection urlConnection = url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(in); NodeList configList = doc.getElementsByTagName("incomingServer"); log.info("configList.getLength(): " + configList.getLength()); int i; for (i = 0; i < configList.getLength(); i++) { Node config = configList.item(i); NamedNodeMap attributes = config.getAttributes(); if (attributes.getNamedItem("type").getNodeValue().equals("imap")) { log.info("[" + i + "] type: " + attributes.getNamedItem("type").getNodeValue()); Node param = config.getFirstChild(); String nodeName, nodeValue; String paramHostName = ""; String paramUserName = ""; do { if (param.getNodeType() == Node.ELEMENT_NODE) { nodeName = param.getNodeName(); nodeValue = param.getTextContent(); log.info(nodeName + "=" + nodeValue); if (nodeName.equals("hostname")) { paramHostName = nodeValue; } else if (nodeName.equals("username")) { paramUserName = nodeValue; } } param = param.getNextSibling(); } while (param != null); log.info("paramHostName = " + paramHostName); log.info("paramUserName = " + paramUserName); server = paramHostName; imapDBLookupFailed = false; if (paramUserName.equals("%EMAILADDRESS%")) { // Nothing to do with loginName } else if (paramUserName.equals("%EMAILLOCALPART%") || paramUserName.equals("%USERNAME%")) { // Cut only local part loginName = loginName.substring(0, loginName.indexOf('@') - 1); } else { imapDBLookupFailed = true; errorMessage = "Invalid auto configuration"; } break; // break after find first IMAP host name } } } catch (Exception e) { Util.print_exception("Exception trying to read ISPDB", e, log); errorStatus = 2; // status code = 2 => ispdb lookup failed errorMessage = "No automatic configuration available for " + emailDomain + ", please use the option to provide a private (IMAP) server. \nDetails: " + e.getMessage() + ". \nRunning with java -Djavax.net.debug=all may provide more details."; } } } if (imapDBLookupFailed) { log.info("ISPDB Fail"); result.put("status", errorStatus); result.put("errorMessage", errorMessage); // add other fields here if needed such as server name attempted to be looked up in case the front end wants to give a message to the user return result; } boolean isServerAccount = accountType.equals("gmail") || accountType.equals("email") || accountType.equals("yahoo") || accountType.equals("live") || accountType.equals("stanford") || accountType.equals("gapps") || accountType.equals("imap") || accountType.equals("pop") || accountType.startsWith("Thunderbird"); if (isServerAccount) { boolean sentOnly = "on".equals(request.getParameter("sent-messages-only")); return m.addServerAccount(server, protocol, defaultFolder, loginName, password, sentOnly); } else if (accountType.equals("mbox") || accountType.equals("tbirdLocalFolders")) { try { String mboxDir = request.getParameter("mboxDir" + accountNum); String emailSource = request.getParameter("emailSource" + accountNum); // for non-std local folders dir, tbird prefs.js has a line like: user_pref("mail.server.server1.directory-rel", "[ProfD]../../../../../../tmp/tb"); log.info("adding mbox account: " + mboxDir); errorMessage = m.addMboxAccount(emailSource, mboxDir, accountType.equals("tbirdLocalFolders")); if (!Util.nullOrEmpty(errorMessage)) { result.put("errorMessage", errorMessage); result.put("status", 1); } else result.put("status", 0); } catch (MboxFolderNotReadableException e) { result.put("errorMessage", e.getMessage()); result.put("status", 1); } } else { result.put("errorMessage", "Sorry, unknown account type: " + accountType); result.put("status", 1); } return result; }