public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String strId = ""; String strBody = ""; // Parse the xml and read data (page id and article body) // Using XOM library Builder builder = new Builder(); try { Document doc = builder.build(value.toString(), null); Nodes nodeId = doc.query("//eecs485_article_id"); strId = nodeId.get(0).getChild(0).getValue(); Nodes nodeBody = doc.query("//eecs485_article_body"); strBody = nodeBody.get(0).getChild(0).getValue(); } catch (ParsingException ex) { System.out.println("Not well-formed."); System.out.println(ex.getMessage()); } catch (IOException ex) { System.out.println("io exception"); } // Tokenize document body Pattern pattern = Pattern.compile("\\w+"); Matcher matcher = pattern.matcher(strBody); while (matcher.find()) { // Write the parsed token // key = term, docid value = 1 context.write(new Text(matcher.group() + "," + strId), one); } }
// TODO report status effectively @Override protected void runTask() { try { LocalDate today = LocalDate.now(DateTimeZone.UTC); LocalDate start = today.minusDays(minusDays); LocalDate finish = today.plusDays(plusDays); List<Channel> youViewChannels = channelResolver.getAllChannels(); UpdateProgress progress = UpdateProgress.START; while (!start.isAfter(finish)) { LocalDate end = start.plusDays(1); for (Channel channel : youViewChannels) { Interval interval = new Interval(start.toDateTimeAtStartOfDay(), end.toDateTimeAtStartOfDay()); Document xml = fetcher.getSchedule(interval.getStart(), interval.getEnd(), getYouViewId(channel)); Element root = xml.getRootElement(); Elements entries = root.getChildElements(ENTRY_KEY, root.getNamespaceURI(ATOM_PREFIX)); progress = progress.reduce(processor.process(channel, entries, interval)); reportStatus(progress.toString()); } start = end; } } catch (Exception e) { log.error("Exception when processing YouView schedule", e); Throwables.propagate(e); } }
public People(String filename) throws Exception { Document doc = new Builder().build(new File(filename)); Elements elements = doc.getRootElement().getChildElements(); for (int i = 0; i < elements.size(); i++) { add(new Person(elements.get(i))); } }
private static boolean isLive(String aServer) { try { URL url = new URL(aServer + "health"); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(BUNDLE.get("TC_STATUS_CHECK"), url); } if (uc.getResponseCode() == 200) { Document xml = new Builder().build(uc.getInputStream()); Element response = (Element) xml.getRootElement(); Element health = response.getFirstChildElement("health"); String status = health.getValue(); if (status.equals("dying") || status.equals("sick")) { if (LOGGER.isWarnEnabled()) { LOGGER.warn(BUNDLE.get("TC_SERVER_STATUS"), status); } return true; } else if (status.equals("ok")) { return true; } else { LOGGER.error(BUNDLE.get("TC_UNEXPECTED_STATUS"), status); } } } catch (UnknownHostException details) { LOGGER.error(BUNDLE.get("TC_UNKNOWN_HOST"), details.getMessage()); } catch (Exception details) { LOGGER.error(details.getMessage()); } return false; }
private Collection<ConnectableDefinition> loadConnectableDefs(File connectableDefs) { Collection<ConnectableDefinition> defs = new HashSet<ConnectableDefinition>(); try { Builder parser = new Builder(); Document doc = parser.build(connectableDefs); Element root = doc.getRootElement(); Elements definitions = root.getChildElements(); for (int i = 0; i < definitions.size(); i++) { Element definition = definitions.get(i); String id = definition.getAttributeValue("id"); String pinCount = definition.getAttributeValue("pins"); String type = definition.getAttributeValue("type"); ConnectableDefinition d = new ConnectableDefinition(id, type, Integer.parseInt(pinCount)); Elements pins = definition.getChildElements(); for (int j = 0; j < pins.size(); j++) { Element pinElement = pins.get(j); String pinNumber = pinElement.getAttributeValue("number"); String pinName = pinElement.getAttributeValue("name"); d.addPin(Integer.parseInt(pinNumber), pinName); } defs.add(d); } } catch (ParsingException ex) { System.err.println("malformed XML file : " + ex.getMessage()); } catch (IOException ex) { System.err.println("io error : " + ex.getMessage()); } return defs; }
/** * Read urn. * * @param file the file * @return The URN specified in the METS file or null if the METS file doesn't specify an URN * @throws IOException Signals that an I/O exception has occurred. * @throws ParseException the parse exception * @author Thomas Kleinke */ public String readURN(File file) throws IOException, ParseException { FileInputStream fileInputStream = new FileInputStream(file); BOMInputStream bomInputStream = new BOMInputStream(fileInputStream); XMLReader xmlReader = null; SAXParserFactory spf = SAXParserFactory.newInstance(); try { xmlReader = spf.newSAXParser().getXMLReader(); } catch (Exception e) { fileInputStream.close(); bomInputStream.close(); throw new IOException("Error creating SAX parser", e); } xmlReader.setErrorHandler(err); NodeFactory nodeFactory = new PremisXmlReaderNodeFactory(); Builder parser = new Builder(xmlReader, false, nodeFactory); logger.trace("Successfully built builder and XML reader"); try { String urn = null; Document doc = parser.build(bomInputStream); Element root = doc.getRootElement(); Element dmdSecEl = root.getFirstChildElement("dmdSec", METS_NS); if (dmdSecEl == null) return null; Element mdWrapEl = dmdSecEl.getFirstChildElement("mdWrap", METS_NS); if (mdWrapEl == null) return null; Element xmlDataEl = mdWrapEl.getFirstChildElement("xmlData", METS_NS); if (xmlDataEl == null) return null; Element modsEl = xmlDataEl.getFirstChildElement("mods", MODS_NS); if (modsEl == null) return null; Elements identifierEls = modsEl.getChildElements("identifier", MODS_NS); for (int i = 0; i < identifierEls.size(); i++) { Element element = identifierEls.get(i); Attribute attribute = element.getAttribute("type"); if (attribute.getValue().toLowerCase().equals("urn")) urn = element.getValue(); } if (urn != null && urn.equals("")) urn = null; return urn; } catch (ValidityException ve) { throw new IOException(ve); } catch (ParsingException pe) { throw new IOException(pe); } catch (IOException ie) { throw new IOException(ie); } finally { fileInputStream.close(); bomInputStream.close(); } }
protected ComponentSet loadSet(File componentsDef, File connectionsDef) { ComponentSet set = null; // for collecting all connectables Map<String, Connectable> connectables = new HashMap<String, Connectable>(); try { // open the components.xml file Builder builder = new Builder(); Document doc = builder.build(componentsDef); Element componentsRoot = doc.getRootElement(); int rows = Integer.parseInt(componentsRoot.getAttributeValue("rows")); int cols = Integer.parseInt(componentsRoot.getAttributeValue("cols")); boolean autoLocate = Boolean.parseBoolean(componentsRoot.getAttributeValue("autoLocate")); // add connectables (components need to be located in the set, // endpoints are not so they are just added to the connectables map Elements componentElements = componentsRoot.getChildElements(); if (autoLocate) { set = addComponentsWithAutoLocate(connectables, rows, cols, componentElements); } else { set = addComponents(connectables, rows, cols, componentElements); } doc = builder.build(connectionsDef); Element connectionsRoot = doc.getRootElement(); // add connections Elements connections = connectionsRoot.getChildElements(); for (int i = 0; i < connections.size(); i++) { Element c = connections.get(i); String from = c.getAttributeValue("from"); String to = c.getAttributeValue("to"); String fromPinLabel = c.getAttributeValue("fromPin"); String toPinLabel = c.getAttributeValue("toPin"); Connectable fromComp = connectables.get(from); Connectable toComp = connectables.get(to); Collection<Pin> fromPins = fromComp.getPins(fromPinLabel); Collection<Pin> toPins = toComp.getPins(toPinLabel); Connection con = new Connection(fromComp, fromPins, toComp, toPins); set.addConnection(con); } } catch (ParsingException ex) { System.err.println("malformed XML file : " + ex.getMessage()); } catch (IOException ex) { System.err.println("io error : " + ex.getMessage()); } return set; }
public static void xomWithURI() { nu.xom.Element root = new nu.xom.Element("todo"); // Setting URI and prefix has the consequence that the namespace declaration is added root.setNamespaceURI("http://www.example.com"); root.setNamespacePrefix("todo"); // System.out.println(root.getAttributeCount()); // prints 0 xmlns etc. are no attributes. nu.xom.Document doc = new nu.xom.Document(root); System.out.println("XOM:"); System.out.println(doc.toXML()); }
/** * In the given glosslist (assuming 1 per doc) 1) collect all glossentries that are referenced * from outside the current glosslist 2) collect all glossentries that are referenced from the * entries in 1 */ private Document process(Document doc) { Nodes linkends = doc.getRootElement().query("//db:*[@linkend]", con); Nodes glosslists = doc.getRootElement().query("//db:glosslist", con); if (glosslists.size() > 1) throw new IllegalArgumentException("only one glosslist per doc"); if (glosslists.size() == 0) return doc; Element glosslist = (Element) glosslists.get(0); // 1) collect all glossentries that are referenced from outside the current glosslist List<Element> usedGlossEntries = new LinkedList<Element>(); Elements allGlossentries = glosslist.getChildElements("glossentry", dbns); for (int k = 0; k < allGlossentries.size(); k++) { Element glossentry = allGlossentries.get(k); String id = glossentry.getAttributeValue("id", xmlns); if (referencedFromOutside(id, linkends, glosslist)) { if (!contains(usedGlossEntries, glossentry)) { usedGlossEntries.add(glossentry); } } } // 2: go through usedEntries nested linkends, and add any referenced glossEntries // recursively until list stops growing while (true) { List<Element> moreUsedGlossEntries = recurse(glosslist, allGlossentries, usedGlossEntries); if (moreUsedGlossEntries.size() == 0) { break; } for (Element more : moreUsedGlossEntries) { if (!contains(usedGlossEntries, more)) { usedGlossEntries.add(more); } } } // finally, remove any unused glossentries for (int k = 0; k < allGlossentries.size(); k++) { Element glossentry = allGlossentries.get(k); if (!contains(usedGlossEntries, glossentry)) { glossentry.getParent().removeChild(glossentry); } } return doc; }
@Test public void update() throws ValidityException, ParsingException, IOException, MojoExecutionException { Document pom = new Builder().build(new File(new File("src/it/reflector"), "pom.xml")); Artifact artifact = new DefaultArtifact("net.stickycode", "sticky-coercion", "jar", "", "[3.1,4)"); new StickyBoundsMojo().updateDependency(pom, artifact, "[3.6,4)"); XPathContext context = new XPathContext("mvn", "http://maven.apache.org/POM/4.0.0"); Nodes versions = pom.query("//mvn:version", context); assertThat(versions.size()).isEqualTo(3); Nodes nodes = pom.query("//mvn:version[text()='[3.6,4)']", context); assertThat(nodes.size()).isEqualTo(1); Node node = nodes.get(0); assertThat(node.getValue()).isEqualTo("[3.6,4)"); }
private static void cacheImage(String aServer, String aID) { try { String id = URLEncoder.encode(aID, "UTF-8"); String baseURL = aServer + "view/image/" + id; URL url = new URL(baseURL + "/info.xml"); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); int status = uc.getResponseCode(); if (status == 200) { Document xml = new Builder().build(uc.getInputStream()); Element info = (Element) xml.getRootElement(); Element elem = info.getFirstChildElement("identifier", IIIF_NS); Element hElem = info.getFirstChildElement("height", IIIF_NS); Element wElem = info.getFirstChildElement("width", IIIF_NS); String idValue = elem.getValue(); try { int height = Integer.parseInt(hElem.getValue()); int width = Integer.parseInt(wElem.getValue()); Iterator<String> tileIterator; List<String> tiles; if (idValue.equals(aID) && height > 0 && width > 0) { if (idValue.startsWith("/") && LOGGER.isWarnEnabled()) { LOGGER.warn(BUNDLE.get("TC_SLASH_ID"), aID); } tiles = CacheUtils.getCachingQueries(height, width); tileIterator = tiles.iterator(); while (tileIterator.hasNext()) { cacheTile(baseURL + tileIterator.next()); } } else if (LOGGER.isErrorEnabled()) { LOGGER.error(BUNDLE.get("TC_ID_404"), aID); } } catch (NumberFormatException nfe) { LOGGER.error(BUNDLE.get("TC_INVALID_DIMS"), aID); } } else { LOGGER.error(BUNDLE.get("TC_SERVER_STATUS_CODE"), status); } } catch (Exception details) { LOGGER.error(details.getMessage()); } }
public void loadLocationsAsync(String kml) { List<LotLocation> locations = new ArrayList<LotLocation>(); try { XMLReader parser = XMLReaderFactory.createXMLReader("org.ccil.cowan.tagsoup.Parser"); InputStream is = new ByteArrayInputStream(kml.getBytes()); // build out an XML document using TagSoup Document doc = new Builder(parser).build(is); // set the ns of the document as the XPathContext or we will not find the elements when we // attempt to parse XPathContext context = new XPathContext("ns", "http://www.w3.org/1999/xhtml"); // get the Placemark nodes within the data Nodes nodes = doc.query(".//ns:Placemark", context); for (int index = 0; index < nodes.size(); index++) { LotLocation placemark = new LotLocation(); Node placemarkNode = nodes.get(index); Node nameNode = placemarkNode.query("ns:name", context).get(0); if (nameNode != null) placemark.setLocation(nameNode.getValue()); Node descriptionNode = placemarkNode.query("ns:description", context).get(0); if (descriptionNode != null) placemark.setDescription(descriptionNode.getValue()); Node lnglatNode = placemarkNode.query("ns:Point/ns:coordinates", context).get(0); if (lnglatNode != null) { // get longitude,latitude,altitude, per KML spec String[] points = lnglatNode.getValue().split(","); placemark.setPoint( new LatLng( Double.parseDouble(points[1].trim()), Double.parseDouble(points[0].trim()))); } locations.add(placemark); } // spin off a new thread and load locations new LoadLocationsTask().execute(locations); } catch (Exception e) { Log.e("LoadLocationsTask", "Failure attempting to load locations", e); } }
@Override public void finishMakingDocument(Document document) { final Element e = document.getRootElement(); for (String namespace : namespacePrefixes.keySet()) { e.addNamespaceDeclaration(namespacePrefixes.get(namespace), namespace); } super.finishMakingDocument(document); }
/** * This method is used to parse a RuleML 0.91 document that is stored in a XOM tree. * * @param doc Document The XOM Document object that represents the RuleML document to be parsed. * @throws ParseException A ParseException is thrown if there is an error parsing. */ public void parseRuleMLDocument(Document doc) throws ParseException { this.skolemMap = new Hashtable<String, String>(); Element documentRoot = doc.getRootElement(); removeReifyElements(documentRoot); Element rmlRoot = getRuleMLRootElement(documentRoot); parseRuleMLRoot(rmlRoot); }
private void desarModel(String rutaFitxer) throws ParcAtraccionsExcepcio { try { FileWriter fitxer = new FileWriter(rutaFitxer, false); // Obrim fitxer per sobreescriure fitxer.write(doc.toXML()); fitxer.close(); } catch (Exception e) { throw new ParcAtraccionsExcepcio("GestorXML.desar"); } }
public void execute(Context context, Writer writer) throws AluminumException { String text = getBodyText(context, writer); logger.debug("body text is '", text, "', now trying to parse"); Document document; try { document = new Builder().build(new StringReader(text)); } catch (ParsingException exception) { throw new AluminumException(exception, "can't parse '", text, "'"); } catch (IOException exception) { throw new AluminumException(exception, "can't parse '", text, "'"); } logger.debug("parsed body text, result: ", document); writer.write(new XomElement(document.getRootElement())); }
private Element getResultElement(HttpResponse res) throws ICTomorrowApiException { try { Builder builder = new Builder(); Document document = builder.build(res.body(), null); Element rootElement = document.getRootElement(); String statusCode = rootElement.getAttributeValue("status_code"); String statusMessage = rootElement.getAttributeValue("status_message"); if (statusCode.equals("200")) { return rootElement; } else { throw new ICTomorrowApiException( "Request returned an error response: " + res.body(), statusCode, statusMessage); } } catch (ParsingException e) { throw new ICTomorrowApiException("Exception while parsing response: " + res.body(), e); } catch (IOException e) { throw new ICTomorrowApiException("Exception while parsing response: " + res.body(), e); } }
@Test public void updateTheClassifier() throws ValidityException, ParsingException, IOException, MojoExecutionException { Document pom = new Builder() .build( new BufferedReader( new InputStreamReader(getClass().getResourceAsStream("classifiers.xml")))); Artifact artifact = new DefaultArtifact("net.stickycode", "sticky-coercion", "jar", "test-jar", "[2.1,4)"); new StickyBoundsMojo().updateDependency(pom, artifact, "[2.6,3)"); XPathContext context = new XPathContext("mvn", "http://maven.apache.org/POM/4.0.0"); Nodes versions = pom.query("//mvn:version", context); assertThat(versions.size()).isEqualTo(4); Nodes nodes = pom.query("//mvn:version[text()='[2.6,3)']", context); assertThat(nodes.size()).isEqualTo(1); Node node = nodes.get(0); assertThat(node.getValue()).isEqualTo("[2.6,3)"); }
public void beforeParsing(Document document) { nu.xom.Element html = document.getRootElement(); nu.xom.Element head = html.getFirstChildElement("head"); Check.notNull(head, "<head> section is missing from document"); script = new nu.xom.Element("script"); script.addAttribute(new Attribute("type", "text/javascript")); // Fix for Issue #26: Strict XHTML DTD requires an explicit end tag for <script> element // Thanks to Matthias Schwegler for reporting and supplying a fix for this. script.appendChild(""); head.appendChild(script); }
@Override public void parse() throws java.io.IOException, org.xml.sax.SAXException, XenaException { // This method is called after the XIS has been parsed by the ContentHandler returned by // getContentHandler. // This means that the document returned by our SaxHandler should be populated. if (documentBuilder != null) { document = documentBuilder.getDocument(); setElement(document.getRootElement()); } super.parse(); // updateViewFromElement(); }
public static void doStatisticsForXMLFile(String filePath) { try { Builder builder = new Builder(false); Document doc = builder.build(filePath); Element corpus = doc.getRootElement(); Elements lexeltElements = corpus.getChildElements("lexelt"); Map<String, Integer> posMap = new HashMap<String, Integer>(); for (int k = 0; k < lexeltElements.size(); k++) { Element lexeltElement = lexeltElements.get(k); Elements instanceElements = lexeltElement.getChildElements("instance"); for (int i = 0; i < instanceElements.size(); i++) { Element instanceElement = instanceElements.get(i); Element postaggingElement = instanceElement.getFirstChildElement("postagging"); Elements wordElements = postaggingElement.getChildElements("word"); for (int j = 0; j < wordElements.size(); j++) { Element wordElement = wordElements.get(j); Elements subwordElements = wordElement.getChildElements("subword"); if (subwordElements.size() == 0) { String pos = wordElement.getAttributeValue("pos"); doIncrement(posMap, pos); } else { for (int m = 0; m < subwordElements.size(); m++) { Element subwordElement = subwordElements.get(m); String pos = subwordElement.getAttributeValue("pos"); doIncrement(posMap, pos); } } } } } doStatistics(filePath, posMap); } catch (Exception e) { e.printStackTrace(); } }
/** * Save the quiz in XML moodle format. * * @return XML code */ public final String exportToString() { /* Create XML context */ boolean bExportOK = true; final Element root = xmlExporter.createXMLContext("quiz"); if (root == null) { bExportOK = false; } /* Save all the question */ Category currentCat = null; for (AbstractQuestion q : questions) { /* Check if new category */ final Category quesCat = q.getCategory(); if (!(quesCat.equals(currentCat))) { if (!(quesCat.doExport(xmlExporter, root))) { bExportOK = false; break; } currentCat = quesCat; } /* Save the question */ if (!(q.doExport(xmlExporter, root))) { bExportOK = false; break; } } /* Create the XML Document */ String result = ""; if (bExportOK) { final Document doc = new Document(root); result = doc.toXML(); } return result; }
static { CurrentStorage.get().openMimeTypesList(); _root = _doc.getRootElement(); }
public void annotate(CoreMap document) throws IOException { // write input file in GUTime format Element inputXML = toInputXML(document); File inputFile = File.createTempFile("gutime", ".input"); // Document doc = new Document(inputXML); PrintWriter inputWriter = new PrintWriter(inputFile); inputWriter.println(inputXML.toXML()); // new XMLOutputter().output(inputXML, inputWriter); inputWriter.close(); boolean useFirstDate = (!document.has(CoreAnnotations.CalendarAnnotation.class) && !document.has(CoreAnnotations.DocDateAnnotation.class)); ArrayList<String> args = new ArrayList<String>(); args.add("perl"); args.add("-I" + this.gutimePath.getPath()); args.add(new File(this.gutimePath, "TimeTag.pl").getPath()); if (useFirstDate) args.add("-FDNW"); args.add(inputFile.getPath()); // run GUTime on the input file ProcessBuilder process = new ProcessBuilder(args); StringWriter outputWriter = new StringWriter(); SystemUtils.run(process, outputWriter, null); String output = outputWriter.getBuffer().toString(); Pattern docClose = Pattern.compile("</DOC>.*", Pattern.DOTALL); output = docClose.matcher(output).replaceAll("</DOC>"); // parse the GUTime output Element outputXML; try { Document newNodeDocument = new Builder().build(output, ""); outputXML = newNodeDocument.getRootElement(); } catch (ParsingException ex) { throw new RuntimeException( String.format( "error:\n%s\ninput:\n%s\noutput:\n%s", ex, IOUtils.slurpFile(inputFile), output)); } /* try { outputXML = new SAXBuilder().build(new StringReader(output)).getRootElement(); } catch (JDOMException e) { throw new RuntimeException(String.format("error:\n%s\ninput:\n%s\noutput:\n%s", e, IOUtils.slurpFile(inputFile), output)); } */ inputFile.delete(); // get Timex annotations List<CoreMap> timexAnns = toTimexCoreMaps(outputXML, document); document.set(TimexAnnotations.class, timexAnns); if (outputResults) { System.out.println(timexAnns); } // align Timex annotations to sentences int timexIndex = 0; for (CoreMap sentence : document.get(CoreAnnotations.SentencesAnnotation.class)) { int sentBegin = beginOffset(sentence); int sentEnd = endOffset(sentence); // skip times before the sentence while (timexIndex < timexAnns.size() && beginOffset(timexAnns.get(timexIndex)) < sentBegin) { ++timexIndex; } // determine times within the sentence int sublistBegin = timexIndex; int sublistEnd = timexIndex; while (timexIndex < timexAnns.size() && sentBegin <= beginOffset(timexAnns.get(timexIndex)) && endOffset(timexAnns.get(timexIndex)) <= sentEnd) { ++sublistEnd; ++timexIndex; } // set the sentence timexes sentence.set(TimexAnnotations.class, timexAnns.subList(sublistBegin, sublistEnd)); } }
@Test public void testGeneration() throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); // new XmlInstanceGenerator(SampleA.class).generateXmlSchema(System.out, false); new XmlInstanceGenerator(SampleA.class).generateXmlSchema(bos, false); Builder domBuilder = new Builder(); Document doc = domBuilder.build(new ByteArrayInputStream(bos.toByteArray())); String namespace = XmlInstanceGenerator.getNamespace(SampleA.class); Element config = doc.getRootElement(); Assert.assertEquals("config", config.getLocalName()); Elements i = config.getChildElements("i", namespace); Assert.assertEquals(1, i.size()); Assert.assertEquals("0", i.get(0).getValue()); Elements s = config.getChildElements("s", namespace); Assert.assertEquals(1, s.size()); Assert.assertEquals("abc", s.get(0).getValue()); Elements r = config.getChildElements("r1", namespace); Assert.assertEquals(1, r.size()); Assert.assertEquals("TODO", r.get(0).getValue()); r = config.getChildElements("r2", namespace); Assert.assertEquals(1, r.size()); Assert.assertEquals("TODO", r.get(0).getValue()); r = config.getChildElements("r3", namespace); Assert.assertEquals(1, r.size()); Assert.assertEquals("SampleC", r.get(0).getValue()); Elements l = config.getChildElements("l", namespace); Assert.assertEquals(1, l.size()); Elements values = l.get(0).getChildElements("value", namespace); Assert.assertEquals(2, values.size()); Assert.assertEquals("abc", values.get(0).getValue()); Assert.assertEquals("xyz", values.get(1).getValue()); Elements m = config.getChildElements("m", namespace); Assert.assertEquals(1, m.size()); Elements entries = m.get(0).getChildElements("entry", namespace); Assert.assertEquals(2, entries.size()); Assert.assertEquals("ABC", entries.get(0).getValue()); Assert.assertEquals("1", entries.get(0).getAttribute("key").getValue()); Assert.assertEquals("XYZ", entries.get(1).getValue()); Assert.assertEquals("2", entries.get(1).getAttribute("key").getValue()); Elements lr = config.getChildElements("lr", namespace); Assert.assertEquals(1, lr.size()); values = lr.get(0).getChildElements("value", namespace); Assert.assertEquals(1, values.size()); Assert.assertEquals("", values.get(0).getValue()); Elements mr = config.getChildElements("mr", namespace); Assert.assertEquals(1, mr.size()); entries = mr.get(0).getChildElements("entry", namespace); Assert.assertEquals(1, entries.size()); Assert.assertEquals("", entries.get(0).getValue()); Assert.assertEquals("", entries.get(0).getAttribute("key").getValue()); }
/** * Removes a model. Removes extension and any files. * * @param model */ public void removeModel(IDSTest model, String pluginID) { // Remove from DSBusinessModel dsBusinessModel.getTests().remove(model); for (Endpoint ep : dsBusinessModel.getEndpoints()) { if (ep.getTests() != null) { ep.getTests().remove(model); logger.debug("Removed model " + model.getName() + " from EP " + ep.getName()); } } // Remove extensions in models.container plugin // ============================================= File pluginXMLfile; try { pluginXMLfile = new File(FileUtil.getFilePath("plugin.xml", pluginID)); Builder parser = new Builder(); Document doc = parser.build(pluginXMLfile); Element root = doc.getRootElement(); Element extension = null; // Find extension in plugin.xml, if exists Elements existingExtensions = root.getChildElements("extension"); if (existingExtensions != null && existingExtensions.size() > 0) { for (int i = 0; i < existingExtensions.size(); i++) { extension = existingExtensions.get(i); // If exists a model with same name, remove it Elements existingTests = extension.getChildElements("test"); if (existingTests != null && existingTests.size() > 0) { for (int j = 0; j < existingTests.size(); j++) { Element test = existingTests.get(j); String testName = test.getAttribute("name").getValue(); // Remove spaces included by XML serialization while (testName.contains(" ")) testName = testName.replace(" ", " "); if (model.getName().equals(testName)) { test.getParent().removeChild(test); logger.debug("Removing existing model extension: " + model.getName()); // Also remove the files Elements resources = test.getChildElements("resource"); for (int rescnt = 0; rescnt < resources.size(); rescnt++) { Element resource = resources.get(rescnt); String path = resource.getAttribute("path").getValue(); try { File reFile = new File(FileUtil.getFilePath(path, pluginID)); if (reFile.exists()) { logger.debug("Removing file: " + reFile); reFile.delete(); } else logger.debug("Unable to locate file to remove: " + path); } catch (Exception e) { logger.error("Problems removing file: " + path); } } } } } } } // Serialize the updated plugin.xml to file Serializer serializer = new Serializer(new FileOutputStream(pluginXMLfile)); serializer.setIndent(4); serializer.setMaxLength(64); serializer.write(doc); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ValidityException e) { e.printStackTrace(); } catch (ParsingException e) { e.printStackTrace(); } }
private void construeixModel(ParcAtraccions pParcAtraccions) throws ParcAtraccionsExcepcio { // Mètode on heu de construir el document XML Element raiz = new Element("parcAtraccions"); raiz.addAttribute(new Attribute("codi", pParcAtraccions.getCodi().toString())); raiz.addAttribute(new Attribute("nom", pParcAtraccions.getNom())); raiz.addAttribute(new Attribute("adreca", pParcAtraccions.getAdreca())); Element coordinadores = new Element("coordinadores"); raiz.appendChild(coordinadores); Element personasMantenimiento = new Element("personasMantenimiento"); raiz.appendChild(personasMantenimiento); Element atracciones = new Element("atracciones"); raiz.appendChild(atracciones); Element zonas = new Element("zonas"); raiz.appendChild(zonas); for (int i = 0; i < pParcAtraccions.getComptaElements(); i++) { Element elemento; if (pParcAtraccions.getElements()[i] instanceof Atraccio) { elemento = new Element("atraccion"); Element nombre = new Element("nombre"); nombre.appendChild(((Atraccio) pParcAtraccions.getElements()[i]).getNom()); elemento.appendChild(nombre); Element tipus = new Element("tipus"); tipus.appendChild(((Atraccio) pParcAtraccions.getElements()[i]).getTipus()); elemento.appendChild(tipus); Element restriccionEdad = new Element("restriccionEdad"); restriccionEdad.appendChild( String.valueOf(((Atraccio) pParcAtraccions.getElements()[i]).getRestriccioEdat())); elemento.appendChild(restriccionEdad); Element restriccionAltura = new Element("restriccionAltura"); restriccionAltura.appendChild( String.valueOf(((Atraccio) pParcAtraccions.getElements()[i]).getRestriccioAlcada())); elemento.appendChild(restriccionAltura); Element tieneProblema = new Element("tieneProblema"); tieneProblema.appendChild( String.valueOf(((Atraccio) pParcAtraccions.getElements()[i]).getTeProblema())); elemento.appendChild(tieneProblema); Element codigoProblema = new Element("codigoProblema"); codigoProblema.appendChild( String.valueOf(((Atraccio) pParcAtraccions.getElements()[i]).getCodiProblema())); elemento.appendChild(codigoProblema); Element estaSolucionado = new Element("estaSolucionado"); estaSolucionado.appendChild( String.valueOf(((Atraccio) pParcAtraccions.getElements()[i]).getEstaSolucionat())); elemento.appendChild(estaSolucionado); atracciones.appendChild(elemento); continue; } else if (pParcAtraccions.getElements()[i] instanceof Zona) { Element raiz2 = new Element("zona"); raiz2.addAttribute(new Attribute("nombre", pParcAtraccions.getCodi().toString())); Element coordinadores2 = new Element("coordinadores"); raiz2.appendChild(coordinadores2); Element personasMantenimiento2 = new Element("personasMantenimiento"); raiz2.appendChild(personasMantenimiento2); Element atracciones2 = new Element("atracciones"); raiz2.appendChild(atracciones2); for (int j = 0; j < ((Zona) pParcAtraccions.getElements()[i]).getComptaElements(); j++) { Element elemento2; if (pParcAtraccions.getElements()[j] instanceof Atraccio) { elemento2 = new Element("atraccion"); Element nombre = new Element("nombre"); nombre.appendChild(((Atraccio) pParcAtraccions.getElements()[j]).getNom()); elemento2.appendChild(nombre); Element tipus = new Element("tipus"); tipus.appendChild(((Atraccio) pParcAtraccions.getElements()[j]).getTipus()); elemento2.appendChild(tipus); Element restriccionEdad = new Element("restriccionEdad"); restriccionEdad.appendChild( String.valueOf(((Atraccio) pParcAtraccions.getElements()[j]).getRestriccioEdat())); elemento2.appendChild(restriccionEdad); Element restriccionAltura = new Element("restriccionAltura"); restriccionAltura.appendChild( String.valueOf( ((Atraccio) pParcAtraccions.getElements()[j]).getRestriccioAlcada())); elemento2.appendChild(restriccionAltura); Element tieneProblema = new Element("tieneProblema"); tieneProblema.appendChild( String.valueOf(((Atraccio) pParcAtraccions.getElements()[j]).getTeProblema())); elemento2.appendChild(tieneProblema); Element codigoProblema = new Element("codigoProblema"); codigoProblema.appendChild( String.valueOf(((Atraccio) pParcAtraccions.getElements()[j]).getCodiProblema())); elemento2.appendChild(codigoProblema); Element estaSolucionado = new Element("estaSolucionado"); estaSolucionado.appendChild( String.valueOf(((Atraccio) pParcAtraccions.getElements()[j]).getEstaSolucionat())); elemento2.appendChild(estaSolucionado); atracciones2.appendChild(elemento2); continue; } if (pParcAtraccions.getElements()[i] instanceof Coordinador) { elemento2 = new Element("coordinador"); coordinadores2.appendChild(elemento2); } else { elemento2 = new Element("personaManteniment"); personasMantenimiento2.appendChild(elemento2); } Element nif = new Element("nif"); nif.appendChild(((Persona) pParcAtraccions.getElements()[i]).getNif()); elemento2.appendChild(nif); Element nom = new Element("nom"); nom.appendChild(((Persona) pParcAtraccions.getElements()[i]).getNom()); elemento2.appendChild(nom); Element cognom = new Element("cognom"); cognom.appendChild(((Persona) pParcAtraccions.getElements()[i]).getCognom()); elemento2.appendChild(cognom); } zonas.appendChild(raiz2); } else if (pParcAtraccions.getElements()[i] instanceof Coordinador) { elemento = new Element("coordinador"); coordinadores.appendChild(elemento); } else if (pParcAtraccions.getElements()[i] instanceof PersonaManteniment) { elemento = new Element("personaManteniment"); personasMantenimiento.appendChild(elemento); } /* Element nif = new Element("nif"); nif.appendChild(((Persona)pParcAtraccions.getElements()[i]).getNif()); elemento.appendChild(nif); Element nom = new Element("nom"); nom.appendChild(((Persona)pParcAtraccions.getElements()[i]).getNom()); elemento.appendChild(nom); Element cognom = new Element("cognom"); cognom.appendChild(((Persona)pParcAtraccions.getElements()[i]).getCognom()); elemento.appendChild(cognom); */ } doc.setRootElement(raiz); // System.out.println(doc.toXML()); }
private void fitxerParcAtraccions() throws ParcAtraccionsExcepcio { // Mètode on heu de crear objectes a partir de les dades guardades en el // document XML. Element raiz = doc.getRootElement(); Elements elemento = raiz.getChildElements(); ArrayList<principal.Element> lista = new ArrayList<>(); for (int i = 0; i < elemento.size(); i++) { // Iteramos sobre todo if (elemento.get(i).getQualifiedName().equals("zonas")) { Elements elemento2 = elemento.get(i).getChildElements(); for (int j = 0; j < elemento2.size(); j++) { // Iteramos sobre las zonas Zona zona = new Zona(elemento2.get(j).getAttributeValue("nombre")); Aplicacio.parcsAtraccions[0].novaZona(zona); Elements elemento3 = elemento2.get(j).getChildElements(); for (int k = 0; k < elemento3.size(); k++) { // Iteramos sobre una zona if (elemento3.get(k).getQualifiedName().equals("coordinadores")) { Elements elemento4 = elemento3.get(k).getChildElements(); for (int l = 0; l < elemento4.size(); l++) { // Iteramos sobre los coordinadores de una zona Elements elemento5 = elemento4.get(l).getChildElements(); String nom = "", cognom = "", nif = ""; for (int m = 0; m < elemento5.size(); m++) { // Iteramos sobre los atributos de un coordinador if (elemento5.get(m).getQualifiedName().equals("nombre")) { nom = elemento5.get(m).getValue(); } if (elemento5.get(m).getQualifiedName().equals("apellido")) { cognom = elemento5.get(m).getValue(); } if (elemento5.get(m).getQualifiedName().equals("nif")) { nif = elemento5.get(m).getValue(); } } zona.afegeixElementZona(new Coordinador(nif, nom, cognom)); } } if (elemento3.get(k).getQualifiedName().equals("personasMantenimiento")) { Elements elemento4 = elemento3.get(k).getChildElements(); for (int l = 0; l < elemento4.size(); l++) { // Iteramos sobre las personas de manteniment de una zona Elements elemento5 = elemento4.get(l).getChildElements(); String nom = "", cognom = "", nif = ""; for (int m = 0; m < elemento5.size(); m++) { // Iteramos sobre los atributos de una persona de manteniment if (elemento5.get(m).getQualifiedName().equals("nombre")) { nom = elemento5.get(m).getValue(); } if (elemento5.get(m).getQualifiedName().equals("apellido")) { cognom = elemento5.get(m).getValue(); } if (elemento5.get(m).getQualifiedName().equals("nif")) { nif = elemento5.get(m).getValue(); } } zona.afegeixElementZona(new PersonaManteniment(nif, nom, cognom)); } } if (elemento3.get(k).getQualifiedName().equals("atraccion")) { Elements elemento4 = elemento3.get(k).getChildElements(); for (int l = 0; l < elemento4.size(); l++) { // Iteramos sobre los coordinadores de una zona Elements elemento5 = elemento4.get(l).getChildElements(); String nombre = "", tipo = "", codigo = ""; boolean problema = false, solucionado = false; int edad = 0; float altura = 0; for (int m = 0; m < elemento5.size(); m++) { // Iteramos sobre los atributos de un coordinador if (elemento5.get(m).getQualifiedName().equals("nombre")) { nombre = elemento5.get(m).getValue(); } if (elemento5.get(m).getQualifiedName().equals("tipo")) { tipo = elemento5.get(m).getValue(); } if (elemento5.get(m).getQualifiedName().equals("restriccionEdad")) { edad = Integer.parseInt(elemento5.get(m).getValue()); } if (elemento5.get(m).getQualifiedName().equals("restriccionAltura")) { altura = Float.parseFloat(elemento5.get(m).getValue()); } if (elemento5.get(m).getQualifiedName().equals("tieneProblema")) { problema = Boolean.valueOf(elemento5.get(m).getValue()); } if (elemento5.get(m).getQualifiedName().equals("codigoProblema")) { codigo = elemento5.get(m).getValue(); } if (elemento5.get(m).getQualifiedName().equals("estaSolucionado")) { solucionado = Boolean.valueOf(elemento5.get(m).getValue()); } } Atraccio atraccion = new Atraccio(nombre, tipo, edad, altura); atraccion.setTeProblema(problema); atraccion.setCodiProblema(codigo); atraccion.setEstaSolucionat(problema); zona.afegeixElementZona(atraccion); } } } } } if (elemento.get(i).getQualifiedName().equals("coordinadores")) { Elements elemento2 = elemento.get(i).getChildElements(); for (int j = 0; j < elemento2.size(); j++) { // Iteramos sobre los coordinadores Elements elemento3 = elemento2.get(j).getChildElements(); String nom = "", cognom = "", nif = ""; for (int k = 0; k < elemento3.size(); k++) { // Iteramos sobre los atributos de un coordinador if (elemento3.get(k).getQualifiedName().equals("nombre")) { nom = elemento3.get(k).getValue(); } if (elemento3.get(k).getQualifiedName().equals("apellido")) { cognom = elemento3.get(k).getValue(); } if (elemento3.get(k).getQualifiedName().equals("nif")) { nif = elemento3.get(k).getValue(); } } lista.add(new Coordinador(nif, nom, cognom)); // zona.afegeixElementZona(new Coordinador(nif, nom, cognom)); } } if (elemento.get(i).getQualifiedName().equals("personasMantenimiento")) { Elements elemento2 = elemento.get(i).getChildElements(); for (int j = 0; j < elemento2.size(); j++) { // Iteramos sobre las personas de manteniment de una zona Elements elemento3 = elemento2.get(j).getChildElements(); String nom = "", cognom = "", nif = ""; for (int k = 0; k < elemento3.size(); k++) { // Iteramos sobre los atributos de una persona de manteniment if (elemento3.get(k).getQualifiedName().equals("nombre")) { nom = elemento3.get(k).getValue(); } if (elemento3.get(k).getQualifiedName().equals("apellido")) { cognom = elemento3.get(k).getValue(); } if (elemento3.get(k).getQualifiedName().equals("nif")) { nif = elemento3.get(k).getValue(); } } lista.add(new PersonaManteniment(nif, nom, cognom)); // zona.afegeixElementZona(new PersonaManteniment(nif, nom, cognom)); } } if (elemento.get(i).getQualifiedName().equals("atraccion")) { Elements elemento2 = elemento.get(i).getChildElements(); for (int l = 0; l < elemento2.size(); l++) { // Iteramos sobre los coordinadores de una zona Elements elemento5 = elemento2.get(l).getChildElements(); String nombre = "", tipo = "", codigo = ""; boolean problema = false, solucionado = false; int edad = 0; float altura = 0; for (int m = 0; m < elemento5.size(); m++) { // Iteramos sobre los atributos de un coordinador if (elemento5.get(m).getQualifiedName().equals("nombre")) { nombre = elemento5.get(m).getValue(); } if (elemento5.get(m).getQualifiedName().equals("tipo")) { tipo = elemento5.get(m).getValue(); } if (elemento5.get(m).getQualifiedName().equals("restriccionEdad")) { edad = Integer.parseInt(elemento5.get(m).getValue()); } if (elemento5.get(m).getQualifiedName().equals("restriccionAltura")) { altura = Float.parseFloat(elemento5.get(m).getValue()); } if (elemento5.get(m).getQualifiedName().equals("tieneProblema")) { problema = Boolean.valueOf(elemento5.get(m).getValue()); } if (elemento5.get(m).getQualifiedName().equals("codigoProblema")) { codigo = elemento5.get(m).getValue(); } if (elemento5.get(m).getQualifiedName().equals("estaSolucionado")) { solucionado = Boolean.valueOf(elemento5.get(m).getValue()); } } Atraccio atraccion = new Atraccio(nombre, tipo, edad, altura); atraccion.setTeProblema(problema); atraccion.setCodiProblema(codigo); atraccion.setEstaSolucionat(problema); lista.add(atraccion); // zona.afegeixElementZona(atraccion); } } } principal.Element[] array = new principal.Element[lista.size()]; for (int i = 0; i < lista.size(); i++) { array[i] = lista.get(i); } Aplicacio.parcsAtraccions[0].setElements(array); }
public TestCaseTemplateParameter(String xmlData) throws Exception { Document doc = new Builder().build(xmlData, null); Element root = doc.getRootElement(); Elements importElements = root.getChildElements("import"); for (int i = 0; i < importElements.size(); i++) { Element importElement = importElements.get(i); this.addImport(importElement.getValue()); } Elements classToMockElements = root.getChildElements("classToMock"); for (int i = 0; i < classToMockElements.size(); i++) { Element classToMockElement = classToMockElements.get(i); Element classNameElement = classToMockElement.getFirstChildElement("className"); Element instanceNameElement = classToMockElement.getFirstChildElement("instanceName"); this.addClassToMockInstanceName(classNameElement.getValue(), instanceNameElement.getValue()); Elements invokeElements = classToMockElement.getChildElements("invoke"); ArrayList<String> invokeList = new ArrayList<String>(); for (int j = 0; j < invokeElements.size(); j++) { Element invokeElement = invokeElements.get(j); invokeList.add(invokeElement.getValue()); } this.addJMockInvokeSequence(classNameElement.getValue(), invokeList.toArray(new String[0])); } this.setPackageName(root.getFirstChildElement("packageName").getValue()); this.setClassUnderTest(root.getFirstChildElement("classUnderTest").getValue()); Elements constructorArguments = root.getChildElements("constructorArgument"); for (int i = 0; i < constructorArguments.size(); i++) { Element constructorArgumentElement = constructorArguments.get(i); String type = constructorArgumentElement.getFirstChildElement("type").getValue(); String value = constructorArgumentElement.getFirstChildElement("value").getValue(); this.addConstructorArgument(type, value); } this.setMethodUnderTest(root.getFirstChildElement("methodUnderTest").getValue()); Elements methodParameters = root.getChildElements("methodParameter"); for (int i = 0; i < methodParameters.size(); i++) { Element methodParameterElement = methodParameters.get(i); String type = methodParameterElement.getFirstChildElement("type").getValue(); String name = methodParameterElement.getFirstChildElement("name").getValue(); this.addMethodParameter(type, name); } this.setStaticMethod( Boolean.parseBoolean(root.getFirstChildElement("isStaticMethod").getValue())); if (root.getFirstChildElement("singletonMethod") != null) { this.setSingletonMethod(root.getFirstChildElement("singletonMethod").getValue()); } if (root.getFirstChildElement("checkStateMethod") != null) { this.setCheckStateMethod(root.getFirstChildElement("checkStateMethod").getValue()); } this.setReturnType(root.getFirstChildElement("returnType").getValue()); if (root.getFirstChildElement("delta") != null) { this.setDelta(Double.parseDouble(root.getFirstChildElement("delta").getValue())); } }
public String toXML() { Element root = new Element("testCaseTemplateParameter"); for (String importName : imports) { Element importElement = new Element("import"); importElement.appendChild(importName); root.appendChild(importElement); } for (Map.Entry<String, String> entry : classToMockInstanceNameMap.entrySet()) { Element classToMockElement = new Element("classToMock"); // ClassName Element classNameElement = new Element("className"); classNameElement.appendChild(entry.getKey()); classToMockElement.appendChild(classNameElement); // InstanceName Element instanceNameElement = new Element("instanceName"); instanceNameElement.appendChild(entry.getValue()); classToMockElement.appendChild(instanceNameElement); // Invokes for (String invoke : jMockInvokeSequenceMap.get(entry.getKey())) { Element invokeElement = new Element("invoke"); invokeElement.appendChild(invoke); classToMockElement.appendChild(invokeElement); } root.appendChild(classToMockElement); } Element packageNameElement = new Element("packageName"); packageNameElement.appendChild(this.getPackageName()); root.appendChild(packageNameElement); Element classUnderTestElement = new Element("classUnderTest"); classUnderTestElement.appendChild(this.getClassUnderTest()); root.appendChild(classUnderTestElement); for (Argument constructorArgument : constructorArguments) { Element constructorArgumentElement = new Element("constructorArgument"); Element typeElement = new Element("type"); typeElement.appendChild(constructorArgument.getType()); Element valueElement = new Element("value"); valueElement.appendChild(constructorArgument.getValue()); constructorArgumentElement.appendChild(typeElement); constructorArgumentElement.appendChild(valueElement); root.appendChild(constructorArgumentElement); } Element methodUnderTestElement = new Element("methodUnderTest"); methodUnderTestElement.appendChild(this.getMethodUnderTest()); root.appendChild(methodUnderTestElement); for (Parameter methodParameter : methodParameters) { Element methodParameterElement = new Element("methodParameter"); Element typeElement = new Element("type"); typeElement.appendChild(methodParameter.getType()); Element nameElement = new Element("name"); nameElement.appendChild(methodParameter.getName()); methodParameterElement.appendChild(typeElement); methodParameterElement.appendChild(nameElement); root.appendChild(methodParameterElement); } Element isStaticMethodElement = new Element("isStaticMethod"); isStaticMethodElement.appendChild("" + this.isStaticMethod()); root.appendChild(isStaticMethodElement); if (this.isSingleton()) { Element singletonMethodElement = new Element("singletonMethod"); singletonMethodElement.appendChild(this.getSingletonMethod()); root.appendChild(singletonMethodElement); } if (this.hasCheckStateMethod()) { Element checkStateMethodElement = new Element("checkStateMethod"); checkStateMethodElement.appendChild(this.getCheckStateMethod()); root.appendChild(checkStateMethodElement); } Element returnTypeElement = new Element("returnType"); returnTypeElement.appendChild(this.getReturnType()); root.appendChild(returnTypeElement); if (this.hasDelta()) { Element deltaElement = new Element("delta"); deltaElement.appendChild("" + this.getDelta()); root.appendChild(deltaElement); } Document doc = new Document(root); return doc.toXML(); }