Java Code Examples for org.jdom2.Element#getAttributeValue()

The following examples show how to use org.jdom2.Element#getAttributeValue() . 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: NcmlConstructor.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void readAtt(Object parent, Element attElem) {
  String name = attElem.getAttributeValue("name");
  if (name == null) {
    errlog.format("NcML Attribute name is required (%s)%n", attElem);
    return;
  }

  try {
    ucar.ma2.Array values = NcMLReader.readAttributeValues(attElem);
    Attribute att = new ucar.nc2.Attribute(name, values);
    if (parent instanceof Group)
      ((Group) parent).addAttribute(att);
    else if (parent instanceof Variable)
      ((Variable) parent).addAttribute(att);
  } catch (RuntimeException e) {
    errlog.format("NcML new Attribute Exception: %s att=%s in=%s%n", e.getMessage(), name, parent);
  }
}
 
Example 2
Source File: MCRRuleParser.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected MCRCondition<?> parseSimpleCondition(Element e) throws MCRParseException {
    String name = e.getName();
    switch (name) {
        case "boolean":
            return super.parseSimpleCondition(e);
        case "condition":
            MCRCondition<?> condition = parseElement(e);
            if (condition == null) {
                throw new MCRParseException("Not a valid condition field <" + e.getAttributeValue("field") + ">");
            }
            return condition;
        default:
            throw new MCRParseException("Not a valid name <" + e.getName() + ">");
    }
}
 
Example 3
Source File: RSS10Parser.java    From rome with Apache License 2.0 6 votes vote down vote up
/**
 * Parses an item element of an RSS document looking for item information.
 * <p/>
 * It first invokes super.parseItem and then parses and injects the description property if
 * present.
 * <p/>
 *
 * @param rssRoot the root element of the RSS document in case it's needed for context.
 * @param eItem the item element to parse.
 * @return the parsed RSSItem bean.
 */
@Override
protected Item parseItem(final Element rssRoot, final Element eItem, final Locale locale) {

    final Item item = super.parseItem(rssRoot, eItem, locale);

    final Element description = eItem.getChild("description", getRSSNamespace());
    if (description != null) {
        item.setDescription(parseItemDescription(rssRoot, description));
    }

    final Element encoded = eItem.getChild("encoded", getContentNamespace());
    if (encoded != null) {
        final Content content = new Content();
        content.setType(Content.HTML);
        content.setValue(encoded.getText());
        item.setContent(content);
    }

    final String about = eItem.getAttributeValue("about", getRDFNamespace());
    if (about != null) {
        item.setUri(about);
    }

    return item;
}
 
Example 4
Source File: XMLBootDelivery.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
public XMLBootDelivery(File xmlsource) throws IOException, JDOMException {
	SAXBuilder builder = new SAXBuilder();
	FileInputStream fin = new FileInputStream(xmlsource);
	Document document = builder.build(fin);
	String spaceid = document.getRootElement().getAttribute("SPACE_ID").getValue();
	bootversion = document.getRootElement().getAttribute("VERSION").getValue().replaceAll(spaceid, "").trim();
	if (bootversion.startsWith("_")) bootversion = bootversion.substring(1);
	Iterator<Element> i=document.getRootElement().getChildren().iterator();
	while (i.hasNext()) {
		Element e = i.next();
		XMLBootConfig c = new XMLBootConfig(e.getAttributeValue("NAME"));
		if (e.getChild("BOOT_CONFIG").getChild("FILE") != null) {
			c.setTA(e.getChild("BOOT_CONFIG").getChild("FILE").getAttributeValue("PATH"));
		}
		Iterator<Element> files = e.getChild("BOOT_IMAGES").getChildren().iterator();
		while (files.hasNext()) {
			c.addFile(files.next().getAttributeValue("PATH"));
		}
		c.setAttributes(e.getChild("ATTRIBUTES").getAttributeValue("VALUE"));
		bootconfigs.add(c);
	}
	fin.close();
}
 
Example 5
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 6
Source File: CatalogBuilder.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected Documentation readDocumentation(Element s) {
  String href = s.getAttributeValue("href", Catalog.xlinkNS);
  String title = s.getAttributeValue("title", Catalog.xlinkNS);
  String type = s.getAttributeValue("type"); // not XLink type
  String content = s.getTextNormalize();

  URI uri = null;
  if (href != null) {
    try {
      uri = Catalog.resolveUri(baseURI, href);
    } catch (Exception e) {
      errlog.format(" ** Invalid documentation href = '%s' err='%s'%n", href, e.getMessage());
      logger.debug(" ** Invalid documentation href = '{}' err='{}'", href, e.getMessage());
    }
  }

  return new Documentation(href, uri, title, type, content);
}
 
