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

The following examples show how to use org.jdom2.Element#setAttribute() . 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: MCRXPathBuilderTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testXPath() {
    Element root = new Element("root");
    Element title1 = new Element("title");
    Element title2 = new Element("title");
    Element author = new Element("contributor");
    Attribute role = new Attribute("role", "author");
    Attribute lang = new Attribute("lang", "de", Namespace.XML_NAMESPACE);
    author.setAttribute(role);
    author.setAttribute(lang);
    root.addContent(title1);
    root.addContent(author);
    root.addContent(title2);
    new Document(root);

    assertEquals("/root", MCRXPathBuilder.buildXPath(root));
    assertEquals("/root/contributor", MCRXPathBuilder.buildXPath(author));
    assertEquals("/root/title", MCRXPathBuilder.buildXPath(title1));
    assertEquals("/root/title[2]", MCRXPathBuilder.buildXPath(title2));
    assertEquals("/root/contributor/@role", MCRXPathBuilder.buildXPath(role));
    assertEquals("/root/contributor/@xml:lang", MCRXPathBuilder.buildXPath(lang));

    root.detach();
    assertEquals("root", MCRXPathBuilder.buildXPath(root));
    assertEquals("root/contributor", MCRXPathBuilder.buildXPath(author));
}
 
Example 2
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 3
Source File: TroopsManager.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
@Override
public Element getExportData(final List<String> pGroupsToExport) {
    Element troopGroups = new Element("troopGroups");
    if (pGroupsToExport == null || pGroupsToExport.isEmpty()) {
        return troopGroups;
    }
    try {
        logger.debug("Generating troop data");
        for (String group : pGroupsToExport) {
            Element troopGroup = new Element("troopGroup");
            troopGroup.setAttribute("name", URLEncoder.encode(group, "UTF-8"));
            
            Element troopInfos = new Element("troopInfos");
            for (ManageableType t : getAllElements(group)) {
                troopInfos.addContent(t.toXml("troopInfo"));
            }
            troopGroup.addContent(troopInfos);
            troopGroups.addContent(troopGroup);
        }
        logger.debug("Data generated successfully");
    } catch (Exception e) {
        logger.error("Failed to generate troop data", e);
    }
    return troopGroups;
}
 
Example 4
Source File: IOProcessorImpl.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
private <T> void persistChildrenMap(Element element, String sequences, String childrenName,
                                    String keyName, String valueName,
                                    Supplier<Map<String, T>> getter) {
    Map<String, T> values = getter.get();
    if (values == null) return;
    Element seqE;
    seqE = persistSequences(element, sequences);
    for (String k : values.keySet()) {
        Element childE = new Element(childrenName, element.getNamespace());
        childE.setAttribute(keyName, k);
        if (valueName == null) {
            childE.setText(values.get(k).toString());
        } else {
            if (values.get(k) != null) {
                childE.setAttribute(valueName, values.get(k).toString());
            }
        }
        seqE.addContent(childE);
    }
}
 
Example 5
Source File: MCRChangeTrackerTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testBreakpoint() {
    Element root = new Element("root");
    Document doc = new Document(root);

    MCRChangeTracker tracker = new MCRChangeTracker();

    Element title = new Element("title");
    root.addContent(title);
    tracker.track(MCRAddedElement.added(title));

    tracker.track(MCRBreakpoint.setBreakpoint(root, "Test"));

    Attribute href = new Attribute("href", "foo", MCRConstants.XLINK_NAMESPACE);
    root.setAttribute(href);
    tracker.track(MCRAddedAttribute.added(href));

    tracker.track(MCRSetAttributeValue.setValue(href, "bar"));

    String label = tracker.undoLastBreakpoint(doc);
    assertEquals("Test", label);
    assertNull(root.getAttribute("href"));
    assertEquals(1, tracker.getChangeCounter());
}
 
Example 6
Source File: VillageTroopsHolder.java    From dsworkbench with Apache License 2.0 5 votes vote down vote up
@Override
public Element toXml(String elementName) {
    Element troopInfo = new Element(elementName);
    troopInfo.setAttribute("type", "normal");
    troopInfo.addContent(new Element("id").setText(Integer.toString(village.getId())));
    troopInfo.addContent(new Element("state").setText(Long.toString(state.getTime())));
    troopInfo.addContent(troops.toXml("troops"));
    return troopInfo;
}
 
