public void setValue(String value) { synchronized (DOMUtils.getDOMLock(elt)) { { String oldValue = getValue(); if (oldValue == null ? value == null : oldValue.equals(value)) return; synchronized (DOMUtils.getDOMLock(elt)) { // Get rid of any text nodes that are children of the element. elt.normalize(); } NodeList nl = elt.getChildNodes(); for (int i = (nl.getLength() - 1); i >= 0; i--) { Node n = nl.item(i); if (n.getNodeType() == Node.TEXT_NODE) { synchronized (DOMUtils.getDOMLock(elt)) { elt.removeChild(n); } IXArch context = getXArch(); if (context != null) { context.fireXArchEvent( new XArchEvent( this, XArchEvent.CLEAR_EVENT, XArchEvent.SIMPLE_TYPE_VALUE_CHANGED, "$SIMPLETYPEVALUE$", null, XArchUtils.getDefaultXArchImplementation().isContainedIn(xArch, this), true)); } } } } elt.normalize(); Document doc = elt.getOwnerDocument(); Text txt = doc.createTextNode(value); elt.appendChild(txt); } IXArch context = getXArch(); if (context != null) { context.fireXArchEvent( new XArchEvent( this, XArchEvent.SET_EVENT, XArchEvent.SIMPLE_TYPE_VALUE_CHANGED, "$SIMPLETYPEVALUE$", value, XArchUtils.getDefaultXArchImplementation().isContainedIn(xArch, this))); } }
public static void write() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc; System.out.println("Writing patient data file\n"); try { DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.newDocument(); Element root = doc.createElement("patientdata"); root.appendChild(XMLInterface.nl(doc)); // get first PatientData from DataStore Iterator<PatientDataStore> pdsIt = GlobalVars.pds.iterator(); while (pdsIt.hasNext()) { PatientDataStore pds = pdsIt.next(); Node n = pds.createXMLNode(doc); XMLInterface.addNode(doc, root, n, 0); } root.normalize(); // create junk to write it out (see java xml tutorial) TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource src = new DOMSource(root); StreamResult result = new StreamResult(new File(GlobalVars.XMLDataFile)); transformer.transform(src, result); } catch (Exception e) { System.err.println("Error WRITING xml patient data file"); e.printStackTrace(); } }
/* * Work down the children tree * @param parent * @param el */ private void processChildren(ESBNodeWithChildren parent, Element el) { el.normalize(); parent.setData(el); if (parent.getEsbObjectType() == null) { String tag = el.getTagName(); if (tag.endsWith("-bus") && el.getAttribute("busid") != null) { // $NON-NLS-1$ //$NON-NLS-2$ parent.setEsbObjectType(ESBType.BUS); } else if (tag.endsWith("-listener") && el.getAttribute("busidref") != null) { // $NON-NLS-1$ //$NON-NLS-2$ parent.setEsbObjectType(ESBType.LISTENER); } else if (tag.endsWith("-provider")) { // $NON-NLS-1$ parent.setEsbObjectType(ESBType.PROVIDER); } else if (tag.equalsIgnoreCase("service")) { // $NON-NLS-1$ parent.setEsbObjectType(ESBType.SERVICE); } else if (tag.equalsIgnoreCase("listeners")) { // $NON-NLS-1$ parent.setEsbObjectType(ESBType.LISTENER); } else if (tag.equalsIgnoreCase("Actions")) { // $NON-NLS-1$ parent.setEsbObjectType(ESBType.ACTION); } else if (tag.equalsIgnoreCase("action")) { // $NON-NLS-1$ parent.setEsbObjectType(ESBType.ACTION); } else if (tag.equalsIgnoreCase("property")) { // $NON-NLS-1$ parent.setEsbObjectType(ESBType.PROPERTY); return; } } NodeList children = el.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { if (children.item(i) instanceof Element) { Element child = (Element) children.item(i); String name = child.getAttribute("name"); // $NON-NLS-1$ if (name == null || name.trim().length() == 0) { name = child.getAttribute("busid"); // $NON-NLS-1$ } if (name == null || name.trim().length() == 0) { name = child.getAttribute("dest-name"); // $NON-NLS-1$ } if (name == null || name.trim().length() == 0) { name = child.getTagName(); } if (name.equalsIgnoreCase("actions")) { // $NON-NLS-1$ name = JBossESBUIMessages.ESBDomParser_Actions_Node_Label; } else if (name.equalsIgnoreCase("listeners")) { // $NON-NLS-1$ name = JBossESBUIMessages.ESBDomParser_Listeners_Node_Label; } ESBNodeWithChildren childNode = new ESBNodeWithChildren(name); String ref = child.getAttribute("busidref"); // $NON-NLS-1$ if (ref != null && ref.trim().length() > 0) { childNode.setRef(ref); } processChildren(childNode, child); if (childNode.getEsbObjectType() != null && !childNode.getEsbObjectType().equals(ESBType.PROPERTY)) { parent.addChild(childNode); childNode.setEsbObjectType(parent.getEsbObjectType()); } } } }
@Test public final void testMove() { try { fs._move(new Move(basePath, sess, uri, null, newProj)); } catch (SyncFailedException e) { fail("SyncFailedException thrown " + e); } File newXml = new File(newTsdir + "/" + sess + ".xml"); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder; Document doc = null; try { docBuilder = docFactory.newDocumentBuilder(); doc = docBuilder.parse(newXml); } catch (ParserConfigurationException e) { fail("Exception thrown " + e.getMessage()); } catch (SAXException e) { fail("Exception thrown " + e.getMessage()); } catch (IOException e) { fail("Exception thrown " + e.getMessage()); } Element e = doc.getDocumentElement(); e.normalize(); Assert.assertEquals(newProj, e.getAttribute("project")); }
public void clearValue() { synchronized (DOMUtils.getDOMLock(elt)) { // Get rid of any text nodes that are children of the element. elt.normalize(); } NodeList nl = elt.getChildNodes(); for (int i = (nl.getLength() - 1); i >= 0; i--) { Node n = nl.item(i); if (n.getNodeType() == Node.TEXT_NODE) { synchronized (DOMUtils.getDOMLock(elt)) { elt.removeChild(n); } IXArch context = getXArch(); if (context != null) { context.fireXArchEvent( new XArchEvent( this, XArchEvent.CLEAR_EVENT, XArchEvent.SIMPLE_TYPE_VALUE_CHANGED, "$SIMPLETYPEVALUE$", null, XArchUtils.getDefaultXArchImplementation().isContainedIn(xArch, this))); } } } }
public boolean loadURDF(String filename) { System.out.println("[INFO]\tLoading URDF file '" + filename + "' ..."); try { File file = new File(filename); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); urdf = db.parse(file); Element el = urdf.getDocumentElement(); el.normalize(); String docElementName = urdf.getDocumentElement().getNodeName(); if (!docElementName.equalsIgnoreCase("robot")) { throw new RuntimeException( "Document element is '" + docElementName + "', but should be 'robot'"); } srdl = new StringBuffer(); } catch (Exception e) { System.out.println("[ERROR]\tCould not load URDF file:"); e.printStackTrace(); return false; } System.out.println("[INFO]\tLoading URDF file '" + filename + "' -> DONE"); return true; }
/** * Extract the normalized text from within an element * * @param fromElement * @return extracted Text node (could be null) */ protected Text extractText(Element fromElement) { fromElement.normalize(); NodeList fromNodeList = fromElement.getChildNodes(); Node currentNode; for (int i = 0; i < fromNodeList.getLength(); ++i) { currentNode = fromNodeList.item(i); if (currentNode.getNodeType() == Node.TEXT_NODE) { return (Text) currentNode; } } return null; }
public static String textInElement(Element elem) { StringBuilder buf = new StringBuilder(100); elem.normalize(); NodeList nlst = elem.getChildNodes(); for (int i = 0, nlen = nlst.getLength(); i < nlen; i++) { Node n = nlst.item(i); if (n instanceof Text) { final String data = ((Text) n).getData(); buf.append(data); } } return buf.toString(); }
public String getValue() { synchronized (DOMUtils.getDOMLock(elt)) { elt.normalize(); NodeList nl = elt.getChildNodes(); for (int i = (nl.getLength() - 1); i >= 0; i--) { Node n = nl.item(i); if (n.getNodeType() == Node.TEXT_NODE) { return n.getNodeValue(); } } return null; } }
@Override public void endElement(final String uri, final String localName, final String qName) { if (current == null) { return; } Node parent = current.getParentNode(); // If the parent is the document itself, then we're done. if (parent.getParentNode() == null) { current.normalize(); current = null; } else { current = (Element) current.getParentNode(); } }
/** * Read device configuration from XML stream * * @param stream Stream for XML content * @return {@link DeviceInfo}s read from stream * @throws Exception on error */ private DeviceInfo[] read(final InputStream stream) throws Exception { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); final DocumentBuilder db = dbf.newDocumentBuilder(); final Document doc = db.parse(stream); // Check root element for <scan_config>, but still allow <beamline> final Element root_node = doc.getDocumentElement(); root_node.normalize(); final String root_name = root_node.getNodeName(); if (!root_name.equals(XML_SCAN_CONFIG)) { if (root_name.equals(XML_BEAMLINE)) Logger.getLogger(ScanConfig.class.getName()) .log( Level.WARNING, "<" + XML_BEAMLINE + "> is deprecated, use <" + XML_SCAN_CONFIG + ">"); else throw new Exception("Got " + root_name + " instead of " + XML_SCAN_CONFIG); } final NodeList hooks = root_node.getElementsByTagName(XML_SIMULATION_HOOK); if (hooks.getLength() == 1) simulation_hook = XMLUtil.getString(hooks.item(0), ""); // Loop over <pv>s, being very lenient where they are in the document. // This allows both <scan_config> and legacy <beamline>. // Users who want strict checking can refer to the schema in their XML files, // use xmllint etc. final List<DeviceInfo> devices = new ArrayList<DeviceInfo>(); final NodeList pvs = root_node.getElementsByTagName(XML_PV); for (int i = 0; i < pvs.getLength(); ++i) { final Element pv = (Element) pvs.item(i); final double slew_rate = XMLUtil.getSubelementDouble(pv, XML_SLEW_RATE, Double.NaN); final String name = XMLUtil.getSubelementString(pv, XML_NAME, ""); if (name.isEmpty()) { // Check if it's a pattern, which then requires a slew rate final String pattern = XMLUtil.getSubelementString(pv, XML_NAME_PATTERN, ""); if (pattern.isEmpty()) throw new Exception("Missing <pv> <name> or <name_pattern>"); if (Double.isNaN(slew_rate)) throw new Exception("Missing <slew_rate> for <pv> <name_pattern>"); patterned_slew_rates.add(new PatternedSlew(pattern, slew_rate)); } else { // Got name, maybe with alias and slew rate final String alias = XMLUtil.getSubelementString(pv, XML_ALIAS, name); devices.add(new DeviceInfo(name, alias)); if (!Double.isNaN(slew_rate)) pv_slew_rates.put(name, slew_rate); } } return devices.toArray(new DeviceInfo[devices.size()]); }
/** * Save the XML description of the circuit * * @param output an output stream to write in * @return true if the dump was successful, false either */ public boolean dumpToXml(OutputStream output) { Document doc; Element root; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); doc = builder.newDocument(); } catch (ParserConfigurationException pce) { System.err.println("dumpToXmlFile: unable to write XML save file."); return false; } root = doc.createElement("Circuit"); root.setAttribute("name", this.getName()); for (iterNodes = this.nodes.iterator(); iterNodes.hasNext(); ) iterNodes.next().dumpToXml(doc, root); root.normalize(); doc.appendChild(root); try { TransformerFactory tffactory = TransformerFactory.newInstance(); Transformer transformer = tffactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(output); transformer.transform(source, result); } catch (TransformerConfigurationException tce) { System.err.println("dumpToXmlFile: Configuration Transformer exception."); return false; } catch (TransformerException te) { System.err.println("dumpToXmlFile: Transformer exception."); return false; } return true; }
/** * Returns the root element of a given input stream * * @param is stream to parse * @return XML DOM element, or null if unable to parse stream */ public static Element getDocumentRoot(InputStream is) { Document doc; try { InputSource xmlInp = new InputSource(is); DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(true); DocumentBuilder parser = docBuilderFactory.newDocumentBuilder(); doc = parser.parse(xmlInp); Element root = doc.getDocumentElement(); root.normalize(); return root; } catch (SAXParseException err) { log.configuratorSAXParseError(err); } catch (SAXException e) { log.configuratorSAXError(e); } catch (Exception pce) { log.configuratorError(pce); } return null; }
/** * submit HTTP Request (Both GET and POST). Parse the response into an xml document element. * * @param method * @param urlString * @param postdata * @param usr * @param pwd * @return response * @throws IOException * @throws ParserConfigurationException * @throws SAXException */ public Element submitHttpRequestAndGetDom( String method, String urlString, String postdata, String usr, String pwd) throws IOException, ParserConfigurationException, SAXException { InputStream inStream = null; Element response; try { inStream = submitHttpRequest(method, urlString, postdata, "", ""); // Get a response DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.parse(inStream); response = doc.getDocumentElement(); response.normalize(); } finally { Utils.close(inStream); } return response; }
public void save() { Document doc = XMLManager.newDocument(); Element root = (Element) doc.createElement("vdct"); doc.appendChild(root); saveRdbSettings(doc, root); root.normalize(); String fileName = System.getProperty(Constants.VDCT_SETTINGS_FILE); if (fileName == null) { fileName = System.getProperty("user.home") + "/" + Constants.VDCT_SETTINGS_FILE_NAME; } try { XMLManager.writeDocument(fileName, doc, null, null, null); } catch (IOException e) { Console.getInstance().println("Error while saving settings file!"); Console.getInstance().println(e); } }
/** * Tries to find the first <code>schemaVersion=""</code> attribute in the XML root and returns * value inside as integer. * * @param xmlInputStream Stream to read from. * @param defaultValue default value to return to caller if version could not be found or * attribute does not have an integer number. * @return Version attribute value in root element found. */ private int getSchemaVersion(InputStream xmlInputStream, int defaultValue) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document document = dBuilder.parse(xmlInputStream); // optional, but recommended // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work Element element = document.getDocumentElement(); element.normalize(); // we expect schemaVersion attribute in the root element if (element.hasAttribute("schemaVersion")) { String version = element.getAttribute("schemaVersion"); return (int) Double.parseDouble(version); } else { return defaultValue; } } catch (ParserConfigurationException | SAXException | IOException | NumberFormatException e) { LOG.warn("Error trying to get the schema version attribute.", e); return defaultValue; } }
/** * Returns the element, optionally normalizing it. * * @param element the element * @param normalize whether or not to normalize the element * @return the element */ public Element pull(Element element, boolean normalize) { if (normalize) { element.normalize(); } return element; }
/** * Unmarshall a Chromosome instance from a given XML Element representation. * * @param a_activeConfiguration current Configuration object * @param a_xmlElement the XML Element representation of the Chromosome * @return a new Chromosome instance setup with the data from the XML Element representation * @throws ImproperXMLException if the given Element is improperly structured or missing data * @throws UnsupportedRepresentationException if the actively configured Gene implementation does * not support the string representation of the alleles used in the given XML document * @throws GeneCreationException if there is a problem creating or populating a Gene instance * @author Neil Rotstan * @since 1.0 */ public static Gene[] getGenesFromElement( Configuration a_activeConfiguration, Element a_xmlElement) throws ImproperXMLException, UnsupportedRepresentationException, GeneCreationException { // Do some sanity checking. Make sure the XML Element isn't null and // that it in fact represents a set of genes. // ----------------------------------------------------------------- if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(GENES_TAG))) { throw new ImproperXMLException( "Unable to build Chromosome instance from XML Element: " + "given Element is not a 'genes' element."); } List genes = Collections.synchronizedList(new ArrayList()); // Extract the nested gene elements. // --------------------------------- NodeList geneElements = a_xmlElement.getElementsByTagName(GENE_TAG); if (geneElements == null) { throw new ImproperXMLException( "Unable to build Gene instances from XML Element: " + "'" + GENE_TAG + "'" + " sub-elements not found."); } // For each gene, get the class attribute so we know what class // to instantiate to represent the gene instance, and then find // the child text node, which is where the string representation // of the allele is located, and extract the representation. // ------------------------------------------------------------- int numberOfGeneNodes = geneElements.getLength(); for (int i = 0; i < numberOfGeneNodes; i++) { Element thisGeneElement = (Element) geneElements.item(i); thisGeneElement.normalize(); // Fetch the class attribute and create an instance of that // class to represent the current gene. // -------------------------------------------------------- String geneClassName = thisGeneElement.getAttribute(CLASS_ATTRIBUTE); Gene thisGeneObject; Class geneClass = null; try { geneClass = Class.forName(geneClassName); try { Constructor constr = geneClass.getConstructor(new Class[] {Configuration.class}); thisGeneObject = (Gene) constr.newInstance(new Object[] {a_activeConfiguration}); } catch (NoSuchMethodException nsme) { // Try it by calling method newGeneInternal. // ----------------------------------------- Constructor constr = geneClass.getConstructor(new Class[] {}); thisGeneObject = (Gene) constr.newInstance(new Object[] {}); thisGeneObject = (Gene) PrivateAccessor.invoke( thisGeneObject, "newGeneInternal", new Class[] {}, new Object[] {}); } } catch (Throwable e) { throw new GeneCreationException(geneClass, e); } // Find the text node and fetch the string representation of // the allele. // --------------------------------------------------------- NodeList children = thisGeneElement.getChildNodes(); int childrenSize = children.getLength(); String alleleRepresentation = null; for (int j = 0; j < childrenSize; j++) { Element alleleElem = (Element) children.item(j); if (alleleElem.getTagName().equals(ALLELE_TAG)) { alleleRepresentation = alleleElem.getAttribute("value"); } if (children.item(j).getNodeType() == Node.TEXT_NODE) { // We found the text node. Extract the representation. // --------------------------------------------------- alleleRepresentation = children.item(j).getNodeValue(); break; } } // Sanity check: Make sure the representation isn't null. // ------------------------------------------------------ if (alleleRepresentation == null) { throw new ImproperXMLException( "Unable to build Gene instance from XML Element: " + "value (allele) is missing representation."); } // Now set the value of the gene to that reflect the // string representation. // ------------------------------------------------- try { thisGeneObject.setValueFromPersistentRepresentation(alleleRepresentation); } catch (UnsupportedOperationException e) { throw new GeneCreationException( "Unable to build Gene because it does not support the " + "setValueFromPersistentRepresentation() method."); } // Finally, add the current gene object to the list of genes. // ---------------------------------------------------------- genes.add(thisGeneObject); } return (Gene[]) genes.toArray(new Gene[genes.size()]); }
public void addWindowPair(WindowPairs win, int nwin, Telescope tel) { nodelist = this.document.getElementsByTagName("RESOURCE"); // if telescope is flipped such that east is left, then take account double dir = 1.0; if (tel.flipped) dir = -1.0; // System.out.println("adding window pair " + nwin); // now - does this window already exist? If it does there's nothing more to do. for (int i = 0; i < nodelist.getLength(); i++) { Element elem = (Element) nodelist.item(i); String check = "WindowPair" + nwin; if (elem.hasAttribute("ID") && elem.getAttribute("ID").equals(check)) { // OK, it exists, let's bail // System.out.println("Window Pair " + nwin + " already exists."); return; } } // OK - it doesn't exist so let's put it in! // get a template for a window descriptor by editing the main window resource // Get elements containing the whole FoV resource and the full CCD Resource Element ccdRes = null; Element fovRes = null; for (int i = 0; i < nodelist.getLength(); i++) { Element elem = (Element) nodelist.item(i); if (elem.hasAttribute("ID") && elem.getAttribute("ID").equals("WCCD")) // this is the resource element detailing the main window ccdRes = (Element) elem; if (elem.hasAttribute("ID") && elem.getAttribute("ID").equals("UCAM_FoV")) // this is the resource element detailing the whole FOV fovRes = (Element) elem; } // let's try copying the ccd Resource element to a window resource element. Element winRes1 = null; winRes1 = (Element) ccdRes.cloneNode(true); // change resource name String id = "WindowPair" + nwin; winRes1.setAttribute("ID", id); winRes1.setAttribute("name", id); // change rest of attributes winRes1.normalize(); nodelist = winRes1.getChildNodes(); for (int i = 0; i < nodelist.getLength(); i++) { if (nodelist.item(i).getNodeType() == 1) { Element elem = (Element) nodelist.item(i); // description if (elem.getTagName().equals("DESCRIPTION")) elem.setTextContent("An ULTRACAM window"); // Short Description if (elem.hasAttribute("ShortDescription")) elem.setAttribute("ShortDescription", "Left Window of Pair"); if (elem.getTagName().equals("TABLE") && elem.hasAttribute("ID")) { elem.setAttribute("ID", "LWin"); elem.setAttribute("name", "Lwin"); } } } // The right window of the pair is represented by a second <TABLE> node in the // resource, so let's copy the one that's already there nodelist = winRes1.getElementsByTagName("TABLE"); Element TableElem = (Element) nodelist.item(0); Element rightWin = (Element) TableElem.cloneNode(true); rightWin.setAttribute("ID", "RWin"); rightWin.setAttribute("name", "RWin"); winRes1.appendChild(rightWin); // normally we set the <TD> datatags here to the 4 corners of the window double x1, x2, x3, x4, y1, y2; double PlateScale = tel.plateScale; double xoff = tel.delta_x; double yoff = tel.delta_y; try { x1 = xoff + dir * (512 - win.getXleft(nwin)) * PlateScale; x3 = (x1 - dir * win.getNx(nwin) * PlateScale); y1 = yoff + (win.getYstart(nwin) - 512) * PlateScale; y2 = y1 + win.getNy(nwin) * PlateScale; x2 = xoff + dir * (512 - win.getXright(nwin)) * PlateScale; x4 = (x2 - dir * win.getNx(nwin) * PlateScale); nodelist = winRes1.getElementsByTagName("TD"); nodelist.item(0).setTextContent("" + x1); nodelist.item(1).setTextContent("" + y1); nodelist.item(2).setTextContent("" + x3); nodelist.item(3).setTextContent("" + y1); nodelist.item(4).setTextContent("" + x3); nodelist.item(5).setTextContent("" + y2); nodelist.item(6).setTextContent("" + x1); nodelist.item(7).setTextContent("" + y2); nodelist.item(8).setTextContent("" + x2); nodelist.item(9).setTextContent("" + y1); nodelist.item(10).setTextContent("" + x4); nodelist.item(11).setTextContent("" + y1); nodelist.item(12).setTextContent("" + x4); nodelist.item(13).setTextContent("" + y2); nodelist.item(14).setTextContent("" + x2); nodelist.item(15).setTextContent("" + y2); } catch (Exception e) { e.printStackTrace(); } // set colour to blue nodelist = winRes1.getElementsByTagName("PARAM"); for (int i = 0; i < nodelist.getLength(); i++) { Element elem = (Element) nodelist.item(i); if (elem.hasAttribute("name") && (elem.getAttribute("name").equals("color"))) elem.setAttribute("value", "blue"); } // append window to file try { fovRes.appendChild(winRes1); } catch (DOMException e) { e.printStackTrace(); } }
private boolean parseResult(InputStream in, JUnitEETest test) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document; byte[] buffer = readInput(in); try { document = builder.parse(new ByteArrayInputStream(buffer)); } catch (SAXException e) { log("Invalid xml:\n " + new String(buffer), Project.MSG_ERR); throw new BuildException("Unable to parse test result (no valid xml)."); } Element root = document.getDocumentElement(); if (root.getAttributeNode("unfinished") != null) { log(String.valueOf(root.getAttributeNode("unfinished")), Project.MSG_DEBUG); return false; } root.normalize(); NodeList testcases = root.getElementsByTagName("testsuite"); Vector<JUnitEEResultFormatter> resultFormatters = createFormatters(test); for (int i = 0; i < testcases.getLength(); i++) { Node node = testcases.item(i); NamedNodeMap attributes = node.getAttributes(); String testClass = attributes.getNamedItem("name").getNodeValue(); String testPkg = attributes.getNamedItem("package").getNodeValue(); int errors = Integer.parseInt(attributes.getNamedItem("errors").getNodeValue()); int failures = Integer.parseInt(attributes.getNamedItem("failures").getNodeValue()); String testName; if (testPkg != null && testPkg.length() != 0) { testName = testPkg + "." + testClass; } else { testName = testClass; } for (JUnitEEResultFormatter formatter : resultFormatters) { log("Calling formatter " + formatter + " for node " + node, Project.MSG_DEBUG); formatter.format(node); formatter.flush(); } if (errors != 0) { if (test.getErrorproperty() != null) { getProject().setNewProperty(test.getErrorproperty(), "true"); } if (test.getHaltonerror() || test.getHaltonfailure()) { throw new BuildException("Test " + testName + " failed."); } } if (failures != 0) { if (test.getFailureproperty() != null) { getProject().setNewProperty(test.getFailureproperty(), "true"); } if (test.getHaltonfailure()) { throw new BuildException("Test " + testName + " failed."); } } } NodeList errorMessages = root.getElementsByTagName("errorMessage"); for (int i = 0; i < errorMessages.getLength(); i++) { Node message = errorMessages.item(i); log(message.getFirstChild().getNodeValue(), Project.MSG_ERR); } if (errorMessages.getLength() != 0) { throw new BuildException("Test execution failed."); } return true; }
public static Composition readOpenRaster(File file) throws IOException, ParserConfigurationException, SAXException { boolean DEBUG = System.getProperty("openraster.debug", "false").equals("true"); String stackXML = null; Map<String, BufferedImage> images = new HashMap<>(); try (ZipFile zipFile = new ZipFile(file)) { Enumeration<? extends ZipEntry> fileEntries = zipFile.entries(); while (fileEntries.hasMoreElements()) { ZipEntry entry = fileEntries.nextElement(); String name = entry.getName(); if (name.equalsIgnoreCase("stack.xml")) { stackXML = extractString(zipFile.getInputStream(entry)); } else if (name.equalsIgnoreCase("mergedimage.png")) { // no need for that } else { String extension = FileExtensionUtils.getFileExtension(name); if ("png".equalsIgnoreCase(extension)) { BufferedImage image = ImageIO.read(zipFile.getInputStream(entry)); images.put(name, image); if (DEBUG) { System.out.println( String.format( "OpenRaster::readOpenRaster: found png image in zip file at the path '%s'", name)); } } } } } if (stackXML == null) { throw new IllegalStateException("No stack.xml found."); } if (DEBUG) { System.out.println(String.format("OpenRaster::readOpenRaster: stackXML = '%s'", stackXML)); } Document doc = loadXMLFromString(stackXML); Element documentElement = doc.getDocumentElement(); documentElement.normalize(); String documentElementNodeName = documentElement.getNodeName(); if (!documentElementNodeName.equals("image")) { throw new IllegalStateException( String.format( "stack.xml root element is '%s', expected: 'image'", documentElementNodeName)); } String w = documentElement.getAttribute("w"); int compositionWidth = Integer.parseInt(w); String h = documentElement.getAttribute("h"); int compositionHeight = Integer.parseInt(h); if (DEBUG) { System.out.println( String.format( "OpenRaster::readOpenRaster: w = '%s', h = '%s', compositionWidth = %d, compositionHeight = %d", w, h, compositionWidth, compositionHeight)); } Composition comp = Composition.empty(compositionWidth, compositionHeight); comp.setFile(file); NodeList layers = documentElement.getElementsByTagName("layer"); for (int i = layers.getLength() - 1; i >= 0; i--) { // stack.xml contains layers in reverse order Node node = layers.item(i); Element element = (Element) node; String layerName = element.getAttribute("name"); String layerVisibility = element.getAttribute("visibility"); String layerVisible = element.getAttribute("visible"); String layerBlendingMode = element.getAttribute("composite-op"); String layerOpacity = element.getAttribute("opacity"); String layerImageSource = element.getAttribute("src"); String layerX = element.getAttribute("x"); String layerY = element.getAttribute("y"); BufferedImage image = images.get(layerImageSource); image = ImageUtils.toCompatibleImage(image); if (DEBUG) { int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); System.out.println( "OpenRaster::readOpenRaster: imageWidth = " + imageWidth + ", imageHeight = " + imageHeight); // Utils.debugImage(image, layerImageSource); } if (layerVisibility == null || layerVisibility.isEmpty()) { // workaround: paint.net exported files use "visible" attribute instead of "visibility" layerVisibility = layerVisible; } boolean visibility = layerVisibility == null ? true : layerVisibility.equals("visible"); ImageLayer layer = new ImageLayer(comp, image, layerName, null); layer.setVisible(visibility, AddToHistory.NO); BlendingMode blendingMode = BlendingMode.fromSVGName(layerBlendingMode); if (DEBUG) { System.out.println("OpenRaster::readOpenRaster: blendingMode = " + blendingMode); } layer.setBlendingMode(blendingMode, UpdateGUI.NO, AddToHistory.NO, false); float opacity = Utils.parseFloat(layerOpacity, 1.0f); layer.setOpacity(opacity, UpdateGUI.NO, AddToHistory.NO, false); int translationX = Utils.parseInt(layerX, 0); int translationY = Utils.parseInt(layerY, 0); // TODO assuming that there is no layer mask layer.setTranslation(translationX, translationY); if (DEBUG) { System.out.println( String.format( "OpenRaster::readOpenRaster: opacity = %.2f, translationX = %d, translationY = %d", opacity, translationX, translationY)); } comp.addLayerNoGUI(layer); } comp.setActiveLayer(comp.getLayer(0), AddToHistory.NO); return comp; }
public Map<String, ModelEntity> getEntityCache() throws GenericEntityException { if (entityCache == null) { // don't want to block here synchronized (ModelReader.class) { // must check if null again as one of the blocked threads can still enter if (entityCache == null) { // now it's safe numEntities = 0; numViewEntities = 0; numFields = 0; numRelations = 0; numAutoRelations = 0; entityCache = new HashMap<String, ModelEntity>(); List<ModelViewEntity> tempViewEntityList = FastList.newInstance(); List<Element> tempExtendEntityElementList = FastList.newInstance(); UtilTimer utilTimer = new UtilTimer(); for (ResourceHandler entityResourceHandler : entityResourceHandlers) { // utilTimer.timerString("Before getDocument in file " + entityFileName); Document document = null; try { document = entityResourceHandler.getDocument(); } catch (GenericConfigException e) { throw new GenericEntityConfException( "Error getting document from resource handler", e); } if (document == null) { throw new GenericEntityConfException( "Could not get document for " + entityResourceHandler.toString()); } // utilTimer.timerString("Before getDocumentElement in " + // entityResourceHandler.toString()); Element docElement = document.getDocumentElement(); if (docElement == null) { return null; } docElement.normalize(); Node curChild = docElement.getFirstChild(); ModelInfo def = new ModelInfo(); def.populateFromElements(docElement); int i = 0; if (curChild != null) { utilTimer.timerString( "Before start of entity loop in " + entityResourceHandler.toString()); do { boolean isEntity = "entity".equals(curChild.getNodeName()); boolean isViewEntity = "view-entity".equals(curChild.getNodeName()); boolean isExtendEntity = "extend-entity".equals(curChild.getNodeName()); if ((isEntity || isViewEntity) && curChild.getNodeType() == Node.ELEMENT_NODE) { i++; ModelEntity modelEntity = buildEntity(entityResourceHandler, (Element) curChild, i, def); // put the view entity in a list to get ready for the second pass to populate // fields... if (isViewEntity) { tempViewEntityList.add((ModelViewEntity) modelEntity); } else { entityCache.put(modelEntity.getEntityName(), modelEntity); } } else if (isExtendEntity && curChild.getNodeType() == Node.ELEMENT_NODE) { tempExtendEntityElementList.add((Element) curChild); } } while ((curChild = curChild.getNextSibling()) != null); } else { Debug.logWarning("No child nodes found.", module); } utilTimer.timerString( "Finished " + entityResourceHandler.toString() + " - Total Entities: " + i + " FINISHED"); } // all entity elements in, now go through extend-entity elements and add their stuff for (Element extendEntityElement : tempExtendEntityElementList) { String entityName = UtilXml.checkEmpty(extendEntityElement.getAttribute("entity-name")); ModelEntity modelEntity = entityCache.get(entityName); if (modelEntity == null) throw new GenericEntityConfException( "Entity to extend does not exist: " + entityName); modelEntity.addExtendEntity(this, extendEntityElement); } // do a pass on all of the view entities now that all of the entities have // loaded and populate the fields while (!tempViewEntityList.isEmpty()) { int startSize = tempViewEntityList.size(); Iterator<ModelViewEntity> mveIt = tempViewEntityList.iterator(); TEMP_VIEW_LOOP: while (mveIt.hasNext()) { ModelViewEntity curViewEntity = mveIt.next(); for (ModelViewEntity.ModelMemberEntity mve : curViewEntity.getAllModelMemberEntities()) { if (!entityCache.containsKey(mve.getEntityName())) { continue TEMP_VIEW_LOOP; } } mveIt.remove(); curViewEntity.populateFields(this); for (ModelViewEntity.ModelMemberEntity mve : curViewEntity.getAllModelMemberEntities()) { ModelEntity me = (ModelEntity) entityCache.get(mve.getEntityName()); me.addViewEntity(curViewEntity); } entityCache.put(curViewEntity.getEntityName(), curViewEntity); } if (tempViewEntityList.size() == startSize) { // Oops, the remaining views reference other entities // that can't be found, or they reference other views // that have some reference problem. break; } } if (!tempViewEntityList.isEmpty()) { StringBuilder sb = new StringBuilder("View entities reference non-existant members:\n"); Set<String> allViews = FastSet.newInstance(); for (ModelViewEntity curViewEntity : tempViewEntityList) { allViews.add(curViewEntity.getEntityName()); } for (ModelViewEntity curViewEntity : tempViewEntityList) { Set<String> perViewMissingEntities = FastSet.newInstance(); Iterator<ModelViewEntity.ModelMemberEntity> mmeIt = curViewEntity.getAllModelMemberEntities().iterator(); while (mmeIt.hasNext()) { ModelViewEntity.ModelMemberEntity mme = mmeIt.next(); String memberEntityName = mme.getEntityName(); if (!entityCache.containsKey(memberEntityName)) { // this member is not a real entity // check to see if it is a view if (!allViews.contains(memberEntityName)) { // not a view, it's a real missing entity perViewMissingEntities.add(memberEntityName); } } } for (String perViewMissingEntity : perViewMissingEntities) { sb.append("\t[") .append(curViewEntity.getEntityName()) .append("] missing member entity [") .append(perViewMissingEntity) .append("]\n"); } } throw new GenericEntityConfException(sb.toString()); } // auto-create relationships TreeSet<String> orderedMessages = new TreeSet<String>(); for (String curEntityName : new TreeSet<String>(this.getEntityNames())) { ModelEntity curModelEntity = this.getModelEntity(curEntityName); if (curModelEntity instanceof ModelViewEntity) { // for view-entities auto-create relationships for all member-entity relationships // that have all corresponding fields in the view-entity } else { // for entities auto-create many relationships for all type one relationships // just in case we add a new relation to the same entity, keep in a separate list and // add them at the end List<ModelRelation> newSameEntityRelations = FastList.newInstance(); Iterator<ModelRelation> relationsIter = curModelEntity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); if (("one".equals(modelRelation.getType()) || "one-nofk".equals(modelRelation.getType())) && !modelRelation.isAutoRelation()) { ModelEntity relatedEnt = null; try { relatedEnt = this.getModelEntity(modelRelation.getRelEntityName()); } catch (GenericModelException e) { throw new GenericModelException( "Error getting related entity [" + modelRelation.getRelEntityName() + "] definition from entity [" + curEntityName + "]", e); } if (relatedEnt != null) { // don't do relationship to the same entity, unless title is "Parent", then do a // "Child" automatically String targetTitle = modelRelation.getTitle(); if (curModelEntity.getEntityName().equals(relatedEnt.getEntityName()) && "Parent".equals(targetTitle)) { targetTitle = "Child"; } // create the new relationship even if one exists so we can show what we are // looking for in the info message ModelRelation newRel = new ModelRelation(); newRel.setModelEntity(relatedEnt); newRel.setRelEntityName(curModelEntity.getEntityName()); newRel.setTitle(targetTitle); newRel.setAutoRelation(true); Set<String> curEntityKeyFields = FastSet.newInstance(); for (int kmn = 0; kmn < modelRelation.getKeyMapsSize(); kmn++) { ModelKeyMap curkm = modelRelation.getKeyMap(kmn); ModelKeyMap newkm = new ModelKeyMap(); newRel.addKeyMap(newkm); newkm.setFieldName(curkm.getRelFieldName()); newkm.setRelFieldName(curkm.getFieldName()); curEntityKeyFields.add(curkm.getFieldName()); } // decide whether it should be one or many by seeing if the key map represents // the complete pk of the relEntity if (curModelEntity.containsAllPkFieldNames(curEntityKeyFields)) { // always use one-nofk, we don't want auto-fks getting in for these automatic // ones newRel.setType("one-nofk"); // to keep it clean, remove any additional keys that aren't part of the PK List<String> curPkFieldNames = curModelEntity.getPkFieldNames(); Iterator<ModelKeyMap> nrkmIter = newRel.getKeyMapsIterator(); while (nrkmIter.hasNext()) { ModelKeyMap nrkm = nrkmIter.next(); String checkField = nrkm.getRelFieldName(); if (!curPkFieldNames.contains(checkField)) { nrkmIter.remove(); } } } else { newRel.setType("many"); } ModelRelation existingRelation = relatedEnt.getRelation(targetTitle + curModelEntity.getEntityName()); if (existingRelation == null) { numAutoRelations++; if (curModelEntity.getEntityName().equals(relatedEnt.getEntityName())) { newSameEntityRelations.add(newRel); } else { relatedEnt.addRelation(newRel); } } else { if (newRel.equals(existingRelation)) { // don't warn if the target title+entity = current title+entity if (!(targetTitle + curModelEntity.getEntityName()) .equals(modelRelation.getTitle() + modelRelation.getRelEntityName())) { // String errorMsg = "Relation already exists to entity [] with title [" + // targetTitle + "],from entity []"; String message = "Entity [" + relatedEnt.getPackageName() + ":" + relatedEnt.getEntityName() + "] already has identical relationship to entity [" + curModelEntity.getEntityName() + "] title [" + targetTitle + "]; would auto-create: type [" + newRel.getType() + "] and fields [" + newRel.keyMapString(",", "") + "]"; orderedMessages.add(message); } } else { String message = "Existing relationship with the same name, but different specs found from what would be auto-created for Entity [" + relatedEnt.getEntityName() + "] and relationship to entity [" + curModelEntity.getEntityName() + "] title [" + targetTitle + "]; would auto-create: type [" + newRel.getType() + "] and fields [" + newRel.keyMapString(",", "") + "]"; Debug.logVerbose(message, module); } } } else { String errorMsg = "Could not find related entity [" + modelRelation.getRelEntityName() + "], no reverse relation added."; Debug.logWarning(errorMsg, module); } } } if (newSameEntityRelations.size() > 0) { for (ModelRelation newRel : newSameEntityRelations) { curModelEntity.addRelation(newRel); } } } } for (String message : orderedMessages) { Debug.logInfo(message, module); } Debug.log( "FINISHED LOADING ENTITIES - ALL FILES; #Entities=" + numEntities + " #ViewEntities=" + numViewEntities + " #Fields=" + numFields + " #Relationships=" + numRelations + " #AutoRelationships=" + numAutoRelations, module); } } } return entityCache; }
private static void loadConfig(java.io.InputStream is) throws java.io.IOException { root.subKeys = new java.util.HashMap(); javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); try { javax.xml.parsers.DocumentBuilder builder = factory.newDocumentBuilder(); org.w3c.dom.Document document = builder.parse(is); org.w3c.dom.Element rootElement = document.getDocumentElement(); rootElement.normalize(); org.w3c.dom.NodeList childNodes = rootElement.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { org.w3c.dom.Node childNode = childNodes.item(i); if (childNode instanceof org.w3c.dom.Element) { org.w3c.dom.Element childElement = (org.w3c.dom.Element) childNode; String tagName = childElement.getTagName(); if (tagName.equals("key")) { Key subKey = loadKey(childElement); if ((subKey != null) && (subKey.name != null)) { root.subKeys.put(subKey.name, subKey); // System.out.println( "loaded subKey: " + subKey ); } } } } // } catch( org.xml.sax.SAXParseException spe ) { // if( spe.getException() != null ) { // edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "Error parsing // preferences file; line " + spe.getLineNumber() + ", uri " + spe.getSystemId() + "\nmessage: // " + spe.getMessage(), spe.getException() ); // } else { // edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "Error parsing // preferences file; line " + spe.getLineNumber() + ", uri " + spe.getSystemId() + "\nmessage: // " + spe.getMessage(), spe ); // } // } catch( org.xml.sax.SAXException sxe ) { // if( sxe.getException() != null ) { // edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "Error parsing // preferences file.", sxe.getException() ); // } else { // edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "Error parsing // preferences file.", sxe ); // } // } catch( javax.xml.parsers.ParserConfigurationException pce ) { // edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "Error parsing // preferences file.", pce ); // } } catch (Exception e) { edu.cmu.cs.stage3.swing.DialogManager.showMessageDialog( java.util.ResourceBundle.getBundle( "edu/cmu/cs/stage3/alice/authoringtool/util/Configuration") .getString( "ALICE_HAD_TROUBLE_READING_YOUR_PREFERENCES_BUT_WILL_CONTINUE_TO_RUN_NORMALLY"), java.util.ResourceBundle.getBundle( "edu/cmu/cs/stage3/alice/authoringtool/util/Configuration") .getString("UNABLE_TO_LOAD_PREFERENCES"), javax.swing.JOptionPane.WARNING_MESSAGE); } }