List of usage examples for org.w3c.dom Document getFirstChild
public Node getFirstChild();
From source file:com.l2jfree.gameserver.datatables.RecipeTable.java
private void loadFromXML() throws SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true);//from w ww. j a va 2s . c o m factory.setIgnoringComments(true); File file = new File(Config.DATAPACK_ROOT, "data/" + RECIPES_FILE); if (file.exists()) { Document doc = factory.newDocumentBuilder().parse(file); List<L2RecipeInstance> recipePartList = new FastList<L2RecipeInstance>(); List<L2RecipeStatInstance> recipeStatUseList = new FastList<L2RecipeStatInstance>(); List<L2RecipeStatInstance> recipeAltStatChangeList = new FastList<L2RecipeStatInstance>(); for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) { if ("list".equalsIgnoreCase(n.getNodeName())) { recipesFile: for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) { if ("item".equalsIgnoreCase(d.getNodeName())) { recipePartList.clear(); recipeStatUseList.clear(); recipeAltStatChangeList.clear(); NamedNodeMap attrs = d.getAttributes(); Node att; int id = -1; boolean haveRare = false; StatsSet set = new StatsSet(); att = attrs.getNamedItem("id"); if (att == null) { _log.fatal("Missing id for recipe item, skipping"); continue; } id = Integer.parseInt(att.getNodeValue()); set.set("id", id); att = attrs.getNamedItem("recipeId"); if (att == null) { _log.fatal("Missing recipeId for recipe item id: " + id + ", skipping"); continue; } set.set("recipeId", Integer.parseInt(att.getNodeValue())); att = attrs.getNamedItem("name"); if (att == null) { _log.fatal("Missing name for recipe item id: " + id + ", skipping"); continue; } set.set("recipeName", att.getNodeValue()); att = attrs.getNamedItem("craftLevel"); if (att == null) { _log.fatal("Missing level for recipe item id: " + id + ", skipping"); continue; } set.set("craftLevel", Integer.parseInt(att.getNodeValue())); att = attrs.getNamedItem("type"); if (att == null) { _log.fatal("Missing type for recipe item id: " + id + ", skipping"); continue; } set.set("isDwarvenRecipe", att.getNodeValue().equalsIgnoreCase("dwarven")); att = attrs.getNamedItem("successRate"); if (att == null) { _log.fatal("Missing successRate for recipe item id: " + id + ", skipping"); continue; } set.set("successRate", Integer.parseInt(att.getNodeValue())); for (Node c = d.getFirstChild(); c != null; c = c.getNextSibling()) { if ("statUse".equalsIgnoreCase(c.getNodeName())) { String statName = c.getAttributes().getNamedItem("name").getNodeValue(); int value = Integer .parseInt(c.getAttributes().getNamedItem("value").getNodeValue()); try { recipeStatUseList.add(new L2RecipeStatInstance(statName, value)); } catch (Exception e) { _log.fatal("Error in StatUse parameter for recipe item id: " + id + ", skipping", e); continue recipesFile; } } else if ("altStatChange".equalsIgnoreCase(c.getNodeName())) { String statName = c.getAttributes().getNamedItem("name").getNodeValue(); int value = Integer .parseInt(c.getAttributes().getNamedItem("value").getNodeValue()); try { recipeAltStatChangeList.add(new L2RecipeStatInstance(statName, value)); } catch (Exception e) { _log.fatal("Error in AltStatChange parameter for recipe item id: " + id + ", skipping", e); continue recipesFile; } } else if ("ingredient".equalsIgnoreCase(c.getNodeName())) { int ingId = Integer .parseInt(c.getAttributes().getNamedItem("id").getNodeValue()); int ingCount = Integer .parseInt(c.getAttributes().getNamedItem("count").getNodeValue()); recipePartList.add(new L2RecipeInstance(ingId, ingCount)); } else if ("production".equalsIgnoreCase(c.getNodeName())) { set.set("itemId", Integer.parseInt(c.getAttributes().getNamedItem("id").getNodeValue())); set.set("count", Integer .parseInt(c.getAttributes().getNamedItem("count").getNodeValue())); } else if ("productionRare".equalsIgnoreCase(c.getNodeName())) { set.set("rareItemId", Integer.parseInt(c.getAttributes().getNamedItem("id").getNodeValue())); set.set("rareCount", Integer .parseInt(c.getAttributes().getNamedItem("count").getNodeValue())); set.set("rarity", Integer .parseInt(c.getAttributes().getNamedItem("rarity").getNodeValue())); haveRare = true; } } L2RecipeList recipeList = new L2RecipeList(set, haveRare); for (L2RecipeInstance recipePart : recipePartList) recipeList.addRecipe(recipePart); for (L2RecipeStatInstance recipeStatUse : recipeStatUseList) recipeList.addStatUse(recipeStatUse); for (L2RecipeStatInstance recipeAltStatChange : recipeAltStatChangeList) recipeList.addAltStatChange(recipeAltStatChange); _lists.put(recipeList.getId(), recipeList); } } } } } else { _log.fatal("Recipes file (" + file.getAbsolutePath() + ") doesnt exists."); } }
From source file:ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository.java
/** * Iterates over the existing image styles and determines whether at least one * style has changed or is missing the previews. * //from w w w.ja v a 2 s .c om * @throws ContentRepositoryException * if preview generation fails */ protected void updatePreviews() throws ContentRepositoryException { // Compile the full list of image styles if (imageStyleTracker == null) { logger.info("Skipping preview generation: image styles are unavailable"); return; } final List<ImageStyle> allStyles = new ArrayList<ImageStyle>(); // Add the global image styles that have the preview flag turned on for (ImageStyle s : imageStyleTracker.getImageStyles()) { allStyles.add(s); } // Add the site's preview image styles as well as for (Module m : getSite().getModules()) { for (ImageStyle s : m.getImageStyles()) { allStyles.add(s); } } // Check whether the image styles still match the current definition. If // not, remove the produced previews and recreate them. boolean styleHasChanged = false; boolean styleIsMissing = false; for (ImageStyle s : allStyles) { File baseDir = ImageStyleUtils.getDirectory(site, s); File definitionFile = new File(baseDir, "style.xml"); // Try and read the file on disk if (definitionFile.isFile()) { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder; Document doc; ImageStyle style; try { docBuilder = docBuilderFactory.newDocumentBuilder(); doc = docBuilder.parse(definitionFile); style = ImageStyleImpl.fromXml(doc.getFirstChild()); // Is the style still the same? boolean stylesMatch = s.getWidth() == style.getWidth(); stylesMatch = stylesMatch && s.getHeight() == style.getHeight(); stylesMatch = stylesMatch && s.getScalingMode().equals(style.getScalingMode()); stylesMatch = stylesMatch && s.isPreview() == style.isPreview(); styleHasChanged = styleHasChanged || !stylesMatch; } catch (ParserConfigurationException e) { logger.error("Error setting up image style parser: {}", e.getMessage()); } catch (SAXException e) { logger.error("Error parsing image style {}: {}", definitionFile, e.getMessage()); } catch (IOException e) { logger.error("Error reading image style {}: {}", definitionFile, e.getMessage()); } } else { if (s.isPreview()) { logger.debug("No previews found for image style '{}'", s.getIdentifier()); styleIsMissing = true; } } // The current definition is no longer valid if (styleHasChanged) { logger.info("Image style '{}' has changed, removing existing previews from {}", s.getIdentifier(), baseDir); FileUtils.deleteQuietly(baseDir); if (!baseDir.mkdirs()) { logger.error("Error creating image style directory {}", baseDir); continue; } } // Store the new definition if (!definitionFile.isFile() || styleHasChanged) { try { definitionFile.getParentFile().mkdirs(); definitionFile.createNewFile(); FileUtils.copyInputStreamToFile(IOUtils.toInputStream(s.toXml(), "UTF-8"), definitionFile); } catch (IOException e) { logger.error("Error creating image style defintion file at {}", definitionFile, e.getMessage()); continue; } } else { logger.debug("Image style {} still matching the current definition", s.getIdentifier()); } } if (styleHasChanged || styleIsMissing) { if (environment.equals(Development)) { logger.info( "Missing or outdated previews found. Skipping preview generation for current environment 'development'"); return; } logger.info("Triggering creation of missing and outdated previews"); createPreviews(); } else { logger.debug("Preview images for {} are still up to date", site.getIdentifier()); } }
From source file:com.rapid.core.Page.java
public static Page load(ServletContext servletContext, File file) throws JAXBException, ParserConfigurationException, SAXException, IOException, TransformerFactoryConfigurationError, TransformerException { // get the logger Logger logger = (Logger) servletContext.getAttribute("logger"); // trace log that we're about to load a page logger.trace("Loading page from " + file); // open the xml file into a document Document pageDocument = XML.openDocument(file); // specify the xmlVersion as -1 int xmlVersion = -1; // look for a version node Node xmlVersionNode = XML.getChildElement(pageDocument.getFirstChild(), "XMLVersion"); // if we got one update the version if (xmlVersionNode != null) xmlVersion = Integer.parseInt(xmlVersionNode.getTextContent()); // if the version of this xml isn't the same as this class we have some work to do! if (xmlVersion != XML_VERSION) { // get the page name String name = XML.getChildElementValue(pageDocument.getFirstChild(), "name"); // log the difference logger.debug("Page " + name + " with version " + xmlVersion + ", current version is " + XML_VERSION); //// w w w .j a va2 s.c o m // Here we would have code to update from known versions of the file to the current version // // check whether there was a version node in the file to start with if (xmlVersionNode == null) { // create the version node xmlVersionNode = pageDocument.createElement("XMLVersion"); // add it to the root of the document pageDocument.getFirstChild().appendChild(xmlVersionNode); } // set the xml to the latest version xmlVersionNode.setTextContent(Integer.toString(XML_VERSION)); // // Here we would use xpath to find all controls and run the Control.upgrade method // // // Here we would use xpath to find all actions, each class has it's own upgrade method so // we need to identify the class, instantiate it and call it's upgrade method // it's probably worthwhile maintaining a map of instantiated classes to avoid unnecessary re-instantiation // // save it XML.saveDocument(pageDocument, file); logger.debug("Updated " + name + " page version to " + XML_VERSION); } // get the unmarshaller from the context Unmarshaller unmarshaller = RapidHttpServlet.getUnmarshaller(); // get a buffered reader for our page with UTF-8 file format BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); // try the unmarshalling try { // unmarshall the page Page page = (Page) unmarshaller.unmarshal(br); // log that the page was loaded logger.debug("Loaded page " + page.getId() + " - " + page.getName() + " from " + file); // close the buffered reader br.close(); // return the page return page; } catch (JAXBException ex) { // close the buffered reader br.close(); // log that the page had an error logger.error("Error loading page from " + file); // re-throw throw ex; } }
From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java
@Override public String escapeText(String inXml) throws SAXException, IOException { Document document = parse(inXml); Element rootNode = (Element) document.getFirstChild(); escapeNodeText(rootNode.getChildNodes()); return DomUtils.elementToString(document).replace("&#", "&#"); }
From source file:org.gvnix.web.menu.roo.addon.MenuEntryOperationsImpl.java
/** * Returns the Root element of the menu.xml file * /* w w w . j a va2 s.co m*/ * @return */ private Element getMenuRootElement() { Document document = getMenuDocument(); // make the root element of the menu the one with the menu identifier // allowing for different decorations of menu Element rootElement = XmlUtils.findFirstElement(ID_MENU_EXP, (Element) document.getFirstChild()); if (!rootElement.getNodeName().equals(GVNIX_MENU)) { throw new IllegalArgumentException(INVALID_XML); } return rootElement; }
From source file:org.gvnix.web.menu.roo.addon.MenuEntryOperationsImpl.java
/** {@inheritDoc} */ public void moveInto(JavaSymbolName pageId, JavaSymbolName intoId) { Document document = getMenuDocument(); // make the root element of the menu the one with the menu identifier // allowing for different decorations of menu Element rootElement = XmlUtils.findFirstElement(ID_MENU_EXP, (Element) document.getFirstChild()); if (!rootElement.getNodeName().equals(GVNIX_MENU)) { throw new IllegalArgumentException(INVALID_XML); }//from w w w . j a v a 2s .c om // check for existence of menu category by looking for the identifier // provided Element pageElement = XmlUtils.findFirstElement(ID_EXP.concat(pageId.getSymbolName()).concat("']"), rootElement); // exit if menu entry doesn't exist Validate.notNull(pageElement, PAGE.concat(pageId.getSymbolName()).concat(NOT_FOUND)); Element intoElement = XmlUtils.findFirstElement(ID_EXP.concat(intoId.getSymbolName()).concat("']"), rootElement); // exit if menu entry doesn't exist Validate.notNull(intoElement, PAGE.concat(intoId.getSymbolName()).concat(NOT_FOUND)); // parent element where remove menu entry element Element parent = (Element) pageElement.getParentNode(); parent.removeChild(pageElement); // insert intoElement.appendChild(pageElement); writeXMLConfigIfNeeded(document); }
From source file:org.gvnix.web.menu.roo.addon.MenuEntryOperationsImpl.java
/** {@inheritDoc} */ public void moveBefore(JavaSymbolName pageId, JavaSymbolName beforeId) { Document document = getMenuDocument(); // make the root element of the menu the one with the menu identifier // allowing for different decorations of menu Element rootElement = XmlUtils.findFirstElement(ID_MENU_EXP, (Element) document.getFirstChild()); if (!rootElement.getNodeName().equals(GVNIX_MENU)) { throw new IllegalArgumentException(INVALID_XML); }/* ww w . j a v a 2 s .c o m*/ // check for existence of menu category by looking for the identifier // provided Element pageElement = XmlUtils.findFirstElement(ID_EXP.concat(pageId.getSymbolName()).concat("']"), rootElement); // exit if menu entry doesn't exist Validate.notNull(pageElement, PAGE.concat(pageId.getSymbolName()).concat(NOT_FOUND)); Element beforeElement = XmlUtils.findFirstElement(ID_EXP.concat(beforeId.getSymbolName()).concat("']"), rootElement); // exit if menu entry doesn't exist Validate.notNull(beforeElement, PAGE.concat(beforeId.getSymbolName()).concat(NOT_FOUND)); // page parent element where remove menu entry element Element pageParentEl = (Element) pageElement.getParentNode(); pageParentEl.removeChild(pageElement); // before parent element where execute insert before Element beforeParentEl = (Element) beforeElement.getParentNode(); beforeParentEl.insertBefore(pageElement, beforeElement); writeXMLConfigIfNeeded(document); }
From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java
@Override public synchronized Map<String, Object> addElementByPath(final String path, final String originalXml, final String elementXml, boolean generateId) throws SAXException, IOException { Assert.hasText(path);/*from w w w. ja v a 2 s .c o m*/ Assert.hasText(originalXml); Assert.hasText(elementXml); logger.debug(elementXml); Document originalDom = parse(originalXml); Document elementDom = parse(elementXml); Document finalDom = originalDom; Element finalDomRoot = (Element) finalDom.getFirstChild(); Element elementRoot = (Element) elementDom.getFirstChild(); List<String> nodeList = getNodeList(path); logger.trace("nodeList: " + nodeList + " =? "); Assert.isTrue(nodeList.size() > 0); // remove first one, should be protocol nodeList.remove(0); String newElementName = nodeList.get(nodeList.size() - 1); logger.trace("adding <" + newElementName + ">"); // remove last one, should be <drug>, we are attaching the drug into // drugs... so we want the rightmost element to be drugs... nodeList.remove(nodeList.size() - 1); Element currentNode = finalDomRoot; int c = 0; for (String n : nodeList) { NodeList cur = currentNode.getElementsByTagName(n); String curName = currentNode.getNodeName(); c = cur.getLength(); if (c > 1) { throw new RuntimeException("illeagl xml structure; find " + c + " elements with name " + n); } if (c == 0) { logger.debug("empty node...; " + n + " doesn't exist under " + curName); Element newN = finalDom.createElement(n); currentNode.appendChild(newN); currentNode = newN; continue; } currentNode = (Element) cur.item(0); } logger.trace("rightmost element: " + currentNode.getNodeName()); String id = ""; if (generateId) { // using jdk UUID as uuid generator... id = UUID.randomUUID().toString(); Assert.isTrue(newElementName.equals(elementRoot.getNodeName()), "the element you are adding does not match the rightmost element name in the path!"); elementRoot.setAttribute("id", id); } currentNode.appendChild(finalDom.importNode(elementRoot, true)); Map<String, Object> resultMap = new HashMap<String, Object>(3); resultMap.put("finalXml", DomUtils.elementToString(finalDom)); resultMap.put("elementXml", DomUtils.elementToString(elementDom)); resultMap.put("elementId", id); return resultMap; }
From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java
/** * Thread-safety tested/* ww w .java2 s .co m*/ */ @Override public Map<String, Object> updateElementByPathById(String path, final String originalXml, String elementId, final String elementXml) throws SAXException, IOException { Assert.hasText(path); Assert.hasText(elementId); Assert.hasText(originalXml); Assert.hasText(elementId); Document originalDom = parse(originalXml); Document elementDom = parse(elementXml); Document finalDom = originalDom; Element finalDomRoot = (Element) finalDom.getFirstChild(); Element elementRoot = (Element) elementDom.getFirstChild(); List<String> nodeList = getNodeList(path); logger.trace("nodeList: " + nodeList + " =? "); // the root node of the path should be the same as the root node of // the originalXml Assert.isTrue(nodeList.size() > 0 && nodeList.get(0).equals(finalDomRoot.getNodeName())); // remove first one, should be protocol nodeList.remove(0); String elementToDeleteName = nodeList.get(nodeList.size() - 1); logger.trace("adding <" + elementToDeleteName + ">"); // remove last one, should be <drug>, we are attaching the drug into // drugs... so we want the rightmost element to be drugs... nodeList.remove(nodeList.size() - 1); Element currentNode = finalDomRoot; int c = 0; for (String n : nodeList) { NodeList cur = currentNode.getElementsByTagName(n); c = cur.getLength(); if (c > 1) { throw new RuntimeException("illeagl xml structure; find " + c + " elements with name " + n); } if (c == 0) { throw new RuntimeException("illeagl xml structure; " + n + " doesn't exist"); } currentNode = (Element) cur.item(0); } logger.trace("rightmost element: " + currentNode.getNodeName()); elementRoot.setAttribute("id", elementId); Node newChild = finalDom.importNode(elementRoot, true); NodeList nodes = currentNode.getChildNodes(); int l = nodes.getLength(); logger.trace("lenght: " + l); for (int i = 0; i < l; i++) { Element cc = (Element) nodes.item(i); if (cc.getAttribute("id").equals(elementId)) { currentNode.replaceChild(newChild, cc); break; } } Map<String, Object> resultMap = new HashMap<String, Object>(3); resultMap.put("finalXml", DomUtils.elementToString(finalDom)); resultMap.put("elementXml", DomUtils.elementToString(elementDom)); resultMap.put("elementId", elementId); return resultMap; }