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

The following examples show how to use org.jdom2.Element#addContent() . These examples are extracted from open source projects. 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 Project: rome   File: Atom10Generator.java    License: Apache License 2.0 6 votes vote down vote up
protected void addEntry(final Entry entry, final Element parent) throws FeedException {

        final Element eEntry = new Element("entry", getFeedNamespace());

        final String xmlBase = entry.getXmlBase();
        if (xmlBase != null) {
            eEntry.setAttribute("base", xmlBase, Namespace.XML_NAMESPACE);
        }

        populateEntry(entry, eEntry);
        generateForeignMarkup(eEntry, entry.getForeignMarkup());
        checkEntryConstraints(eEntry);
        generateItemModules(entry.getModules(), eEntry);
        parent.addContent(eEntry);

    }
 
Example 2
@RequestMapping(value = {"**/dataset.xml", "**/pointDataset.xml"})
// Same response for both Grid and GridAsPoint.
public ModelAndView getDatasetDescriptionXml(HttpServletRequest req, HttpServletResponse res) throws IOException {
  String datasetPath = getDatasetPath(req);

  try (CoverageCollection gcd = TdsRequestedDataset.getCoverageCollection(req, res, datasetPath)) {
    if (gcd == null)
      return null; // restricted dataset
    String datasetUrlPath = buildDatasetUrl(datasetPath);

    CoverageDatasetCapabilities writer = new CoverageDatasetCapabilities(gcd, "path");
    Document doc = writer.makeDatasetDescription();
    Element root = doc.getRootElement();
    root.setAttribute("location", datasetUrlPath);
    root.addContent(makeAcceptXML(SupportedOperation.GRID_REQUEST));

    return new ModelAndView("threddsXmlView", "Document", doc);
  }
}
 
Example 3
private Element createPreamble(String rootName, Namespace defNS) {

        // create a new doc with a root element called 'schema'
        Element root = new Element("schema", defNS);
        root.setAttribute("elementFormDefault", "qualified");
        new Document(root);     // attaches a default doc as parent of root element

        // attach an element set to the supplied root name
        Element taskElem = new Element("element", defNS);
        taskElem.setAttribute("name", rootName);
        root.addContent(taskElem);

        Element complex = new Element("complexType", defNS);
        Element sequence = new Element("sequence", defNS);
        taskElem.addContent(complex);
        complex.addContent(sequence);

        return sequence;
    }
 
Example 4
private Document asInputDocument(final List<ToDoItem> items) {

        final Element html = new Element("html");
        final Document document = new Document(html);

        final Element body = new Element("body");
        html.addContent(body);

        addPara(body, "ExportedOn", "date", clockService.nowAsLocalDateTime().toString("dd-MMM-yyyy"));

        final Element table = addTable(body, "ToDoItems");
        for(final ToDoItem item: items) {
            addTableRow(table, new String[]{item.getDescription(), item.getCost() != null? item.getCost().toString(): "", item.getDueBy() != null ? item.getDueBy().toString("dd-MMM"): ""});
        }
        return document;
    }
 
Example 5
Source Project: rome   File: Atom10Generator.java    License: Apache License 2.0 6 votes vote down vote up
protected Element generateTagLineElement(final Content tagline) {

        final Element taglineElement = new Element("subtitle", getFeedNamespace());

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

        final String value = tagline.getValue();
        if (value != null) {
            taglineElement.addContent(value);
        }

        return taglineElement;

    }
 
Example 6
/**
 * This method adds all parents and their derivates
 * iterative to the given element.
 * 
 * @param toElement the element where the parents and derivates will be added
 * @param objId the source object id
 */
private void addParentsToElement(Element toElement, MCRObjectID objId) {
    MCRObjectID pId = objId;
    while ((pId = getParentId(pId)) != null) {
        Element parentElement = getMyCoReObjectElement(pId);
        if (parentElement != null) {
            toElement.addContent(parentElement);
        }
    }
}
 
Example 7
Source Project: rome   File: MediaModuleGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generation of responses tag.
 * 
 * @param m source
 * @param e element to attach new element to
 */
