List of usage examples for org.w3c.dom Node getAttributes
public NamedNodeMap getAttributes();
NamedNodeMap
containing the attributes of this node (if it is an Element
) or null
otherwise. From source file:Main.java
public static void writeOutAttributesForNode(String[][] attributes, Node node) { if (attributes != null) { // Add attributes for (int n = 0; n < attributes.length; n++) { String key = attributes[n][0]; String value = attributes[n][1]; if ((key != null) && (value != null)) { Attr attNode = node.getOwnerDocument().createAttribute(key.toString()); attNode.setNodeValue(value.toString()); node.getAttributes().setNamedItem(attNode); }/*w ww. j a va 2 s . c o m*/ } } }
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 ww w . j av a 2 s . c om*/ 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; }
From source file:Main.java
/** * Sets a named attribute of a Node/*from w w w. j av a 2s. co m*/ * @param node The node * @param attr The name of the attribute to set * @param value The value to assign to the attribute */ public synchronized static void setAttribute(Node node, String attr, String value) { if (node == null) throw new IllegalArgumentException("Node argument cannot be null"); if (attr == null) throw new IllegalArgumentException("Node attribute argument cannot be null"); if (value == null) throw new IllegalArgumentException("Node attribute value argument cannot be null"); Node attrN = null; NamedNodeMap map = node.getAttributes(); if (map != null) attrN = map.getNamedItem(attr); if (attrN == null) { attrN = node.getOwnerDocument().createAttribute(attr); map.setNamedItem(attrN); } attrN.setNodeValue(value); }
From source file:Main.java
public static String format(Node n, int indentLevel) { String indent = ""; for (int i = 0; i < indentLevel; i++) { indent += "\t"; }/*from w ww . j a v a 2 s .com*/ StringBuilder result = new StringBuilder(); result.append(indent); if (n.getNodeType() == Node.ELEMENT_NODE) { result.append("<"); result.append(n.getNodeName()); NamedNodeMap attrs = n.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); result.append(" "); result.append(attr.getNodeName()); result.append("=\""); result.append(attr.getNodeValue()); result.append("\""); } result.append(">\n"); } if (n.getNodeType() == Node.TEXT_NODE) { String str = n.getNodeValue(); result.append(str + "\n"); } NodeList childNodes = n.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node n2 = childNodes.item(i); if (isEmptyTextNode(n2)) { continue; } result.append(format(n2, indentLevel + 1)); } if (n.getNodeType() == Node.ELEMENT_NODE) { result.append(indent); result.append("</"); result.append(n.getNodeName()); result.append(">\n"); } return result.toString(); }
From source file:org.ale.scanner.zotero.web.zotero.ZoteroAPIClient.java
public static Access parsePermissions(String resp, Account user) { /* example://from www.jav a2s .c om <key key="xxx"> <access library="1" files="1" notes="1" write="1"/> <access group="12345" write="1"/> <access group="all" write="1"/> </key> */ Document doc = ZoteroAPIClient.parseXML(resp); if (doc == null) return null; NodeList keys = doc.getElementsByTagName("key"); if (keys.getLength() == 0) return null; Node keyNode = keys.item(0); Node keyAttr = keyNode.getAttributes().getNamedItem("key"); if (keyAttr == null) return null; String key = keyAttr.getNodeValue(); if (!key.equals(user.getKey())) return null; NodeList accessTags = doc.getElementsByTagName("access"); int[] groups = new int[accessTags.getLength()]; int[] permissions = new int[accessTags.getLength()]; for (int i = 0; i < accessTags.getLength(); i++) { permissions[i] = Access.READ; NamedNodeMap attr = accessTags.item(i).getAttributes(); Node groupNode = attr.getNamedItem("group"); if (groupNode == null) { // Library access? groupNode = attr.getNamedItem("library"); if (groupNode == null) return null; groups[i] = Group.GROUP_LIBRARY; } else { // Individual group or all groups if (groupNode.getNodeValue().equals("all")) groups[i] = Group.GROUP_ALL; else groups[i] = Integer.parseInt(groupNode.getNodeValue()); } Node writeNode = attr.getNamedItem("write"); if (writeNode != null && writeNode.getNodeValue().equals("1")) { permissions[i] |= Access.WRITE; } Node noteNode = attr.getNamedItem("notes"); if (noteNode != null && noteNode.getNodeValue().equals("1")) { permissions[i] |= Access.NOTE; } } return new Access(user.getDbId(), groups, permissions); }
From source file:com.github.sevntu.checkstyle.internal.ChecksTest.java
private static void validateEclipseCsMetaXmlFileRule(String pkg, Class<?> module, Set<Node> children) throws Exception { final String moduleName = module.getSimpleName(); final Set<String> properties = getFinalProperties(module); final Set<Field> fieldMessages = CheckUtil.getCheckMessages(module); final Set<String> messages = new TreeSet<>(); for (Field fieldMessage : fieldMessages) { // below is required for package/private classes if (!fieldMessage.isAccessible()) { fieldMessage.setAccessible(true); }/*from w ww .j av a 2 s . c o m*/ messages.add(fieldMessage.get(null).toString()); } for (Node child : children) { final NamedNodeMap attributes = child.getAttributes(); switch (child.getNodeName()) { case "alternative-name": final Node internalNameNode = attributes.getNamedItem("internal-name"); Assert.assertNotNull( pkg + " checkstyle-metadata.xml must contain an internal name for " + moduleName, internalNameNode); final String internalName = internalNameNode.getTextContent(); Assert.assertEquals( pkg + " checkstyle-metadata.xml requires a valid internal-name for " + moduleName, module.getName(), internalName); break; case "description": Assert.assertEquals(pkg + " checkstyle-metadata.xml requires a valid description for " + moduleName, "%" + moduleName + ".desc", child.getTextContent()); break; case "property-metadata": final String propertyName = attributes.getNamedItem("name").getTextContent(); Assert.assertTrue(pkg + " checkstyle-metadata.xml has an unknown parameter for " + moduleName + ": " + propertyName, properties.remove(propertyName)); final Node firstChild = child.getFirstChild().getNextSibling(); Assert.assertNotNull(pkg + " checkstyle-metadata.xml requires atleast one child for " + moduleName + ", " + propertyName, firstChild); Assert.assertEquals(pkg + " checkstyle-metadata.xml should have a description for the " + "first child of " + moduleName + ", " + propertyName, "description", firstChild.getNodeName()); Assert.assertEquals(pkg + " checkstyle-metadata.xml requires a valid description for " + moduleName + ", " + propertyName, "%" + moduleName + "." + propertyName, firstChild.getTextContent()); break; case "message-key": final String key = attributes.getNamedItem("key").getTextContent(); Assert.assertTrue( pkg + " checkstyle-metadata.xml has an unknown message for " + moduleName + ": " + key, messages.remove(key)); break; default: Assert.fail(pkg + " checkstyle-metadata.xml unknown node for " + moduleName + ": " + child.getNodeName()); break; } } for (String property : properties) { Assert.fail(pkg + " checkstyle-metadata.xml missing parameter for " + moduleName + ": " + property); } for (String message : messages) { Assert.fail(pkg + " checkstyle-metadata.xml missing message for " + moduleName + ": " + message); } }
From source file:Main.java
public static void writeOutAttributesForNode(Map<?, ?> attributes, Node node) { if (attributes != null) { // Add attributes for (Iterator<?> i = attributes.keySet().iterator(); i.hasNext();) { Object key = i.next(); Object value = attributes.get(key); if ((key != null) && (value != null)) { Attr attNode = node.getOwnerDocument().createAttribute(key.toString()); attNode.setNodeValue(value.toString()); node.getAttributes().setNamedItem(attNode); }/*ww w. java 2 s .c o m*/ } } }
From source file:com.runwaysdk.browser.JavascriptTestRunner.java
public static Test suite() throws Exception { // Read project.version Properties prop1 = new Properties(); ClassLoader loader1 = Thread.currentThread().getContextClassLoader(); InputStream stream1 = loader1.getResourceAsStream("avail-maven.properties"); prop1.load(stream1);//from ww w . j av a 2s . c o m String projVer = prop1.getProperty("mvn.project.version"); TestSuite suite = new TestSuite(); int browserLoopIterationNumber = 0; System.out.println("Preparing to run cross-browser javascript unit tests."); long totalTime = System.currentTimeMillis(); for (String browser : supportedBrowsers) { try { String browserDisplayName = String.valueOf(browser.charAt(1)).toUpperCase() + browser.substring(2); System.out.println("Opening " + browserDisplayName); TestSuite browserSuite = new TestSuite(browserDisplayName); selenium = new DefaultSelenium("localhost", 4444, browser, "http://localhost:8080/runwaysdk-browser-test-" + projVer + "/"); selenium.start(); isSeleniumStarted = true; selenium.open("MasterTestLauncher.jsp"); // selenium.waitForCondition("selenium.browserbot.getCurrentWindow().document.getElementById('all');", "6000"); selenium.setTimeout("1000"); System.out.println("Running tests..."); long time = System.currentTimeMillis(); selenium.click("all"); selenium.waitForCondition( "!selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Runner.isRunning()", Integer.toString(MAXIMUM_TOTAL_TEST_DURATION * 1000)); time = System.currentTimeMillis() - time; // elapsed time in milis if (time < 1000) { System.out.println("Tests completed in " + time + " miliseconds."); } else if (time < 60000) { time = time / 1000; System.out.println("Tests completed in " + time + " seconds."); } else if (time < 3600000) { time = time / (1000 * 60); System.out.println("Tests completed in " + time + " minutes."); } else { time = time / (1000 * 60 * 60); System.out.println("Tests completed in " + time + " hours."); } //System.out.println(selenium.getEval("\n\n" + "selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Runner.getResults(selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Format.XML);") + "\n\n"); // tests are done running, get the results and display them through junit DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); String resultsJunitXML = selenium.getEval( "selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Runner.getResults(selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Format.JUnitXML);"); String resultsYUITestXML = selenium.getEval( "selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Runner.getResults(selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Format.XML);"); // Write the test output to xml Properties prop = new Properties(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream stream = loader.getResourceAsStream("default/common/terraframe.properties"); prop.load(stream); String basedir = prop.getProperty("local.root"); System.out.println("Writing javascript test results to '" + basedir + "/target/surefire-reports/TEST-com.runwaysdk.browser.JavascriptTestRunner-" + browserDisplayName + ".xml."); File dir = new File(basedir + "/target/surefire-reports"); dir.mkdirs(); final OutputStream os = new FileOutputStream(dir.getAbsolutePath() + "/TEST-com.runwaysdk.browser.JavascriptTestRunner-" + browserDisplayName + ".xml", false); final PrintStream printStream = new PrintStream(os); printStream.print(resultsJunitXML); printStream.close(); InputSource in = new InputSource(); in.setCharacterStream(new StringReader(resultsYUITestXML)); Element doc = db.parse(in).getDocumentElement(); NodeList suiteList = doc.getElementsByTagName("testsuite"); if (suiteList == null || suiteList.getLength() == 0) { //suiteList = (NodeList)doc; throw new Exception("Unable to find any suites!"); } String uniqueWhitespace = ""; for (int j = 0; j < browserLoopIterationNumber; j++) { uniqueWhitespace = uniqueWhitespace + " "; } for (int i = 0; i < suiteList.getLength(); i++) //looping through test suites { Node n = suiteList.item(i); TestSuite s = new TestSuite(); NamedNodeMap nAttrMap = n.getAttributes(); s.setName(nAttrMap.getNamedItem("name").getNodeValue() + uniqueWhitespace); NodeList testCaseList = ((Element) n).getElementsByTagName("testcase"); for (int j = 0; j < testCaseList.getLength(); j++) // looping through test cases { Node x = testCaseList.item(j); NamedNodeMap xAttrMap = x.getAttributes(); TestSuite testCaseSuite = new TestSuite(); testCaseSuite.setName(xAttrMap.getNamedItem("name").getNodeValue() + uniqueWhitespace); NodeList testList = ((Element) x).getElementsByTagName("test"); for (int k = 0; k < testList.getLength(); k++) // looping through tests { Node testNode = testList.item(k); NamedNodeMap testAttrMap = testNode.getAttributes(); Test t = new GeneratedTest( testAttrMap.getNamedItem("name").getNodeValue() + uniqueWhitespace); if (testAttrMap.getNamedItem("result").getNodeValue().equals("fail")) { ((GeneratedTest) t).testFailMessage = testAttrMap.getNamedItem("message") .getNodeValue(); } testCaseSuite.addTest(t); } s.addTest(testCaseSuite); } browserSuite.addTest(s); } //suite.addTest(browserSuite); browserLoopIterationNumber++; } // end try catch (Exception e) { throw (e); } finally { if (isSeleniumStarted) { selenium.stop(); isSeleniumStarted = false; } } } // end for loop on browsers totalTime = System.currentTimeMillis() - totalTime; // elapsed time in milis if (totalTime < 1000) { System.out.println("Cross-browser javascript unit tests completed in " + totalTime + " miliseconds."); } else if (totalTime < 60000) { totalTime = totalTime / 1000; System.out.println("Cross-browser javascript unit tests completed in " + totalTime + " seconds."); } else if (totalTime < 3600000) { totalTime = totalTime / (1000 * 60); System.out.println("Cross-browser javascript unit tests completed in " + totalTime + " minutes."); } else { totalTime = totalTime / (1000 * 60 * 60); System.out.println("Cross-browser javascript unit tests completed in " + totalTime + " hours."); } return suite; }
From source file:com.netsteadfast.greenstep.util.BusinessProcessManagementUtils.java
public static String getResourceProcessId(File activitiBpmnFile) throws Exception { if (null == activitiBpmnFile || !activitiBpmnFile.exists()) { throw new Exception("file no exists!"); }/*from www . ja v a 2s. c om*/ if (!activitiBpmnFile.getName().endsWith(_SUB_NAME)) { throw new Exception("not resource file."); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(activitiBpmnFile); Element element = doc.getDocumentElement(); if (!"definitions".equals(element.getNodeName())) { throw new Exception("not resource file."); } String processId = activitiBpmnFile.getName(); if (processId.endsWith(_SUB_NAME)) { processId = processId.substring(0, processId.length() - _SUB_NAME.length()); } NodeList nodes = element.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if ("process".equals(node.getNodeName())) { NamedNodeMap nodeMap = node.getAttributes(); for (int attr = 0; attr < nodeMap.getLength(); attr++) { Node processAttr = nodeMap.item(attr); if ("id".equals(processAttr.getNodeName())) { processId = processAttr.getNodeValue(); } } } } return processId; }
From source file:org.dasein.cloud.terremark.TerremarkMethod.java
private static ParsedError parseErrorResponse(String responseBody) throws CloudException, InternalException { try {//from w w w. j a v a2s.c om ByteArrayInputStream bas = new ByteArrayInputStream(responseBody.getBytes()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(bas); bas.close(); Node errorNode = doc.getElementsByTagName(ERROR_TAG).item(0); ParsedError error = new ParsedError(); if (errorNode != null) { error.message = errorNode.getAttributes().getNamedItem(MESSAGE_ATTR).getNodeValue(); error.code = Integer .parseInt(errorNode.getAttributes().getNamedItem(MAJOR_CODE_ATTR).getNodeValue()); } return error; } catch (IOException e) { throw new CloudException(e); } catch (ParserConfigurationException e) { throw new CloudException(e); } catch (SAXException e) { throw new CloudException(e); } }