Example 7
Source File: YMarshal.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Gets the specification's schema version form its root Element
 * @param specRoot the root Element of a specification set Document
 * @return the specification's schema version
 */
private static YSchemaVersion getVersion(Element specRoot) {
    String version = specRoot.getAttributeValue("version");

    // version attribute was not mandatory in version 2
    // therefore a missing version number would likely be version 2
    return (null == version) ? YSchemaVersion.Beta2 : YSchemaVersion.fromString(version);
}
 
Example 8
Source File: WorkletSpecification.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected YSpecificationID extractSpecID(String xml) {
    YSpecificationID specID = null;
    Document doc = JDOMUtil.stringToDocument(xml);
    if (doc != null) {
        Element root = doc.getRootElement();
        if (root != null) {
            YSchemaVersion schemaVersion = YSchemaVersion.fromString(
                    root.getAttributeValue("version"));
            Namespace ns = root.getNamespace();
            Element spec = root.getChild("specification", ns);
            if (spec != null) {
                String uri = spec.getAttributeValue("uri");
                String version = "0.1";
                String identifier = null;
                if (! (schemaVersion == null || schemaVersion.isBetaVersion())) {
                    Element metadata = spec.getChild("metaData", ns);
                    if (metadata != null) {
                        version = metadata.getChildText("version", ns);
                        identifier = metadata.getChildText("identifier", ns);
                    }
                }
                specID = new YSpecificationID(identifier, version, uri);
            }
        }
    }
    return specID;
}
 
Example 9
Source File: LanguageUpdater.java    From Digital with GNU General Public License v3.0 5 votes vote down vote up
private void add(Document xml, String key, String text) throws IOException {
    for (Element e : (List<Element>) xml.getRootElement().getChildren()) {
        String k = e.getAttributeValue("name");
        if (k.equals(key)) {
            throw new IOException("key " + key + " is already present in " + xml);
        }
    }
    xml.getRootElement().addContent("    ");
    xml.getRootElement().addContent(new Element("string").setAttribute("name", key).setText(text));
    xml.getRootElement().addContent("\n");
}
 
Example 10
Source File: BlockParser.java    From CardinalPGM with MIT License 5 votes vote down vote up
public BlockParser(Element element) {
    super(element.getAttributeValue("name") != null ? element.getAttributeValue("name") : element.getAttributeValue("id"));
    double x, y, z;
    String working = element.getAttributeValue("location") == null ? element.getText() : element.getAttributeValue("location");
    if (element.getText().contains(",")) {
        x = Numbers.parseDouble(working.split(",")[0].trim());
        y = Numbers.parseDouble(working.split(",")[1].trim());
        z = Numbers.parseDouble(working.split(",")[2].trim());
    } else {
        x = Numbers.parseDouble(working.trim().replaceAll(" ", ",").split(",")[0]);
        y = Numbers.parseDouble(working.trim().replaceAll(" ", ",").split(",")[1]);
        z = Numbers.parseDouble(working.trim().replaceAll(" ", ",").split(",")[2]);
    }
    this.vector = new Vector(Math.floor(x), Math.floor(y), Math.floor(z));
}
 
Example 11
Source File: NameGenPanel.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String loadList(Element list) throws DataConversionException
{
	pcgen.core.doomsdaybook.DDList dataList = new pcgen.core.doomsdaybook.DDList(allVars,
		list.getAttributeValue("title"), list.getAttributeValue("id"));
	java.util.List<?> elements = list.getChildren();

	for (final Object element : elements)
	{
		Element child = (Element) element;
		String elementName = child.getName();

		if (elementName.equals("VALUE"))
		{
			WeightedDataValue dv =
					new WeightedDataValue(child.getText(), child.getAttribute("weight").getIntValue());
			List<?> subElements = child.getChildren("SUBVALUE");

			for (final Object subElement1 : subElements)
			{
				Element subElement = (Element) subElement1;
				dv.addSubValue(subElement.getAttributeValue("type"), subElement.getText());
			}

			dataList.add(dv);
		}
	}

	allVars.addDataElement(dataList);

	return dataList.getId();
}
 