private void generateResponses(final Metadata m, final Element e) {
    if (m.getResponses() == null || m.getResponses().length == 0) {
        return;
    }
    final Element responsesElements = new Element("responses", NS);
    for (final String response : m.getResponses()) {
        addNotNullElement(responsesElements, "response", response);
    }
    e.addContent(responsesElements);
}
 
Example 8
public Map<String, List<Element>> removeReservations(Document rup, String statusToBe)
           throws JDOMException {
	Map<String, List<Element>> res = new HashMap<String, List<Element>>();
	String where = statusToBe == null ? "" : "[" + XML_STATUSTOBE + "='" + statusToBe + "']";
	String xpath = XMLUtils.getXPATH_ActivityElement(null, XML_RESERVATION + where, null);
	List<Element> reservations = XMLUtils.getXMLObjects(rup, xpath);
	for (Element reservation : reservations) {
		Element activity = reservation.getParentElement();
		activity.removeContent(reservation);

		List<Element> l = res.get(activity.getChildText(XML_ACTIVITYNAME));
		if (l == null)	l = new ArrayList<Element>();

		Element reservationId = reservation.getChild(XML_RESERVATIONID);
		if (reservationId == null) {
			reservation.addContent(new Element(XML_RESERVATIONID));
		}
		else {
			reservationId.setText("");
		}

		l.add(reservation);
		res.put(activity.getChildText(XML_ACTIVITYNAME), l);
	}

	return res;
}
 
Example 9
private void addTime(Element parent, String type, int hh, int mm, int ss) {
    Element xTime = new Element(type);
    parent.addContent(xTime);

    GregorianCalendar date = new GregorianCalendar(TimeZone.getDefault(), Locale.ROOT);
    date.set(2002, Calendar.FEBRUARY, 1, hh, mm, ss);
    String time = TIME_FORMATTER.format(date.getTime());

    xTime.setAttribute("format", TIME_FORMAT);
    xTime.addContent(time);
}
 
Example 10
private Element writeCoordTransform(CoordinateTransform ct) {
  Element ctElem = new Element("coordTransform");
  ctElem.setAttribute("name", ct.getName());
  ctElem.setAttribute("transformType", ct.getTransformType().toString());
  List params = ct.getParameters();
  for (int i = 0; i < params.size(); i++) {
    Parameter param = (Parameter) params.get(i);
    Element pElem = new Element("parameter");
    pElem.setAttribute("name", param.getName());
    pElem.setAttribute("value", param.getStringValue());
    ctElem.addContent(pElem);
  }
  return ctElem;
}
 
Example 11
Source Project: rome   File: RSS090Generator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Populates the given channel with parsed data from the ROME element that holds the channel
 * data.
 *
 * @param channel the channel into which parsed data will be added.
 * @param eChannel the XML element that holds the data for the channel.
 */
protected void populateChannel(final Channel channel, final Element eChannel) {
    final String title = channel.getTitle();
    if (title != null) {
        eChannel.addContent(generateSimpleElement("title", title));
    }
    final String link = channel.getLink();
    if (link != null) {
        eChannel.addContent(generateSimpleElement("link", link));
    }
    final String description = channel.getDescription();
    if (description != null) {
        eChannel.addContent(generateSimpleElement("description", description));
    }
}
 
Example 12
Source Project: rome   File: GoogleBaseGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void generate(final Module module, final Element element) {
    final GoogleBaseImpl mod = (GoogleBaseImpl) module;
    final HashMap<Object, Object> props2tags = new HashMap<Object, Object>(GoogleBaseParser.PROPS2TAGS);
    final List<PropertyDescriptor> pds = GoogleBaseParser.pds;

    for (final PropertyDescriptor pd : pds) {
        final String tagName = (String) props2tags.get(pd.getName());

        if (tagName == null) {
            continue;
        }

        Object[] values = null;

        try {
            if (pd.getPropertyType().isArray()) {
                values = (Object[]) pd.getReadMethod().invoke(mod, (Object[]) null);
            } else {
                values = new Object[] {pd.getReadMethod().invoke(mod, (Object[]) null)};
            }

            for (int j = 0; values != null && j < values.length; j++) {
                if (values[j] != null) {
                    element.addContent(generateTag(values[j], tagName));
                }
            }
        } catch (final Exception e) {
            LOG.error("Error", e);
        }
    }
}
 