Example 7
Source File: GridDatasetInfo.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Element writeAxis2(CoordinateAxis axis, String name) {
  if (axis == null)
    return null;

  NcmlWriter ncmlWriter = new NcmlWriter();

  Element varElem = new Element(name);
  varElem.setAttribute("name", axis.getFullName());
  varElem.setAttribute("shape", getShapeString(axis.getShape())); // axis.getDimensionsString());

  DataType dt = axis.getDataType();
  varElem.setAttribute("type", dt.toString());

  AxisType axisType = axis.getAxisType();
  if (null != axisType)
    varElem.setAttribute("axisType", axisType.toString());

  // attributes
  for (Attribute att : axis.attributes())
    varElem.addContent(ncmlWriter.makeAttributeElement(att));

  try {
    Element values = ncmlWriter.makeValuesElement(axis, false);
    values.setAttribute("npts", Long.toString(axis.getSize()));
    varElem.addContent(values);
  } catch (IOException e) {
    String message = String.format("Couldn't read values for %s. Omitting <values> element.", axis.getFullName());
    logger.warn(message, e);
  }

  return varElem;
}
 
Example 8
Source File: N2oCheckboxButtonsPersister.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Element persist(N2oCheckboxButtons control, Namespace namespace) {
    Element element = new Element(getElementName(), namespacePrefix, namespaceUri);
    PersisterJdomUtil.setAttribute(element, "color-field-id", control.getColorFieldId());
    element.setAttribute("data-toggle", "buttons-checkbox");
    setControl(element, control);
    setField(element, control);
    setListField(element, control);
    setListQuery(element, control);
    setOptionsList(element, control.getOptions());
    return element;
}
 
Example 9
Source File: NcMLWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Element makeGroupElement(Group group) {
  Element elem = new Element("group", namespace);
  elem.setAttribute("name", group.getShortName());

  // enumTypeDef
  for (EnumTypedef etd : group.getEnumTypedefs()) {
    elem.addContent(makeEnumTypedefElement(etd));
  }

  // dimensions
  for (Dimension dim : group.getDimensions()) {
    elem.addContent(makeDimensionElement(dim));
  }

  // regular variables
  for (Variable var : group.getVariables()) {
    boolean showValues = writeVariablesPredicate.apply(var);
    elem.addContent(makeVariableElement(var, showValues));
  }

  // nested groups
  for (Group g : group.getGroups()) {
    Element groupElem = new Element("group", namespace);
    groupElem.setAttribute("name", g.getShortName());
    elem.addContent(makeGroupElement(g));
  }

  // attributes
  for (Attribute att : group.attributes()) {
    elem.addContent(makeAttributeElement(att));
  }

  return elem;
}
 
Example 10
Source File: N2oRadioButtonsPersister.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Element persist(N2oRadioButtons control, Namespace namespace) {
    Element element = new Element(getElementName(), namespacePrefix, namespaceUri);
    PersisterJdomUtil.setAttribute(element, "color-field-id", control.getColorFieldId());
    setControl(element, control);
    setField(element, control);
    setListField(element, control);
    setListQuery(element, control);
    element.setAttribute("data-toggle", "buttons-radio");
    setOptionsList(element, control.getOptions());
    return element;
}
 
Example 11
Source File: MCRMetaIFS.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method create a XML stream for all data in this class, defined by
 * the MyCoRe XML MCRMetaIFS definition for the given subtag.
 * 
 * @exception MCRException
 *                if the content of this class is not valid
 * @return a JDOM Element with the XML MCRClassification part
 */
@Override
public Element createXML() throws MCRException {
    Element elm = super.createXML();
    if (sourcePath != null) {
        elm.setAttribute("sourcepath", sourcePath);
    }
    elm.setAttribute("maindoc", maindoc);

    return elm;
}
 
Example 12
Source File: CoordRefSysToGML.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Element genProjectedCRS(ucar.unidata.geoloc.Projection proj) {
  Element projElem = new Element("ProjectedCRS", gmlNS);
  projElem.setAttribute("id", "", gmlNS);
  projElem.addContent(new Element("identifier", gmlNS).setAttribute("codeSpace", "", gmlNS).addContent(""));
  projElem.addContent(new Element("name", gmlNS).addContent(proj.getName()));
  projElem.addContent(new Element("scope", gmlNS).addContent(""));
  projElem.addContent(new Element("conversion", gmlNS).addContent(""));

  return projElem;
}
 
