List of usage examples for org.w3c.dom Document getFirstChild
public Node getFirstChild();
From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java
private Document parseXML(Resource resource, List<Rule> rules) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { debug("Now loading " + resource); try (InputStream in = resource.getInputStream()) { final Document doc = XMLRewrite.parseXML(in); rewriteXML(doc, rules, false, false); final List<Node> importNodes = evaluateXPath("/beans//import", doc); debug("Found " + importNodes.size() + " import statements"); for (Node importNode : importNodes) { debug("(1) Node has parent: " + importNode.getParentNode()); String path = importNode.getAttributes().getNamedItem("resource").getNodeValue(); if (path.startsWith("classpath:")) { path = path.substring("classpath:".length()); }/*from w ww .ja v a 2 s . c o m*/ debug("Including '" + path + "' , now at " + resource); final Resource imported; if (path.startsWith("/")) { // absolute imported = new ClassPathResource(path); } else { imported = resource.createRelative(path); } final Document importedXML = parseXML(imported, rules); mergeAttributes(importedXML.getFirstChild(), doc.getFirstChild(), doc); final List<Node> beans = wrapNodeList(importedXML.getFirstChild().getChildNodes()); for (Node beanNode : beans) { final Node adoptedNode = doc.adoptNode(beanNode.cloneNode(true)); importNode.getParentNode().insertBefore(adoptedNode, importNode); } importNode.getParentNode().removeChild(importNode); } debug("*** return ***"); return doc; } catch (Exception e) { throw new RuntimeException("Failed to load XML from '" + resource + "'", e); } }
From source file:com.twinsoft.convertigo.engine.admin.services.database_objects.Set.java
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception { Element root = document.getDocumentElement(); Document post = null; Element response = document.createElement("response"); try {//from www . j a v a 2 s .c o m Map<String, DatabaseObject> map = com.twinsoft.convertigo.engine.admin.services.projects.Get .getDatabaseObjectByQName(request); xpath = new TwsCachedXPathAPI(); post = XMLUtils.parseDOM(request.getInputStream()); postElt = document.importNode(post.getFirstChild(), true); String objectQName = xpath.selectSingleNode(postElt, "./@qname").getNodeValue(); DatabaseObject object = map.get(objectQName); // String comment = getPropertyValue(object, "comment").toString(); // object.setComment(comment); if (object instanceof Project) { Project project = (Project) object; String objectNewName = getPropertyValue(object, "name").toString(); Engine.theApp.databaseObjectsManager.renameProject(project, objectNewName); map.remove(objectQName); map.put(project.getQName(), project); } BeanInfo bi = CachedIntrospector.getBeanInfo(object.getClass()); PropertyDescriptor[] propertyDescriptors = bi.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String propertyName = propertyDescriptor.getName(); Method setter = propertyDescriptor.getWriteMethod(); Class<?> propertyTypeClass = propertyDescriptor.getReadMethod().getReturnType(); if (propertyTypeClass.isPrimitive()) { propertyTypeClass = ClassUtils.primitiveToWrapper(propertyTypeClass); } try { String propertyValue = getPropertyValue(object, propertyName).toString(); Object oPropertyValue = createObject(propertyTypeClass, propertyValue); if (object.isCipheredProperty(propertyName)) { Method getter = propertyDescriptor.getReadMethod(); String initialValue = (String) getter.invoke(object, (Object[]) null); if (oPropertyValue.equals(initialValue) || DatabaseObject.encryptPropertyValue(initialValue).equals(oPropertyValue)) { oPropertyValue = initialValue; } else { object.hasChanged = true; } } if (oPropertyValue != null) { Object args[] = { oPropertyValue }; setter.invoke(object, args); } } catch (IllegalArgumentException e) { } } Engine.theApp.databaseObjectsManager.exportProject(object.getProject()); response.setAttribute("state", "success"); response.setAttribute("message", "Project have been successfully updated!"); } catch (Exception e) { Engine.logAdmin.error("Error during saving the properties!\n" + e.getMessage()); response.setAttribute("state", "error"); response.setAttribute("message", "Error during saving the properties!"); Element stackTrace = document.createElement("stackTrace"); stackTrace.setTextContent(e.getMessage()); root.appendChild(stackTrace); } finally { xpath.resetCache(); } root.appendChild(response); }
From source file:com.portfolio.data.utils.DomUtils.java
private static void insererXML(Connection connexion, Document xmlSourceDoc, String partageableId, StringBuffer outTrace, boolean trace) throws Exception { // --------------------------------------------------- if (trace)/*from w w w . jav a 2 s. c om*/ outTrace.append("<br>insererPartageable -- entre"); if (trace) outTrace.append("<br>partageableId=" + partageableId); // ===============chargement du document source ======================================== if (trace) outTrace.append("<br>lecture du document xml :" + partageableId + "..."); Document xmlPartageable = buildDOM(readXmlString(connexion, partageableId, outTrace)); if (trace) outTrace.append(" ok"); DocumentFragment aInserer = xmlSourceDoc.createDocumentFragment(); NodeList liste = xmlPartageable.getDocumentElement().getChildNodes(); int nbListe = liste.getLength(); if (trace) outTrace.append("<br> nbListe=" + nbListe); for (int i = 0; i < nbListe; i++) { aInserer.appendChild(xmlSourceDoc.importNode(liste.item(i), true)); } xmlSourceDoc.getFirstChild().insertBefore(aInserer, xmlSourceDoc.getFirstChild().getFirstChild()); if (trace) outTrace.append("<br>insererPartageable -- sortie"); }
From source file:de.ingrid.iplug.csw.dsc.cache.impl.DefaultFileCache.java
@Override public CSWRecord getRecord(String id, ElementSetName elementSetName) throws IOException { if (!this.isInitialized()) initialize();/*from ww w. ja v a2s . c o m*/ String filePath = this.getAbsoluteFilename(id, elementSetName); File file = new File(filePath); if (file.exists()) { StringBuilder content = new StringBuilder(); BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); try { String line = null; while ((line = input.readLine()) != null) { content.append(line); content.append(System.getProperty("line.separator")); } input.close(); input = null; Document document = StringUtils.stringToDocument(content.toString()); CSWRecord record = this.factory.createRecord(); record.initialize(elementSetName, document.getFirstChild()); return record; } catch (Exception e) { throw new IOException(e); } finally { if (input != null) input.close(); } } else throw new IOException("No cache entry with id " + id + " and elementset " + elementSetName + " found."); }
From source file:com.mnxfst.testing.client.TSClientPlanExecCallable.java
/** * @see java.util.concurrent.Callable#call() *//*w w w. j av a 2s .co m*/ @SuppressWarnings("unused") public NameValuePair call() throws Exception { InputStream ptestServerInputStream = null; try { // HttpResponse response = httpClient.execute(httpHost, getMethod); HttpResponse response = httpClient.execute(httpHost, postMethod); ptestServerInputStream = response.getEntity().getContent(); XPath xpath = XPathFactory.newInstance().newXPath(); Document responseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(ptestServerInputStream); if (response == null) throw new TSClientExecutionException( "No response document received from " + httpHost.getHostName()); // fetch root node Node rootNode = responseDoc.getFirstChild(); if (rootNode == null) throw new TSClientExecutionException( "No valid root node found in document received from " + httpHost.getHostName()); if (rootNode.getNodeName() == null || !rootNode.getNodeName().equalsIgnoreCase(TEST_EXEC_RESPONSE_ROOT)) throw new TSClientExecutionException( "No valid root node found in document received from " + httpHost.getHostName()); int responseCode = parseResponseCode(rootNode, xpath); switch (responseCode) { case RESPONSE_CODE_EXECUTION_STARTED: { String responseIdentifier = parseResultIdentifier(rootNode, xpath); return new BasicNameValuePair(httpHost.getHostName(), responseIdentifier); } case RESPONSE_CODE_ERROR: { List<Long> errorCodes = parseErrorCodes(rootNode, xpath); StringBuffer codes = new StringBuffer(); for (Iterator<Long> iter = errorCodes.iterator(); iter.hasNext();) { codes.append(iter.next()); if (iter.hasNext()) codes.append(","); } throw new TSClientExecutionException("Failed to execute test plan on " + httpHost.getHostName() + ":" + httpHost.getPort() + ". Error codes: " + codes.toString()); } default: { throw new TSClientExecutionException("Unexpected response code '" + responseCode + "' received from " + httpHost.getHostName() + ":" + httpHost.getPort()); } } } catch (ClientProtocolException e) { throw new TSClientExecutionException("Failed to call " + httpHost.getHostName() + ":" + httpHost.getPort() + "/" + postMethod.getURI() + ". Error: " + e.getMessage()); } catch (IOException e) { throw new TSClientExecutionException("Failed to call " + httpHost.getHostName() + ":" + httpHost.getPort() + "/" + postMethod.getURI() + ". Error: " + e.getMessage()); } finally { if (ptestServerInputStream != null) { try { ptestServerInputStream.close(); httpClient.getConnectionManager().shutdown(); } catch (Exception e) { System.out.println("Failed to close ptest-server connection"); } } } }
From source file:com.mnxfst.testing.server.cfg.PTestServerConfigurationParser.java
/** * Parses the contents of the provided configuration file contents into an object * @param configFileContents//from ww w. ja va 2s . c om * @return * @throws ServerConfigurationFailedException */ public PTestServerConfiguration parseServerConfiguration(byte[] configFileContents) throws ServerConfigurationFailedException { if (configFileContents == null || configFileContents.length < 1) throw new ServerConfigurationFailedException("Missing required config file contents"); try { // parse the provided byte array into a valid document and check resul Document cfgDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new ByteArrayInputStream(configFileContents)); if (cfgDocument == null) throw new ServerConfigurationFailedException( "Provided contents could not be parsed into a valid document"); Node rootNode = cfgDocument.getFirstChild(); if (rootNode == null) throw new ServerConfigurationFailedException( "The provided document does not have a valid root node"); if (rootNode.getNodeName() == null || rootNode.getNodeName().isEmpty()) throw new ServerConfigurationFailedException( "The root node of the provided document does not have a valid name"); if (!rootNode.getNodeName().equalsIgnoreCase(XML_ROOT)) throw new ServerConfigurationFailedException( "The provided document does not contain a valid configuration since it misses the required root node"); // extract hostname, port and socket pool size from configuration String hostname = evaluateString(xpathExpressionHostname, cfgDocument); if (hostname == null || hostname.trim().isEmpty()) throw new ServerConfigurationFailedException("Missing the required settings for 'hostname'"); Integer port = evaluateInteger(xpathExpressionPort, cfgDocument); if (port == null) throw new ServerConfigurationFailedException("Missing the required settings for 'port'"); Integer socketPoolSize = evaluateInteger(xpathExpressionSocketPoolSize, cfgDocument); if (socketPoolSize == null) throw new ServerConfigurationFailedException("Missing the required settings for 'socketPoolSize'"); // extract handler configurations and validate for emptiness and null NodeList handlerCfgs = evaluateNodeList(xpathExpressionAllHandlerSettings, cfgDocument); if (handlerCfgs == null || handlerCfgs.getLength() < 1) throw new ServerConfigurationFailedException( "No context handlers defined. Please provide at least one context"); PTestServerConfiguration serverConfiguration = new PTestServerConfiguration(hostname, port, socketPoolSize); // step through handler configurations and extract path and class for (int i = 0; i < handlerCfgs.getLength(); i++) { Node handlerCfgNode = handlerCfgs.item(i); String ctxPath = evaluateString(xpathExpressionHandlerPath, handlerCfgNode); String ctxClass = evaluateString(xpathExpressionHandlerClass, handlerCfgNode); // validate path and class - invalid values provided for any of them leads to an exception if (ctxPath == null || ctxPath.trim().isEmpty()) throw new ServerConfigurationFailedException( "Invalid context path found in configuration file contents"); if (ctxClass == null || ctxClass.trim().isEmpty()) throw new ServerConfigurationFailedException( "Invalid handler class found in configuration file contents"); // TODO additional configuration serverConfiguration.addContextHandlerSetting(ctxPath, new BasicNameValuePair("class", ctxClass)); } return serverConfiguration; } catch (IOException e) { throw new ServerConfigurationFailedException( "Failed to read contents from provided configuration. Error: " + e.getMessage()); } catch (SAXException e) { throw new ServerConfigurationFailedException( "Failed to parse contents from provided configuration. Error: " + e.getMessage()); } catch (ParserConfigurationException e) { throw new ServerConfigurationFailedException( "Failed to parse contents from provided configuration. Error: " + e.getMessage()); } catch (XPathExpressionException e) { throw new ServerConfigurationFailedException( "Failed to evaluate xpath expression on configuration. Error: " + e.getMessage()); } }
From source file:MSUmpire.SpectrumParser.mzXMLReadUnit.java
public ScanData Parse() throws ParserConfigurationException, SAXException, IOException, DataFormatException { if (XMLtext.replaceFirst("</scan>", "").contains("</scan>")) { XMLtext = XMLtext.replaceFirst("</scan>", ""); }//from w ww . j av a2 s. c om if (!XMLtext.contains("</scan>")) { XMLtext += "</scan>"; } ScanData scan = new ScanData(); final DocumentBuilder docBuilder = tls.get(); docBuilder.reset(); InputSource input = new InputSource(new StringReader(XMLtext)); Document doc = null; try { doc = docBuilder.parse(input); } catch (Exception ex) { Logger.getRootLogger().error(ExceptionUtils.getStackTrace(ex)); Logger.getRootLogger().error(XMLtext); } Node root = doc.getFirstChild(); for (int i = 0; i < root.getAttributes().getLength(); i++) { switch (root.getAttributes().item(i).getNodeName()) { case ("num"): scan.ScanNum = Integer.parseInt(root.getAttributes().item(i).getNodeValue()); break; case ("centroided"): { if ("1".equals(root.getAttributes().item(i).getNodeValue())) { scan.centroided = true; } else { scan.centroided = false; } break; } case ("msLevel"): scan.MsLevel = Integer.parseInt(root.getAttributes().item(i).getNodeValue()); break; case ("scanType"): scan.scanType = root.getAttributes().item(i).getNodeValue(); break; case ("peaksCount"): scan.PeaksCountString = Integer.parseInt(root.getAttributes().item(i).getNodeValue()); break; case ("retentionTime"): scan.RetentionTime = Float.parseFloat(root.getAttributes().item(i).getNodeValue().substring(2, root.getAttributes().item(i).getNodeValue().indexOf("S"))) / 60f; break; case ("lowMz"): { String value = root.getAttributes().item(i).getNodeValue(); if ("inf".equals(value)) { value = String.valueOf(Float.MIN_VALUE); } scan.StartMz = Float.parseFloat(value); break; } case ("highMz"): { String value = root.getAttributes().item(i).getNodeValue(); if ("inf".equals(value)) { value = String.valueOf(Float.MAX_VALUE); } scan.EndMz = Float.parseFloat(value); break; } case ("startMz"): scan.StartMz = Float.parseFloat(root.getAttributes().item(i).getNodeValue()); break; case ("endMz"): { String value = root.getAttributes().item(i).getNodeValue(); if ("inf".equals(value)) { value = String.valueOf(Float.MAX_VALUE); } scan.EndMz = Float.parseFloat(value); break; } case ("basePeakMz"): { String value = root.getAttributes().item(i).getNodeValue(); if ("inf".equals(value)) { value = String.valueOf(Float.MAX_VALUE); } scan.BasePeakMz = Float.parseFloat(value); break; } case ("basePeakIntensity"): scan.BasePeakIntensity = Float.parseFloat(root.getAttributes().item(i).getNodeValue()); break; case ("totIonCurrent"): scan.SetTotIonCurrent(Float.parseFloat(root.getAttributes().item(i).getNodeValue())); break; } } for (int i = 0; i < root.getChildNodes().getLength(); i++) { Node childNode = root.getChildNodes().item(i); switch (childNode.getNodeName()) { case ("precursorMz"): { scan.PrecursorMz = Float.parseFloat(childNode.getTextContent()); for (int j = 0; j < childNode.getAttributes().getLength(); j++) { switch (childNode.getAttributes().item(j).getNodeName()) { case ("precursorScanNum"): scan.precursorScanNum = Integer.parseInt(childNode.getAttributes().item(j).getNodeValue()); break; case ("precursorIntensity"): scan.PrecursorIntensity = Float .parseFloat(childNode.getAttributes().item(j).getNodeValue()); break; case ("precursorCharge"): scan.PrecursorCharge = Integer.parseInt(childNode.getAttributes().item(j).getNodeValue()); break; case ("activationMethod"): scan.ActivationMethod = childNode.getAttributes().item(j).getNodeValue(); break; case ("windowWideness"): scan.windowWideness = Float.parseFloat(childNode.getAttributes().item(j).getNodeValue()); break; } } break; } case ("peaks"): { for (int j = 0; j < childNode.getAttributes().getLength(); j++) { switch (childNode.getAttributes().item(j).getNodeName()) { case ("compressionType"): scan.compressionType = childNode.getAttributes().item(j).getNodeValue(); break; case ("precision"): scan.precision = Integer.parseInt(childNode.getAttributes().item(j).getNodeValue()); break; } } ParsePeakString(scan, childNode.getTextContent()); break; } } childNode = null; } if ("calibration".equals(scan.scanType)) { scan.MsLevel = -1; } XMLtext = null; scan.Data.Finalize(); return scan; }
From source file:org.gvnix.service.roo.addon.addon.security.SecurityServiceImpl.java
/** * {@inheritDoc}// w w w . ja va 2 s. co m */ public void addOrUpdateAxisClientService(String serviceName, Map<String, String> parameters) throws SAXException, IOException { createAxisClientConfigFile(); String axisClientPath = getAxisClientConfigPath(); Document document = XmlUtils.getDocumentBuilder().parse(new File(axisClientPath)); Element deployment = (Element) document.getFirstChild(); Element serviceElementDescriptor = getAxisClientService(document, serviceName, parameters); List<Element> previousServices = XmlUtils .findElements("/deployment/service[@name='".concat(serviceName).concat("']"), deployment); if (previousServices.isEmpty()) { deployment.appendChild(serviceElementDescriptor); } else { deployment.replaceChild(serviceElementDescriptor, previousServices.get(0)); } OutputStream outputStream = new ByteArrayOutputStream(); Transformer transformer = XmlUtils.createIndentingTransformer(); XmlUtils.writeXml(transformer, outputStream, document); fileManager.createOrUpdateTextFileIfRequired(axisClientPath, outputStream.toString(), false); }
From source file:edu.mit.csail.sls.wami.relay.WamiRelay.java
public void handleClientUpdate(HttpSession session, String xmlUpdate) { Document doc = XmlUtils.toXMLDocument(xmlUpdate); Element root = (Element) doc.getFirstChild(); logClientEvent(xmlUpdate, root);/*from w ww. j a v a2 s . c om*/ String type = root.getAttribute("type"); if ("hotswap".equals(type)) { hotswapComponent(WamiConfig.getConfiguration(session.getServletContext()), root); } else if (wamiApp != null) { wamiApp.onClientMessage(root); } else { System.err.println("warming: handleClientUpdate called with null wami app"); } }
From source file:net.sf.l2j.gameserver.instancemanager.DimensionalRiftManager.java
public void loadSpawns() { int countGood = 0, countBad = 0; try {/*from w w w.ja v a 2 s .co m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); File file = new File(Config.DATAPACK_ROOT + "/data/dimensionalRift.xml"); if (!file.exists()) throw new IOException(); Document doc = factory.newDocumentBuilder().parse(file); NamedNodeMap attrs; byte type, roomId; int mobId, x, y, z, delay, count; L2Spawn spawnDat; L2NpcTemplate template; for (Node rift = doc.getFirstChild(); rift != null; rift = rift.getNextSibling()) { if ("rift".equalsIgnoreCase(rift.getNodeName())) { for (Node area = rift.getFirstChild(); area != null; area = area.getNextSibling()) { if ("area".equalsIgnoreCase(area.getNodeName())) { attrs = area.getAttributes(); type = Byte.parseByte(attrs.getNamedItem("type").getNodeValue()); for (Node room = area.getFirstChild(); room != null; room = room.getNextSibling()) { if ("room".equalsIgnoreCase(room.getNodeName())) { attrs = room.getAttributes(); roomId = Byte.parseByte(attrs.getNamedItem("id").getNodeValue()); for (Node spawn = room.getFirstChild(); spawn != null; spawn = spawn .getNextSibling()) { if ("spawn".equalsIgnoreCase(spawn.getNodeName())) { attrs = spawn.getAttributes(); mobId = Integer.parseInt(attrs.getNamedItem("mobId").getNodeValue()); delay = Integer.parseInt(attrs.getNamedItem("delay").getNodeValue()); count = Integer.parseInt(attrs.getNamedItem("count").getNodeValue()); template = NpcTable.getInstance().getTemplate(mobId); if (template == null) _log.warn("Template " + mobId + " not found!"); if (!_rooms.containsKey(type)) _log.warn("Type " + type + " not found!"); else if (!_rooms.get(type).containsKey(roomId)) _log.warn("Room " + roomId + " in Type " + type + " not found!"); for (int i = 0; i < count; i++) { DimensionalRiftRoom riftRoom = _rooms.get(type).get(roomId); x = riftRoom.getRandomX(); y = riftRoom.getRandomY(); z = riftRoom.getTeleportCoords()[2]; if (template != null && _rooms.containsKey(type) && _rooms.get(type).containsKey(roomId)) { spawnDat = new L2Spawn(template); spawnDat.setAmount(1); spawnDat.setLocx(x); spawnDat.setLocy(y); spawnDat.setLocz(z); spawnDat.setHeading(-1); spawnDat.setRespawnDelay(delay); SpawnTable.getInstance().addNewSpawn(spawnDat, false); _rooms.get(type).get(roomId).getSpawns().add(spawnDat); countGood++; } else { countBad++; } } } } } } } } } } } catch (Exception e) { _log.warn("Error on loading dimensional rift spawns: " + e); e.printStackTrace(); } _log.info("DimensionalRiftManager: Loaded " + countGood + " dimensional rift spawns, " + countBad + " errors."); }