Example 13
Source Project: rome   File: OPML10Generator.java    License: Apache License 2.0 5 votes vote down vote up
protected boolean addNotNullSimpleElement(final Element target, final String name, final Object value) {
    if (target == null || name == null || value == null) {
        return false;
    }

    final Element e = new Element(name);
    e.addContent(value.toString());
    target.addContent(e);

    return true;
}
 
Example 14
private static Element addListItem(final Element ul, final String... paras) {
    final Element li = new Element("li");
    ul.addContent(li);
    for (final String para : paras) {
        addPara(li, para);
    }
    return ul;
}
 
Example 15
private Element writeService(Service service) {
  Element serviceElem = new Element("service", Catalog.defNS);
  serviceElem.setAttribute("name", service.getName());
  String svctype = service.getServiceTypeName();
  serviceElem.setAttribute("serviceType", svctype);
  String base = service.getBase();
  if ("compound".equalsIgnoreCase(svctype) && base == null)
    base = ""; // Add some error tolerance
  serviceElem.setAttribute("base", base);
  if ((service.getSuffix() != null) && (!service.getSuffix().isEmpty()))
    serviceElem.setAttribute("suffix", service.getSuffix());

  // properties
  for (Property p : service.getProperties()) {
    serviceElem.addContent(writeProperty(p));
  }

  // services
  for (Service nested : service.getNestedServices()) {
    serviceElem.addContent(writeService(nested));
  }

  /*
   * dataset roots
   * if (raw) {
   * for (Property p : service.getDatasetRoots()) {
   * serviceElem.addContent(writeDatasetRoot(p));
   * }
   * }
   */

  return serviceElem;
}
 
Example 16
Document generateDescribeCoverageDoc() {
  // CoverageDescription (wcs) [1]
  Element coverageDescriptionsElem = new Element("CoverageDescription", wcsNS);
  coverageDescriptionsElem.addNamespaceDeclaration(gmlNS);
  coverageDescriptionsElem.addNamespaceDeclaration(xlinkNS);
  coverageDescriptionsElem.setAttribute("version", this.getVersion());
  // ToDo Consider dealing with "updateSequence"
  // coverageDescriptionsElem.setAttribute( "updateSequence", this.getCurrentUpdateSequence() );

  for (String curCoverageId : this.coverages)
    coverageDescriptionsElem.addContent(genCoverageOfferingElem(curCoverageId));

  return new Document(coverageDescriptionsElem);
}
 
Example 17
Source Project: java-client-api   File: JDOMHandleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReadWrite() throws SAXException, IOException {
  // create an identifier for the database document
  String docId = "/example/jdom-test.xml";

  // create a manager for XML database documents
  XMLDocumentManager docMgr = Common.client.newXMLDocumentManager();

  // create a JDOM document
  Document writeDocument = new Document();
  Element root = new Element("root");
  root.setAttribute("foo", "bar");
  root.addContent(new Element("child"));
  root.addContent("mixed");
  writeDocument.setRootElement(root);

  // create a handle for the JDOM document
  JDOMHandle writeHandle = new JDOMHandle(writeDocument);

  // write the JDOM document to the database
  docMgr.write(docId, writeHandle);

  // create a handle to receive the database content as a JDOM document
  JDOMHandle readHandle = new JDOMHandle();

  // read the document content from the database as a JDOM document
  docMgr.read(docId, readHandle);

  // access the document content
  Document readDocument = readHandle.get();
  assertNotNull("Wrote null JDOM document", readDocument);
  assertXMLEqual("JDOM document not equal",
    writeHandle.toString(), readHandle.toString());

  // delete the document
  docMgr.delete(docId);
}
 
