Java Code Examples for org.jdom2.Document#getRootElement()

The following examples show how to use org.jdom2.Document#getRootElement() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MCRLoginServlet.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private void listRealms(HttpServletRequest req, HttpServletResponse res)
    throws IOException, TransformerException, SAXException {
    String redirectURL = getReturnURL(req);
    Document realmsDoc = MCRRealmFactory.getRealmsDocument();
    Element realms = realmsDoc.getRootElement();
    addCurrentUserInfo(realms);
    List<Element> realmList = realms.getChildren(REALM_URL_PARAMETER);
    for (Element realm : realmList) {
        String realmID = realm.getAttributeValue("id");
        Element login = realm.getChild("login");
        if (login != null) {
            login.setAttribute("url", MCRRealmFactory.getRealm(realmID).getLoginURL(redirectURL));
        }
    }
    getLayoutService().doLayout(req, res, new MCRJDOMContent(realmsDoc));
}
 
Example 2
Source File: YDataStateException.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static YDataStateException unmarshall(Document exceptionDoc) {
    Element root = exceptionDoc.getRootElement();
    String queryString = root.getChildText(QUERYSTRING_NM);
    Element queriedData = root.getChild(QUERIEDDATA_NM);

    Element schema = root.getChild(SCHEMA_NM);
    Element dataInput = root.getChild(DATAINPUT_NM);
    String xercesErrors = root.getChildText(XERCESERRORS_NM);

    String source = root.getChildText(SOURCE_NM);
    String message = parseMessage(exceptionDoc);
    if (queryString == null) {
        return new YDataValidationException(
                _out.outputString(schema), dataInput, xercesErrors, source, message);
    } else if (schema == null) {
        return new YDataQueryException(queryString, queriedData, source, message);
    }
    return new YDataStateException(
            queryString, queriedData, _out.outputString(schema), dataInput,
            xercesErrors, source, message);
}
 
Example 3
Source File: SvnLogXmlParser.java    From gocd with Apache License 2.0 6 votes vote down vote up
private List<Modification> parseDOMTree(Document document, String path) throws ParseException {
    List<Modification> modifications = new ArrayList<>();

    Element rootElement = document.getRootElement();
    List logEntries = rootElement.getChildren("logentry");
    for (Iterator iterator = logEntries.iterator(); iterator.hasNext();) {
        Element logEntry = (Element) iterator.next();

        Modification modification = parseLogEntry(logEntry, path);
        if (modification != null) {
            modifications.add(modification);
        }
    }

    return modifications;
}
 
Example 4
Source File: CommandSnippetXmlParser.java    From gocd with Apache License 2.0 6 votes vote down vote up
public CommandSnippet parse(String xmlContent, String fileName, String relativeFilePath) {
    try {
        Document document = buildXmlDocument(xmlContent, CommandSnippet.class.getResource("command-snippet.xsd"));
        CommandSnippetComment comment = getComment(document);

        Element execTag = document.getRootElement();
        String commandName = execTag.getAttributeValue("command");
        List<String> arguments = new ArrayList<>();
        for (Object child : execTag.getChildren()) {
            Element element = (Element) child;
            arguments.add(element.getValue());
        }
        return new CommandSnippet(commandName, arguments, comment, fileName, relativeFilePath);
    } catch (Exception e) {
        String errorMessage = String.format("Reason: %s", e.getMessage());
        LOGGER.info("Could not load command '{}'. {}", fileName, errorMessage);
        return CommandSnippet.invalid(fileName, errorMessage, new EmptySnippetComment());
    }
}
 
Example 5
Source File: FeatureDatasetCapabilitiesWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static String getAltUnits(Document doc) {
  Element root = doc.getRootElement();
  String altUnits = root.getChildText("AltitudeUnits");
  if (altUnits == null || altUnits.isEmpty())
    return null;
  return altUnits;
}
 
