private void guardaRes(String resu, CliGol cliGol) throws ParserConfigurationException, SAXException, IOException { String[] nodos = {"NoHit", "Hit", "Buro"}; DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(new StringReader(resu)); Document xml = db.parse(is); Element raiz = xml.getDocumentElement(); String nombre = obtenerNombre(raiz); for (String s : nodos) { Node nodo = raiz.getElementsByTagName(s) == null ? null : raiz.getElementsByTagName(s).item(0); if (nodo != null) { String informacion = sustraerInformacionNodo(cliGol, nodo); guardarEnListas(nodo.getNodeName(), nombre + "," + informacion); } } }
public List parsePage(String pageCode) { List sections = new ArrayList(); List folders = new ArrayList(); List files = new ArrayList(); int start = pageCode.indexOf("<div id=\"list-view\" class=\"view\""); int end = pageCode.indexOf("<div id=\"gallery-view\" class=\"view\""); String usefulSection = ""; if (start != -1 && end != -1) { usefulSection = pageCode.substring(start, end); } else { debug("Could not parse page"); } try { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(usefulSection)); Document doc = db.parse(is); NodeList divs = doc.getElementsByTagName("div"); for (int i = 0; i < divs.getLength(); i++) { Element div = (Element) divs.item(i); boolean isFolder = false; if (div.getAttribute("class").equals("filename")) { NodeList imgs = div.getElementsByTagName("img"); for (int j = 0; j < imgs.getLength(); j++) { Element img = (Element) imgs.item(j); if (img.getAttribute("class").indexOf("folder") > 0) { isFolder = true; } else { isFolder = false; // it's a file } } NodeList anchors = div.getElementsByTagName("a"); Element anchor = (Element) anchors.item(0); String attr = anchor.getAttribute("href"); String fileName = anchor.getAttribute("title"); String fileURL; if (isFolder && !attr.equals("#")) { folders.add(attr); folders.add(fileName); } else if (!isFolder && !attr.equals("#")) { // Dropbox uses ajax to get the file for download, so the url isn't enough. We must be // sneaky here. fileURL = "https://dl.dropbox.com" + attr.substring(23) + "?dl=1"; files.add(fileURL); files.add(fileName); } } } } catch (Exception e) { debug(e.toString()); } sections.add(files); sections.add(folders); return sections; }
@Override public VPackage parse() { logger.debug("Starting parsing package: " + xmlFile.getAbsolutePath()); long startParsing = System.currentTimeMillis(); try { Document document = getDocument(); Element root = document.getDocumentElement(); _package = new VPackage(xmlFile); Node name = root.getElementsByTagName(EL_NAME).item(0); _package.setName(name.getTextContent()); Node descr = root.getElementsByTagName(EL_DESCRIPTION).item(0); _package.setDescription(descr.getTextContent()); NodeList list = root.getElementsByTagName(EL_CLASS); boolean initPainters = false; for (int i = 0; i < list.getLength(); i++) { PackageClass pc = parseClass((Element) list.item(i)); if (pc.getPainterName() != null) { initPainters = true; } } if (initPainters) { _package.initPainters(); } logger.info( "Parsing the package '{}' finished in {}ms.\n", _package.getName(), (System.currentTimeMillis() - startParsing)); } catch (Exception e) { collector.collectDiagnostic(e.getMessage(), true); if (RuntimeProperties.isLogDebugEnabled()) { e.printStackTrace(); } } try { checkProblems("Error parsing package file " + xmlFile.getName()); } catch (Exception e) { return null; } return _package; }
private static String getElementValue(String elementName, Element baseElement) { String toreturn = ""; if (baseElement.getElementsByTagName(elementName).item(0) != null) { toreturn = baseElement .getElementsByTagName(elementName) .item(0) .getChildNodes() .item(0) .getNodeValue(); } // System.out.println(elementName+": "+toreturn); return toreturn; // String l2thresholdoverride = }
/** * Unmarshall a Genotype instance from a given XML Element representation. Its population of * Chromosomes will be unmarshalled from the Chromosome sub-elements. * * @param a_activeConfiguration the current active Configuration object that is to be used during * construction of the Genotype and Chromosome instances * @param a_xmlElement the XML Element representation of the Genotype * @return a new Genotype instance, complete with a population of Chromosomes, setup with the data * from the XML Element representation * @throws ImproperXMLException if the given Element is improperly structured or missing data * @throws InvalidConfigurationException if the given Configuration is in an inconsistent state * @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 * @author Klaus Meffert * @since 1.0 */ public static Genotype getGenotypeFromElement( Configuration a_activeConfiguration, Element a_xmlElement) throws ImproperXMLException, InvalidConfigurationException, UnsupportedRepresentationException, GeneCreationException { // Sanity check. Make sure the XML element isn't null and that it // actually represents a genotype. if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(GENOTYPE_TAG))) { throw new ImproperXMLException( "Unable to build Genotype instance from XML Element: " + "given Element is not a 'genotype' element."); } // Fetch all of the nested chromosome elements and convert them // into Chromosome instances. // ------------------------------------------------------------ NodeList chromosomes = a_xmlElement.getElementsByTagName(CHROMOSOME_TAG); int numChromosomes = chromosomes.getLength(); Population population = new Population(a_activeConfiguration, numChromosomes); for (int i = 0; i < numChromosomes; i++) { population.addChromosome( getChromosomeFromElement(a_activeConfiguration, (Element) chromosomes.item(i))); } // Construct a new Genotype with the chromosomes and return it. // ------------------------------------------------------------ return new Genotype(a_activeConfiguration, population); }
/** * Unmarshall a Chromosome instance from a given XML Element representation. * * @param a_activeConfiguration the current active Configuration object that is to be used during * construction of the Chromosome * @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 InvalidConfigurationException if the given Configuration is in an inconsistent state * @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 Chromosome getChromosomeFromElement( Configuration a_activeConfiguration, Element a_xmlElement) throws ImproperXMLException, InvalidConfigurationException, UnsupportedRepresentationException, GeneCreationException { // Do some sanity checking. Make sure the XML Element isn't null and // that in fact represents a chromosome. // ----------------------------------------------------------------- if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(CHROMOSOME_TAG))) { throw new ImproperXMLException( "Unable to build Chromosome instance from XML Element: " + "given Element is not a 'chromosome' element."); } // Extract the nested genes element and make sure it exists. // --------------------------------------------------------- Element genesElement = (Element) a_xmlElement.getElementsByTagName(GENES_TAG).item(0); if (genesElement == null) { throw new ImproperXMLException( "Unable to build Chromosome instance from XML Element: " + "'genes' sub-element not found."); } // Construct the genes from their representations. // ----------------------------------------------- Gene[] geneAlleles = getGenesFromElement(a_activeConfiguration, genesElement); // Construct the new Chromosome with the genes and return it. // ---------------------------------------------------------- return new Chromosome(a_activeConfiguration, geneAlleles); }
public ArrayList<String> parseXML() throws Exception { ArrayList<String> ret = new ArrayList<String>(); handshake(); URL url = new URL( "http://mangaonweb.com/page.do?cdn=" + cdn + "&cpn=book.xml&crcod=" + crcod + "&rid=" + (int) (Math.random() * 10000)); String page = DownloaderUtils.getPage(url.toString(), "UTF-8", cookies); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(page)); Document d = builder.parse(is); Element doc = d.getDocumentElement(); NodeList pages = doc.getElementsByTagName("page"); total = pages.getLength(); for (int i = 0; i < pages.getLength(); i++) { Element e = (Element) pages.item(i); ret.add(e.getAttribute("path")); } return (ret); }
private Element getElement(String eltName) { NodeList nodeList = docElt.getElementsByTagName(eltName); if (nodeList.getLength() != 0) { Node node = nodeList.item(0); if (node instanceof Element) return (Element) node; } return null; }
/** @deprecated use uniqueChild(Element elem, String childTagName) */ public static Element uniqueChildByTagName(Element elem, String childTagName) throws DOMException { NodeList nl = elem.getElementsByTagName(childTagName); int len = nl.getLength(); if (DEBUG) DebugUtils.myAssert( len <= 1, "There is more than one (" + len + ") child with tag name: " + childTagName + "!!!"); return (len == 1 ? (Element) nl.item(0) : null); }
// Set up the age range parameters private void setAgeRange(Element root) { NodeList nl = root.getElementsByTagName("pt-age"); if (nl.getLength() != 0) { Element ptAge = (Element) nl.item(0); int[] ageRange = getAgeRange(ptAge); containsAgeQuery = (ageRange[0] != -1); if (containsAgeQuery) { minAge = ageRange[1]; maxAge = ageRange[2]; } } }
public void load(InputStream is) throws IOException, ParserConfigurationException, SAXException { doc = db.parse(is); docElt = doc.getDocumentElement(); if (docElt.getTagName().equals(docElementName)) { NodeList nl = docElt.getElementsByTagName(trackElementName); for (int i = 0; i < nl.getLength(); i++) { Element elt = (Element) nl.item(i); Track track = new Track(elt); tracks.add(track); hash.put(track.getKey(), track); } } }
@Override public void readPageFromXML(Element element) { NodeList nodes = element.getElementsByTagName("tooltype"); if (nodes != null) type = nodes.item(0).getTextContent(); nodes = element.getElementsByTagName("recipe"); if (nodes != null) { String recipe = nodes.item(0).getTextContent(); icons = MantleClientRegistry.getRecipeIcons(recipe); if (type.equals("travelmulti")) { List<ItemStack[]> stacks = new LinkedList<ItemStack[]>(); List<String> tools = new LinkedList<String>(); String[] suffixes = new String[] {"goggles", "vest", "wings", "boots", "glove", "belt"}; for (String suffix : suffixes) { ItemStack[] icons2 = MantleClientRegistry.getRecipeIcons(nodes.item(0).getTextContent() + suffix); if (icons2 != null) { stacks.add(icons2); tools.add(suffix); } } iconsMulti = new ItemStack[stacks.size()][]; toolMulti = new ItemStack[stacks.size()]; for (int i = 0; i < stacks.size(); i++) { iconsMulti[i] = stacks.get(i); toolMulti[i] = MantleClientRegistry.getManualIcon("travel" + tools.get(i)); } icons = iconsMulti[0]; lastUpdate = System.currentTimeMillis(); counter = 0; } } }
private String obtenerNombre(Element raiz) { String comillas = "\""; StringBuilder nombre = new StringBuilder(comillas); String[] vars = {"CliApePat", "CliApeMat", "CliNom"}; for (String s : vars) { nombre.append(raiz.getElementsByTagName(s).item(0).getTextContent() + " "); } nombre.append(comillas); return nombre.toString(); }
public Command executeStep(Element stepRow) throws Exception { Command command = new Command(); NodeList stepFields = stepRow.getElementsByTagName("td"); String cmd = stepFields.item(0).getTextContent().trim(); command.cmd = cmd; ArrayList<String> argList = new ArrayList<String>(); if (stepFields.getLength() == 1) { // skip comments command.result = "OK"; return command; } for (int i = 1; i < stepFields.getLength(); i++) { String content = stepFields.item(i).getTextContent(); content = content.replaceAll(" +", " "); content = content.replace('\u00A0', ' '); content = content.trim(); argList.add(content); } String args[] = argList.toArray(new String[0]); command.args = args; if (this.verbose) { System.out.println(cmd + " " + Arrays.asList(args)); } try { command.result = this.commandProcessor.doCommand(cmd, args); command.error = false; } catch (Exception e) { command.result = e.getMessage(); command.error = true; } command.failure = command.error && !cmd.startsWith("verify"); if (this.verbose) { System.out.println(command.result); } return command; }
public static void read() { int x; Document doc = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); System.out.println("Reading in XML patient data"); try { DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(new File(GlobalVars.XMLDataFile)); Element root = doc.getDocumentElement(); NodeList nl = root.getElementsByTagName("patient"); for (x = 0; x < nl.getLength(); x++) { Element e = (Element) nl.item(x); PatientDataStore p = new PatientDataStore(e); GlobalVars.pds.add(p); } } catch (Exception e) { System.err.println("Error READING xml patient data file"); System.err.println("Going to default to no patients read"); e.printStackTrace(); } }
public boolean runSuite(String filename) throws Exception { if (this.verbose) { System.out.println( "Running test suite " + filename + " against " + this.host + ":" + this.port + " with " + this.browser); } TestSuite suite = new TestSuite(); long start = System.currentTimeMillis(); suite.numTestPasses = 0; suite.file = new File(filename); File suiteDirectory = suite.file.getParentFile(); this.document = parseDocument(filename); Element table = (Element) this.document.getElementsByTagName("table").item(0); NodeList tableRows = table.getElementsByTagName("tr"); Element tableNameRow = (Element) tableRows.item(0); suite.name = tableNameRow.getTextContent(); suite.result = true; suite.tests = new Test[tableRows.getLength() - 1]; for (int i = 1; i < tableRows.getLength(); i++) { Element tableRow = (Element) tableRows.item(i); Element cell = (Element) tableRow.getElementsByTagName("td").item(0); Element link = (Element) cell.getElementsByTagName("a").item(0); Test test = new Test(); test.label = link.getTextContent(); test.file = new File(suiteDirectory, link.getAttribute("href")); SeleniumHtmlClient subclient = new SeleniumHtmlClient(); subclient.setHost(this.host); subclient.setPort(this.port); subclient.setBrowser(this.browser); // subclient.setResultsWriter(this.resultsWriter); subclient.setBaseUrl(this.baseUrl); subclient.setVerbose(this.verbose); subclient.runTest(test); if (test.result) { suite.numTestPasses++; } suite.result &= test.result; suite.tests[i - 1] = test; } long end = System.currentTimeMillis(); suite.totalTime = (end - start) / 1000; if (this.resultsWriter != null) { this.resultsWriter.write("<html><head>\n"); this.resultsWriter.write("<style type='text/css'>\n"); this.resultsWriter.write( "body, table {font-family: Verdana, Arial, sans-serif;font-size: 12;}\n"); this.resultsWriter.write("table {border-collapse: collapse;border: 1px solid #ccc;}\n"); this.resultsWriter.write("th, td {padding-left: 0.3em;padding-right: 0.3em;}\n"); this.resultsWriter.write("a {text-decoration: none;}\n"); this.resultsWriter.write(".title {font-style: italic;}"); this.resultsWriter.write(".selected {background-color: #ffffcc;}\n"); this.resultsWriter.write(".status_done {background-color: #eeffee;}\n"); this.resultsWriter.write(".status_passed {background-color: #ccffcc;}\n"); this.resultsWriter.write(".status_failed {background-color: #ffcccc;}\n"); this.resultsWriter.write( ".breakpoint {background-color: #cccccc;border: 1px solid black;}\n"); this.resultsWriter.write("</style>\n"); this.resultsWriter.write("<title>" + suite.name + "</title>\n"); this.resultsWriter.write("</head><body>\n"); this.resultsWriter.write("<h1>Test suite results </h1>\n\n"); this.resultsWriter.write("<table>\n"); this.resultsWriter.write( "<tr>\n<td>result:</td>\n<td>" + (suite.result ? "passed" : "failed") + "</td>\n</tr>\n"); this.resultsWriter.write( "<tr>\n<td>totalTime:</td>\n<td>" + suite.totalTime + "</td>\n</tr>\n"); this.resultsWriter.write( "<tr>\n<td>numTestTotal:</td>\n<td>" + suite.tests.length + "</td>\n</tr>\n"); this.resultsWriter.write( "<tr>\n<td>numTestPasses:</td>\n<td>" + suite.numTestPasses + "</td>\n</tr>\n"); int numTestFailures = suite.tests.length - suite.numTestPasses; this.resultsWriter.write( "<tr>\n<td>numTestFailures:</td>\n<td>" + numTestFailures + "</td>\n</tr>\n"); this.resultsWriter.write("<tr>\n<td>numCommandPasses:</td>\n<td>0</td>\n</tr>\n"); this.resultsWriter.write("<tr>\n<td>numCommandFailures:</td>\n<td>0</td>\n</tr>\n"); this.resultsWriter.write("<tr>\n<td>numCommandErrors:</td>\n<td>0</td>\n</tr>\n"); this.resultsWriter.write("<tr>\n<td>Selenium Version:</td>\n<td>2.24</td>\n</tr>\n"); this.resultsWriter.write("<tr>\n<td>Selenium Revision:</td>\n<td>.1</td>\n</tr>\n"); // test suite this.resultsWriter.write("<tr>\n<td>\n"); this.resultsWriter.write( "<table id=\"suiteTable\" class=\"selenium\" border=\"1\" cellpadding=\"1\" cellspacing=\"1\"><tbody>\n"); this.resultsWriter.write( "<tr class=\"title " + (suite.result ? "status_passed" : "status_failed") + "\"><td><b>Test Suite</b></td></tr>\n"); int i = 0; for (Test test : suite.tests) { this.resultsWriter.write( "<tr class=\"" + (test.result ? "status_passed" : "status_failed") + "\"><td><a href=\"#testresult" + i + "\">" + test.name + "</a></td></tr>"); i++; } this.resultsWriter.write( "</tbody></table>\n</td>\n<td> </td>\n</tr>\n</table>\n<table>"); int j = 0; for (Test test : suite.tests) { this.resultsWriter.write( "<tr><td><a name=\"testresult" + j + "\">" + test.file + "</a><br/><div>\n"); this.resultsWriter.write("<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\">\n"); this.resultsWriter.write( "<thead>\n<tr class=\"title " + (test.result ? "status_passed" : "status_failed") + "\"><td rowspan=\"1\" colspan=\"3\">" + test.name + "</td></tr>"); this.resultsWriter.write("</thead><tbody>\n"); for (Command command : test.commands) { boolean result = command.result.startsWith("OK"); boolean isAssert = command.cmd.startsWith("assert") || command.cmd.startsWith("verify"); ; if (!isAssert) { this.resultsWriter.write( "<tr class=\"" + (result ? "status_done" : "") + "\">\n<td>\n"); } else { this.resultsWriter.write( "<tr class=\"" + (result ? "status_passed" : "status_failed") + "\">\n<td>\n"); } this.resultsWriter.write(command.cmd); this.resultsWriter.write("</td>\n"); if (command.args != null) { for (String arg : Arrays.asList(command.args)) { this.resultsWriter.write("<td>" + arg + "</td>\n"); } } } this.resultsWriter.write("</tr>\n"); this.resultsWriter.write("</tbody></table>\n"); this.resultsWriter.write("</div></td>\n<td> </td>\n</tr>"); j++; } int k = 0; for (Test test : suite.tests) { k++; } this.resultsWriter.write("</tbody></table>\n</td><td> </td>\n</tr>\n</table>\n"); this.resultsWriter.write("</body></html>"); } return suite.result; }
public static void main(String[] args) { String specloc = System.getProperty("spec"); if (specloc == null) { System.out.print("No spec file given, quitting"); System.exit(0); } DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z"); java.util.Date date = new java.util.Date(); String startstamp = dateFormat.format(date); boolean firstrun = true; while (true) { System.out.println("Loading XML Spec file: " + specloc); // BufferedWriter out = null; SocketAcceptor acceptor = null; SocketAcceptor statusacceptor = null; Vector<MonitorThread> monitorlist = new Vector<MonitorThread>(); try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File(specloc)); doc.getDocumentElement().normalize(); String heartbeatportString = doc.getDocumentElement().getAttribute("heartbeatport"); String statusportString = doc.getDocumentElement().getAttribute("statusport"); String logfiledir = doc.getDocumentElement().getAttribute("logfiledir"); String masterlabel = doc.getDocumentElement().getAttribute("label"); String nodeid = doc.getDocumentElement().getAttribute("id"); String smtphost = doc.getDocumentElement().getAttribute("smtphost"); String l1mailto = doc.getDocumentElement().getAttribute("l1mailto"); String l2mailto = doc.getDocumentElement().getAttribute("l2mailto"); String l2threshold = doc.getDocumentElement().getAttribute("l2threshold"); if (heartbeatportString == null || heartbeatportString.equals("")) { System.out.println("No heartbeat specified in spec, quitting"); System.exit(0); } if (statusportString == null || statusportString.equals("")) { System.out.println("No status port specified in spec, quitting"); System.exit(0); } if (logfiledir == null || logfiledir.equals("")) { System.out.println("No logfile directory location specified in spec, quitting"); System.exit(0); } int heartbeatport = Integer.valueOf(heartbeatportString).intValue(); System.out.println("This Monitor is using port " + heartbeatport + " for heartbeat"); int statusport = Integer.valueOf(statusportString).intValue(); System.out.println("This Monitor is using port " + statusport + " for status updates"); System.out.println("Logging to directory " + logfiledir); Log log = new Log(logfiledir); log.nodelabel = masterlabel; log.setMailer(smtphost, l1mailto, l2mailto, convertStringToInt(l2threshold)); if (firstrun) { firstrun = false; log.logit("Monitor Node Started", "start", null); } log.logit("Logging started", "", null); ThreadPing threadping = new ThreadPing(log, false); Thread pinger = new Thread(threadping); threadping.thisThread = pinger; pinger.start(); log.pinger = threadping; // ShutdownHook hook = new ShutdownHook(out); // Runtime.getRuntime().addShutdownHook(hook); // Starting Heartbeat server acceptor = new NioSocketAcceptor(); acceptor.getSessionConfig().setReuseAddress(true); acceptor.getSessionConfig().setTcpNoDelay(true); acceptor.setReuseAddress(true); // acceptor.getFilterChain().addLast("logger", new LoggingFilter()); acceptor .getFilterChain() .addLast( "codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); acceptor.setReuseAddress(true); // acceptor.setCloseOnDeactivation(true); acceptor.getSessionConfig().setTcpNoDelay(true); acceptor.setDefaultLocalAddress(new InetSocketAddress(heartbeatport)); Vector<IoSession> sessionlist = new Vector<IoSession>(); acceptor.setHandler(new HeartBeatHandler(sessionlist)); acceptor.bind(); // Starting Path Monitoring NodeList listOfServers = doc.getElementsByTagName("check"); int totalServers = listOfServers.getLength(); System.out.println("Total # of checks: " + totalServers); // Vector<PingMonitorThread> pinglist = new Vector<PingMonitorThread>(); // Vector<PortMonitorThread> portlist = new Vector<PortMonitorThread>(); // Vector<HeartbeatMonitorThread> heartbeatlist = new Vector<HeartbeatMonitorThread>(); System.out.println(); for (int i = 0; i < totalServers; i++) { Node serverNode = listOfServers.item(i); Element serverNodeElement = (Element) serverNode; String checklabel = serverNodeElement.getAttribute("label"); String host = serverNodeElement .getElementsByTagName("host") .item(0) .getChildNodes() .item(0) .getNodeValue(); String checktype = serverNodeElement .getElementsByTagName("checktype") .item(0) .getChildNodes() .item(0) .getNodeValue(); boolean enabled = true; if (serverNodeElement.getElementsByTagName("enabled").item(0) != null && serverNodeElement .getElementsByTagName("enabled") .item(0) .getChildNodes() .item(0) .getNodeValue() .toLowerCase() .equals("false")) { enabled = false; } String successrateString = serverNodeElement .getElementsByTagName("successrate") .item(0) .getChildNodes() .item(0) .getNodeValue(); String retryrateString = serverNodeElement .getElementsByTagName("retryrate") .item(0) .getChildNodes() .item(0) .getNodeValue(); // String l2thresholdoverride = // serverNodeElement.getElementsByTagName("l2threshold").item(0).getChildNodes().item(0).getNodeValue(); String l2thresholdoverride = getElementValue("l2threshold", serverNodeElement); // String l1mailtoadd = // serverNodeElement.getElementsByTagName("l1mailto").item(0).getChildNodes().item(0).getNodeValue(); String l1mailtoadd = getElementValue("l1mailto", serverNodeElement); // String l2mailtoadd = // serverNodeElement.getElementsByTagName("l2mailto").item(0).getChildNodes().item(0).getNodeValue(); String l2mailtoadd = getElementValue("l2mailto", serverNodeElement); int l2thresholdoverrideint = convertStringToInt(l2thresholdoverride); String[] l1mailtoaddarray = new String[0]; String[] l2mailtoaddarray = new String[0]; if (!l1mailtoadd.equals("")) { l1mailtoaddarray = l1mailtoadd.split(","); } if (!l2mailtoadd.equals("")) { l2mailtoaddarray = l2mailtoadd.split(","); } // System.out.println(l1mailtoaddarray.length + "-" + l2mailtoaddarray.length); int successrate = 30; int retryrate = 30; if (host == null || host.equals("")) { System.out.println("No Host, skipping this path"); enabled = false; } if (successrateString == null || successrateString.equals("")) { System.out.println( "No Success Rate defined, using default (" + successrate + " seconds)"); } else { successrate = Integer.valueOf(successrateString).intValue(); } if (retryrateString == null || retryrateString.equals("")) { System.out.println("No retry rate defined, using default (" + retryrate + " seconds)"); } else { retryrate = Integer.valueOf(retryrateString).intValue(); } System.out.println(checklabel); if (checktype.equals("heartbeat")) { String portString = serverNodeElement .getElementsByTagName("port") .item(0) .getChildNodes() .item(0) .getNodeValue(); if (portString == null || portString.equals("")) { System.out.println("No Heartbeat, skipping this path"); } else { int heartbeat = Integer.valueOf(portString).intValue(); System.out.println("Starting Heartbeat Check:"); System.out.println("Host: " + host); System.out.println("Port: " + heartbeat); System.out.println(); HeartbeatMonitorThread m = new HeartbeatMonitorThread( host, heartbeat, log, successrate, retryrate, checklabel); m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray); Thread t = new Thread(m); m.thisthread = t; if (enabled) { t.start(); log.logit( "Starting Heartbeat Check - " + host + ":" + heartbeat, "enable-" + successrate + "-" + retryrate, m.getStatus()); } else { log.logit( "Heartbeat Check - " + host + ":" + heartbeat + " Disabled on start", "disable", m.getStatus()); } monitorlist.add(m); } } else if (checktype.equals("ping")) { System.out.println("Starting Ping Check:"); System.out.println("Host: " + host); System.out.println(); PingMonitorThread m = new PingMonitorThread(host, log, successrate, retryrate, checklabel); m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray); Thread t = new Thread(m); m.thisthread = t; if (enabled) { t.start(); log.logit( "Starting Ping Check - " + host, "enable-" + successrate + "-" + retryrate, m.getStatus()); } else { log.logit("Ping Check - " + host + " Disabled on start", "disable", m.getStatus()); } monitorlist.add(m); } else if (checktype.equals("port")) { String portString = serverNodeElement .getElementsByTagName("port") .item(0) .getChildNodes() .item(0) .getNodeValue(); if (portString == null || portString.equals("")) { System.out.println("No Port Given, skipping"); } else { int heartbeat = Integer.valueOf(portString).intValue(); System.out.println("Starting Port Check:"); System.out.println("Host: " + host); System.out.println("Port: " + heartbeat); System.out.println(); PortMonitorThread m = new PortMonitorThread(host, heartbeat, log, successrate, retryrate, checklabel); m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray); Thread t = new Thread(m); m.thisthread = t; if (enabled) { t.start(); log.logit( "Starting Port Check - " + host + ":" + heartbeat, "enable-" + successrate + "-" + retryrate, m.getStatus()); } else { log.logit( "Port Check - " + host + ":" + heartbeat + " Disabled on start", "disable", m.getStatus()); } monitorlist.add(m); } } } statusacceptor = new NioSocketAcceptor(); statusacceptor.setReuseAddress(true); // statusacceptor.getFilterChain().addLast("logger", new LoggingFilter()); statusacceptor.getSessionConfig().setTcpNoDelay(true); statusacceptor.getSessionConfig().setKeepAlive(true); statusacceptor.getSessionConfig().setBothIdleTime(5); statusacceptor.getSessionConfig().setReaderIdleTime(5); statusacceptor.getSessionConfig().setWriteTimeout(5); // statusacceptor.setReuseAddress(true); statusacceptor.setCloseOnDeactivation(true); statusacceptor.setDefaultLocalAddress(new InetSocketAddress(statusport)); statusacceptor.setHandler( new StatusHttpProtocolHandler( monitorlist, acceptor, statusacceptor, log, masterlabel, nodeid, sessionlist, startstamp)); statusacceptor.bind(); System.out.println("Status Listener activated..."); } catch (Exception e) { e.printStackTrace(); try { // out.flush(); // out.close(); } catch (Exception e2) { } try { Thread.sleep(30000); } catch (Exception e3) { } } for (int x = 0; x < monitorlist.size(); x++) { if (monitorlist.get(x).getThisThread() != null) { try { monitorlist.get(x).getThisThread().join(); } catch (Exception e) { } } } if (acceptor != null) { while (acceptor.isActive() || !acceptor.isDisposed()) { try { Thread.sleep(1000); } catch (Exception e) { } } } if (statusacceptor != null) { while (statusacceptor.isActive() || !statusacceptor.isDisposed()) { try { Thread.sleep(1000); } catch (Exception e) { } } } System.out.println("Main thread has reached end, reloading..."); /* try { Thread.sleep(9999999); } catch (Exception e) { e.printStackTrace(); } */ } }
public Map getFajok() { Map fajok = new HashMap(); NodeList elements = document.getElementsByTagName("faj"); int elementCount = elements.getLength(); for (int i = 0; i < elementCount; i++) { Faj faj = new Faj(); Element element = (Element) elements.item(i); faj.setNev(element.getElementsByTagName("név").item(0).getTextContent()); Element foErtek = (Element) element.getElementsByTagName("főérték").item(0); faj.setFizikumMin( Integer.parseInt( ((Element) foErtek.getElementsByTagName("fizikum").item(0)) .getElementsByTagName("min") .item(0) .getTextContent())); faj.setFizikumMax( Integer.parseInt( ((Element) foErtek.getElementsByTagName("fizikum").item(0)) .getElementsByTagName("max") .item(0) .getTextContent())); faj.setRatermettsegMin( Integer.parseInt( ((Element) foErtek.getElementsByTagName("rátermettség").item(0)) .getElementsByTagName("min") .item(0) .getTextContent())); faj.setRatermettsegMax( Integer.parseInt( ((Element) foErtek.getElementsByTagName("rátermettség").item(0)) .getElementsByTagName("max") .item(0) .getTextContent())); faj.setTudatMin( Integer.parseInt( ((Element) foErtek.getElementsByTagName("tudat").item(0)) .getElementsByTagName("min") .item(0) .getTextContent())); faj.setTudatMax( Integer.parseInt( ((Element) foErtek.getElementsByTagName("tudat").item(0)) .getElementsByTagName("max") .item(0) .getTextContent())); faj.setEsszenciaMin( Integer.parseInt( ((Element) foErtek.getElementsByTagName("esszencia").item(0)) .getElementsByTagName("min") .item(0) .getTextContent())); faj.setEsszenciaMax( Integer.parseInt( ((Element) foErtek.getElementsByTagName("esszencia").item(0)) .getElementsByTagName("max") .item(0) .getTextContent())); faj.setGyorsasagMin( Integer.parseInt( ((Element) element.getElementsByTagName("gyorsaság").item(0)) .getElementsByTagName("min") .item(0) .getTextContent())); faj.setGyorsasagAtlag( Integer.parseInt( ((Element) element.getElementsByTagName("gyorsaság").item(0)) .getElementsByTagName("átlag") .item(0) .getTextContent())); faj.setGyorsasagMax( Integer.parseInt( ((Element) element.getElementsByTagName("gyorsaság").item(0)) .getElementsByTagName("max") .item(0) .getTextContent())); Map specialitasokMap = new HashMap(); if (element.getElementsByTagName("specialitasok").getLength() != 0) { Element specialitasok = (Element) element.getElementsByTagName("specialitasok").item(0); NodeList specialElements = specialitasok.getElementsByTagName("special"); int specialElementCount = specialElements.getLength(); for (int j = 0; j < specialElementCount; j++) { Specialitas specObject = new Specialitas(); Element special = (Element) specialElements.item(j); specObject.setNev(special.getElementsByTagName("név").item(0).getTextContent()); specObject.setAr( Integer.parseInt(special.getElementsByTagName("ár").item(0).getTextContent())); specObject.setMennyiseg( special.getElementsByTagName("mennyiség").item(0).getTextContent()); ArrayList eloFeltetelLista = new ArrayList(); NodeList eloFeltetelek = special.getElementsByTagName("előfeltétel"); int eloFeltetelCount = eloFeltetelek.getLength(); for (int k = 0; k < eloFeltetelCount; k++) eloFeltetelLista.add(eloFeltetelek.item(k).getTextContent()); specObject.setEloFeltetlek(eloFeltetelLista); specialitasokMap.put(specObject.getNev(), specObject); } } faj.setSpecialitasok(specialitasokMap); faj.setMaxJartassagSzint( Integer.parseInt( element.getElementsByTagName("maximálisJártasságszint").item(0).getTextContent())); fajok.put(faj.getNev(), faj); } return fajok; }
public static NodeList depthFirst(Element self) { List result = new ArrayList(); result.add(createNodeList(self)); result.add(self.getElementsByTagName("*")); return new NodeListsHolder(result); }
/** * XML Circuit constructor * * @param file the file that contains the XML description of the circuit * @param g the graphics that will paint the node * @throws CircuitLoadingException if the internal circuit can not be loaded */ public CircuitUI(File file, Graphics g) throws CircuitLoadingException { this(""); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; Document doc; Element root; Hashtable<Integer, Link> linkstable = new Hashtable<Integer, Link>(); try { builder = factory.newDocumentBuilder(); doc = builder.parse(file); } catch (SAXException sxe) { throw new CircuitLoadingException("SAX exception raised, invalid XML file."); } catch (ParserConfigurationException pce) { throw new CircuitLoadingException( "Parser exception raised, parser configuration is invalid."); } catch (IOException ioe) { throw new CircuitLoadingException("I/O exception, file cannot be loaded."); } root = (Element) doc.getElementsByTagName("Circuit").item(0); this.setName(root.getAttribute("name")); NodeList nl = root.getElementsByTagName("Node"); Element e; Node n; Class cl; for (int i = 0; i < nl.getLength(); ++i) { e = (Element) nl.item(i); try { cl = Class.forName(e.getAttribute("class")); } catch (Exception exc) { System.err.println(exc.getMessage()); throw new RuntimeException("Circuit creation from xml."); } try { n = ((Node) cl.newInstance()); } catch (Exception exc) { System.err.println(exc.getMessage()); throw new RuntimeException("Circuit creation from xml."); } this.nodes.add(n); n.setLocation(new Integer(e.getAttribute("x")), new Integer(e.getAttribute("y"))); if (n instanceof giraffe.ui.Nameable) ((Nameable) n).setNodeName(e.getAttribute("node_name")); if (n instanceof giraffe.ui.CompositeNode) { try { ((CompositeNode) n) .load(new File(file.getParent() + "/" + e.getAttribute("file_name")), g); } catch (Exception exc) { /* try to load from the lib */ ((CompositeNode) n) .load(new File(giraffe.Giraffe.PATH + "/lib/" + e.getAttribute("file_name")), g); } } NodeList nlist = e.getElementsByTagName("Anchor"); Element el; for (int j = 0; j < nlist.getLength(); ++j) { el = (Element) nlist.item(j); Anchor a = n.getAnchor(new Integer(el.getAttribute("id"))); NodeList linklist = el.getElementsByTagName("Link"); Element link; Link l; for (int k = 0; k < linklist.getLength(); ++k) { link = (Element) linklist.item(k); int id = new Integer(link.getAttribute("id")); int index = new Integer(link.getAttribute("index")); if (id >= this.linkID) linkID = id + 1; if (linkstable.containsKey(id)) { l = linkstable.get(id); l.addLinkedAnchorAt(a, index); a.addLink(l); } else { l = new Link(id); l.addLinkedAnchorAt(a, index); this.links.add(l); linkstable.put(id, l); a.addLink(l); } } } } }
/** * 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()]); }
/** * Edit the properties of a resource. The updates must refer to a Document containing a WebDAV * propertyupdates element as the document root. * * @param updates an XML Document containing propertyupdate elements * @return the result of making the updates describing the edits to be made. * @exception com.ibm.webdav.WebDAVException */ public MultiStatus setProperties(Document propertyUpdates) throws WebDAVException { // create a MultiStatus to hold the results. It will hold a MethodResponse // for each update, and one for the method as a whole MultiStatus multiStatus = new MultiStatus(); boolean errorsOccurred = false; // first, load the properties so they can be edited Document propertiesDocument = resource.loadProperties(); Element properties = (Element) propertiesDocument.getDocumentElement(); // be sure the updates have at least one update Element propertyupdate = (Element) propertyUpdates.getDocumentElement(); String tagName = propertyupdate.getNamespaceURI() + propertyupdate.getLocalName(); if (!tagName.equals("DAV:propertyupdate")) { throw new WebDAVException( WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "missing propertyupdate element"); } NodeList updates = propertyupdate.getChildNodes(); if (updates.getLength() == 0) { throw new WebDAVException(WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no updates in request"); } Vector propsGood = new Vector(); // a list of properties that // were patched correctly or would have been if another // property hadn't gone bad. // apply the updates Node temp = null; for (int i = 0; i < updates.getLength(); i++) { temp = updates.item(i); // skip any ignorable TXText elements if (!(temp.getNodeType() == Node.ELEMENT_NODE)) { continue; } Element update = (Element) temp; int updateCommand = -1; tagName = update.getNamespaceURI() + update.getLocalName(); if (tagName.equals("DAV:set")) { updateCommand = set; } else if (tagName.equals("DAV:remove")) { updateCommand = remove; } else { throw new WebDAVException( WebDAVStatus.SC_UNPROCESSABLE_ENTITY, update.getTagName() + " is not a valid property update request"); } // iterate through the props in the set or remove element and update the // properties as directed Element prop = (Element) update.getElementsByTagNameNS("DAV:", "prop").item(0); if (prop == null) { throw new WebDAVException( WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no propeprties in update request"); } NodeList propsToUpdate = prop.getChildNodes(); for (int j = 0; j < propsToUpdate.getLength(); j++) { temp = propsToUpdate.item(j); // skip any TXText elements?? if (!(temp.getNodeType() == Node.ELEMENT_NODE)) { continue; } Element propToUpdate = (Element) temp; // find the property in the properties element Element property = null; PropertyName propertyName = new PropertyName(propToUpdate); if (((Element) propToUpdate).getNamespaceURI() != null) { property = (Element) properties .getElementsByTagNameNS( propToUpdate.getNamespaceURI(), propToUpdate.getLocalName()) .item(0); } else { property = (Element) properties.getElementsByTagName(propToUpdate.getTagName()).item(0); } boolean liveone = isLive(propertyName.asExpandedString()); if (liveone) { errorsOccurred = true; PropertyResponse response = new PropertyResponse(resource.getURL().toString()); response.addProperty(propertyName, propToUpdate, WebDAVStatus.SC_FORBIDDEN); multiStatus.addResponse(response); } // do the update if (updateCommand == set) { if (property != null) { try { properties.removeChild(property); } catch (DOMException exc) { } } if (!liveone) { // I don't think we're allowed to update live properties // here. Doing so effects the cache. A case in // point is the lockdiscoveryproperty. properties // is actually the properites cache "document" of this // resource. Even though we don't "save" the request // if it includes live properties, we don't remove // it from the cache after we'd set it here, so it // can affect other queries. (jlc 991002) properties.appendChild(propertiesDocument.importNode(propToUpdate, true)); propsGood.addElement(propToUpdate); } } else if (updateCommand == remove) { try { if (property != null) { properties.removeChild(property); propsGood.addElement(propToUpdate); } } catch (DOMException exc) { } } } } { Enumeration els = propsGood.elements(); for (; els.hasMoreElements(); ) { Object ob1 = els.nextElement(); Element elProp = (Element) ob1; PropertyName pn = new PropertyName(elProp); PropertyResponse response = new PropertyResponse(resource.getURL().toString()); response.addProperty( pn, (Element) elProp.cloneNode(false), (errorsOccurred ? WebDAVStatus.SC_FAILED_DEPENDENCY : WebDAVStatus.SC_OK)); // todo: add code for responsedescription multiStatus.addResponse(response); } } // write out the properties if (!errorsOccurred) { resource.saveProperties(propertiesDocument); } return multiStatus; }
private Element getElementByName(Element root, String name) { return (Element) root.getElementsByTagName(name).item(0); }
private PackageClass parseClass(Element classNode) { PackageClass newClass = new PackageClass(); _package.getClasses().add(newClass); newClass.setComponentType(PackageClass.ComponentType.getType(classNode.getAttribute(ATR_TYPE))); newClass.setStatic(Boolean.parseBoolean(classNode.getAttribute(ATR_STATIC))); newClass.setName(getElementByName(classNode, EL_NAME).getTextContent()); final String source = getElementStringByName(classNode, EL_FILE); if (source != null) { newClass.setSource(source); } newClass.setTarget(getElementStringByName(classNode, EL_EXTENDS)); newClass.setDescription(getElementByName(classNode, EL_DESCRIPTION).getTextContent()); newClass.setIcon(getElementByName(classNode, EL_ICON).getTextContent()); // parse all variables declared in the corresponding specification if (newClass.getComponentType().hasSpec()) { final String newClassName = newClass.getName(); try { switch (RuntimeProperties.getSpecParserKind()) { case REGEXP: { ClassList classList = new ClassList(); SpecParser.parseSpecClass(newClassName, getWorkingDir(), classList); newClass.setSpecFields(classList.getType(newClassName).getFields()); break; } case ANTLR: { if (specificationLoader == null) { specificationLoader = new SpecificationLoader(new PackageSpecSourceProvider(_package), null); } final AnnotatedClass annotatedClass = specificationLoader.getSpecification(newClassName); newClass.setSpecFields(annotatedClass.getFields()); break; } default: throw new IllegalStateException("Undefined specification language parser"); } } catch (SpecParseException e) { final String msg = "Unable to parse the specification of class " + newClassName; logger.error(msg, e); collector.collectDiagnostic(msg + "\nReason: " + e.getMessage() + "\nLine: " + e.getLine()); } } // Graphics Element grNode = getElementByName(classNode, EL_GRAPHICS); newClass.addGraphics( getGraphicsParser().parse(grNode/*, newClass.getComponentType() == ComponentType.REL*/ )); Element painter; if ((painter = getElementByName(grNode, EL_PAINTER)) != null) { newClass.setPainterName(painter.getTextContent()); } // Ports NodeList ports = classNode.getElementsByTagName(EL_PORT); for (int i = 0; i < ports.getLength(); i++) { parsePort(newClass, (Element) ports.item(i)); } // Fields NodeList fields = classNode.getElementsByTagName(EL_FIELD); for (int i = 0; i < fields.getLength(); i++) { parseField(newClass, (Element) fields.item(i)); } return newClass; }
private ClassGraphics parse(Element grNode /*, boolean isRelation*/) { ClassGraphics newGraphics = new ClassGraphics(); newGraphics.setShowFields(Boolean.parseBoolean(grNode.getAttribute(ATR_SHOW_FIELDS))); // newGraphics.setRelation( isRelation ); NodeList list = grNode.getChildNodes(); for (int k = 0; k < list.getLength(); k++) { if (list.item(k).getNodeType() != Node.ELEMENT_NODE) continue; Element node = (Element) list.item(k); String nodeName = node.getNodeName(); Shape shape = null; if (EL_BOUNDS.equals(nodeName)) { Dim dim = getDim(node); newGraphics.setBounds(dim.x, dim.y, dim.width, dim.height); continue; } else if (EL_LINE.equals(nodeName)) { shape = makeLine(node, newGraphics); } else if (EL_RECT.equals(nodeName)) { Dim dim = getDim(node); Lineprops lp = getLineProps(node); shape = new Rect( dim.x, dim.y, dim.width, dim.height, getColor(node), isShapeFilled(node), lp.strokeWidth, lp.lineType); } else if (EL_OVAL.equals(nodeName)) { Dim dim = getDim(node); Lineprops lp = getLineProps(node); shape = new Oval( dim.x, dim.y, dim.width, dim.height, getColor(node), isShapeFilled(node), lp.strokeWidth, lp.lineType); } else if (EL_ARC.equals(nodeName)) { Dim dim = getDim(node); Lineprops lp = getLineProps(node); int startAngle = Integer.parseInt(node.getAttribute(ATR_START_ANGLE)); int arcAngle = Integer.parseInt(node.getAttribute(ATR_ARC_ANGLE)); shape = new Arc( dim.x, dim.y, dim.width, dim.height, startAngle, arcAngle, getColor(node), isShapeFilled(node), lp.strokeWidth, lp.lineType); } else if (EL_POLYGON.equals(nodeName)) { Lineprops lp = getLineProps(node); Polygon polygon = new Polygon(getColor(node), isShapeFilled(node), lp.strokeWidth, lp.lineType); // points NodeList points = node.getElementsByTagName(EL_POINT); int pointCount = points.getLength(); // arrays of polygon points int[] xs = new int[pointCount]; int[] ys = new int[pointCount]; // arrays of FIXED information about polygon points int[] fxs = new int[pointCount]; int[] fys = new int[pointCount]; int width = newGraphics.getBoundWidth(); int height = newGraphics.getBoundHeight(); for (int j = 0; j < pointCount; j++) { FixedCoords fc = getFixedCoords((Element) points.item(j), width, height, null); xs[j] = fc.x; fxs[j] = fc.fx; ys[j] = fc.y; fys[j] = fc.fy; } polygon.setPoints(xs, ys, fxs, fys); shape = polygon; } else if (EL_IMAGE.equals(nodeName)) { Dim dim = getDim(node); // image path should be relative to the package xml String imgPath = node.getAttribute(ATR_PATH); String fullPath = FileFuncs.preparePathOS(getWorkingDir() + imgPath); shape = new Image(dim.x, dim.y, fullPath, imgPath, isShapeFixed(node)); } else if (EL_TEXT.equals(nodeName)) { shape = makeText(node, newGraphics); /* * if (str.equals("*self")) newText.name = "self"; else if * (str.equals("*selfWithName")) newText.name = "selfName"; */ } if (shape != null) newGraphics.addShape(shape); } return newGraphics; }
// ----------------------------------------------------- // Description: Get the value from the node. // YUUGAMEE! // ----------------------------------------------------- String getTagValue(String sTag, Element eElement) { NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes(); Node nValue = (Node) nlList.item(0); return nValue.getNodeValue(); }
public Tile(Map map, int x, int y, Element tile) { this.map = map; this.x = x; this.y = y; height = (int) Float.parseFloat(tile.getAttribute("height")); if (!tile.getAttribute("caveHeight").equals("")) { caveHeight = (int) Float.parseFloat(tile.getAttribute("caveHeight")); } if (!tile.getAttribute("caveSize").equals("")) { caveSize = (int) Float.parseFloat(tile.getAttribute("caveSize")); } ground = new Ground((Element) tile.getElementsByTagName("ground").item(0)); if (tile.getElementsByTagName("cave").getLength() != 0) { cave = CaveData.get((Element) tile.getElementsByTagName("cave").item(0)); } NodeList labels = tile.getElementsByTagName("label"); if (labels.getLength() != 0) { label = new Label((Element) labels.item(0)); } NodeList caveLabels = tile.getElementsByTagName("caveLabel"); if (caveLabels.getLength() != 0) { caveLabel = new Label((Element) caveLabels.item(0)); } entities = new HashMap<>(); NodeList list = tile.getElementsByTagName("level"); for (int i = 0; i < list.getLength(); i++) { Element level = (Element) list.item(i); int floor = Integer.parseInt(level.getAttribute("value")); NodeList childNodes = level.getElementsByTagName("*"); for (int i2 = 0; i2 < childNodes.getLength(); i2++) { Element entity = (Element) childNodes.item(i2); switch (entity.getNodeName().toLowerCase()) { case "floor": entities.put(new EntityData(floor, EntityType.FLOORROOF), new Floor(entity)); break; case "hwall": Wall hwall = new Wall(entity); if (hwall.data.houseWall) { entities.put(new EntityData(floor, EntityType.HWALL), hwall); } else { entities.put(new EntityData(floor, EntityType.HFENCE), hwall); } break; case "vwall": Wall vwall = new Wall(entity); if (vwall.data.houseWall) { entities.put(new EntityData(floor, EntityType.VWALL), vwall); } else { entities.put(new EntityData(floor, EntityType.VFENCE), vwall); } break; case "hborder": entities.put(new EntityData(0, EntityType.HBORDER), BorderData.get(entity)); break; case "vborder": entities.put(new EntityData(0, EntityType.VBORDER), BorderData.get(entity)); break; case "roof": entities.put(new EntityData(floor, EntityType.FLOORROOF), new Roof(entity)); break; case "object": ObjectLocation loc = ObjectLocation.parse(entity.getAttribute("position")); entities.put(new ObjectEntityData(floor, loc), new GameObject(entity)); break; case "cave": cave = CaveData.get(entity); break; } } } }
public void addPackageClass(PackageClass pClass) { Document doc; try { doc = getDocument(); } catch (Exception e) { e.printStackTrace(); return; } String name = pClass.getName(); // check if such class exists and remove duplicates Element rootEl = doc.getDocumentElement(); NodeList classEls = rootEl.getElementsByTagName(EL_CLASS); for (int i = 0; i < classEls.getLength(); i++) { Element nameEl = getElementByName((Element) classEls.item(i), EL_NAME); if (name.equals(nameEl.getTextContent())) { rootEl.removeChild(classEls.item(i)); } } Element classNode = doc.createElement(EL_CLASS); doc.getDocumentElement().appendChild(classNode); classNode.setAttribute(ATR_TYPE, PackageClass.ComponentType.SCHEME.getXmlName()); classNode.setAttribute(ATR_STATIC, "false"); Element className = doc.createElement(EL_NAME); className.setTextContent(name); classNode.appendChild(className); Element desrc = doc.createElement(EL_DESCRIPTION); desrc.setTextContent(pClass.getDescription()); classNode.appendChild(desrc); Element icon = doc.createElement(EL_ICON); icon.setTextContent(pClass.getIcon()); classNode.appendChild(icon); // graphics classNode.appendChild(generateGraphicsNode(doc, pClass.getGraphics())); // ports List<Port> ports = pClass.getPorts(); if (!ports.isEmpty()) { Element portsEl = doc.createElement(EL_PORTS); classNode.appendChild(portsEl); for (Port port : ports) { portsEl.appendChild(generatePortNode(doc, port)); } } // fields Collection<ClassField> fields = pClass.getFields(); if (!fields.isEmpty()) { Element fieldsEl = doc.createElement(EL_FIELDS); classNode.appendChild(fieldsEl); for (ClassField cf : fields) { fieldsEl.appendChild(generateFieldNode(doc, cf)); } } // write try { writeDocument(doc, new FileOutputStream(xmlFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } }
public ArrayList<QuakeEntry> read(String source) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); // Document document = builder.parse(new File(source)); // Document document = // builder.parse("http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.atom"); Document document = null; if (source.startsWith("http")) { document = builder.parse(source); } else { document = builder.parse(new File(source)); } // Document document = // builder.parse("http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.atom"); NodeList nodeList = document.getDocumentElement().getChildNodes(); ArrayList<QuakeEntry> list = new ArrayList<QuakeEntry>(); for (int k = 0; k < nodeList.getLength(); k++) { Node node = nodeList.item(k); if (node.getNodeName().equals("entry")) { Element elem = (Element) node; NodeList t1 = elem.getElementsByTagName("georss:point"); NodeList t2 = elem.getElementsByTagName("title"); NodeList t3 = elem.getElementsByTagName("georss:elev"); double lat = 0.0, lon = 0.0, depth = 0.0; String title = "NO INFORMATION"; double mag = 0.0; if (t1 != null) { String s2 = t1.item(0).getChildNodes().item(0).getNodeValue(); // System.out.print("point2: "+s2); String[] args = s2.split(" "); lat = Double.parseDouble(args[0]); lon = Double.parseDouble(args[1]); } if (t2 != null) { String s2 = t2.item(0).getChildNodes().item(0).getNodeValue(); String mags = s2.substring(2, 5); if (mags.contains("?")) { mag = 0.0; System.err.println("unknown magnitude in data"); } else { mag = Double.parseDouble(mags); } int sp = s2.indexOf(" ", 5); title = s2.substring(sp + 1); if (title.startsWith("-")) { int pos = title.indexOf(" "); title = title.substring(pos + 1); } } if (t2 != null) { String s2 = t3.item(0).getChildNodes().item(0).getNodeValue(); depth = Double.parseDouble(s2); } QuakeEntry loc = new QuakeEntry(lat, lon, mag, title, depth); list.add(loc); } } return list; } catch (ParserConfigurationException pce) { System.err.println("parser configuration exception"); } catch (SAXException se) { System.err.println("sax exception"); } catch (IOException ioe) { System.err.println("ioexception"); } return null; }
public void handleDocument(Document document) { /* Tutti i nodi contenuti in document che si chiamano "NodoCella" */ NodeList cas = document.getElementsByTagName("NodoCella"); Element casellona = (Element) cas.item(0); id = casellona.getElementsByTagName("id").item(0).getTextContent(); x = casellona.getElementsByTagName("XCOR").item(0).getTextContent(); y = casellona.getElementsByTagName("YCOR").item(0).getTextContent(); text = casellona.getElementsByTagName("text").item(0).getTextContent(); down = casellona.getElementsByTagName("down").item(0).getTextContent(); up = casellona.getElementsByTagName("up").item(0).getTextContent(); laterale = casellona.getElementsByTagName("laterale").item(0).getTextContent(); laterale1 = casellona.getElementsByTagName("laterale1").item(0).getTextContent(); laterale2 = casellona.getElementsByTagName("laterale2").item(0).getTextContent(); laterale3 = casellona.getElementsByTagName("laterale3").item(0).getTextContent(); laterale4 = casellona.getElementsByTagName("laterale4").item(0).getTextContent(); laterale5 = casellona.getElementsByTagName("laterale5").item(0).getTextContent(); laterale6 = casellona.getElementsByTagName("laterale6").item(0).getTextContent(); CasellaStart casella_start = new CasellaStart( id, text, x, y, down, up, laterale, laterale1, laterale2, laterale3, laterale4, laterale5, laterale6); GestioneCaselle.caselle.add(casella_start); for (int i = 0; i < cas.getLength(); i++) { Element casella = (Element) cas.item(i); id = casella.getElementsByTagName("id").item(0).getTextContent(); x = casella.getElementsByTagName("XCOR").item(0).getTextContent(); y = casella.getElementsByTagName("YCOR").item(0).getTextContent(); text = casella.getElementsByTagName("text").item(0).getTextContent(); down = casella.getElementsByTagName("down").item(0).getTextContent(); up = casella.getElementsByTagName("up").item(0).getTextContent(); laterale = casella.getElementsByTagName("laterale").item(0).getTextContent(); Casella nuova_casella = new Casella(id, text, x, y, down, up, laterale); GestioneCaselle.caselle.add(nuova_casella); } // this.caselle.remove(1); casella_start.setLaterali(); }