Example 18
private void writeDatasetInfo(Dataset ds, Element dsElem, boolean doNestedDatasets, boolean showNcML) {
  String name = ds.getName();
  if (name == null)
    name = ""; // eg catrefs
  dsElem.setAttribute("name", name);

  // other attributes, note the others get made into an element
  if (ds.getCollectionType() != null)
    dsElem.setAttribute("collectionType", ds.getCollectionType());
  if (ds.isHarvest())
    dsElem.setAttribute("harvest", "true");
  if (ds.getID() != null)
    dsElem.setAttribute("ID", ds.getID());
  if (ds.getUrlPath() != null)
    dsElem.setAttribute("urlPath", ds.getUrlPath());
  if (ds.getRestrictAccess() != null)
    dsElem.setAttribute("restrictAccess", ds.getRestrictAccess());

  /*
   * services (local only)
   * for (Service service : ds.getServices()) {
   * dsElem.addContent(writeService(service));
   * }
   */

  // thredds metadata
  writeThreddsMetadata(dsElem, ds);
  writeInheritedMetadata(dsElem, ds);

  // access (local only)
  List<Access> access = (List<Access>) ds.getLocalFieldAsList(Dataset.Access);
  for (Access a : access) {
    dsElem.addContent(writeAccess(a));
  }

  /*
   * if (showNcML && ds.getNcmlElement() != null) {
   * org.jdom2.Element ncml = ds.getNcmlElement().clone();
   * ncml.detach();
   * dsElem.addContent(ncml);
   * }
   */

  if (!doNestedDatasets)
    return;

  // nested datasets
  for (Dataset nested : ds.getDatasetsLocal()) {
    // if (nested instanceof DatasetScan)
    // dsElem.addContent(writeDatasetScan((DatasetScan) nested));
    if (nested instanceof CatalogRef)
      dsElem.addContent(writeCatalogRef((CatalogRef) nested));
    else
      dsElem.addContent(writeDataset(nested));
  }
}
 
Example 19
public Element toXML() {
    Element not = new Element("boolean");
    not.setAttribute("operator", "not");
    not.addContent(child.toXML());
    return not;
}
 
Example 20
/**
 * The method add a default ACL-block.
 *
 * @param service
 * @throws IOException
 * @throws JDOMException
 */
private void setDefaultObjectACLs(Element service) throws JDOMException, IOException {
    if (!MCRConfiguration2.getBoolean("MCR.Access.AddObjectDefaultRule").orElse(true)) {
        LOGGER.info("Adding object default acl rule is disabled.");
        return;
    }
    String resourcetype = "/editor_default_acls_" + id.getTypeId() + ".xml";
    String resourcebase = "/editor_default_acls_" + id.getBase() + ".xml";
    // Read stylesheet and add user
    InputStream aclxml = MCREditorOutValidator.class.getResourceAsStream(resourcebase);
    if (aclxml == null) {
        aclxml = MCREditorOutValidator.class.getResourceAsStream(resourcetype);
        if (aclxml == null) {
            LOGGER.warn("Can't find default object ACL file {} or {}", resourcebase.substring(1),
                resourcetype.substring(1));
            String resource = "/editor_default_acls.xml"; // fallback
            aclxml = MCREditorOutValidator.class.getResourceAsStream(resource);
            if (aclxml == null) {
                return;
            }
        }
    }
    Document xml = SAX_BUILDER.build(aclxml);
    Element acls = xml.getRootElement().getChild("servacls");
    if (acls == null) {
        return;
    }
    for (Element acl : acls.getChildren()) {
        Element condition = acl.getChild("condition");
        if (condition == null) {
            continue;
        }
        Element rootbool = condition.getChild("boolean");
        if (rootbool == null) {
            continue;
        }
        for (Element orbool : rootbool.getChildren("boolean")) {
            for (Element firstcond : orbool.getChildren("condition")) {
                if (firstcond == null) {
                    continue;
                }
                String value = firstcond.getAttributeValue("value");
                if (value == null) {
                    continue;
                }
                if (value.equals("$CurrentUser")) {
                    String thisuser = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID();
                    firstcond.setAttribute("value", thisuser);
                    continue;
                }
                if (value.equals("$CurrentGroup")) {
                    throw new MCRException(
                        "The parameter $CurrentGroup in default ACLs is not supported as of MyCoRe 2014.06"
                            + " because it is not supported in Servlet API 3.0");
                }
                int i = value.indexOf("$CurrentIP");
                if (i != -1) {
                    String thisip = MCRSessionMgr.getCurrentSession().getCurrentIP();
                    firstcond.setAttribute("value",
                        value.substring(0, i) + thisip + value.substring(i + 10));
                }
            }
        }
    }
    service.addContent(acls.detach());
}