Example 6
Source File: GtfsFromNextBus.java    From core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets list of all the paths for
 * the route document.
 * 
 * @param doc
 * @return Map of Path objects, keyed on the NextBus path ID
 */
private static Map<String, Path> getPaths(Document doc) {
	// Keyed on path ID
	Map<String, Path> pathMap = new HashMap<String, Path>();
	
	// Get the paths from the XML doc
	Element rootNode = doc.getRootElement();
	Element route = rootNode.getChild("route");
	List<Element> paths = route.getChildren("path");
	for (Element path : paths) {
		Element pathTag = path.getChild("tag");		
		String pathId = pathTag.getAttributeValue("id");
		
		// Create new Path and add to list
		Path p = new Path();
		List<Element> points = path.getChildren("point");
		for (Element point : points) {
			String lat = point.getAttributeValue("lat");
			String lon = point.getAttributeValue("lon");
		
			p.lats.add(lat);
			p.lons.add(lon);
		}			
		pathMap.put(pathId, p);
	}
	
	return pathMap;
}
 
Example 7
Source File: MCRWCMSContentManager.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return a json object with the content of a MyCoRe webpage.
 * <p>
 * {
 *  type: "content",
 *  content: @see {@link MCRWCMSDefaultSectionProvider}
 * }
 * </p>
 * <p>
 * If an error occur (e.g. file not exist) the returning json
 * looks like:<br>
 * {
 *  type: "error",
 *  errorType: "invalidFile"
 *  webpageId: "myfolder/webpage1.xml"
 * }
 * </p>
 *
 * @param webpageId id of the webpage
 * @return json object
 * @see ErrorType
 */
public JsonObject getContent(String webpageId) throws IOException, JDOMException, SAXException {
    boolean isXML = webpageId.endsWith(".xml");
    URL resourceURL = null;
    try {
        resourceURL = MCRWebPagesSynchronizer.getURL(webpageId);
    } catch (MalformedURLException e) {
        throwError(ErrorType.invalidDirectory, webpageId);
    }
    // file is not in web application directory
    if (!isXML) {
        throwError(ErrorType.invalidFile, webpageId);
    }
    Document doc = null;
    if (resourceURL == null) {
        MyCoReWebPageProvider wpp = new MyCoReWebPageProvider();
        wpp.addSection("neuer Eintrag", new Element("p").setText("TODO"), "de");
        doc = wpp.getXML();
    } else {
        doc = new MCRURLContent(resourceURL).asXML();
    }
    Element rootElement = doc.getRootElement();
    if (!rootElement.getName().equals("MyCoReWebPage")) {
        throwError(ErrorType.notMyCoReWebPage, webpageId);
    }
    // return content
    return getContent(rootElement);
}
 