Example 13
Source File: MCRMetaLink.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method create a XML stream for all data in this class,
 * defined by the MyCoRe XML MCRMetaLink definition for the given subtag.
 * 
 * @exception MCRException
 *                if the content of this class is not valid
 * @return a JDOM Element with the XML MCRMetaLink part
 */
@Override
public Element createXML() throws MCRException {
    Element elm = super.createXML();
    elm.setAttribute("type", linktype, XLINK_NAMESPACE);

    if (title != null) {
        elm.setAttribute("title", title, XLINK_NAMESPACE);
    }

    if (label != null) {
        elm.setAttribute("label", label, XLINK_NAMESPACE);
    }

    if (role != null) {
        elm.setAttribute("role", role, XLINK_NAMESPACE);
    }

    if (linktype.equals("locator")) {
        elm.setAttribute("href", href, XLINK_NAMESPACE);
    } else {
        elm.setAttribute("from", from, XLINK_NAMESPACE);
        elm.setAttribute("to", to, XLINK_NAMESPACE);
    }

    return elm;
}
 
Example 14
Source File: Bookmarks.java    From Zettelkasten with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Adds a new bookmark to the bookmark-file. First, we have to check whether
 * the bookmark already exists. If not, add it. Then we have to check for
 * the category. If it already exists, retrieve the category's index-number.
 * Else add a new category.
 * <br><br>
 * Use "getCompleteBookmark" for retrieving a bookmark's entry-number,
 * category and comment.
 *
 * @param index the index-number of the bookmark, i.e. the entry's number
 * @param cat the category, under which the bookmark should appear.
 * @param comment an optional comment for the bookmark
 */
public void addBookmark(int index, String cat, String comment) {
    // first check whether this index-number was already bookmarked...
    // if not, a -1 is return, else the index-number
    // if the bookmark already exists, do nothing
    if (-1 == getBookmarkPosition(index)) {
        try {
            // retrieve the position of the category
            int catpos = getCategoryPosition(cat);
            // check whether the category exists
            if (-1 == catpos) {
                // if the category doesn't already exist, add it
                catpos = addCategory(cat);
            }
            // create new bookmark-element
            Element bm = new Element(Daten.ELEMENT_ENTRY);
            // set the id, i.e. the number of the entry which is bookmarked
            bm.setAttribute("id", String.valueOf(index));
            // set the category-index for this bookmark
            bm.setAttribute("cat", String.valueOf(catpos));
            // and add the comment
            if (null == comment) {
                comment = "";
            }
            bm.setText(comment);
            // retrieve the bookmark-"root"-element
            Element bookbase = bookmarks.getRootElement().getChild("bookmark");
            // and add the bookmark-element
            bookbase.addContent(bm);
            // change modified-state
            setModified(true);
        } catch (IllegalAddException | IllegalNameException | IllegalDataException ex) {
            Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage());
        }
    }
}
 
Example 15
Source File: Atom10Generator.java    From rome with Apache License 2.0 4 votes vote down vote up
protected Element generateLinkElement(final Link link) {

        final Namespace namespace = getFeedNamespace();
        final Element linkElement = new Element("link", namespace);

        final String rel = link.getRel();
        if (rel != null) {
            final Attribute relAttribute = new Attribute("rel", rel);
            linkElement.setAttribute(relAttribute);
        }

        final String type = link.getType();
        if (type != null) {
            final Attribute typeAttribute = new Attribute("type", type);
            linkElement.setAttribute(typeAttribute);
        }

        final String href = link.getHref();
        if (href != null) {
            final Attribute hrefAttribute = new Attribute("href", href);
            linkElement.setAttribute(hrefAttribute);
        }

        final String hreflang = link.getHreflang();
        if (hreflang != null) {
            final Attribute hreflangAttribute = new Attribute("hreflang", hreflang);
            linkElement.setAttribute(hreflangAttribute);
        }

        final String linkTitle = link.getTitle();
        if (linkTitle != null) {
            final Attribute title = new Attribute("title", linkTitle);
            linkElement.setAttribute(title);
        }

        if (link.getLength() != 0) {
            final Attribute lenght = new Attribute("length", Long.toString(link.getLength()));
            linkElement.setAttribute(lenght);
        }

        return linkElement;

    }
 