Example 12
Source File: DesktopData.java    From Zettelkasten with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method recursivly scans all elements of a desktop. If an
 * entry-element which id-attribute matches the parameter
 * {@code entrynumber} was found, this method returns {@code true}.
 *
 * @param e the element where we start scanning. for the first call, use
 * {@link #getDesktopElement(int) getDesktopElement(int)} to retrieve the
 * root-element for starting the recursive scan.
 * @param entrynumber the number of the entry we are looking for. if any
 * element's id-attribut matches this parameter, the element is return, else
 * null
 * @param found the initial value, should be {@code false} when initially
 * called
 * @return {@code true} when the entry with the number {@code entrynumber}
 * was found, {@code false} otherwise.
 */
public boolean desktopHasElement(Element e, String entrynumber, boolean found) {
    // if we don't have any element, return null
    if (e == null) {
        return false;
    }
    // get a list with all children of the element
    List<Element> children = e.getChildren();
    // create an iterator
    Iterator<Element> it = children.iterator();
    // go through all children
    while (it.hasNext()) {
        // get the child
        e = it.next();
        // else check whether we have child-elements - if so, re-call method
        if (hasChildren(e)) {
            found = desktopHasElement(e, entrynumber, found);
        }
        // check whether an entry was found in children
        if (found) {
            return true;
        }
        // check whether we have an entry-element that matched the requested id-number
        if (e != null && e.getName().equals(ELEMENT_ENTRY)) {
            // check whether attribute exists
            String att = e.getAttributeValue("id");
            // if so, and it machtes the requested id-number, add element to list
            if (att != null && att.equals(entrynumber)) {
                // save element
                foundDesktopElement = e;
                return true;
            }
        }
    }
    return found;
}
 
Example 13
Source File: MediaModuleParser.java    From rome with Apache License 2.0 5 votes vote down vote up
/**
 * @param e element to parse
 * @param md metadata to fill in
 */
private void parseRights(final Element e, final Metadata md) {
    final Element rightsElement = e.getChild("rights", getNS());
    if (rightsElement != null && rightsElement.getAttributeValue("status") != null) {
        md.setRights(RightsStatus.valueOf(rightsElement.getAttributeValue("status")));
    }
}
 
Example 14
Source File: LightweightBMLParser.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Generates a sync poing element.
 * 
 * @param xmlSyncPointElement
 *                      the xml element, which represents a bml sync point
 */
protected final void generateSyncPoint(final Element xmlSyncPointElement) {
  String id = xmlSyncPointElement.getAttributeValue("id", "");
  String time = xmlSyncPointElement.getAttributeValue("time", "");
  String globalTime =
      xmlSyncPointElement.getAttributeValue("globalTime", "");
  String character =
      xmlSyncPointElement.getAttributeValue("characterId", "");

  bmlTree.getSyncPoints().add(new SyncPoint(id, time, globalTime, character));
}
 
Example 15
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 16
Source File: NcmlConstructor.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void readGroup(NetcdfFile ncfile, Group parent, Element groupElem) {

    String name = groupElem.getAttributeValue("name");

    Group g;
    if (parent == ncfile.getRootGroup()) { // special handling
      g = parent;

    } else {
      if (name == null) {
        errlog.format("NcML Group name is required (%s)%n", groupElem);
        return;
      }
      g = new Group(ncfile, parent, name);
      parent.addGroup(g);
    }

    // look for attributes
    java.util.List<Element> attList = groupElem.getChildren("attribute", Catalog.ncmlNS);
    for (Element attElem : attList) {
      readAtt(g, attElem);
    }

    // look for dimensions
    java.util.List<Element> dimList = groupElem.getChildren("dimension", Catalog.ncmlNS);
    for (Element dimElem : dimList) {
      readDim(g, dimElem);
    }

    // look for variables
    java.util.List<Element> varList = groupElem.getChildren("variable", Catalog.ncmlNS);
    for (Element varElem : varList) {
      readVariable(ncfile, g, null, varElem);
    }

    // LOOK for typedef enums

    // look for nested groups
    java.util.List<Element> groupList = groupElem.getChildren("group", Catalog.ncmlNS);
    for (Element gElem : groupList) {
      readGroup(ncfile, g, gElem);
    }
  }
 
Example 17
Source File: Repository.java    From CardinalPGM with MIT License 4 votes vote down vote up
private static Contributor parseContributor(Element element) {
    if (element.getAttributeValue("uuid") != null) {
        return new Contributor(UUID.fromString(element.getAttributeValue("uuid")), element.getAttributeValue("contribution"));
    } else return new Contributor(element.getText(), element.getAttributeValue("contribution"));
}
 
Example 18
Source File: NcMLReaderNew.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private Optional<Builder> readVariableExisting(Group.Builder groupBuilder,
    @Nullable StructureDS.Builder<?> parentStructure, DataType dtype, Variable refv, Element varElem) {
  String name = varElem.getAttributeValue("name");
  String typedefS = dtype.isEnum() ? varElem.getAttributeValue("typedef") : null;
  String nameInFile = Optional.ofNullable(varElem.getAttributeValue("orgName")).orElse(name);

  VariableDS.Builder vb;
  if (this.explicit) { // all metadata is in the ncml, do not copy
    vb = VariableDS.builder().setOriginalVariable(refv);
  } else { // modify existing
    if (parentStructure != null) {
      vb = (VariableDS.Builder<?>) parentStructure.findMemberVariable(nameInFile)
          .orElseThrow(() -> new IllegalStateException("Cant find variable " + nameInFile));
    } else {
      vb = (VariableDS.Builder) groupBuilder.findVariableLocal(nameInFile)
          .orElseThrow(() -> new IllegalStateException("Cant find variable " + nameInFile));
    }
  }
  vb.setName(name).setDataType(dtype);
  if (typedefS != null) {
    vb.setEnumTypeName(typedefS);
  }

  String dimNames = varElem.getAttributeValue("shape"); // list of dimension names
  if (dimNames != null) {
    List<Dimension> varDims = groupBuilder.makeDimensionsList(dimNames);
    vb.setDimensions(varDims); // TODO check conformable
  }

  java.util.List<Element> attList = varElem.getChildren("attribute", ncNS);
  for (Element attElem : attList) {
    readAtt(vb.getAttributeContainer(), refv, attElem);
  }

  // deal with legacy use of attribute with Unsigned = true
  Attribute att = vb.getAttributeContainer().findAttribute(CDM.UNSIGNED);
  boolean isUnsignedSet = att != null && att.getStringValue().equalsIgnoreCase("true");
  if (isUnsignedSet) {
    dtype = dtype.withSignedness(DataType.Signedness.UNSIGNED);
    vb.setDataType(dtype);
  }

  // process remove command
  java.util.List<Element> removeList = varElem.getChildren("remove", ncNS);
  for (Element remElem : removeList) {
    cmdRemove(vb, remElem.getAttributeValue("type"), remElem.getAttributeValue("name"));
  }

  Element valueElem = varElem.getChild("values", ncNS);
  if (valueElem != null) {
    readValues(vb, dtype, varElem, valueElem);
  }
  /*
   * else {
   * // see if we need to munge existing data. use case : aggregation
   * if (v.hasCachedData()) {
   * Array data;
   * try {
   * data = v.read();
   * } catch (IOException e) {
   * throw new IllegalStateException(e.getMessage());
   * }
   * if (data.getClass() != v.getDataType().getPrimitiveClassType()) {
   * Array newData = Array.factory(v.getDataType(), v.getShape());
   * MAMath.copy(newData, data);
   * v.setCachedData(newData, false);
   * }
   * }
   * }
   */

  // look for logical views
  // processLogicalViews(v, refGroup, varElem);
  // only return if it needs to be added
  return (this.explicit) ? Optional.of(vb) : Optional.empty();
}
 
Example 19
Source File: ApiXmlLinksHereResult.java    From wpcleaner with Apache License 2.0 4 votes vote down vote up
/**
 * Execute links here request.
 * 
 * @param properties Properties defining request.
 * @param page Main page.
 * @param lists Lists to be filled with links to the page.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean executeLinksHere(
    Map<String, String> properties,
    Page page,
    Map<String, List<Page>> lists) throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Retrieve links to page
    // TODO
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/pages/page", Filters.element());
    List<Element> listPages = xpa.evaluate(root);
    Iterator<Element> itPages = listPages.iterator();
    XPathExpression<Element> xpaLinksHere = XPathFactory.instance().compile(
        "./linkshere/lh", Filters.element());
    while (itPages.hasNext()) {
      Element currentPage = itPages.next();
      String title = currentPage.getAttributeValue("title");
      List<Page> list = lists.get(title);
      if (list == null) {
        list = new ArrayList<>();
        lists.put(title, list);
      }
      List<Element> listLinks = xpaLinksHere.evaluate(currentPage);
      Iterator<Element> itLinks = listLinks.iterator();
      while (itLinks.hasNext()) {
        Element currentLink = itLinks.next();
        Page link = DataManager.getPage(
            getWiki(), currentLink.getAttributeValue("title"),
            null, null, page.getRelatedPages(RelatedPages.REDIRECTS));
        link.setNamespace(currentLink.getAttributeValue("ns"));
        link.setPageId(currentLink.getAttributeValue("pageid"));
        if (currentLink.getAttribute("redirect") != null) {
          link.getRedirects().isRedirect(true);
        }
        if (!list.contains(link)) {
          list.add(link);
        }
      }
    }

    // Retrieve continue
    return shouldContinue(
        root, "/api/query-continue/linkshere",
        properties);
  } catch (JDOMException e) {
    log.error("Error loading links here", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 20
Source File: PersonConfig.java    From mars-sim with GNU General Public License v3.0 3 votes vote down vote up
/**
	 * Gets the value of an element as a double
	 * 
	 * @param an element
	 * 
	 * @return a double
	 */
	private double getValueAsDouble(String child) {
		Element element = personDoc.getRootElement().getChild(child);
		String str = element.getAttributeValue(VALUE);
//		System.out.println("str : " + str);
		return Double.parseDouble(str);
	}