Example 8
Source File: PersisterTestUtil.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
private static Element getRootElement(InputStream xml)
{
    SAXBuilder builder = new SAXBuilder();
    Document doc = null;
    try
    {
        doc = builder.build(xml);
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
    return doc.getRootElement();
}
 
Example 9
Source File: NeuronamesXmlParser.java    From bluima with Apache License 2.0 5 votes vote down vote up
public static Map<String, Concept> parse(File f) throws JDOMException,
		IOException {

	Map<String, Concept> concepts = newHashMap();

	InputStream corpusIs = new FileInputStream(f);

	SAXBuilder builder = new SAXBuilder();
	Document doc = builder.build(corpusIs);
	Element rootNode = doc.getRootElement();

	Iterator<Element> cs = rootNode.getChildren().iterator();
	while (cs.hasNext()) {
		Element concept = cs.next();

		String id = concept.getAttributeValue("brainInfoID");
		String canonical = concept.getAttributeValue("standardName");
		canonical = canonical.replaceAll("\\(.*\\)$", "").trim();

		Set<String> variantStrings = Sets.newHashSet();

		List<Element> variants = concept.getChild("synonyms").getChildren();
		for (Element variant : variants) {
			if (variant.getAttribute("synonymLanguage").getValue()
					.matches("Latin|English")) {

				variantStrings.add(variant.getText()
						.replaceAll("\\(.*\\)$", "").trim());
			}
		}
		concepts.put(canonical, new Concept(canonical, id, variantStrings));
	}
	checkArgument(concepts.size() > 0, "empty concepts!");
	return concepts;
}
 
Example 10
Source File: OPML10Parser.java    From rome with Apache License 2.0 5 votes vote down vote up
/**
 * Inspects an XML Document (JDOM) to check if it can parse it.
 * <p>
 * It checks if the given document if the type of feeds the parser understands.
 * <p>
 *
 * @param document XML Document (JDOM) to check if it can be parsed by this parser.
 * @return <b>true</b> if the parser know how to parser this feed, <b>false</b> otherwise.
 */
@Override
public boolean isMyType(final Document document) {
    final Element e = document.getRootElement();

    if (e.getName().equals("opml") && (e.getChild("head") == null || e.getChild("head").getChild("docs") == null)
            && (e.getAttributeValue("version") == null || e.getAttributeValue("version").equals("1.0"))) {
        return true;
    }

    return false;
}
 
Example 11
Source File: WmsViewer.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean getCapabilities() {

    Formatter f = new Formatter();
    if (endpoint.indexOf("?") > 0) {
      f.format("%s&request=GetCapabilities&service=WMS&version=%s", endpoint, version);
    } else {
      f.format("%s?request=GetCapabilities&service=WMS&version=%s", endpoint, version);
    }
    System.out.printf("getCapabilities request = '%s'%n", f);
    String url = f.toString();
    info = new Formatter();
    info.format("%s%n", url);

    try (HTTPSession session = HTTPFactory.newSession(url); HTTPMethod method = HTTPFactory.Get(session, url)) {
      int statusCode = method.execute();

      info.format(" Status = %d %s%n", method.getStatusCode(), method.getStatusText());
      info.format(" Status Line = %s%n", method.getStatusLine());
      printHeaders(" Response Headers", method.getResponseHeaders().entries());
      info.format("GetCapabilities:%n%n");

      if (statusCode == 404) {
        throw new FileNotFoundException(method.getPath() + " " + method.getStatusLine());
      }
      if (statusCode >= 300) {
        throw new IOException(method.getPath() + " " + method.getStatusLine());
      }

      SAXBuilder builder = new SAXBuilder();
      Document tdoc = builder.build(method.getResponseAsStream());
      Element root = tdoc.getRootElement();
      parseGetCapabilities(root);
    } catch (Exception e) {
      info.format("%s%n", e.getMessage());
      JOptionPane.showMessageDialog(this, "Failed " + e.getMessage());
      return false;
    }

    return true;
  }
 
Example 12
Source File: TestRDFXMLSerializer.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
@Test
	public void workflow() throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		// To test that seeAlso URIs are stored
		serializer.workflowDoc(outStream, workflowBundle.getMainWorkflow(), URI.create(HELLOWORLD_RDF));
//		System.out.write(outStream.toByteArray());
		Document doc = parseXml(outStream);
		Element root = doc.getRootElement();

		checkRoot(root);
		checkWorkflowDocument(root);
	}
 