Example 16
Source File: NcMLWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public Element makeVariableElement(Variable var, boolean showValues) {
  boolean isStructure = var instanceof Structure;

  Element varElem = new Element("variable", namespace);
  varElem.setAttribute("name", var.getShortName());

  StringBuilder buff = new StringBuilder();
  List dims = var.getDimensions();
  for (int i = 0; i < dims.size(); i++) {
    Dimension dim = (Dimension) dims.get(i);
    if (i > 0)
      buff.append(" ");
    if (dim.isShared())
      buff.append(dim.getShortName());
    else if (dim.isVariableLength())
      buff.append("*");
    else
      buff.append(dim.getLength());
  }
  // if (buff.length() > 0)
  varElem.setAttribute("shape", buff.toString());

  DataType dt = var.getDataType();
  if (dt != null) {
    varElem.setAttribute("type", dt.toString());
    if (dt.isEnum())
      varElem.setAttribute("typedef", var.getEnumTypedef().getShortName());
  }


  // attributes
  for (Attribute att : var.attributes()) {
    varElem.addContent(makeAttributeElement(att));
  }

  if (isStructure) {
    Structure s = (Structure) var;
    for (Variable variable : s.getVariables()) {
      varElem.addContent(makeVariableElement(variable, showValues));
    }
  } else if (showValues) {
    try {
      varElem.addContent(makeValuesElement(var, true));
    } catch (IOException e) {
      String message = String.format("Couldn't read values for %s. Omitting <values> element.%n\t%s",
          var.getFullName(), e.getMessage());
      log.warn(message);
    }
  }

  return varElem;
}
 
Example 17
Source File: CoverageDatasetCapabilities.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private Element writeAxis(CoverageCoordAxis axis) {
  Element varElem = new Element("axis");
  varElem.setAttribute("name", axis.getName());
  varElem.setAttribute("shape", Arrays.toString(axis.getShape()));

  DataType dt = axis.getDataType();
  varElem.setAttribute("type", dt.toString());

  AxisType axisType = axis.getAxisType();
  if (null != axisType)
    varElem.setAttribute("axisType", axisType.toString());

  if (axis.getDependsOn() != null && !axis.getDependsOn().trim().isEmpty())
    varElem.setAttribute("dependsOn", axis.getDependsOn().trim());

  // attributes
  for (Attribute att : axis.getAttributes()) {
    varElem.addContent(ncmlWriter.makeAttributeElement(att));
  }

  /*
   * f.format("%s  npts: %d [%f,%f] spacing=%s", indent, ncoords, startValue, endValue, spacing);
   * if (getResolution() != 0.0)
   * f.format(" resolution=%f", resolution);
   * f.format(" %s :", getDependenceType());
   * for (String s : dependsOn)
   */

  Element values = new Element("values");
  if (!axis.isRegular()) {
    Array array = axis.getCoordsAsArray();
    boolean isRealType = (array.getDataType() == DataType.DOUBLE) || (array.getDataType() == DataType.FLOAT);
    IndexIterator iter = array.getIndexIterator();

    StringBuilder buff = new StringBuilder();
    buff.append(isRealType ? iter.getDoubleNext() : iter.getIntNext());

    while (iter.hasNext()) {
      buff.append(" ");
      buff.append(isRealType ? iter.getDoubleNext() : iter.getIntNext());
    }

    values.setText(buff.toString());
  }

  values.setAttribute("spacing", axis.getSpacing().toString());
  values.setAttribute("npts", Long.toString(axis.getNcoords()));
  values.setAttribute("start", Double.toString(axis.getStartValue()));
  values.setAttribute("end", Double.toString(axis.getEndValue()));
  if (axis.getResolution() != 0.0)
    values.setAttribute("resolution", Double.toString(axis.getResolution()));

  varElem.addContent(values);
  return varElem;
}
 
Example 18
Source File: CatalogXmlWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private Element writeProperty(Property prop) {
  Element propElem = new Element("property", Catalog.defNS);
  propElem.setAttribute("name", prop.getName());
  propElem.setAttribute("value", prop.getValue());
  return propElem;
}
 
