List of usage examples for org.w3c.dom NamedNodeMap getNamedItem
public Node getNamedItem(String name);
From source file:com.cloud.hypervisor.kvm.resource.wrapper.LibvirtMigrateCommandWrapper.java
private String replaceStorage(String xmlDesc, Map<String, MigrateCommand.MigrateDiskInfo> migrateStorage) throws IOException, ParserConfigurationException, SAXException, TransformerException { InputStream in = IOUtils.toInputStream(xmlDesc); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(in); // Get the root element Node domainNode = doc.getFirstChild(); NodeList domainChildNodes = domainNode.getChildNodes(); for (int i = 0; i < domainChildNodes.getLength(); i++) { Node domainChildNode = domainChildNodes.item(i); if ("devices".equals(domainChildNode.getNodeName())) { NodeList devicesChildNodes = domainChildNode.getChildNodes(); for (int x = 0; x < devicesChildNodes.getLength(); x++) { Node deviceChildNode = devicesChildNodes.item(x); if ("disk".equals(deviceChildNode.getNodeName())) { Node diskNode = deviceChildNode; String sourceFileDevText = getSourceFileDevText(diskNode); String path = getPathFromSourceFileDevText(migrateStorage.keySet(), sourceFileDevText); if (path != null) { MigrateCommand.MigrateDiskInfo migrateDiskInfo = migrateStorage.remove(path); NamedNodeMap diskNodeAttributes = diskNode.getAttributes(); Node diskNodeAttribute = diskNodeAttributes.getNamedItem("type"); diskNodeAttribute.setTextContent(migrateDiskInfo.getDiskType().toString()); NodeList diskChildNodes = diskNode.getChildNodes(); for (int z = 0; z < diskChildNodes.getLength(); z++) { Node diskChildNode = diskChildNodes.item(z); if ("driver".equals(diskChildNode.getNodeName())) { Node driverNode = diskChildNode; NamedNodeMap driverNodeAttributes = driverNode.getAttributes(); Node driverNodeAttribute = driverNodeAttributes.getNamedItem("type"); driverNodeAttribute.setTextContent(migrateDiskInfo.getDriverType().toString()); } else if ("source".equals(diskChildNode.getNodeName())) { diskNode.removeChild(diskChildNode); Element newChildSourceNode = doc.createElement("source"); newChildSourceNode.setAttribute(migrateDiskInfo.getSource().toString(), migrateDiskInfo.getSourceText()); diskNode.appendChild(newChildSourceNode); } else if ("auth".equals(diskChildNode.getNodeName())) { diskNode.removeChild(diskChildNode); } else if ("iotune".equals(diskChildNode.getNodeName())) { diskNode.removeChild(diskChildNode); }/* ww w . ja v a 2 s . c o m*/ } } } } } } if (!migrateStorage.isEmpty()) { throw new CloudRuntimeException( "Disk info was passed into LibvirtMigrateCommandWrapper.replaceStorage that was not used."); } return getXml(doc); }
From source file:com.rest4j.generator.Generator.java
private void cleanupFinal(Element element) { if ("http://www.w3.org/1999/xhtml".equals(element.getNamespaceURI())) { element.getOwnerDocument().renameNode(element, null, element.getLocalName()); }//from w w w .j a va 2 s . c om NamedNodeMap attrs = element.getAttributes(); if (attrs.getNamedItem("xmlns") != null) { attrs.removeNamedItem("xmlns"); } if (attrs.getNamedItem("xmlns:html") != null) { attrs.removeNamedItem("xmlns:html"); } for (Node child : Util.it(element.getChildNodes())) { if (child instanceof Element) { cleanupFinal((Element) child); } } }
From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java
/** * Retrieve a configuration parameter value. * * Retrieves the value of the config parameter from the config section * that is supplied./*from w w w.j a v a 2 s . c o m*/ * @param eSection The base section. * @param sName The parameter name. * @return The paramater value. * @throws ConfigurationException If retrieving fails. */ public synchronized String getParam(Element eSection, String sName) throws ConfigurationException { if (eSection == null) throw new IllegalArgumentException("Suplied section is empty"); if (sName == null) throw new IllegalArgumentException("Suplied name is empty"); String sValue = null; try { //check attributes within the section tag if (eSection.hasAttributes()) { NamedNodeMap oNodeMap = eSection.getAttributes(); Node nAttribute = oNodeMap.getNamedItem(sName); if (nAttribute != null) sValue = nAttribute.getNodeValue(); } if (sValue == null) {//check sub sections NodeList nlChilds = eSection.getChildNodes(); for (int i = 0; i < nlChilds.getLength(); i++) { Node nTemp = nlChilds.item(i); if (nTemp != null && nTemp.getNodeName().equalsIgnoreCase(sName)) { NodeList nlSubNodes = nTemp.getChildNodes(); if (nlSubNodes.getLength() > 0) { for (int iSub = 0; iSub < nlSubNodes.getLength(); iSub++) { Node nSubTemp = nlSubNodes.item(iSub); if (nSubTemp.getNodeType() == Node.TEXT_NODE) { sValue = nSubTemp.getNodeValue(); if (sValue == null) sValue = ""; return sValue; } } } else { if (sValue == null) sValue = ""; return sValue; } } } } } catch (DOMException e) { _logger.error("Could not retrieve parameter: " + sValue, e); throw new ConfigurationException(SystemErrors.ERROR_CONFIG_READ); } return sValue; }
From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java
/** * @see com.alfaariss.oa.api.configuration.IConfigurationManager#getParams(org.w3c.dom.Element, java.lang.String) *///from w w w . j a v a 2s . co m public synchronized List<String> getParams(Element eSection, String sParamName) throws ConfigurationException { if (eSection == null) throw new IllegalArgumentException("Suplied section is empty"); if (sParamName == null) throw new IllegalArgumentException("Suplied parameter name is empty"); List<String> listValues = new Vector<String>(); try { //check attributes within the section tag if (eSection.hasAttributes()) { NamedNodeMap oNodeMap = eSection.getAttributes(); Node nAttribute = oNodeMap.getNamedItem(sParamName); if (nAttribute != null) { String sAttributeValue = nAttribute.getNodeValue(); if (sAttributeValue != null) listValues.add(sAttributeValue); } } NodeList nlChilds = eSection.getChildNodes(); for (int i = 0; i < nlChilds.getLength(); i++) { Node nTemp = nlChilds.item(i); if (nTemp != null && nTemp.getNodeName().equalsIgnoreCase(sParamName)) { String sValue = ""; NodeList nlSubNodes = nTemp.getChildNodes(); if (nlSubNodes.getLength() > 0) { for (int iSub = 0; iSub < nlSubNodes.getLength(); iSub++) { Node nSubTemp = nlSubNodes.item(iSub); if (nSubTemp.getNodeType() == Node.TEXT_NODE) { sValue = nSubTemp.getNodeValue(); if (sValue == null) sValue = ""; } } } listValues.add(sValue); } } if (listValues.isEmpty()) return null; } catch (DOMException e) { _logger.error("Could not retrieve parameter: " + sParamName, e); throw new ConfigurationException(SystemErrors.ERROR_CONFIG_READ); } return listValues; }
From source file:gov.nasa.ensemble.core.jscience.csvxml.ProfileLoader.java
private ProfileWithLazyDatapointsFromCsv<?> createLazyProfile(Node columnElement) throws ProfileLoadingException { ProfileWithLazyDatapointsFromCsv result = new ProfileWithLazyDatapointsFromCsv(this); NamedNodeMap attributes = columnElement.getAttributes(); result.setId(attributes.getNamedItem("id").getTextContent()); Node unitAttribute = attributes.getNamedItem("units"); if (unitAttribute == null) { result.setUnits(Unit.ONE);/*from ww w. j a v a 2 s . c o m*/ } else { String unitName = unitAttribute.getTextContent(); Unit unit = null; try { unit = EnsembleUnitFormat.INSTANCE.parse(unitName); } catch (Exception e) { /* leave null */} if (unit == null) LogUtil.warn("Undefined unit name: " + unitName); result.setUnits(unit == null ? new BaseUnit(unitName + " (unrecognized units)") : unit); } Node displayNameAttribute = attributes.getNamedItem("displayName"); if (displayNameAttribute == null) { result.setName(null); } else { result.setName(displayNameAttribute.getTextContent()); } Node interpolationAttribute = attributes.getNamedItem("interpolation"); String interpolationString = interpolationAttribute.getTextContent(); result.setInterpolation(INTERPOLATION.valueOf(interpolationString.toUpperCase())); String typeAttribute = attributes.getNamedItem("type").getTextContent(); result.setDataType(EMFUtils.createEDataTypeFromString(typeAttribute)); Node defaultValueAttribute = attributes.getNamedItem("defaultValue"); if (defaultValueAttribute != null) { String defaultValueString = defaultValueAttribute.getTextContent(); result.setDefaultValue(parseValueCell(defaultValueString, Datatype.valueOf(typeAttribute))); } if (columnElement.hasChildNodes()) { NodeList properties = columnElement.getChildNodes(); for (int i = 0; i < properties.getLength(); i++) { Node property = properties.item(i); if (property.getNodeType() == Node.ELEMENT_NODE) { NamedNodeMap propertyAttributes = property.getAttributes(); result.getAttributes().put(propertyAttributes.getNamedItem("key").getTextContent(), propertyAttributes.getNamedItem("value").getTextContent()); } } } return result; }
From source file:hoot.services.models.osm.Changeset.java
/** * Inserts all tags for an element into the services database * * @param xml list of XML tags//from ww w. j a va 2 s .c o m * @param conn JDBC Connection * @throws Exception */ public void insertTags(final long mapId, final NodeList xml, Connection conn) throws Exception { String POSTGRESQL_DRIVER = "org.postgresql.Driver"; Statement stmt = null; try { log.debug("Inserting tags for changeset with ID: " + getId()); String strKv = ""; for (int i = 0; i < xml.getLength(); i++) { NamedNodeMap tagAttributes = xml.item(i).getAttributes(); String key = "\"" + tagAttributes.getNamedItem("k").getNodeValue() + "\""; String val = "\"" + tagAttributes.getNamedItem("v").getNodeValue() + "\""; if (strKv.length() > 0) { strKv += ","; } strKv += key + "=>" + val; } String strTags = "'"; strTags += strKv; strTags += "'"; Class.forName(POSTGRESQL_DRIVER); stmt = conn.createStatement(); String sql = "UPDATE changesets_" + mapId + " SET tags = " + strTags + " WHERE id=" + getId(); stmt.executeUpdate(sql); } catch (Exception e) { throw new Exception("Error inserting tags for changeset with ID: " + getId() + " - " + e.getMessage()); } finally { // finally block used to close resources try { if (stmt != null) stmt.close(); } catch (SQLException se2) { } // nothing we can do } // end try }
From source file:com.l2jfree.gameserver.instancemanager.CursedWeaponsManager.java
private final void load() { Connection con = null;/*w w w .jav a 2 s . c om*/ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setIgnoringComments(true); File file = new File(Config.DATAPACK_ROOT, "data/cursedWeapons.xml"); if (!file.exists()) throw new IOException(); Document doc = factory.newDocumentBuilder().parse(file); for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) { if ("list".equalsIgnoreCase(n.getNodeName())) { for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) { if ("item".equalsIgnoreCase(d.getNodeName())) { NamedNodeMap attrs = d.getAttributes(); int id = Integer.parseInt(attrs.getNamedItem("id").getNodeValue()); int skillId = Integer.parseInt(attrs.getNamedItem("skillId").getNodeValue()); String name = attrs.getNamedItem("name").getNodeValue(); CursedWeapon cw = new CursedWeapon(id, skillId, name); int val; for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) { if ("dropRate".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue()); cw.setDropRate(val); } else if ("duration".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue()); cw.setDuration(val); } else if ("durationLost".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue()); cw.setDurationLost(val); } else if ("disapearChance".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue()); cw.setDisapearChance(val); } else if ("stageKills".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue()); cw.setStageKills(val); } else if ("transformId".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); val = Integer.parseInt(attrs.getNamedItem("val").getNodeValue()); cw.setTransformId(val); } } // Store cursed weapon _cursedWeapons.put(id, cw); } } } } // Retrieve the L2Player from the characters table of the database con = L2DatabaseFactory.getInstance().getConnection(); if (Config.ALLOW_CURSED_WEAPONS) { PreparedStatement statement = con.prepareStatement( "SELECT itemId, charId, playerKarma, playerPkKills, nbKills, endTime FROM cursed_weapons"); ResultSet rset = statement.executeQuery(); while (rset.next()) { int itemId = rset.getInt("itemId"); int playerId = rset.getInt("charId"); int playerKarma = rset.getInt("playerKarma"); int playerPkKills = rset.getInt("playerPkKills"); int nbKills = rset.getInt("nbKills"); long endTime = rset.getLong("endTime"); CursedWeapon cw = _cursedWeapons.get(itemId); cw.setPlayerId(playerId); cw.setPlayerKarma(playerKarma); cw.setPlayerPkKills(playerPkKills); cw.setNbKills(nbKills); cw.setEndTime(endTime); cw.reActivate(); } rset.close(); statement.close(); } else { PreparedStatement statement = con.prepareStatement("TRUNCATE TABLE cursed_weapons"); ResultSet rset = statement.executeQuery(); rset.close(); statement.close(); } //L2DatabaseFactory.close(con); // Retrieve the L2Player from the characters table of the database //con = L2DatabaseFactory.getInstance().getConnection(con); for (CursedWeapon cw : _cursedWeapons.values()) { if (cw.isActivated()) continue; // Do an item check to be sure that the cursed weapon isn't hold by someone int itemId = cw.getItemId(); try { PreparedStatement statement = con .prepareStatement("SELECT owner_id FROM items WHERE item_id=?"); statement.setInt(1, itemId); ResultSet rset = statement.executeQuery(); if (rset.next()) { // A player has the cursed weapon in his inventory ... int playerId = rset.getInt("owner_id"); _log.info("PROBLEM : Player " + playerId + " owns the cursed weapon " + itemId + " but he shouldn't."); // Delete the item PreparedStatement statement2 = con .prepareStatement("DELETE FROM items WHERE owner_id=? AND item_id=?"); statement2.setInt(1, playerId); statement2.setInt(2, itemId); if (statement2.executeUpdate() != 1) { _log.warn("Error while deleting cursed weapon " + itemId + " from userId " + playerId); } statement2.close(); // Delete the skill /* statement = con.prepareStatement("DELETE FROM character_skills WHERE charId=? AND skill_id="); statement.setInt(1, playerId); statement.setInt(2, cw.getSkillId()); if (statement.executeUpdate() != 1) { _log.warn("Error while deleting cursed weapon "+itemId+" skill from userId "+playerId); } */ // Restore the player's old karma and pk count statement2 = con .prepareStatement("UPDATE characters SET karma=?, pkkills=? WHERE charId = ?"); statement2.setInt(1, cw.getPlayerKarma()); statement2.setInt(2, cw.getPlayerPkKills()); statement2.setInt(3, playerId); if (statement2.executeUpdate() != 1) { _log.warn("Error while updating karma & pkkills for charId " + cw.getPlayerId()); } statement2.close(); // clean up the cursedweapons table. removeFromDb(itemId); } rset.close(); statement.close(); } catch (Exception e) { _log.warn("", e); } } } catch (Exception e) { _log.warn("Could not load CursedWeapons data: ", e); } finally { L2DatabaseFactory.close(con); } _log.info("CursedWeaponsManager: loaded " + _cursedWeapons.size() + " cursed weapon(s)."); }
From source file:com.doculibre.constellio.lang.html.HtmlLangDetector.java
private List<String> parse(Node node) { List<String> langs = new ArrayList<String>(); if (node.getNodeType() == Node.ELEMENT_NODE) { // Check for the lang HTML attribute final String htmlLang = parseLanguage(((Element) node).getAttribute("lang")); if (StringUtils.isNotBlank(htmlLang)) { langs.add(htmlLang);// w w w . ja v a2 s . co m } // Check for Meta if ("meta".equalsIgnoreCase(node.getNodeName())) { NamedNodeMap attrs = node.getAttributes(); // Check for the dc.language Meta for (int i = 0; i < attrs.getLength(); i++) { Node attrnode = attrs.item(i); if ("name".equalsIgnoreCase(attrnode.getNodeName())) { if ("dc.language".equalsIgnoreCase(attrnode.getNodeValue())) { Node valueattr = attrs.getNamedItem("content"); if (valueattr != null) { final String dublinCore = parseLanguage(valueattr.getNodeValue()); if (StringUtils.isNotBlank(dublinCore)) { langs.add(dublinCore); } } } } } // Check for the http-equiv content-language for (int i = 0; i < attrs.getLength(); i++) { Node attrnode = attrs.item(i); if ("http-equiv".equalsIgnoreCase(attrnode.getNodeName())) { if ("content-language".equalsIgnoreCase(attrnode.getNodeValue().toLowerCase())) { Node valueattr = attrs.getNamedItem("content"); if (valueattr != null) { final String httpEquiv = parseLanguage(valueattr.getNodeValue()); if (StringUtils.isNotBlank(httpEquiv)) { langs.add(httpEquiv); } } } } } // Check for the <meta name="language" content="xyz" /> tag for (int i = 0; i < attrs.getLength(); i++) { Node attrnode = attrs.item(i); if ("name".equalsIgnoreCase(attrnode.getNodeName())) { if ("language".equalsIgnoreCase(attrnode.getNodeValue().toLowerCase())) { Node valueattr = attrs.getNamedItem("content"); if (valueattr != null) { final String metaLanguage = parseLanguage(valueattr.getNodeValue()); if (StringUtils.isNotBlank(metaLanguage)) { langs.add(metaLanguage); } } } } } } } if (langs.isEmpty()) { // Recurse NodeList children = node.getChildNodes(); for (int i = 0; children != null && i < children.getLength(); i++) { langs.addAll(parse(children.item(i))); if (!langs.isEmpty()) { break; } } } return langs; }
From source file:com.vimeo.VimeoUploadClient.java
/** * call method//from w ww . ja va 2s. co m * * @param method * @param params * @return */ private ResponseWrapper call(String method, Map<String, String> params) throws APIException { if (verbose) System.out.println("Calling method: \"" + method + "\""); OAuthRequest orequest = new OAuthRequest(Verb.GET, VimeoUploadClient.ENDPOINT); orequest.addQuerystringParameter("method", method); if (params != null) { for (Map.Entry<String, String> p : params.entrySet()) { orequest.addQuerystringParameter(p.getKey(), p.getValue()); } } service.signRequest(accessToken, orequest); Response response = orequest.send(); if (verbose) System.out.println(response.getBody()); /* * NodeList nodes = (NodeList) path(response.getBody(), "//username", * XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) * { System.out.println(nodes.item(i).getTextContent()); } */ NamedNodeMap nodeMap3 = ((Node) path(response.getBody(), "//rsp", XPathConstants.NODE)).getAttributes(); String stat = nodeMap3.getNamedItem("stat").getNodeValue(); if (stat.equals("fail")) { System.out.println(" response " + response); throw new APIException(method, response); } return new ResponseWrapper(response, stat); }
From source file:com.example.fypv2.dataprocessor.OsmDataProcessor.java
@Override public List<Marker> load(String rawData, int taskId, int colour) throws JSONException { Element root = convertToXmlDocument(rawData).getDocumentElement(); List<Marker> markers = new ArrayList<Marker>(); NodeList nodes = root.getElementsByTagName("node"); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); NamedNodeMap att = node.getAttributes(); NodeList tags = node.getChildNodes(); for (int j = 0; j < tags.getLength(); j++) { Node tag = tags.item(j); if (tag.getNodeType() != Node.TEXT_NODE) { String key = tag.getAttributes().getNamedItem("k").getNodeValue(); if (key.equals("name")) { String name = tag.getAttributes().getNamedItem("v").getNodeValue(); String id = att.getNamedItem("id").getNodeValue(); double lat = Double.valueOf(att.getNamedItem("lat").getNodeValue()); double lon = Double.valueOf(att.getNamedItem("lon").getNodeValue()); Log.v(MainFrame.TAG, "OSM Node: " + name + " lat " + lat + " lon " + lon + "\n"); Marker ma = new NavigationMarker(id, name, lat, lon, 0, "http://www.openstreetmap.org/?node=" + id, taskId, colour); markers.add(ma);/*from w w w . j a v a2 s . c o m*/ // skip to next node continue; } } } } return markers; }