Example 13
Source File: SelectiveUtil.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <N> N readByPath(String uri, NamespaceReaderFactory readerFactory) {
    try (InputStream inputStream = FileSystemUtil.getContentAsStream(uri)) {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(inputStream);
        Element root = doc.getRootElement();
        return (N) readerFactory.produce(root).read(root);
    } catch (JDOMException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 14
Source File: FeatureDatasetCapabilitiesWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<VariableSimpleIF> getDataVariables(Document doc) {
  Element root = doc.getRootElement();

  List<VariableSimpleIF> dataVars = new ArrayList<>();
  List<Element> varElems = root.getChildren("variable");
  for (Element varElem : varElems) {
    dataVars.add(new VariableSimpleAdapter(varElem));
  }
  return dataVars;
}
 
Example 15
Source File: LightweightBMLParser.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * scans the incoming stream for bml-string and interprets
 * the xml-tree for bml-data.
 * 
 * @param bmlString the string for parsing the bml tree
 * @return BML-Message with a list of bml information
 * @throws JDOMException xml-string is corrupted
 * @throws IOException cannot read from stream
 */
public final BML generateBML(final String bmlString) throws JDOMException,
    IOException {
  // Build XML-Tree
  Document doc = xmlBuilder.build(new StringReader(bmlString.trim()));
  Element root = doc.getRootElement();

  // Generate BML From Document
  return generateBML(root);
}
 
Example 16
Source File: HgModificationSplitter.java    From gocd with Apache License 2.0 5 votes vote down vote up
private List<Modification> parseDOMTree(Document document) throws ParseException {
    List<Modification> modifications = new ArrayList<>();

    Element rootElement = document.getRootElement();
    List logEntries = rootElement.getChildren("changeset");
    for (Iterator iterator = logEntries.iterator(); iterator.hasNext();) {
        Element changeset = (Element) iterator.next();
        modifications.add(parseChangeset(changeset));
    }

    return modifications;
}
 
Example 17
Source File: XmlBuilder.java    From iaf with Apache License 2.0 5 votes vote down vote up
private Element buildElement(String value)
		throws JDOMException, IOException {
	StringReader stringReader = new StringReader(value);
	SAXBuilder saxBuilder = new SAXBuilder();
	Document document;
	document = saxBuilder.build(stringReader);
	Element element = document.getRootElement();
	return element.detach();
}
 
Example 18
Source File: RdrSetParser.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Map<RuleType, RdrTreeSet> parse(Document doc, boolean newSet) {
    if (doc == null) return Collections.emptyMap();  // no such file or unsuccessful load
    Map<RuleType, RdrTreeSet> treeMap = new HashMap<RuleType, RdrTreeSet>();
    try {
        Element root = doc.getRootElement();      // spec

        // extract the rule nodes for each exception type
        for (Element e : root.getChildren()) {       // these are exception type tags
            String exName = e.getName();
            if (exName.equalsIgnoreCase("selection")) {
                buildItemLevelTree(treeMap, RuleType.ItemSelection, e, newSet);
            }
            else if (exName.equalsIgnoreCase("abort")) {
                buildItemLevelTree(treeMap, RuleType.ItemAbort, e, newSet);
            }
            else if (exName.equalsIgnoreCase("timeout")) {
                buildItemLevelTree(treeMap, RuleType.ItemTimeout, e, newSet);
            }
            else if (exName.equalsIgnoreCase("resourceUnavailable")) {
                buildItemLevelTree(treeMap, RuleType.ItemResourceUnavailable, e, newSet);
            }
            else if (exName.equalsIgnoreCase("violation")) {
                buildItemLevelTree(treeMap, RuleType.ItemConstraintViolation, e, newSet);
            }
            else if (exName.equalsIgnoreCase("external")) {
                getExternalRules(treeMap, e, newSet) ;
            }
            else if (exName.equalsIgnoreCase("constraints")) {
                getConstraintRules(treeMap, e, newSet) ;
            }

            // if 'task' is a child of 'root', this is a version one rules file
            // so treat it as though it contains selection rules only
            else if (exName.equalsIgnoreCase("task")) {
                buildItemLevelTree(treeMap, RuleType.ItemSelection, root, newSet);
            }
        }
        return treeMap;
    }
    catch (Exception ex) {
        LogManager.getLogger(RdrSetLoader.class).error(
                "Exception retrieving rule nodes from rules file", ex);
        return Collections.emptyMap();
    }
}
 
Example 19
Source File: SettlementConfig.java    From mars-sim with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Load new arriving settlements.
 * 
 * @param settlementDoc DOM document with settlement configuration.
 */
private void loadNewArrivingSettlements(Document settlementDoc) {
	Element root = settlementDoc.getRootElement();
	Element arrivingSettlementList = root.getChild(NEW_ARRIVING_SETTLEMENT_LIST);
	List<Element> settlementNodes = arrivingSettlementList.getChildren(ARRIVING_SETTLEMENT);
	for (Element settlementElement : settlementNodes) {
		NewArrivingSettlement arrivingSettlement = new NewArrivingSettlement();

		String settlementName = settlementElement.getAttributeValue(NAME);
		if (settlementName.equals(RANDOM))
			arrivingSettlement.randomName = true;
		else
			arrivingSettlement.name = settlementName;

		arrivingSettlement.template = settlementElement.getAttributeValue(TEMPLATE);

		arrivingSettlement.arrivalTime = Double.parseDouble(settlementElement.getAttributeValue(ARRIVAL_TIME));

		List<Element> locationNodes = settlementElement.getChildren(LOCATION);
		if (locationNodes.size() > 0) {
			Element locationElement = locationNodes.get(0);

			String longitudeString = locationElement.getAttributeValue(LONGITUDE);
			if (longitudeString.equals(RANDOM))
				arrivingSettlement.randomLongitude = true;
			else
				arrivingSettlement.longitude = longitudeString;

			String latitudeString = locationElement.getAttributeValue(LATITUDE);
			if (latitudeString.equals(RANDOM))
				arrivingSettlement.randomLatitude = true;
			else
				arrivingSettlement.latitude = latitudeString;
		} else {
			arrivingSettlement.randomLongitude = true;
			arrivingSettlement.randomLatitude = true;
		}

		Element populationElement = settlementElement.getChild(POPULATION);
		String numberStr = populationElement.getAttributeValue(NUMBER);
		int number = Integer.parseInt(numberStr);
		if (number < 0) {
			throw new IllegalStateException("populationNumber cannot be less than zero: " + number);
		}
		arrivingSettlement.populationNumber = number;

		Element numOfRobotsElement = settlementElement.getChild(NUM_OF_ROBOTS);
		String numOfRobotsStr = numOfRobotsElement.getAttributeValue(ROBOTS_NUMBER);
		int numOfRobots = Integer.parseInt(numOfRobotsStr);
		if (numOfRobots < 0) {
			throw new IllegalStateException("numOfRobots cannot be less than zero: " + number);
		}
		arrivingSettlement.numOfRobots = number;

		Element sponsorElement = settlementElement.getChild(SPONSOR);
		String sponsor = sponsorElement.getAttributeValue(NAME);
		arrivingSettlement.sponsor = sponsor;

		newArrivingSettlements.add(arrivingSettlement);
	}
}
 
Example 20
Source File: UscTteCollectionReader.java    From bluima with Apache License 2.0 4 votes vote down vote up
public void getNext(JCas jcas) throws IOException, CollectionException {

        File file = fileIterator.next();
        try {
            // LOG.debug("reading {}", file.getName());
            Document doc = builder.build(new FileInputStream(file));
            Element rootNode = doc.getRootElement();

            String title = xo.outputString(rootNode.getChild("Title")
                    .getContent());
            Header h = new Header(jcas);
            h.setSource(file.getName());
            h.setTitle(title);
            h.setDocId(docCnt++ + "");
            h.addToIndexes();

            StringBuilder sb = new StringBuilder();
            int textIndex = 0;

            for (Object sentence : sentenceXPath.evaluate(rootNode)) {
                Element sentenceE = (Element) sentence;

                // skip some classes (titles and bibliography)
                String classStr = sentenceE.getAttribute("class").getValue();
                if (!classStr.matches("(references\\.body|.*heading)")) {

                    textIndex = addAnnotations(jcas, sentenceE.getContent(),
                            sb, textIndex, xo);
                    // space btw sentences
                    textIndex++;
                    sb.append(" ");

                }
            }

            jcas.setDocumentText(sb.toString().trim()); // trim last space

        } catch (JDOMException e) {
            throw new CollectionException(e);
        }
    }