Example 19
Source File: GridDatasetInfo.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private Element writeGridSet(GridDataset.Gridset gridset) {
  Element csElem = new Element("gridSet");
  GridCoordSystem cs = gridset.getGeoCoordSystem();
  csElem.setAttribute("name", cs.getName());

  ProjectionRect rect = cs.getBoundingBox();
  Element projBBOX = new Element("projectionBox");
  Element minx = new Element("minx");
  minx.addContent(Double.valueOf(rect.getMinX()).toString());
  projBBOX.addContent(minx);
  Element maxx = new Element("maxx");
  maxx.addContent(Double.valueOf(rect.getMaxX()).toString());
  projBBOX.addContent(maxx);
  Element miny = new Element("miny");
  miny.addContent(Double.valueOf(rect.getMinY()).toString());
  projBBOX.addContent(miny);
  Element maxy = new Element("maxy");
  maxy.addContent(Double.valueOf(rect.getMaxY()).toString());
  projBBOX.addContent(maxy);

  csElem.addContent(projBBOX);

  for (CoordinateAxis axis : cs.getCoordinateAxes()) {
    Element axisElem = new Element("axisRef");
    axisElem.setAttribute("name", axis.getFullName());
    csElem.addContent(axisElem);
  }

  for (CoordinateTransform ct : cs.getCoordinateTransforms()) {
    Element elem = new Element("coordTransRef");
    elem.setAttribute("name", ct.getName());
    csElem.addContent(elem);
  }

  List<GridDatatype> grids = gridset.getGrids();
  Collections.sort(grids);
  for (GridDatatype grid : grids) {
    csElem.addContent(writeGrid(grid));
  }

  return csElem;
}
 
Example 20
Source File: StationObsDatasetInfo.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Create an XML document from this info
 */
public Document makeStationObsDatasetDocument() {
  Element rootElem = new Element("stationObsDataset");
  Document doc = new Document(rootElem);
  rootElem.setAttribute("location", sobs.getLocationURI());
  if (null != path)
    rootElem.setAttribute("path", path);

  /*
   * dimensions
   * List dims = getDimensions(sobs);
   * for (int j = 0; j < dims.size(); j++) {
   * Dimension dim = (Dimension) dims.get(j);
   * rootElem.addContent(ucar.nc2.ncml.NcMLWriter.writeDimension(dim, null));
   * }
   */

  /*
   * coordinate axes
   * List coordAxes = getCoordAxes(sobs);
   * for (int i = 0; i < coordAxes.size(); i++) {
   * CoordinateAxis axis = (CoordinateAxis) coordAxes.get(i);
   * rootElem.addContent(writeAxis(axis));
   * }
   */

  // grids
  List vars = sobs.getDataVariables();
  Collections.sort(vars);
  for (int i = 0; i < vars.size(); i++) {
    VariableSimpleIF v = (VariableSimpleIF) vars.get(i);
    rootElem.addContent(writeVariable(v));
  }

  /*
   * global attributes
   * Iterator atts = sobs.getGlobalAttributes().iterator();
   * while (atts.hasNext()) {
   * ucar.nc2.Attribute att = (ucar.nc2.Attribute) atts.next();
   * rootElem.addContent(ucar.nc2.ncml.NcMLWriter.writeAttribute(att, "attribute", null));
   * }
   */

  // add lat/lon bounding box
  LatLonRect bb = sobs.getBoundingBox();
  if (bb != null)
    rootElem.addContent(writeBoundingBox(bb));

  // add date range
  Date start = sobs.getStartDate();
  Date end = sobs.getEndDate();
  if ((start != null) && (end != null)) {
    DateFormatter format = new DateFormatter();
    Element dateRange = new Element("TimeSpan");
    dateRange.addContent(new Element("begin").addContent(format.toDateTimeStringISO(start)));
    dateRange.addContent(new Element("end").addContent(format.toDateTimeStringISO(end)));
    rootElem.addContent(dateRange);
  }

  // add accept list
  Element elem = new Element("AcceptList");
  elem.addContent(new Element("accept").addContent("raw"));
  elem.addContent(new Element("accept").addContent("xml"));
  elem.addContent(new Element("accept").addContent("csv"));
  elem.addContent(new Element("accept").addContent("netcdf"));
  elem.addContent(new Element("accept").addContent("netcdfStream"));
  rootElem.addContent(elem);

  return doc;
}