Java Examples for org.jdom2.Content
The following java examples will help you to understand the usage of org.jdom2.Content. These source code samples are taken from different open source projects.
Example 1
| Project: cms-ce-master File: DataEntryXmlCreator.java View source code |
private void addHtmlAreaDataEntry(final Element dataEntrySetEl, final HtmlAreaDataEntry entry) {
final String wrapElementName = "temp-wraped-element-if-you-can-see-me-something-went-wrong";
final Element entryEl = ContentDataXPathCreator.ensurePath(dataEntrySetEl, stripContentdataWhenNotBlockGroup(entry.getConfig()));
if (!entry.isEmpty()) {
final String xmlStr = ensureXmlProlog(wrapElement(entry.getValue(), wrapElementName));
Document document;
try {
final XMLDocument xml = XMLDocumentFactory.create(xmlStr);
document = xml.getAsJDOMDocument();
} catch (XMLException e) {
throw new RuntimeException("Failed to parse xml when adding entry: " + entry.getName(), e);
}
final Element rootEl = document.getRootElement();
if (rootEl.getName().equals(wrapElementName)) {
@SuppressWarnings({ "unchecked" }) final List<Content> children = rootEl.cloneContent();
entryEl.addContent(children);
} else {
entryEl.addContent((Element) rootEl.clone());
}
}
}Example 2
| Project: codehaus-mojo-master File: MavenJDOMWriter.java View source code |
//-- void updateDistributionManagement(DistributionManagement, String, Counter, Element)
/**
* Method updateElement
*
* @param counter
* @param shouldExist
* @param name
* @param parent
*/
protected Element updateElement(Counter counter, Element parent, String name, boolean shouldExist) {
Element element = parent.getChild(name, parent.getNamespace());
if (element != null && shouldExist) {
counter.increaseCount();
}
if (element == null && shouldExist) {
element = factory.element(name, parent.getNamespace());
insertAtPreferredLocation(parent, element, counter);
counter.increaseCount();
}
if (!shouldExist && element != null) {
int index = parent.indexOf(element);
if (index > 0) {
Content previous = parent.getContent(index - 1);
if (previous instanceof Text) {
Text txt = (Text) previous;
if (txt.getTextTrim().length() == 0) {
parent.removeContent(txt);
}
}
}
parent.removeContent(element);
}
return element;
}Example 3
| Project: consulo-master File: BeanBinding.java View source code |
public void deserializeInto(@NotNull Object result, @NotNull Element element, @Nullable Set<String> accessorNameTracker) {
nextAttribute: for (org.jdom.Attribute attribute : element.getAttributes()) {
if (StringUtil.isEmpty(attribute.getNamespaceURI())) {
for (Binding binding : myBindings) {
if (binding instanceof AttributeBinding && ((AttributeBinding) binding).myName.equals(attribute.getName())) {
if (accessorNameTracker != null) {
accessorNameTracker.add(binding.getAccessor().getName());
}
((AttributeBinding) binding).set(result, attribute.getValue());
continue nextAttribute;
}
}
}
}
MultiMap<Binding, Element> data = null;
nextNode: for (Content content : element.getContent()) {
if (content instanceof Comment) {
continue;
}
for (Binding binding : myBindings) {
if (content instanceof org.jdom.Text) {
if (binding instanceof TextBinding) {
((TextBinding) binding).set(result, content.getValue());
}
continue;
}
Element child = (Element) content;
if (binding.isBoundTo(child)) {
if (binding instanceof MultiNodeBinding && ((MultiNodeBinding) binding).isMulti()) {
if (data == null) {
data = MultiMap.createLinked();
}
data.putValue(binding, child);
} else {
if (accessorNameTracker != null) {
accessorNameTracker.add(binding.getAccessor().getName());
}
binding.deserialize(result, child);
}
continue nextNode;
}
}
}
if (data != null) {
for (Binding binding : data.keySet()) {
if (accessorNameTracker != null) {
accessorNameTracker.add(binding.getAccessor().getName());
}
((MultiNodeBinding) binding).deserializeList(result, (List<Element>) data.get(binding));
}
}
}Example 4
| Project: intellij-community-master File: StudySerializationUtils.java View source code |
public static Element convertToFifthVersion(Element state) throws StudyUnrecognizedFormatException {
Element taskManagerElement = state.getChild(MAIN_ELEMENT);
Element courseElement = getChildWithName(taskManagerElement, COURSE).getChild(COURSE_TITLED);
final int courseId = getAsInt(courseElement, ID);
if (courseElement != null && courseId > 0) {
courseElement.setName(REMOTE_COURSE);
}
final Element adaptive = getChildWithName(courseElement, ADAPTIVE);
for (Element lesson : getChildList(courseElement, LESSONS)) {
for (Element task : getChildList(lesson, TASK_LIST)) {
//could be broken by 3->4 migration
final Element lastSubtaskIndex = getChildWithName(task, LAST_SUBTASK_INDEX, true);
final Element adaptiveParams = getChildWithName(task, ADAPTIVE_TASK_PARAMETERS, true);
Element theoryTask = getChildWithName(task, THEORY_TAG, true);
if (theoryTask == null && adaptiveParams != null) {
theoryTask = getChildWithName(adaptiveParams, THEORY_TAG, true);
}
final boolean hasAdaptiveParams = adaptiveParams != null && !adaptiveParams.getChildren().isEmpty();
if (lastSubtaskIndex != null && Integer.valueOf(lastSubtaskIndex.getAttributeValue(VALUE)) != 0) {
task.setName(TASK_WITH_SUBTASKS);
} else if (theoryTask != null && Boolean.valueOf(theoryTask.getAttributeValue(VALUE))) {
task.setName(THEORY_TASK);
} else if (hasAdaptiveParams) {
task.setName(CHOICE_TASK);
final Element adaptiveParameters = adaptiveParams.getChildren().get(0);
for (Element element : adaptiveParameters.getChildren()) {
final Attribute name = element.getAttribute(NAME);
if (name != null && !THEORY_TAG.equals(name.getValue())) {
final Content elementCopy = element.clone();
task.addContent(elementCopy);
}
}
} else if (Boolean.valueOf(adaptive.getAttributeValue(VALUE))) {
task.setName(CODE_TASK);
} else {
task.setName(PYCHARM_TASK);
}
task.removeContent(adaptiveParams);
task.removeContent(theoryTask);
}
}
return state;
}Example 5
| Project: jdom-master File: TestSAXBuilder.java View source code |
/**
* Test that when setExpandEntities is true, enties are
* always expanded and when false, entities declarations
* are added to the DocType
*/
@Test
public void test_TCM__void_setExpandEntities_boolean() throws JDOMException, IOException {
//test entity exansion on internal entity
URL src = FidoFetch.getFido().getURL("/SAXBuilderTestEntity.xml");
SAXBuilder builder = new SAXBuilder();
builder.setExpandEntities(true);
assertTrue(builder.getExpandEntities());
Document doc = builder.build(src);
assertTrue("didn't get entity text", doc.getRootElement().getText().indexOf("simple entity") == 0);
assertTrue("didn't get entity text", doc.getRootElement().getText().indexOf("another simple entity") > 1);
//test that entity declaration appears in doctype
//and EntityRef is created in content with internal entity
builder.setExpandEntities(false);
assertFalse(builder.getExpandEntities());
doc = builder.build(src);
assertTrue("got entity text", !(doc.getRootElement().getText().indexOf("simple entity") > 1));
assertTrue("got entity text", !(doc.getRootElement().getText().indexOf("another simple entity") > 1));
List<Content> content = doc.getRootElement().getContent();
assertTrue("didn't get EntityRef for unexpanded entities", content.get(0) instanceof EntityRef);
assertTrue("didn't get EntityRef for unexpanded entities", content.get(2) instanceof EntityRef);
//test entity expansion on external entity
URL src2 = FidoFetch.getFido().getURL("/SAXBuilderTestEntity2.xml");
builder.setExpandEntities(true);
assertTrue(builder.getExpandEntities());
doc = builder.build(src2);
assertTrue("didn't get entity text", doc.getRootElement().getText().indexOf("simple entity") == 0);
assertTrue("didn't get entity text", doc.getRootElement().getText().indexOf("another simple entity") > 1);
//test that entity declaration appears in doctype
//and EntityRef is created in content with external entity
builder.setExpandEntities(false);
assertFalse(builder.getExpandEntities());
doc = builder.build(src2);
assertTrue("got entity text", !(doc.getRootElement().getText().indexOf("simple entity") > 1));
assertTrue("got entity text", !(doc.getRootElement().getText().indexOf("another simple entity") > 1));
content = doc.getRootElement().getContent();
assertTrue("didn't get EntityRef for unexpanded entities", content.get(0) instanceof EntityRef);
assertTrue("didn't get EntityRef for unexpanded entities", content.get(2) instanceof EntityRef);
}Example 6
| Project: meaningfulweb-master File: ArticleProcessor.java View source code |
private void cleanStructureNodes(int level, Content node, Set<Content> remove) { // don't go on forever, spider traps can kill JVM through stack overflow if (level == maxRecurseDepth) { return; } if (node instanceof Element) { Element elem = (Element) node; String name = StringUtils.lowerCase(elem.getName()); List<String> attrVals = getClassAndIdVals(elem); String[] removeLabels = { "header", "menu", "footer", "masthead", "comment", "quotes", "resources", "tools", "headline", "caption", "share", "font", "opinion", "timestamp", "posted", "metadata", "toolbar", "disqus", "sign_up", "nav", "like", "advertisement", "sidebar", "print", "email", "more", "links", "enlarge", "tags", "breadcrumb", "facebook", "stumble", "twitter", "callout", "widget", "related", "announcement", "neighbor", "sponsor", "support", "flash" }; boolean shouldRemove = false; if (!StringUtils.equals("body", name)) { for (String attrVal : attrVals) { for (int i = 0; i < removeLabels.length; i++) { if (StringUtils.contains(attrVal, removeLabels[i])) { shouldRemove = true; remove.add(node); break; } } } } if (!shouldRemove) { Attribute styleAttr = elem.getAttribute("style"); if (styleAttr != null) { String styleVal = StringUtils.lowerCase(styleAttr.getValue()); if (StringUtils.isNotBlank(styleVal) & styleVal.matches(".*display:\\s*none.*")) { remove.add(node); } } } if (!shouldRemove) { List<Content> children = elem.getContent(); if (children != null && children.size() > 0) { for (Content child : children) { cleanStructureNodes(++level, child, remove); } } } } else if (node instanceof Comment) { remove.add(node); } }
Example 7
| Project: ps-framework-master File: XMLResponseGenerator.java View source code |
public static Element generate(Response response, List<RequestedOutput> requestedOutputs) throws ResponseGenerateException {
// get identifier, process, outputs
String processIdentifier = response.getProcessIdentifier();
AbstractProcess process = ProcessRepository.getInstance().getProcess(processIdentifier);
ProcessOutputs outputs = response.getOutputs();
// generate response
Element responseElement = new Element(processIdentifier + "Response", Namespaces.PS);
// add outputs
for (String outputIdentifier : process.getOutputIdentifiers()) {
// get output from process
Output output = outputs.get(outputIdentifier);
// check if output was requested and as reference
boolean requested = false;
boolean reference = false;
if (requestedOutputs == null) {
requested = true;
} else {
for (RequestedOutput reqOutput : requestedOutputs) {
if (reqOutput.getName().equals(output.getIdentifier())) {
requested = true;
reference = reqOutput.isReference();
}
}
}
// add output
if (requested) {
// get objects related to output
List<Object> objects;
if (output.isSingleOutput()) {
objects = new ArrayList<Object>();
objects.add(output.getAsSingleOutput().getObject());
} else {
objects = output.getAsMultipleOutput().getObjects();
}
// encode each object
DataDescription dataDescription = process.getOutputDataDescription(outputIdentifier);
for (Object o : objects) {
try {
// base element
Element outputElement = new Element(outputIdentifier, Namespaces.PS);
responseElement.addContent(outputElement);
// generate
Content dataContent = generateData(o, dataDescription.getType(), reference);
outputElement.addContent(dataContent);
} catch (EncodeException e) {
String message = "Couldn't encode data for " + output.getIdentifier() + ".";
logger.error(message);
throw new ResponseGenerateException(message, e);
}
}
}
}
return responseElement;
}Example 8
| Project: cxf-build-utils-master File: CXFAllTransformer.java View source code |
public void modifyOutputStream(JarOutputStream jos) throws IOException {
List<String> imps = new ArrayList<String>(extensions.keySet());
for (Map.Entry<String, ByteArrayOutputStream> ent : extensions.entrySet()) {
jos.putNextEntry(new JarEntry(ent.getKey()));
ent.getValue().writeTo(jos);
try {
Document r = new SAXBuilder().build(new ByteArrayInputStream(ent.getValue().toByteArray()));
Element root = r.getRootElement();
for (Iterator itr = root.getChildren().iterator(); itr.hasNext(); ) {
Content n = (Content) itr.next();
if (n instanceof Element) {
Element e = (Element) n;
if ("import".equals(e.getName()) && "http://www.springframework.org/schema/beans".equals(e.getNamespaceURI())) {
//remove stuff that is imported from other extensions to
//keep them from being loaded twice. (it's not an issue
//to load them twice, there just is a performance
//penalty in doing so
String loc = e.getAttributeValue("resource");
if (loc.startsWith("classpath:META-INF/cxf/cxf")) {
loc = loc.substring(10);
imps.remove(loc);
}
}
}
}
} catch (JDOMException e) {
throw new RuntimeException(e);
}
}
if (imps.size() > 0) {
jos.putNextEntry(new JarEntry("META-INF/cxf/cxf-all.xml"));
Writer writer = new OutputStreamWriter(jos, "UTF-8");
writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writer.append("<beans xmlns=\"http://www.springframework.org/schema/beans\"\n");
writer.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
writer.append(" xsi:schemaLocation=\"");
writer.append("http://www.springframework.org/schema/beans ");
writer.append("http://www.springframework.org/schema/beans/spring-beans.xsd\">\n");
writer.append(" <import resource=\"classpath:META-INF/cxf/cxf.xml\"/>\n");
for (String res : imps) {
writer.append(" <import resource=\"classpath:");
writer.append(res);
writer.append("\"/>\n");
}
writer.append("</beans>");
writer.flush();
}
}Example 9
| Project: isis-module-docx-master File: DocxService.java View source code |
private static void merge(final Element htmlBody, final Body docXBody, final MatchingPolicy matchingPolicy) throws MergeException {
final List<String> matchedInputIds = Lists.newArrayList();
final List<String> unmatchedInputIds = Lists.newArrayList();
final List<Content> htmlBodyContents = htmlBody.getContent();
for (final Content input : htmlBodyContents) {
if (!(input instanceof Element)) {
continue;
}
mergeInto((Element) input, docXBody, matchedInputIds, unmatchedInputIds);
}
final List<String> unmatchedPlaceHolders = unmatchedPlaceholders(docXBody, matchedInputIds);
matchingPolicy.unmatchedInputs(unmatchedInputIds);
matchingPolicy.unmatchedPlaceholders(unmatchedPlaceHolders);
}Example 10
| Project: kbot-master File: MainSettings.java View source code |
private static Element getSettingElement(Document document, String name) {
Element root = document.getRootElement();
for (Content node : (List<Content>) root.getChildren("setting")) {
if (node instanceof Element) {
Element element = (Element) node;
if (name.equals(element.getAttributeValue("name"))) {
return element;
}
}
}
return null;
}Example 11
| Project: MvnRunner-master File: MvnJettyConfigurationProducer.java View source code |
@Override
protected String getPortInfo() {
String portInfo = getProperty("jetty.port");
if (!StringUtil.isEmptyOrSpaces(portInfo))
return portInfo;
try {
final String portPath = "connectors/connector/port";
List list = XPath.selectNodes(plugin.getConfigurationElement(), portPath);
for (Object e : list) {
Content content = (Content) e;
if (!StringUtil.isEmptyOrSpaces(content.getValue())) {
return content.getValue();
}
}
} catch (JDOMException ignore) {
}
return super.getPortInfo();
}Example 12
| Project: Wolfram-Language-Parser-master File: MapBinding.java View source code |
public Object serialize(Object o, Object context, SerializationFilter filter) {
Map map = (Map) o;
Element m;
if (myMapAnnotation == null || myMapAnnotation.surroundWithTag()) {
m = new Element(Constants.MAP);
} else {
m = (Element) context;
}
final Set keySet = map.keySet();
final Object[] keys = ArrayUtil.toObjectArray(keySet);
if (myMapAnnotation == null || myMapAnnotation.sortBeforeSave()) {
Arrays.sort(keys, KEY_COMPARATOR);
}
for (Object k : keys) {
Object v = map.get(k);
Element entry = new Element(getEntryAttributeName());
m.addContent(entry);
Object kNode = myKeyBinding.serialize(k, entry, filter);
if (kNode instanceof Text) {
Text text = (Text) kNode;
entry.setAttribute(getKeyAttributeValue(), text.getText());
} else {
if (myMapAnnotation != null && !myMapAnnotation.surroundKeyWithTag()) {
entry.addContent((Content) kNode);
} else {
Element key = new Element(getKeyAttributeValue());
entry.addContent(key);
key.addContent((Content) kNode);
}
}
Object vNode = myValueBinding.serialize(v, entry, filter);
if (vNode instanceof Text) {
Text text = (Text) vNode;
entry.setAttribute(getValueAttributeName(), text.getText());
} else {
if (myMapAnnotation != null && !myMapAnnotation.surroundValueWithTag()) {
entry.addContent((Element) vNode);
} else {
Element value = new Element(getValueAttributeName());
entry.addContent(value);
value.addContent((Content) vNode);
}
}
}
return m;
}Example 13
| Project: xweb-master File: XmlFormatter2.java View source code |
private Element toElement(final Object object) {
if (object instanceof Map) {
final Map<?, ?> map = (Map) object;
final String name = (object instanceof AnnotedMap) ? ((AnnotedMap) object).name : "Map";
final Element element = new Element(name);
for (Map.Entry e : map.entrySet()) {
if (e.getValue() != null) {
final Element sub = toElement(e.getValue());
sub.setAttribute("key", e.getKey().toString());
element.addContent(sub);
}
}
return element;
} else if (object instanceof Collection) {
final Collection<?> collection = (Collection) object;
final Element element = new Element("Collection");
for (Object o : collection) {
if (o != null) {
final Content c = toElement(o);
element.addContent(c);
}
/*if(c instanceof Text) {
final Element sub = new Element(o.getClass().getSimpleName());
sub.addContent(c);
element.addContent(sub);
} else {
final List<?> childs = ((Element)c).getChildren();
for(int i=childs.size()-1; i>=0; i--) {
final Content child = (Content) childs.get(i);
child.detach();
element.addContent(child);
}
}*/
}
return element;
} else {
final Element element = new Element(getType(object));
element.addContent(object.toString());
return element;
}
}Example 14
| Project: android-maven-plugin-master File: XpathAppendingTransformer.java View source code |
@SuppressWarnings("unchecked")
private void appendElement(Element source, Element target) {
for (Iterator<Attribute> itr = source.getAttributes().iterator(); itr.hasNext(); ) {
Attribute a = itr.next();
itr.remove();
Attribute mergedAtt = target.getAttribute(a.getName(), a.getNamespace());
if (mergedAtt == null) {
target.setAttribute(a);
}
}
for (Iterator<Element> itr = source.getChildren().iterator(); itr.hasNext(); ) {
Content n = itr.next();
itr.remove();
target.addContent(n);
}
}Example 15
| Project: jgitflow-master File: ProjectReleaseVersionChange.java View source code |
@Override
public boolean applyChange(MavenProject project, Element root, String eol) throws ProjectRewriteException {
boolean modified = false;
Namespace ns = getNamespaceOrNull(root);
Element versionElement = root.getChild("version", ns);
String projectId = ArtifactUtils.versionlessKey(project.getGroupId(), project.getArtifactId());
String releaseVersion = releaseVersions.get(projectId);
if (Strings.isNullOrEmpty(releaseVersion)) {
if (consistentProjectVersions && releaseVersions.size() > 0) {
// Use any release version, as the project's versions are consistent/global
releaseVersion = releaseVersions.values().iterator().next();
} else {
throw new ProjectRewriteException("Release version for " + project.getName() + " was not found");
}
}
if (null == versionElement) {
String parentVersion = null;
if (project.hasParent()) {
MavenProject parent = project.getParent();
String parentId = ArtifactUtils.versionlessKey(parent.getGroupId(), parent.getArtifactId());
parentVersion = releaseVersions.get(parentId);
if (Strings.isNullOrEmpty(parentVersion) && consistentProjectVersions && releaseVersions.size() > 0) {
// Use any version for the parent, as the project's versions are consistent/global
parentVersion = releaseVersions.values().iterator().next();
}
}
if (!releaseVersion.equals(parentVersion)) {
Element artifactId = root.getChild("artifactId", ns);
versionElement = new Element("version", ns);
Text indent = new Text("");
workLog.add("setting version to '" + releaseVersion + "'");
versionElement.setText(releaseVersion);
int index = root.indexOf(artifactId);
List<Content> cList = root.getContent();
//get the previous sibling if it exists
if (index > 0 && index < cList.size()) {
Content prevSibling = cList.get(index - 1);
if (Text.class.isInstance(prevSibling)) {
String siblingText = ((Text) prevSibling).getText();
if (siblingText.matches("^\\s*$")) {
indent = new Text("");
indent.setText(eol + NamingUtil.afterLastNewline(siblingText));
}
}
}
root.addContent(index + 1, indent);
root.addContent(index + 2, versionElement);
modified = true;
}
} else {
workLog.add("updating version '" + versionElement.getTextTrim() + " to '" + releaseVersion + "'");
versionElement.setText(releaseVersion);
modified = true;
}
return modified;
}Example 16
| Project: lichtflut-foundation-master File: XhtmlProvider.java View source code |
//------------------------------------------------------
@SuppressWarnings("unchecked")
protected HtmlElement toHtmlRecursive(Element xmlElement) {
HtmlElement html = toHtml(xmlElement);
List<Content> contents = xmlElement.getContent();
for (Content node : contents) {
HtmlElement childHtml;
if (node instanceof Text) {
childHtml = new HtmlText(WellKnownElement.TEXT);
childHtml.setText(((Text) node).getText());
((HtmlText) childHtml).setNormalizedText(((Text) node).getTextNormalize());
childHtml.setParent(html);
html.addChild(childHtml);
} else if (node instanceof Element) {
childHtml = toHtmlRecursive((Element) node);
childHtml.setParent(html);
html.addChild(childHtml);
}
}
return html;
}Example 17
| Project: maven-plugins-master File: MavenJDOMWriter.java View source code |
// -- void updateDistributionManagement(DistributionManagement, String, Counter, Element)
/**
* Method updateElement
*
* @param counter
* @param shouldExist
* @param name
* @param parent
*/
protected Element updateElement(Counter counter, Element parent, String name, boolean shouldExist) {
Element element = parent.getChild(name, parent.getNamespace());
if (element != null && shouldExist) {
counter.increaseCount();
}
if (element == null && shouldExist) {
element = factory.element(name, parent.getNamespace());
insertAtPreferredLocation(parent, element, counter);
counter.increaseCount();
}
if (!shouldExist && element != null) {
int index = parent.indexOf(element);
if (index > 0) {
Content previous = parent.getContent(index - 1);
if (previous instanceof Text) {
Text txt = (Text) previous;
if (txt.getTextTrim().length() == 0) {
parent.removeContent(txt);
}
}
}
parent.removeContent(element);
}
return element;
}Example 18
| Project: maven-shade-plugin-master File: MavenJDOMWriter.java View source code |
// -- void updateDistributionManagement(DistributionManagement, String, Counter, Element)
/**
* Method updateElement
*
* @param counter
* @param shouldExist
* @param name
* @param parent
*/
protected Element updateElement(Counter counter, Element parent, String name, boolean shouldExist) {
Element element = parent.getChild(name, parent.getNamespace());
if (element != null && shouldExist) {
counter.increaseCount();
}
if (element == null && shouldExist) {
element = factory.element(name, parent.getNamespace());
insertAtPreferredLocation(parent, element, counter);
counter.increaseCount();
}
if (!shouldExist && element != null) {
int index = parent.indexOf(element);
if (index > 0) {
Content previous = parent.getContent(index - 1);
if (previous instanceof Text) {
Text txt = (Text) previous;
if (txt.getTextTrim().length() == 0) {
parent.removeContent(txt);
}
}
}
parent.removeContent(element);
}
return element;
}Example 19
| Project: montagnesdor-master File: ODXMLDocument.java View source code |
@SuppressWarnings("unchecked")
private void add(Factory elemF, int lindex, ODXMLDocument other, String rpath, ElementTransformer addTransf) throws JDOMException {
final Element toAdd = other.getDescendant(rpath);
// si on a qqchose à ajouter
if (toAdd != null) {
final List<Content> cloned = toAdd.cloneContent();
final List<Content> listToAdd;
if (addTransf == null) {
listToAdd = cloned;
} else {
listToAdd = new ArrayList<Content>(cloned.size());
final Iterator iter = cloned.iterator();
while (iter.hasNext()) {
final Content c = (Content) iter.next();
if (c instanceof Element) {
final Element transformedElem = addTransf.transform((Element) c);
if (transformedElem != null)
listToAdd.add(transformedElem);
}
}
}
// on crée si besoin le "récepteur"
final Element thisElem = (Element) elemF.create();
if (lindex < 0)
thisElem.addContent(listToAdd);
else
thisElem.addContent(lindex, listToAdd);
}
}Example 20
| Project: mvnplugins-master File: MavenJDOMWriter.java View source code |
//-- void updateDistributionManagement(DistributionManagement, String, Counter, Element)
/**
* Method updateElement
*
* @param counter
* @param shouldExist
* @param name
* @param parent
*/
protected Element updateElement(Counter counter, Element parent, String name, boolean shouldExist) {
Element element = parent.getChild(name, parent.getNamespace());
if (element != null && shouldExist) {
counter.increaseCount();
}
if (element == null && shouldExist) {
element = factory.element(name, parent.getNamespace());
insertAtPreferredLocation(parent, element, counter);
counter.increaseCount();
}
if (!shouldExist && element != null) {
int index = parent.indexOf(element);
if (index > 0) {
Content previous = parent.getContent(index - 1);
if (previous instanceof Text) {
Text txt = (Text) previous;
if (txt.getTextTrim().length() == 0) {
parent.removeContent(txt);
}
}
}
parent.removeContent(element);
}
return element;
}Example 21
| Project: org.openscada.external-master File: ODXMLDocument.java View source code |
@SuppressWarnings("unchecked")
private void add(Factory elemF, int lindex, ODXMLDocument other, String rpath, ElementTransformer addTransf) throws JDOMException {
final Element toAdd = other.getDescendant(rpath);
// si on a qqchose à ajouter
if (toAdd != null) {
final List<Content> cloned = toAdd.cloneContent();
final List<Content> listToAdd;
if (addTransf == null) {
listToAdd = cloned;
} else {
listToAdd = new ArrayList<Content>(cloned.size());
final Iterator iter = cloned.iterator();
while (iter.hasNext()) {
final Content c = (Content) iter.next();
if (c instanceof Element) {
final Element transformedElem = addTransf.transform((Element) c);
if (transformedElem != null)
listToAdd.add(transformedElem);
}
}
}
// on crée si besoin le "récepteur"
final Element thisElem = (Element) elemF.create();
if (lindex < 0)
thisElem.addContent(listToAdd);
else
thisElem.addContent(lindex, listToAdd);
}
}Example 22
| Project: teamcity-vmware-plugin-master File: GetSnapshotsListController.java View source code |
@Override
protected void doPost(@NotNull final HttpServletRequest request, @NotNull final HttpServletResponse response, @NotNull final Element xmlResponse) {
final BasePropertiesBean propsBean = new BasePropertiesBean(null);
PluginPropertiesUtil.bindPropertiesFromRequest(request, propsBean, true);
final Map<String, String> props = propsBean.getProperties();
final String serverUrl = props.get(VMWareWebConstants.SERVER_URL);
final String username = props.get(VMWareWebConstants.USERNAME);
final String password = props.get(VMWareWebConstants.SECURE_PASSWORD);
final String imageName = props.get("image");
try {
final VMWareApiConnector myApiConnector = VmwareApiConnectorsPool.getOrCreateConnector(new URL(serverUrl), username, password, null, null, null);
final Map<String, VirtualMachineSnapshotTree> snapshotList = myApiConnector.getSnapshotList(imageName);
Element snapshots = new Element("Snapshots");
snapshots.setAttribute("vmName", imageName);
final Element currentVersion = new Element("Snapshot");
currentVersion.setAttribute("name", "<Current State>");
currentVersion.setAttribute("value", VmwareConstants.CURRENT_STATE);
snapshots.addContent((Content) currentVersion);
if (snapshotList.size() > 0 && TeamCityProperties.getBoolean(VmwareConstants.ENABLE_LATEST_SNAPSHOT)) {
final Element latestSnapshot = new Element("Snapshot");
latestSnapshot.setAttribute("name", "<Latest snapshot>");
latestSnapshot.setAttribute("value", VmwareConstants.LATEST_SNAPSHOT);
snapshots.addContent((Content) latestSnapshot);
}
for (String snapshotName : snapshotList.keySet()) {
Element snap = new Element("Snapshot");
snap.setAttribute("name", snapshotName);
snap.setAttribute("value", snapshotName);
snapshots.addContent((Content) snap);
}
xmlResponse.addContent((Content) snapshots);
} catch (VmwareCheckedCloudException e) {
LOG.warn("Unable to get snapshot list: " + e.toString());
LOG.debug("Unable to get snapshot list: " + e.toString(), e);
} catch (MalformedURLException e) {
LOG.warn("Unable to get snapshot list: " + e.toString());
}
}Example 23
| Project: DroidClic-master File: ContentList.java View source code |
/**
* Inserts the specified object at the specified position in this list.
* Shifts the object currently at that position (if any) and any subsequent
* objects to the right (adds one to their indices).
*
* @param index
* The location to set the value to.
* @param obj
* The object to insert into the list. throws
* IndexOutOfBoundsException if index < 0 || index > size()
*/
public void add(int index, Object obj) {
if (obj == null) {
throw new IllegalAddException("Cannot add null object");
}
if (// String is OK to add as special case
obj instanceof String) {
// wrap it as a Content
obj = new Text(obj.toString());
}
if ((obj instanceof Content)) {
add(index, (Content) obj);
} else {
throw new IllegalAddException("Class " + obj.getClass().getName() + " is of unrecognized type and cannot be added");
}
}Example 24
| Project: EclipseTrader-master File: SAXOutputter.java View source code |
/**
* <p>
* This will invoke the callbacks for the content of an element.
* </p>
*
* @param content element content as a <code>List</code> of nodes.
* @param namespaces <code>List</code> stack of Namespaces in scope.
*/
private void elementContent(List content, NamespaceStack namespaces) throws JDOMException {
for (Iterator i = content.iterator(); i.hasNext(); ) {
Object obj = i.next();
if (obj instanceof Content) {
this.elementContent((Content) obj, namespaces);
} else {
// Not a valid element child. This could happen with
// application-provided lists which may contain non
// JDOM objects.
handleError(new JDOMException("Invalid element content: " + obj));
}
}
}Example 25
| Project: jclic-master File: SAXOutputter.java View source code |
/**
* <p>
* This will invoke the callbacks for the content of an element.
* </p>
*
* @param content element content as a <code>List</code> of nodes.
* @param namespaces <code>List</code> stack of Namespaces in scope.
*/
private void elementContent(List content, NamespaceStack namespaces) throws JDOMException {
for (Iterator i = content.iterator(); i.hasNext(); ) {
Object obj = i.next();
if (obj instanceof Content) {
this.elementContent((Content) obj, namespaces);
} else {
// Not a valid element child. This could happen with
// application-provided lists which may contain non
// JDOM objects.
handleError(new JDOMException("Invalid element content: " + obj));
}
}
}Example 26
| Project: bvira-master File: StaticDriverAdaptor.java View source code |
public List<String> getElementValues(String xpath) {
List<String> values = new ArrayList<String>();
List<Object> result = selectMultiElements(xpath);
for (Object object : result) {
if (object instanceof Content) {
values.add(((Element) object).getValue());
}
if (object instanceof Attribute) {
values.add(((Attribute) object).getValue());
}
}
return values;
}Example 27
| Project: cxf-master File: StaxBuilder.java View source code |
/**
* This takes a <code>XMLStreamReader</code> and builds up a JDOM tree.
* Recursion has been eliminated by using local stack of open elements; this
* improves performance somewhat (classic
* recursion-by-iteration-and-explicit stack transformation)
*
* @param node <code>Code</node> to examine.
* @param doc JDOM <code>Document</code> being built.
*/
@SuppressWarnings("fallthrough")
private void buildTree(JDOMFactory f, XMLStreamReader r, Document doc) throws XMLStreamException {
// At top level
Element current = null;
int event = r.getEventType();
// if we're at the start then we need to do a next
if (event == -1) {
event = r.next();
}
while (true) {
boolean noadd = false;
Content child = null;
switch(event) {
case XMLStreamConstants.CDATA:
child = f.cdata(r.getText());
break;
case XMLStreamConstants.SPACE:
if (cfgIgnoreWS) {
noadd = true;
break;
}
case XMLStreamConstants.CHARACTERS:
/*
* Small complication: although (ignorable) white space is
* allowed in prolog/epilog, and StAX may report such event,
* JDOM barfs if trying to add it. Thus, let's just ignore all
* textual stuff outside the tree:
*/
if (current == null) {
noadd = true;
break;
}
child = f.text(r.getText());
break;
case XMLStreamConstants.COMMENT:
child = f.comment(r.getText());
break;
case XMLStreamConstants.END_DOCUMENT:
return;
case XMLStreamConstants.END_ELEMENT:
/**
* If current.getParentElement() previously returned null and we
* get this event again we shouldn't bail out with a
* NullPointerException
*/
if (current != null) {
current = current.getParentElement();
}
noadd = true;
if (isReadingMidStream && current == null)
return;
break;
case XMLStreamConstants.ENTITY_DECLARATION:
case XMLStreamConstants.NOTATION_DECLARATION:
/*
* Shouldn't really get these, but maybe some stream readers do
* provide the info. If so, better ignore it -- DTD event should
* have most/all we need.
*/
noadd = true;
break;
case XMLStreamConstants.ENTITY_REFERENCE:
child = f.entityRef(r.getLocalName());
break;
case XMLStreamConstants.PROCESSING_INSTRUCTION:
child = f.processingInstruction(r.getPITarget(), r.getPIData());
break;
case XMLStreamConstants.START_ELEMENT:
{
// Ok, need to add a new element and simulate recursion
Element newElem = null;
String nsURI = r.getNamespaceURI();
// needed for special
String elemPrefix = r.getPrefix();
// handling of elem's
// namespace
String ln = r.getLocalName();
if (nsURI == null || nsURI.length() == 0) {
if (elemPrefix == null || elemPrefix.length() == 0) {
newElem = f.element(ln);
} else {
/*
* Happens when a prefix is bound to the default (empty)
* namespace...
*/
newElem = f.element(ln, elemPrefix, "");
}
} else {
newElem = f.element(ln, elemPrefix, nsURI);
}
/*
* Let's add element right away (probably have to do it to bind
* attribute namespaces, too)
*/
if (current == null) {
// at root
doc.setRootElement(newElem);
if (additionalNamespaces != null) {
for (Iterator<String> iter = additionalNamespaces.keySet().iterator(); iter.hasNext(); ) {
String prefix = iter.next();
String uri = additionalNamespaces.get(prefix);
newElem.addNamespaceDeclaration(Namespace.getNamespace(prefix, uri));
}
}
} else {
f.addContent(current, newElem);
}
// Any declared namespaces?
int i;
int len;
for (i = 0, len = r.getNamespaceCount(); i < len; ++i) {
String prefix = r.getNamespacePrefix(i);
Namespace ns = Namespace.getNamespace(prefix, r.getNamespaceURI(i));
// JDOM has special handling for element's "own" ns:
if (prefix != null && prefix.equals(elemPrefix)) {
// already set by when it was constructed...
} else {
f.addNamespaceDeclaration(newElem, ns);
}
}
// And then the attributes:
for (i = 0, len = r.getAttributeCount(); i < len; ++i) {
String prefix = r.getAttributePrefix(i);
Namespace ns;
if (prefix == null || prefix.length() == 0) {
// Attribute not in any namespace
ns = Namespace.NO_NAMESPACE;
} else {
ns = newElem.getNamespace(prefix);
}
Attribute attr = f.attribute(r.getAttributeLocalName(i), r.getAttributeValue(i), resolveAttrType(r.getAttributeType(i)), ns);
f.setAttribute(newElem, attr);
}
// And then 'push' new element...
current = newElem;
// Already added the element, can continue
noadd = true;
break;
}
case XMLStreamConstants.START_DOCUMENT:
case XMLStreamConstants.DTD:
// case XMLStreamConstants.NAMESPACE:
default:
/*
* throw new XMLStreamException("Unrecognized iterator event
* type: " + r.getEventType() + "; should not receive such types
* (broken stream reader?)");
*/
break;
}
if (!noadd && child != null) {
if (current == null) {
f.addContent(doc, child);
} else {
f.addContent(current, child);
}
}
if (r.hasNext()) {
event = r.next();
} else {
break;
}
}
}Example 28
| Project: dkpro-wsd-master File: CLexicalCorpus.java View source code |
private String loadInstance(Element p_Instance, String p_LexeltID) throws IOException {
// head found or not
boolean status = false;
String id = p_Instance.getAttributeValue("id");
String docID = p_Instance.getAttributeValue("docsrc");
String[] tags = new String[0];
Element context = p_Instance.getChild("context");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < context.getContentSize(); i++) {
Content content = context.getContent(i);
if (org.jdom2.Text.class.isInstance(content)) {
builder.append(" " + content.getValue());
} else {
Element element = (Element) content;
String name = element.getName();
if (name.equals("head")) {
builder.append(" " + HEADSTART + element.getValue().trim().replace(' ', '_') + HEADEND);
if (status) {
throw new IOException("Error: Multiple target word in one instance:" + id + "\n");
} else {
status = true;
}
Attribute sats = element.getAttribute("sats");
this.m_IDs.add(id);
this.m_DocIDs.add(docID);
this.m_Tags.add(tags);
if (sats != null) {
this.m_SatIDs.add(sats.getValue().split("\\s"));
String tail = "";
if (p_LexeltID.endsWith("\\.[nvar]")) {
tail = p_LexeltID.substring(p_LexeltID.length() - 2, p_LexeltID.length());
}
this.m_LexeltIDs.add(p_LexeltID + LEXELTMARK + tail);
} else {
this.m_SatIDs.add(new String[0]);
this.m_LexeltIDs.add(p_LexeltID);
}
} else if (name.equals("sat")) {
builder.append(" " + SATSTART + element.getValue() + SATEND);
Attribute satID = element.getAttribute("id");
this.m_SatID2Index.put(satID.getValue(), this.m_SatID2Index.size());
}
}
}
if (// no head word
!status) {
throw new IOException("Error:No head word in instance:" + id + "\n");
}
return builder.toString().trim();
}Example 29
| Project: fudanweixin-master File: WeixinMessageHelper.java View source code |
/**
* 将微信XML转�化DBO
*
* @param xml
* MESSAGE XML
* @return DBO
*/
public static BasicDBObject xml2dbo(Document xml) {
if (xml == null)
return null;
List<Element> params = xml.getRootElement().getChildren();
if (params == null || params.size() <= 0)
return null;
//log.info(xml2str(xml));
BasicDBObject dbo = new BasicDBObject();
for (Element e : params) {
List<Content> cs = e.getContent();
if (cs != null && cs.size() > 0) {
for (Content c : cs) {
if (c != null) {
Object o = null;
switch(c.getCType()) {
case Text:
case CDATA:
o = c.getValue();
break;
default:
;
}
if (!CommonUtil.isEmpty(o)) {
if (e.getName().equalsIgnoreCase("createtime"))
o = Integer.parseInt(o.toString());
dbo.append(e.getName(), o);
}
}
}
}
}
return dbo;
}Example 30
| Project: jspwiki-master File: JSPWikiMarkupParser.java View source code |
/**
* Gobbles up all hyperlinks that are encased in square brackets.
*/
private Element handleHyperlinks(String linktext, int pos) {
ResourceBundle rb = Preferences.getBundle(m_context, InternationalizationManager.CORE_BUNDLE);
StringBuilder sb = new StringBuilder(linktext.length() + 80);
if (isAccessRule(linktext)) {
return handleAccessRule(linktext);
}
if (isMetadata(linktext)) {
return handleMetadata(linktext);
}
if (isPluginLink(linktext)) {
try {
PluginContent pluginContent = PluginContent.parsePluginLine(m_context, linktext, pos);
//
if (pluginContent != null) {
addElement(pluginContent);
pluginContent.executeParse(m_context);
}
} catch (PluginException e) {
log.info(m_context.getRealPage().getWiki() + " : " + m_context.getRealPage().getName() + " - Failed to insert plugin: " + e.getMessage());
if (!m_wysiwygEditorMode) {
ResourceBundle rbPlugin = Preferences.getBundle(m_context, WikiPlugin.CORE_PLUGINS_RESOURCEBUNDLE);
return addElement(makeError(MessageFormat.format(rbPlugin.getString("plugin.error.insertionfailed"), m_context.getRealPage().getWiki(), m_context.getRealPage().getName(), e.getMessage())));
}
}
return m_currentElement;
}
try {
LinkParser.Link link = m_linkParser.parse(linktext);
linktext = link.getText();
String linkref = link.getReference();
//
if (VariableManager.isVariableLink(linktext)) {
Content el = new VariableContent(linktext);
addElement(el);
} else if (isExternalLink(linkref)) {
// It's an external link, out of this Wiki
callMutatorChain(m_externalLinkMutatorChain, linkref);
if (isImageLink(linkref)) {
handleImageLink(linkref, linktext, link.hasReference());
} else {
makeLink(EXTERNAL, linkref, linktext, null, link.getAttributes());
addElement(outlinkImage());
}
} else if (link.isInterwikiLink()) {
// It's an interwiki link
// InterWiki links also get added to external link chain
// after the links have been resolved.
// FIXME: There is an interesting issue here: We probably should
// URLEncode the wikiPage, but we can't since some of the
// Wikis use slashes (/), which won't survive URLEncoding.
// Besides, we don't know which character set the other Wiki
// is using, so you'll have to write the entire name as it appears
// in the URL. Bugger.
String extWiki = link.getExternalWiki();
String wikiPage = link.getExternalWikiPage();
if (m_wysiwygEditorMode) {
makeLink(INTERWIKI, extWiki + ":" + wikiPage, linktext, null, link.getAttributes());
} else {
String urlReference = m_engine.getInterWikiURL(extWiki);
if (urlReference != null) {
urlReference = TextUtil.replaceString(urlReference, "%s", wikiPage);
urlReference = callMutatorChain(m_externalLinkMutatorChain, urlReference);
if (isImageLink(urlReference)) {
handleImageLink(urlReference, linktext, link.hasReference());
} else {
makeLink(INTERWIKI, urlReference, linktext, null, link.getAttributes());
}
if (isExternalLink(urlReference)) {
addElement(outlinkImage());
}
} else {
Object[] args = { extWiki };
addElement(makeError(MessageFormat.format(rb.getString("markupparser.error.nointerwikiref"), args)));
}
}
} else if (linkref.startsWith("#")) {
// It defines a local footnote
makeLink(LOCAL, linkref, linktext, null, link.getAttributes());
} else if (TextUtil.isNumber(linkref)) {
// It defines a reference to a local footnote
makeLink(LOCALREF, linkref, linktext, null, link.getAttributes());
} else {
int hashMark = -1;
//
// Internal wiki link, but is it an attachment link?
//
String attachment = findAttachment(linkref);
if (attachment != null) {
callMutatorChain(m_attachmentLinkMutatorChain, attachment);
if (isImageLink(linkref)) {
attachment = m_context.getURL(WikiContext.ATTACH, attachment);
sb.append(handleImageLink(attachment, linktext, link.hasReference()));
} else {
makeLink(ATTACHMENT, attachment, linktext, null, link.getAttributes());
}
} else if ((hashMark = linkref.indexOf('#')) != -1) {
// It's an internal Wiki link, but to a named section
String namedSection = linkref.substring(hashMark + 1);
linkref = linkref.substring(0, hashMark);
linkref = MarkupParser.cleanLink(linkref);
callMutatorChain(m_localLinkMutatorChain, linkref);
String matchedLink;
if ((matchedLink = linkExists(linkref)) != null) {
String sectref = "section-" + m_engine.encodeName(matchedLink + "-" + wikifyLink(namedSection));
sectref = sectref.replace('%', '_');
makeLink(READ, matchedLink, linktext, sectref, link.getAttributes());
} else {
makeLink(EDIT, linkref, linktext, null, link.getAttributes());
}
} else {
// It's an internal Wiki link
linkref = MarkupParser.cleanLink(linkref);
callMutatorChain(m_localLinkMutatorChain, linkref);
String matchedLink = linkExists(linkref);
if (matchedLink != null) {
makeLink(READ, matchedLink, linktext, null, link.getAttributes());
} else {
makeLink(EDIT, linkref, linktext, null, link.getAttributes());
}
}
}
} catch (ParseException e) {
log.info("Parser failure: ", e);
Object[] args = { e.getMessage() };
addElement(makeError(MessageFormat.format(rb.getString("markupparser.error.parserfailure"), args)));
}
return m_currentElement;
}Example 31
| Project: kixmpp-master File: KixmppWebSocketCodec.java View source code |
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
WebSocketFrame frame = null;
if (msg instanceof Element) {
Element element = (Element) msg;
if (element.getNamespace() == null || element.getNamespace() == Namespace.NO_NAMESPACE) {
if ("stream".equals(element.getNamespacePrefix())) {
element.setNamespace(Namespace.getNamespace("http://etherx.jabber.org/streams"));
} else {
element.setNamespace(Namespace.getNamespace("jabber:client"));
IteratorIterable<Content> descendants = element.getDescendants();
while (descendants.hasNext()) {
Content content = descendants.next();
if (content instanceof Element) {
Element descendantElement = (Element) content;
if (descendantElement.getNamespace() == null || descendantElement.getNamespace() == Namespace.NO_NAMESPACE) {
descendantElement.setNamespace(element.getNamespace());
}
}
}
}
}
ByteBuf binaryData = ctx.alloc().buffer();
new XMLOutputter().output((Element) msg, new ByteBufOutputStream(binaryData));
frame = new TextWebSocketFrame(binaryData);
} else if (msg instanceof KixmppStreamStart) {
KixmppStreamStart streamStart = (KixmppStreamStart) msg;
StringWriter writer = new StringWriter();
if (streamStart.doesIncludeXmlHeader()) {
writer.append("<?xml version='1.0' encoding='UTF-8'?>");
}
writer.append("<stream:stream ");
if (streamStart.getId() != null) {
writer.append(String.format("id=\"%s\" ", streamStart.getId()));
}
if (streamStart.getFrom() != null) {
writer.append(String.format("from=\"%s\" ", streamStart.getFrom().getFullJid()));
}
if (streamStart.getTo() != null) {
writer.append(String.format("to=\"%s\" ", streamStart.getTo()));
}
writer.append("version=\"1.0\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\">");
frame = new TextWebSocketFrame(writer.toString());
} else if (msg instanceof KixmppStreamEnd) {
frame = new TextWebSocketFrame("</stream:stream>");
} else if (msg instanceof String) {
frame = new TextWebSocketFrame((String) msg);
} else if (msg instanceof ByteBuf) {
frame = new TextWebSocketFrame((ByteBuf) msg);
}
if (frame != null) {
if (logger.isDebugEnabled()) {
logger.debug("Sending: [{}]", frame.content().toString(StandardCharsets.UTF_8));
}
out.add(frame);
}
}Example 32
| Project: otrunk-master File: ExporterJDOM.java View source code |
public Element exportObject(OTDataObject dataObj, OTDataObject parent, String parentResourceName) throws Exception {
OTID id = dataObj.getGlobalId();
// Check if we should write out a reference
if (shouldWriteReference(dataObj, parent, parentResourceName)) {
// never write an object reference
if (parentResourceName.startsWith(OTOverlay.NON_DELTA_OBJECTS_ATTRIBUTE + "[")) {
// System.out.println("skipping writing object reference");
return null;
}
return exportObjectReference(id);
}
// If we are here then the object hasn't been written out before
// and if it has a valid container then we are inside of that container
writtenIds.add(id);
// System.err.println("writing object: " + id);
String objectFullClassName = OTrunkImpl.getClassName(dataObj);
String objectElementName = getObjectElementName(objectFullClassName);
Element objectEl = new Element(objectElementName);
XMLDataObject xmlDO = null;
if (dataObj instanceof XMLDataObject) {
xmlDO = (XMLDataObject) dataObj;
}
if (xmlDO != null && xmlDO.getLocalId() != null) {
// FIXME this is dangerous if the object is being copied from one db
// to another, the references in this export should be checked to see
// if they use the local_id or its global as a reference.
objectEl.setAttribute("local_id", xmlDO.getLocalId());
} else {
// check to see if this object has any references that
// are not containment references.
// there is only one containment reference and every object
// should have one (with the exception of the root object)
// so if there is more than one incoming reference than this object
// needs an id.
// We should also check to see if the objects id has been explicitly set
// in that case it should be written out anyhow. I'm not sure how to
// do that yet.
ArrayList<OTDataObject> incomingReferences = incomingReferenceMap.get(id);
if ((xmlDO != null && xmlDO.isPreserveUUID() && id instanceof OTUUID) || (incomingReferences != null && incomingReferences.size() > 1)) {
objectEl.setAttribute("id", id.toExternalForm());
}
}
String resourceKeys[] = dataObj.getResourceKeys();
ArrayList<String> nullResources = new ArrayList<String>();
for (int i = 0; i < resourceKeys.length; i++) {
// FIXME: we are ignoring special keys there should way
// to identify special keys.
String resourceName = resourceKeys[i];
if (resourceName.equals("currentRevision") || resourceName.equals("localId")) {
continue;
}
Object resource = dataObj.getResource(resourceName);
if (resource instanceof OTID) {
// this is an object reference
// recurse
Element objectIDEl = exportID(dataObj, (OTID) resource, resourceName);
writeResourceElement(dataObj, objectEl, resourceName, objectIDEl);
} else if (resource instanceof OTDataList) {
OTDataList list = (OTDataList) resource;
if (list.size() == 0) {
continue;
}
ArrayList<Content> content = new ArrayList<Content>();
for (int j = 0; j < list.size(); j++) {
Object listElement = list.get(j);
if (list instanceof XMLDataList) {
XMLReferenceInfo info = ((XMLDataList) list).getReferenceInfo(j);
if (info != null && info.comment != null) {
content.add(new Comment(info.comment));
}
}
Element collectionEl = exportCollectionItem(dataObj, listElement, resourceName + "[" + j + "]");
if (collectionEl != null) {
content.add(collectionEl);
}
}
writeResourceElement(dataObj, objectEl, resourceName, content);
} else if (resource instanceof OTDataMap) {
OTDataMap map = (OTDataMap) resource;
String[] mapKeys = map.getKeys();
ArrayList<Content> content = new ArrayList<Content>();
for (int j = 0; j < mapKeys.length; j++) {
Element entryEl = new Element("entry");
content.add(entryEl);
// We currently support special maps that use object ids as keys. Inorder to preserve the otml
// correctly we need to check if the mapKey is an id and if so then it should be converted.
// When it is converted it will be turned into a ${} local_id reference. Because we don't know
// if the keys of the map are supposed to be ids or just plain strings. We have to be careful to
// not screw up regular strings that look like ids.
// So we only modify the key if it is a local_id in this database.
String exportedKey = mapKeys[j];
try {
OTID otid = OTIDFactory.createOTID(mapKeys[j]);
if (otid != null) {
if (isLocalId(otid)) {
exportedKey = convertId(otid);
}
}
} catch (Throwable t) {
}
entryEl.setAttribute("key", exportedKey);
Object mapValue = map.get(mapKeys[j]);
Element collectionEl = exportCollectionItem(dataObj, mapValue, resourceName + "['" + exportedKey + "']");
entryEl.addContent(collectionEl);
}
writeResourceElement(dataObj, objectEl, resourceName, content);
} else if (resource instanceof BlobResource) {
BlobResource blob = (BlobResource) resource;
URL blobUrl = blob.getBlobURL();
String blobString = null;
XmlType defaultType = XmlType.ELEMENT;
if (blobUrl != null) {
if (contextURL != null) {
blobString = URLUtil.getRelativeURL(contextURL, blobUrl);
} else {
blobString = blobUrl.toString();
}
defaultType = XmlType.ATTRIBUTE;
} else {
blobString = BlobTypeHandler.base64(blob.getBytes());
}
writeResource(dataObj, objectEl, resourceName, blobString, defaultType);
} else if (resource == null) {
if (xmlDO.getSaveNulls()) {
nullResources.add(resourceName);
} else {
System.err.println("Got null resource value");
}
} else if (resource instanceof Integer || resource instanceof Float || resource instanceof Byte || resource instanceof Short || resource instanceof Boolean) {
String primitiveString = resource.toString();
writeResource(dataObj, objectEl, resourceName, primitiveString, XmlType.ATTRIBUTE);
} else if (resource instanceof OTXMLString) {
// The xml string is wrapped with a fake root element
// and loaded as a JDOM document
// and if it doesn't fail then clone the contents of the fake root
// element and add it to the resourceElement
// FIXME if it does fail then write it out as CDATA
// FIXME we should process any references
String xmlString = ((OTXMLString) resource).getContent();
xmlString = exportXMLString(refidPattern, xmlString);
xmlString = exportXMLString(viewidPattern, xmlString);
xmlString = exportXMLString(hrefPattern, xmlString);
String originalString = xmlString.trim();
SAXBuilder builder = new SAXBuilder();
xmlString = "<root>" + originalString + "</root>";
StringReader reader = new StringReader(xmlString);
try {
Document xmlStringDoc = builder.build(reader, resourceName);
Element rootXMLStringEl = xmlStringDoc.getRootElement();
writeResourceElement(dataObj, objectEl, resourceName, rootXMLStringEl.cloneContent());
} catch (JDOMParseException e) {
System.err.println("User-generated XML error: " + e.getCause());
System.err.println("Invalid xmlString");
System.err.println("-----");
System.err.println(xmlString);
System.err.println("-----");
String warning = "Warning: There is an HTML error in your text.\n " + e.getCause();
Object[] options = { "Save anyway and ignore the errors", "I will go back and fix the error" };
boolean saveAnyway = JOptionPane.showOptionDialog(null, warning, "HTML error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[1]) == 0;
if (!saveAnyway) {
throw new Exception("JDOMParseException caught. User will edit invalid XML");
} else {
writeResource(dataObj, objectEl, resourceName, XMLStringTypeHandler.INVALID_PREFIX + originalString, XmlType.ELEMENT);
}
e.printStackTrace();
}
} else if (resource instanceof String) {
writeResource(dataObj, objectEl, resourceName, (String) resource, XmlType.ATTRIBUTE);
} else if (resource instanceof Enum) {
EnumType enumType = EnumType.STRING;
if (dataObj instanceof XMLDataObject) {
XMLDataObject xmlObj = (XMLDataObject) dataObj;
XMLReferenceInfo resInfo = xmlObj.getReferenceInfo(resourceName);
if (resInfo != null) {
enumType = resInfo.enumType;
}
}
String str = null;
switch(enumType) {
case INT:
str = Integer.toString(((Enum) resource).ordinal());
break;
case STRING:
str = ((Enum) resource).name();
break;
}
writeResource(dataObj, objectEl, resourceName, str, XmlType.ATTRIBUTE);
} else {
String primitiveString = resource.toString();
writeResource(dataObj, objectEl, resourceName, primitiveString, XmlType.ATTRIBUTE);
}
}
if (nullResources.size() > 0) {
String unsetList = "";
for (int i = 0; i < nullResources.size(); i++) {
unsetList += nullResources.get(i) + " ";
}
unsetList = unsetList.trim();
objectEl.setAttribute("unset", unsetList);
}
return objectEl;
}Example 33
| Project: rome-master File: Atom10Generator.java View source code |
protected void populateFeedHeader(final Feed feed, final Element eFeed) throws FeedException {
final Content titleEx = feed.getTitleEx();
if (titleEx != null) {
final Element titleElement = new Element("title", getFeedNamespace());
fillContentElement(titleElement, titleEx);
eFeed.addContent(titleElement);
}
final List<Link> alternateLinks = feed.getAlternateLinks();
if (alternateLinks != null) {
for (final Link link : alternateLinks) {
eFeed.addContent(generateLinkElement(link));
}
}
final List<Link> otherLinks = feed.getOtherLinks();
if (otherLinks != null) {
for (final Link link : otherLinks) {
eFeed.addContent(generateLinkElement(link));
}
}
final List<Category> cats = feed.getCategories();
if (cats != null) {
for (final Category category : cats) {
eFeed.addContent(generateCategoryElement(category));
}
}
final List<SyndPerson> authors = feed.getAuthors();
if (Lists.isNotEmpty(authors)) {
for (final SyndPerson author : authors) {
final Element authorElement = new Element("author", getFeedNamespace());
fillPersonElement(authorElement, author);
eFeed.addContent(authorElement);
}
}
final List<SyndPerson> contributors = feed.getContributors();
if (Lists.isNotEmpty(contributors)) {
for (final SyndPerson contributor : contributors) {
final Element contributorElement = new Element("contributor", getFeedNamespace());
fillPersonElement(contributorElement, contributor);
eFeed.addContent(contributorElement);
}
}
final Content subtitle = feed.getSubtitle();
if (subtitle != null) {
final Element subtitleElement = new Element("subtitle", getFeedNamespace());
fillContentElement(subtitleElement, subtitle);
eFeed.addContent(subtitleElement);
}
final String id = feed.getId();
if (id != null) {
eFeed.addContent(generateSimpleElement("id", id));
}
final Generator generator = feed.getGenerator();
if (generator != null) {
eFeed.addContent(generateGeneratorElement(generator));
}
final String rights = feed.getRights();
if (rights != null) {
eFeed.addContent(generateSimpleElement("rights", rights));
}
final String icon = feed.getIcon();
if (icon != null) {
eFeed.addContent(generateSimpleElement("icon", icon));
}
final String logo = feed.getLogo();
if (logo != null) {
eFeed.addContent(generateSimpleElement("logo", logo));
}
final Date updated = feed.getUpdated();
if (updated != null) {
final Element updatedElement = new Element("updated", getFeedNamespace());
updatedElement.addContent(DateParser.formatW3CDateTime(updated, Locale.US));
eFeed.addContent(updatedElement);
}
}Example 34
| Project: s1tbx-master File: Project.java View source code |
public void LoadProject(final File file) {
showProjectsView();
initProject(file);
Document doc;
try {
doc = XMLSupport.LoadXML(file.getAbsolutePath());
} catch (IOException e) {
Dialogs.showError("Unable to load " + file.toString() + ": " + e.getMessage());
return;
}
final List<ProjectSubFolder> folderList = new ArrayList<>();
final List<ProjectFile> prodList = new ArrayList<>();
final Element root = doc.getRootElement();
final List<Content> children = root.getContent();
for (Object aChild : children) {
if (aChild instanceof Element) {
final Element child = (Element) aChild;
if (child.getName().equals("subFolder")) {
final Attribute attrib = child.getAttribute("name");
final ProjectSubFolder subFolder = projectSubFolders.addSubFolder(attrib.getValue());
subFolder.fromXML(child, folderList, prodList);
}
}
}
loadProducts(folderList, prodList);
loadSession(file);
notifyEvent(false);
}Example 35
| Project: Slipstream-Mod-Manager-master File: XMLPatcher.java View source code |
public Document patch(Document mainDoc, Document appendDoc) {
Document resultDoc = mainDoc.clone();
Element resultRoot = resultDoc.getRootElement();
Element appendRoot = appendDoc.getRootElement();
ElementFilter modFilter = new ElementFilter(modNS);
for (Content content : appendRoot.getContent()) {
if (modFilter.matches(content)) {
Element node = (Element) content;
boolean handled = false;
List<Element> matchedNodes = handleModFind(resultRoot, node);
if (matchedNodes != null) {
handled = true;
for (Element matchedNode : matchedNodes) {
handleModCommands(matchedNode, node);
}
}
if (!handled) {
throw new IllegalArgumentException(String.format("Unrecognized mod tag <%s> (%s).", node.getName(), getPathToRoot(node)));
}
} else {
resultRoot.addContent(content.clone());
}
}
return resultDoc;
}Example 36
| Project: step-master File: InterlinearProviderImpl.java View source code |
/**
* TODO: can be optimized by not iterating through major elements such as Notes for example setups all the initial
* textual information for fast retrieval during XSL transformation.
*
* @param element element to start with.
*/
@SuppressWarnings("unchecked")
private boolean scanForTextualInformation(final Element element, final String untaggedText) {
// check to see if we've hit a new verse, if so, we update the verse
updateVerseRef(element);
// check to see if we've hit a node of interest
if (element.getName().equals(OSISUtil.OSIS_ELEMENT_W)) {
extractTextualInfoFromNode(element, untaggedText);
return true;
}
//small optimization to remove processing of potentially verbose notes
if (element.getName().equals(OSISUtil.OSIS_ELEMENT_NOTE)) {
return false;
}
// iterate through all children and call recursively
Object data;
Element ele;
final Iterator<Content> contentIter = element.getContent().iterator();
StringBuilder untaggedContent = null;
while (contentIter.hasNext()) {
data = contentIter.next();
//we capture untagged content at the same level as the elements that we process
if (data instanceof Text) {
if (untaggedContent == null) {
untaggedContent = new StringBuilder(32);
}
untaggedContent.append(((Text) data).getText());
}
if (data instanceof Element) {
ele = (Element) data;
if (untaggedContent != null) {
if (scanForTextualInformation(ele, untaggedContent.toString())) {
//we've consumed the untagged content, so remove it now
untaggedContent = null;
}
} else {
scanForTextualInformation(ele, null);
}
}
}
return false;
}Example 37
| Project: superluminal2-master File: IOUtils.java View source code |
/**
* Merges the file-byte map with the specified ShipContainer, effectively saving
* the ship in the file-byte map.
*/
public static void merge(Map<String, byte[]> base, ShipContainer container) throws JDOMParseException, IOException {
ShipObject ship = container.getShipController().getGameObject();
Map<String, byte[]> fileMap = ShipSaveUtils.saveShip(container);
for (String file : fileMap.keySet()) {
if (base.containsKey(file)) {
// Mod already contains that file; need to consider further
if (file.endsWith(".png") || file.equals(ship.getLayoutTXT()) || file.equals(ship.getLayoutXML())) {
// Overwrite graphics and layout files
base.put(file, fileMap.get(file));
} else if (file.endsWith(".xml") || file.endsWith(".append") || file.endsWith(".rawappend") || file.endsWith(".rawclobber")) {
// Merge XML files, while removing obscured elements
Document docBase = IOUtils.parseXML(new String(base.get(file)));
Document docAdd = IOUtils.parseXML(new String(fileMap.get(file)));
Element root = docBase.getRootElement();
List<Content> addList = docAdd.getContent();
for (int i = 0; i < addList.size(); ++i) {
Content c = addList.get(i);
if (c instanceof Element == false)
continue;
Element e = (Element) c;
String name = e.getAttributeValue("name");
if (name == null) {
// Can't identify; just add it.
e.detach();
root.addContent(e);
} else {
// Remove elements that are obscured, in order to prevent bloating
List<Element> baseList = root.getChildren(e.getName(), e.getNamespace());
for (int j = 0; j < baseList.size(); ++j) {
Element el = baseList.get(j);
String name2 = el.getAttributeValue("name");
if (name2 != null && name2.equals(name)) {
el.detach();
}
}
e.detach();
root.addContent(e);
}
}
base.put(file, readDocument(docBase).getBytes());
}
} else {
// Doesn't exist; add it
base.put(file, fileMap.get(file));
}
}
}Example 38
| Project: collaborationtoday-master File: Atom10Parser.java View source code |
private Feed parseFeedMetadata(String baseURI, Element eFeed) {
com.sun.syndication.feed.atom.Feed feed = new com.sun.syndication.feed.atom.Feed(getType());
Element e = eFeed.getChild("title", getAtomNamespace());
if (e != null) {
Content c = new Content();
c.setValue(parseTextConstructToString(e));
c.setType(getAttributeValue(e, "type"));
feed.setTitleEx(c);
}
List eList = eFeed.getChildren("link", getAtomNamespace());
feed.setAlternateLinks(parseAlternateLinks(feed, null, baseURI, eList));
feed.setOtherLinks(parseOtherLinks(feed, null, baseURI, eList));
List cList = eFeed.getChildren("category", getAtomNamespace());
feed.setCategories(parseCategories(baseURI, cList));
eList = eFeed.getChildren("author", getAtomNamespace());
if (eList.size() > 0) {
feed.setAuthors(parsePersons(baseURI, eList));
}
eList = eFeed.getChildren("contributor", getAtomNamespace());
if (eList.size() > 0) {
feed.setContributors(parsePersons(baseURI, eList));
}
e = eFeed.getChild("subtitle", getAtomNamespace());
if (e != null) {
Content subtitle = new Content();
subtitle.setValue(parseTextConstructToString(e));
subtitle.setType(getAttributeValue(e, "type"));
feed.setSubtitle(subtitle);
}
e = eFeed.getChild("id", getAtomNamespace());
if (e != null) {
feed.setId(e.getText());
}
e = eFeed.getChild("generator", getAtomNamespace());
if (e != null) {
Generator gen = new Generator();
gen.setValue(e.getText());
String att = getAttributeValue(e, "uri");
if (att != null) {
gen.setUrl(att);
}
att = getAttributeValue(e, "version");
if (att != null) {
gen.setVersion(att);
}
feed.setGenerator(gen);
}
e = eFeed.getChild("rights", getAtomNamespace());
if (e != null) {
feed.setRights(parseTextConstructToString(e));
}
e = eFeed.getChild("icon", getAtomNamespace());
if (e != null) {
feed.setIcon(e.getText());
}
e = eFeed.getChild("logo", getAtomNamespace());
if (e != null) {
feed.setLogo(e.getText());
}
e = eFeed.getChild("updated", getAtomNamespace());
if (e != null) {
feed.setUpdated(DateParser.parseDate(e.getText()));
}
return feed;
}Example 39
| Project: blogbridge-master File: Atom10ParserV2.java View source code |
protected WireFeed parseFeed(Element eFeed) throws FeedException {
com.sun.syndication.feed.atom.Feed feed = new com.sun.syndication.feed.atom.Feed(getType());
String baseURI;
try {
baseURI = findBaseURI(eFeed);
} catch (Exception e) {
throw new FeedException("ERROR while finding base URI of feed", e);
}
String xmlBase = eFeed.getAttributeValue("base", Namespace.XML_NAMESPACE);
if (xmlBase != null) {
feed.setXmlBase(xmlBase);
}
Element e = eFeed.getChild("title", getAtomNamespace());
if (e != null) {
Content c = new Content();
c.setValue(parseTextConstructToString(e));
//, Namespace.XML_NAMESPACE));
c.setType(e.getAttributeValue("type"));
feed.setTitleEx(c);
}
List<Element> eList = getChildren(eFeed, "link");
feed.setAlternateLinks(parseAlternateLinks(feed, null, baseURI, eList));
feed.setOtherLinks(parseOtherLinks(feed, null, baseURI, eList));
List cList = eFeed.getChildren("category", getAtomNamespace());
feed.setCategories(parseCategories(baseURI, cList));
eList = getChildren(eFeed, "author");
if (eList.size() > 0) {
feed.setAuthors(parsePersons(baseURI, eList));
}
eList = getChildren(eFeed, "contributor");
if (eList.size() > 0) {
feed.setContributors(parsePersons(baseURI, eList));
}
e = eFeed.getChild("subtitle", getAtomNamespace());
if (e != null) {
Content subtitle = new Content();
subtitle.setValue(parseTextConstructToString(e));
//, Namespace.XML_NAMESPACE));
subtitle.setType(e.getAttributeValue("type"));
feed.setSubtitle(subtitle);
}
e = eFeed.getChild("id", getAtomNamespace());
if (e != null) {
feed.setId(e.getText());
}
e = eFeed.getChild("generator", getAtomNamespace());
if (e != null) {
Generator gen = new Generator();
gen.setValue(e.getText());
//getAtomNamespace()); DONT KNOW WHY DOESN'T WORK
String att = e.getAttributeValue("uri");
if (att != null) {
gen.setUrl(att);
}
//getAtomNamespace()); DONT KNOW WHY DOESN'T WORK
att = e.getAttributeValue("version");
if (att != null) {
gen.setVersion(att);
}
feed.setGenerator(gen);
}
e = eFeed.getChild("rights", getAtomNamespace());
if (e != null) {
feed.setRights(parseTextConstructToString(e));
}
e = eFeed.getChild("icon", getAtomNamespace());
if (e != null) {
feed.setIcon(e.getText());
}
e = eFeed.getChild("logo", getAtomNamespace());
if (e != null) {
feed.setLogo(e.getText());
}
e = eFeed.getChild("updated", getAtomNamespace());
if (e != null) {
feed.setUpdated(DateParser.parseDate(e.getText()));
}
feed.setModules(parseFeedModules(eFeed));
eList = getChildren(eFeed, "entry");
if (eList.size() > 0) {
feed.setEntries(parseEntries(feed, baseURI, eList));
}
List foreignMarkup = extractForeignMarkup(eFeed, feed, getAtomNamespace());
if (foreignMarkup.size() > 0) {
feed.setForeignMarkup(foreignMarkup);
}
return feed;
}Example 40
| Project: and-bible-master File: CustomHandler.java View source code |
/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
*/
@Override
public void characters(char[] data, int offset, int length) {
// what we are adding
String text = new String(data, offset, length);
if (stack.isEmpty()) {
stack.addFirst(new Text(text));
return;
}
// What we are adding to
Content top = stack.getFirst();
// then there is a null element on the stack
if (top == null) {
return;
}
if (top instanceof Text) {
((Text) top).append(text);
return;
}
if (top instanceof Element) {
Element current = (Element) top;
int size = current.getContentSize();
// split a word.
if (size > 0) {
Content last = current.getContent(size - 1);
if (last instanceof Text) {
((Text) last).append(text);
return;
}
}
current.addContent(new Text(text));
}
}Example 41
| Project: Application-Builder-master File: XmlDocument.java View source code |
public Element sort(Element root, java.lang.String[] tagsToSort) throws AppBuilderException {
Element tempRoot = (Element) root.clone();
tempRoot.detach();
tempRoot.removeContent();
/**
* Makes groups of elements by tag
*/
List eltLstLst = new ArrayList(tagsToSort.length);
for (int iTag = 0; iTag < tagsToSort.length; iTag++) {
List children = root.getChildren(tagsToSort[iTag], root.getNamespace());
List eltLst = new ArrayList();
if (children != null && !children.isEmpty()) {
for (Object child : children) {
if (child instanceof Content) {
Content newElement = (Content) ((Content) child).clone();
newElement.detach();
eltLst.add(newElement);
}
}
}
eltLstLst.add(iTag, eltLst);
}
/**
* Orders the content of the resulting document
*/
for (int iTag = 0; iTag < tagsToSort.length; iTag++) {
if (!((List) eltLstLst.get(iTag)).isEmpty()) {
tempRoot.addContent((List) eltLstLst.get(iTag));
}
}
/**
* the result
*/
return tempRoot;
}Example 42
| Project: gwt-maven-plugin-master File: GwtWebInfProcessor.java View source code |
private int getInsertPosition(Element webapp, String[] startAfter, String[] stopBefore) throws JDOMException, IOException {
List children = webapp.getContent();
Content insertAfter = new Comment("inserted by gwt-maven-plugin");
ArrayList<String> namesBefore = new ArrayList<String>();
ArrayList<String> namesAfter = new ArrayList<String>();
for (int i = 0; i < startAfter.length; i++) {
namesBefore.add(startAfter[i]);
}
for (int i = 0; i < stopBefore.length; i++) {
namesAfter.add(stopBefore[i]);
}
if ((children == null) || (children.size() == 0)) {
webapp.addContent(insertAfter);
} else {
boolean foundPoint = false;
for (int i = 0; !foundPoint && i < children.size(); i++) {
Object o = children.get(i);
if (!(o instanceof Element)) {
continue;
}
Element child = (Element) o;
if (namesAfter.contains(child.getName())) {
webapp.addContent(i, insertAfter);
foundPoint = true;
break;
}
if (!namesBefore.contains(child.getName())) {
webapp.addContent(i + 1, insertAfter);
foundPoint = true;
break;
}
}
if (!foundPoint) {
webapp.addContent(insertAfter);
}
}
return webapp.indexOf(insertAfter);
}Example 43
| Project: jodtemplate-master File: StylePostprocessor.java View source code |
@Override
public Document process(final Map<String, Object> context, final Document document, final Slide slide, final Resources resources, final Configuration configuration) throws JODTemplateException {
final IteratorIterable<Element> atElements = document.getDescendants(Filters.element(PPTXDocument.T_ELEMENT, getNamespace()));
final List<Element> atElementsList = new ArrayList<>();
while (atElements.hasNext()) {
atElementsList.add(atElements.next());
}
for (Element at : atElementsList) {
if (at.getContentSize() != 0) {
final Content content = at.getContent(0);
if (content instanceof Comment) {
final Comment comment = (Comment) content;
processComment(comment, at, slide, configuration);
}
}
}
return document;
}Example 44
| Project: MathMLCan-master File: OperatorNormalizer.java View source code |
private void normalizeUnicode(final Element ancestor, final Normalizer.Form form) {
assert ancestor != null && form != null;
final List<Text> texts = new ArrayList<Text>();
final ContentFilter textFilter = new ContentFilter(ContentFilter.TEXT);
for (Content text : ancestor.getContent(textFilter)) {
texts.add((Text) text);
}
for (Element element : ancestor.getDescendants(new ElementFilter())) {
for (Content text : element.getContent(textFilter)) {
texts.add((Text) text);
}
}
for (Text text : texts) {
if (Normalizer.isNormalized(text.getText(), form)) {
continue;
}
final String normalizedString = Normalizer.normalize(text.getText(), form);
LOGGER.log(Level.FINE, "Text ''{0}'' normalized to ''{1}''", new Object[] { text.getText(), normalizedString });
text.setText(normalizedString);
assert Normalizer.isNormalized(text.getText(), form);
}
}Example 45
| Project: oliot-fc-master File: TagReportData.java View source code |
/**
* {@inheritDoc}
*/
public Content encodeXML(String name, Namespace ns) {
// element in namespace defined by parent element
Element element = new Element(name, ns);
// child element are always in default LLRP namespace
ns = Namespace.getNamespace("llrp", LLRPConstants.LLRPNAMESPACE);
//parameters
if (ePCParameter == null) {
LOGGER.info("ePCParameter not set");
throw new MissingParameterException("ePCParameter not set");
} else {
element.addContent(ePCParameter.encodeXML(ePCParameter.getClass().getSimpleName(), ns));
}
if (rOSpecID == null) {
LOGGER.info("rOSpecID not set");
} else {
element.addContent(rOSpecID.encodeXML(rOSpecID.getClass().getSimpleName(), ns));
}
if (specIndex == null) {
LOGGER.info("specIndex not set");
} else {
element.addContent(specIndex.encodeXML(specIndex.getClass().getSimpleName(), ns));
}
if (inventoryParameterSpecID == null) {
LOGGER.info("inventoryParameterSpecID not set");
} else {
element.addContent(inventoryParameterSpecID.encodeXML(inventoryParameterSpecID.getClass().getSimpleName(), ns));
}
if (antennaID == null) {
LOGGER.info("antennaID not set");
} else {
element.addContent(antennaID.encodeXML(antennaID.getClass().getSimpleName(), ns));
}
if (peakRSSI == null) {
LOGGER.info("peakRSSI not set");
} else {
element.addContent(peakRSSI.encodeXML(peakRSSI.getClass().getSimpleName(), ns));
}
if (channelIndex == null) {
LOGGER.info("channelIndex not set");
} else {
element.addContent(channelIndex.encodeXML(channelIndex.getClass().getSimpleName(), ns));
}
if (firstSeenTimestampUTC == null) {
LOGGER.info("firstSeenTimestampUTC not set");
} else {
element.addContent(firstSeenTimestampUTC.encodeXML(firstSeenTimestampUTC.getClass().getSimpleName(), ns));
}
if (firstSeenTimestampUptime == null) {
LOGGER.info("firstSeenTimestampUptime not set");
} else {
element.addContent(firstSeenTimestampUptime.encodeXML(firstSeenTimestampUptime.getClass().getSimpleName(), ns));
}
if (lastSeenTimestampUTC == null) {
LOGGER.info("lastSeenTimestampUTC not set");
} else {
element.addContent(lastSeenTimestampUTC.encodeXML(lastSeenTimestampUTC.getClass().getSimpleName(), ns));
}
if (lastSeenTimestampUptime == null) {
LOGGER.info("lastSeenTimestampUptime not set");
} else {
element.addContent(lastSeenTimestampUptime.encodeXML(lastSeenTimestampUptime.getClass().getSimpleName(), ns));
}
if (tagSeenCount == null) {
LOGGER.info("tagSeenCount not set");
} else {
element.addContent(tagSeenCount.encodeXML(tagSeenCount.getClass().getSimpleName(), ns));
}
if (airProtocolTagDataList == null) {
LOGGER.info("airProtocolTagDataList not set");
} else {
for (AirProtocolTagData field : airProtocolTagDataList) {
element.addContent(field.encodeXML(field.getClass().getName().replaceAll(field.getClass().getPackage().getName() + ".", ""), ns));
}
}
if (accessSpecID == null) {
LOGGER.info("accessSpecID not set");
} else {
element.addContent(accessSpecID.encodeXML(accessSpecID.getClass().getSimpleName(), ns));
}
if (accessCommandOpSpecResultList == null) {
LOGGER.info("accessCommandOpSpecResultList not set");
} else {
for (AccessCommandOpSpecResult field : accessCommandOpSpecResultList) {
element.addContent(field.encodeXML(field.getClass().getName().replaceAll(field.getClass().getPackage().getName() + ".", ""), ns));
}
}
if (customList == null) {
LOGGER.info("customList not set");
} else {
for (Custom field : customList) {
element.addContent(field.encodeXML(field.getClass().getName().replaceAll(field.getClass().getPackage().getName() + ".", ""), ns));
}
}
return element;
}Example 46
| Project: phenoscape-nlp-master File: Type4Transformer.java View source code |
protected void getDescriptionFrom(Element root, int fn, int count) {
try {
List<Element> divs = XPath.selectNodes(root, "/tax:taxonx/tax:taxonxBody/tax:treatment/tax:div");
Iterator<Element> it = divs.iterator();
int i = 0;
while (it.hasNext()) {
Element div = it.next();
if (div.getAttributeValue("type").compareToIgnoreCase("description") == 0) {
//List<Element> ps = div.getChildren("p", div.getNamespace());
List<Element> ps = div.getChildren("description");
Iterator<Element> t = ps.iterator();
while (t.hasNext()) {
Element p = t.next();
int size = p.getContentSize();
StringBuffer sb = new StringBuffer();
for (int c = 0; c < size; c++) {
Content cont = p.getContent(c);
if (cont instanceof Element) {
sb.append(((Element) cont).getTextNormalize() + " ");
} else if (cont instanceof Text) {
sb.append(((Text) cont).getTextNormalize() + " ");
}
}
//writeDescription2Descriptions(sb.toString(), fn+"_"+count+"_"+i); //record the position for each paragraph.
//record the position for each paragraph.
writeDescription2Descriptions(sb.toString(), fn + "_" + count + ".txtp" + i);
i++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}Example 47
| Project: plexus-containers-master File: AbstractMergeableElement.java View source code |
public void merge(Mergeable me) throws MergeException {
if (!isExpectedElementType(me)) {
// getLogger().error ("Cannot Merge dissimilar elements. (Expected : '" + getClass ().getName () + "', found '" + me.getClass ().getName () + "')");
throw new MergeException("Cannot Merge dissimilar elements. " + "(Expected : '" + getClass().getName() + "', found '" + me.getClass().getName() + "')");
}
// recessive Component Element.
AbstractMergeableElement rce = (AbstractMergeableElement) me;
Set allowedTags = new HashSet();
for (int i = 0; i < getAllowedTags().length; i++) {
String tagName = getAllowedTags()[i].getTagName();
allowedTags.add(tagName);
List defaultConflictChecklist = new ArrayList();
defaultConflictChecklist.add(tagName);
if (!isRecessiveElementInConflict(rce, defaultConflictChecklist) && mergeableElementComesFromRecessive(rce, tagName)) {
this.addContent((Element) rce.getChild(tagName).clone());
// else dominant wins in anycase!
} else if (getAllowedTags()[i].isMergeable() && isRecessiveElementInConflict(rce, defaultConflictChecklist)) {
// this allows for merging multiple/list of elements.
try {
getAllowedTags()[i].createMergeable(this.getChild(tagName)).merge(getAllowedTags()[i].createMergeable(rce.getChild(tagName)), getDefaultMergeStrategy());
} catch (Exception e) {
throw new MergeException("Unable to create Mergeable instance for tag " + "'" + getAllowedTags()[i] + "'.", e);
}
}
}
for (Iterator i = me.getElement().getChildren().iterator(); i.hasNext(); ) {
Element child = (Element) i.next();
if (!allowedTags.contains(child.getName())) {
// not yet merged, copy over
element.addContent((Content) child.clone());
}
}
}Example 48
| Project: ProjectAres-master File: MapFilePreprocessor.java View source code |
private List<Content> readIncludedDocument(Path fullPath, @Nullable Element includeElement) throws InvalidXMLException {
if (includeStack.contains(fullPath)) {
throw new InvalidXMLException("Circular include: " + Joiner.on(" --> ").join(includeStack), includeElement);
}
includeStack.push(fullPath);
try {
return readDocument(fullPath).getRootElement().cloneContent();
} finally {
includeStack.pop();
}
}Example 49
| Project: ps3mediaserver-master File: Feed.java View source code |
@SuppressWarnings("unchecked")
public void parse() throws Exception {
SyndFeedInput input = new SyndFeedInput();
byte b[] = downloadAndSendBinary(url);
if (b != null) {
SyndFeed feed = input.build(new XmlReader(new ByteArrayInputStream(b)));
setName(feed.getTitle());
if (feed.getCategories() != null && feed.getCategories().size() > 0) {
SyndCategory category = (SyndCategory) feed.getCategories().get(0);
setTempCategory(category.getName());
}
List<SyndEntry> entries = feed.getEntries();
for (SyndEntry entry : entries) {
setTempItemTitle(entry.getTitle());
setTempItemLink(entry.getLink());
setTempFeedLink(entry.getUri());
setTempItemThumbURL(null);
ArrayList<Element> elements = (ArrayList<Element>) entry.getForeignMarkup();
for (Element elt : elements) {
if ("group".equals(elt.getName()) && "media".equals(elt.getNamespacePrefix())) {
List<Content> subElts = elt.getContent();
for (Content subelt : subElts) {
if (subelt instanceof Element) {
parseElement((Element) subelt, false);
}
}
}
parseElement(elt, true);
}
List<SyndEnclosure> enclosures = entry.getEnclosures();
for (SyndEnclosure enc : enclosures) {
if (StringUtils.isNotBlank(enc.getUrl())) {
setTempItemLink(enc.getUrl());
}
}
manageItem();
}
}
setLastModified(System.currentTimeMillis());
}Example 50
| Project: rascal-master File: DOM.java View source code |
private Content nodeToContent(IConstructor n) {
if (n.getConstructorType() == Factory.Node_element) {
return nodeToElement(n);
}
if (n.getConstructorType() == Factory.Node_pi) {
IString target = (IString) n.get(0);
IString data = (IString) n.get(1);
return new ProcessingInstruction(target.getValue(), data.getValue());
}
if (n.getConstructorType() == Factory.Node_charRef) {
IInteger code = (IInteger) n.get(0);
int c = java.lang.Integer.parseInt(code.getStringRepresentation());
return new Text(new java.lang.String(Character.toChars(c)));
}
if (n.getConstructorType() == Factory.Node_entityRef) {
return new EntityRef(((IString) n.get(0)).getValue());
}
java.lang.String text = ((IString) n.get(0)).getValue();
if (n.getConstructorType() == Factory.Node_cdata) {
return new CDATA(text);
}
if (n.getConstructorType() == Factory.Node_charData) {
return new Text(text);
}
if (n.getConstructorType() == Factory.Node_comment) {
return new Comment(text);
}
wellformednessError();
return null;
}Example 51
| Project: rome-modules-master File: SSEParserTest.java View source code |
private void asserEqualContent(final Element one, final Element two) {
final List<Content> oneContent = one.getContent();
final List<Content> twoContent = two.getContent();
if (bothNull(oneContent, twoContent)) {
return;
}
assertNullEqual("missing compare content", oneContent, twoContent);
assertEqualAttributes(one, two);
// scan through the content to make sure each element is equal
for (final Object content1 : oneContent) {
if (content1 instanceof Element) {
final Element e1 = (Element) content1;
boolean foundEqual = false;
final ArrayList<String> messages = new ArrayList<String>();
for (final Object o : twoContent) {
if (o instanceof Element) {
final Element e2 = (Element) o;
try {
// have to check all elements to be order insensitive
if (e1.getName().equals(e2.getName()) && equalAttributes(e1, e2, false)) {
assertEqualElements(e1, e2);
foundEqual = true;
messages.clear();
break;
}
} catch (final Error e) {
messages.add(e.getMessage());
}
}
}
// if (!foundEqual) {
// // show accumulated error messages
// for (Iterator mesgIter = messages.iterator(); mesgIter.hasNext();) {
// LOG.debug((String) mesgIter.next());
// }
// }
// look for the content in the other tree
assertTrue("could not find matching element for: " + one.getName(), foundEqual);
}
}
}Example 52
| Project: turmeric-eclipse-master File: WebXMLParser.java View source code |
@SuppressWarnings("unchecked")
private static int getNextNodeIndex(Element root, String nodeName) {
List<Object> child = root.getChildren(SERVLET_NODE);
int index = -1;
if (child == null) {
return index;
}
for (Object objEle : child) {
if (objEle instanceof Element == false) {
continue;
}
int currIdx = root.indexOf((Content) objEle);
if (index < currIdx) {
index = currIdx;
}
}
return index;
}Example 53
| Project: UniversalMediaServer-master File: Feed.java View source code |
@SuppressWarnings("unchecked")
public void parse() throws Exception {
SyndFeedInput input = new SyndFeedInput();
byte b[] = downloadAndSendBinary(url);
if (b != null) {
SyndFeed feed = input.build(new XmlReader(new ByteArrayInputStream(b)));
name = feed.getTitle();
if (feed.getCategories() != null && feed.getCategories().size() > 0) {
SyndCategory category = (SyndCategory) feed.getCategories().get(0);
tempCategory = category.getName();
}
List<SyndEntry> entries = feed.getEntries();
for (SyndEntry entry : entries) {
tempItemTitle = entry.getTitle();
tempItemLink = entry.getLink();
tempFeedLink = entry.getUri();
tempItemThumbURL = null;
ArrayList<Element> elements = (ArrayList<Element>) entry.getForeignMarkup();
for (Element elt : elements) {
if ("group".equals(elt.getName()) && "media".equals(elt.getNamespacePrefix())) {
List<Content> subElts = elt.getContent();
for (Content subelt : subElts) {
if (subelt instanceof Element) {
parseElement((Element) subelt, false);
}
}
}
parseElement(elt, true);
}
List<SyndEnclosure> enclosures = entry.getEnclosures();
for (SyndEnclosure enc : enclosures) {
if (StringUtils.isNotBlank(enc.getUrl())) {
tempItemLink = enc.getUrl();
}
}
manageItem();
}
}
setLastModified(System.currentTimeMillis());
}Example 54
| Project: FoxyDocs-master File: Export.java View source code |
public static List<Content> transform(Document doc, String stylesheet) throws JDOMException, FileNotFoundException {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(getInternalFile(stylesheet)));
JDOMSource in = new JDOMSource(doc);
JDOMResult out = new JDOMResult();
transformer.transform(in, out);
return out.getResult();
} catch (TransformerException e) {
throw new JDOMException("XSLT Transformation failed", e);
}
}Example 55
| Project: XFlat-master File: JDOMStreamReader.java View source code |
@Override
public int next() throws XMLStreamException {
if (depth < 0) {
throw new NoSuchElementException("No more data available.");
}
curi = null;
clocalname = null;
cprefix = null;
ctext = null;
ctarget = null;
cdata = null;
if (currentEvt == END_ELEMENT) {
nsstack.pop();
formatstack.pop();
emtstack[depth + 1] = null;
}
// confirm next walker item.
if (!stack[depth].hasNext()) {
// no more items at this level.
stack[depth] = null;
// we kill the element stack at the end of the END_ELEMENT event.
// emtstack[depth] = null
depth--;
return currentEvt = (depth < 0 ? END_DOCUMENT : END_ELEMENT);
}
final Content c = stack[depth].next();
if (c == null) {
// formatted text or CDATA.
ctext = stack[depth].text();
return currentEvt = stack[depth].isCDATA() ? CDATA : CHARACTERS;
}
switch(c.getCType()) {
case CDATA:
ctext = c.getValue();
return currentEvt = CDATA;
case Text:
ctext = c.getValue();
return currentEvt = CHARACTERS;
case Comment:
ctext = c.getValue();
return currentEvt = COMMENT;
case DocType:
// format doctype appropriately.
XMLOutputter xout = new XMLOutputter();
ctext = xout.outputString((DocType) c);
return currentEvt = DTD;
case EntityRef:
clocalname = ((EntityRef) c).getName();
ctext = "";
return currentEvt = ENTITY_REFERENCE;
case ProcessingInstruction:
final ProcessingInstruction pi = (ProcessingInstruction) c;
ctarget = pi.getTarget();
cdata = pi.getData();
return currentEvt = PROCESSING_INSTRUCTION;
case Element:
// we deal with Element outside the switch statement.
break;
default:
throw new IllegalStateException("Unexpected content " + c);
}
// OK, we break out here if we are an Element start.
final Element emt = (Element) c;
clocalname = emt.getName();
cprefix = emt.getNamespacePrefix();
curi = emt.getNamespaceURI();
nsstack.push(emt);
formatstack.push();
final String space = emt.getAttributeValue("space", Namespace.XML_NAMESPACE);
// Check for xml:space and adjust format settings
if ("default".equals(space)) {
formatstack.setTextMode(formatstack.getDefaultMode());
} else if ("preserve".equals(space)) {
formatstack.setTextMode(TextMode.PRESERVE);
}
depth++;
if (depth >= stack.length) {
stack = ArrayCopy.copyOf(stack, depth + 32);
emtstack = ArrayCopy.copyOf(emtstack, depth + 32);
}
emtstack[depth] = emt;
stack[depth] = buildWalker(formatstack, emt.getContent(), false);
return currentEvt = START_ELEMENT;
}Example 56
| Project: Carolina-Digital-Repository-master File: DepositController.java View source code |
@RequestMapping(value = { "{uuid}/events" }, method = RequestMethod.GET)
@ResponseBody
public Document getEvents(@PathVariable String uuid) throws Exception {
LOG.debug("getEvents( {} )", uuid);
String bagDirectory;
try (Jedis jedis = getJedisPool().getResource()) {
bagDirectory = jedis.hget(RedisWorkerConstants.DEPOSIT_STATUS_PREFIX + uuid, RedisWorkerConstants.DepositField.directory.name());
}
File bagFile = new File(bagDirectory);
if (!bagFile.exists())
return null;
File eventsFile = new File(bagDirectory, DepositConstants.EVENTS_FILE);
if (!eventsFile.exists())
return null;
Element events = new Element("events", JDOMNamespaceUtil.PREMIS_V2_NS);
Document result = new Document(events);
XMLInputFactory factory = XMLInputFactory.newInstance();
try (FileInputStream fis = new FileInputStream(eventsFile)) {
XMLStreamReader reader = factory.createXMLStreamReader(fis);
StAXStreamBuilder builder = new StAXStreamBuilder();
List<Content> list = builder.buildFragments(reader, new DefaultStAXFilter());
events.addContent(list);
return result;
}
}Example 57
| Project: DB-Builder-master File: DBXmlDocument.java View source code |
/**
* Merges only the children of the root element of each document. It takes all the elements
* concerned by the array of tags from all the documents to merge and adds them to the resulting
* document. <strong>In the resulting document, the comments, processing instructions and entities
* are removed.</strong>
* @param tagsToMerge
* @param XmlFile
* @throws AppBuilderException
* @roseuid 3AAF3793006E
*/
public void mergeWith(String[] tagsToMerge, DBXmlDocument XmlFile) throws AppBuilderException {
/**
* gets the resulting document from the master document. Cloning the document is important. If
* you clone or copy an element, the copy keeps his owner and, as a result, the element appears
* twice in the document
*/
Element root = getDocument().getRootElement();
root.detach();
/** merges the elements in the resulting document */
/** gets the root element of the documents to merge (excluding master) */
Document documentToBeMerged = (Document) XmlFile.getDocument().clone();
Element tempRoot = documentToBeMerged.getRootElement();
/** gets all the elements which will be included in the resulting document */
for (int iTag = 0; iTag < tagsToMerge.length; iTag++) {
for (Object child : tempRoot.getChildren(tagsToMerge[iTag])) {
if (child instanceof Content) {
Content newElement = (Content) ((Content) child).clone();
newElement.detach();
root.addContent(newElement);
}
}
}
/** the result */
setDocument(new Document(root));
}Example 58
| Project: metadata-editor-master File: EditorTemplate.java View source code |
/**
* Prune the tree recursively by making all children of editor variable nodes point to their grandparent
* or if there is no grandparent attach them to the document directly, even though this leads to an invalid XML document.
* @param element The element to process
* @param parent The parent of the processed element
* @param doc The document
*/
private void pruneTreeRecursive(Element element, Element parent, org.jdom2.Document doc) {
List<Content> children = new ArrayList<>();
for (Content child : element.getContent()) {
children.add(child);
}
if (supportedTags.containsKey(element.getName())) {
// need the index of the element to know where to insert the elements
// children
int elementIndex;
if (parent != null) {
elementIndex = parent.indexOf(element);
} else {
elementIndex = doc.indexOf(element);
}
element.detach();
for (Content child : children) {
if (child instanceof Element) {
Element e = (Element) child;
pruneTreeRecursive(e, parent, doc);
}
child.detach();
if (parent != null) {
parent.addContent(elementIndex++, child);
} else {
doc.addContent(elementIndex++, child);
}
}
} else {
for (Content child : children) {
if (child instanceof Element) {
Element e = (Element) child;
pruneTreeRecursive(e, element, doc);
}
}
}
}Example 59
| Project: openflexo-master File: XMLDecoder.java View source code |
/**
* Internally used during XML decoding process.<br>
* Build and returns newly created object matching the specified node, asserting <code>node</code> is the key node.<br>
* Note that if some attributes are here defined, the first one will be interpreted as a String and returned as the key (eventual other
* child nodes will be ignored) else the first child node will be interpreted as the key.
*
* @param node
* an <code>Element</code> value
* @param modelEntity
* a <code>ModelEntity</code> value
* @return an <code>Object</code> value
* @exception InvalidXMLDataException
* if an error occurs
* @exception InvalidObjectSpecificationException
* if an error occurs
*/
protected Object buildKeyFromKeyNode(Element node) throws InvalidXMLDataException, InvalidObjectSpecificationException {
List childNodesList = node.getContent();
List attributes = node.getAttributes();
if (attributes.size() > 0) {
// the key (eventual other child nodes will be ignored)
return ((Attribute) attributes.get(0)).getValue();
} else if (childNodesList.size() > 0) {
int i = 0;
while (i < childNodesList.size()) {
Content tempNode = (Content) childNodesList.get(i);
if (tempNode instanceof Text) {
String potentialValue = ((Text) tempNode).getTextTrim();
if (potentialValue.length() > 0) {
return potentialValue;
}
} else if (tempNode instanceof Element) {
Element element = (Element) tempNode;
ModelEntity relatedModelEntity = xmlMapping.entityWithXMLTag(element.getName());
if (relatedModelEntity == null) {
throw new InvalidXMLDataException("Tag '" + element.getName() + "' not found in model");
} else {
return buildObjectFromNodeAndModelEntity(element, relatedModelEntity);
}
}
i++;
}
}
throw new InvalidXMLDataException("No key found for storing object in a hastable-like data structure");
}Example 60
| Project: programd-master File: GenericParser.java View source code |
/** * Evaluates the given content list and returns the result. * * @param list the list of content to evaluate * @return the result of evaluating the given list of nodes * @throws ProcessorException if there is an error in processing */ public String evaluate(List<Content> list) throws ProcessorException { StringBuilder result = new StringBuilder(); for (Content node : list) { // Would be nice not to have to do this: if (node instanceof Element) { result.append(this.evaluate((Element) node)); } else if (node instanceof Text) { result.append(GenericParser.evaluate((Text) node)); } else if (node instanceof CDATA) { result.append(GenericParser.evaluate((CDATA) node)); } else if (node instanceof Comment) { result.append(GenericParser.evaluate((Comment) node)); } else { assert false : "Unknown subclass of jdom.org.Content!"; } } return result.toString(); }
Example 61
| Project: pystructure-master File: TypeAnnotator.java View source code |
private Content goalDetails(IGoal goal) {
if (goal instanceof ILocatable) {
Location location = ((ILocatable) goal).getLocation();
Element span = emptyTag("span");
if (location.node == null) {
span.addContent("null");
} else {
span.addContent(location.node.getClass().getSimpleName() + " ");
span.addContent(linkTo(location));
}
return span;
} else if (goal instanceof PossibleReferencesGoal) {
PossibleReferencesGoal g = (PossibleReferencesGoal) goal;
return new Text(g.getName());
} else if (goal instanceof ClassAttributeTypeGoal) {
ClassAttributeTypeGoal g = (ClassAttributeTypeGoal) goal;
return linkTo(g.getContext(), g.getClassType().getKlass(), g.getAttributeName());
} else if (goal instanceof AttributeReferencesGoal) {
AttributeReferencesGoal g = (AttributeReferencesGoal) goal;
Attribute attribute = g.getAttribute();
return linkTo(g.getContext(), attribute.getKlass(), attribute.getName());
} else if (goal instanceof PossibleAttributeReferencesGoal) {
PossibleAttributeReferencesGoal g = (PossibleAttributeReferencesGoal) goal;
return new Text(g.getName());
} else if (goal instanceof MethodResolveGoal) {
MethodResolveGoal g = (MethodResolveGoal) goal;
return new Text(g.getClassType().getKlass() + " " + g.getAttributeName());
} else if (goal instanceof MethodResolutionOrderGoal) {
MethodResolutionOrderGoal g = (MethodResolutionOrderGoal) goal;
return new Text("MRO for " + g.getKlass());
} else if (goal instanceof CalculateTypeHierarchyGoal) {
return new Text("Calculate all Types");
} else {
throw new RuntimeException("Cannot format goal, unknown goal type: " + goal);
}
}Example 62
| Project: cismap-commons-master File: WFSFacade.java View source code |
/**
* Replaces the current property names with the given property names in the getFeature query.
*
* @param query getFeature request as JDOM-element
* @param properties the property names
* @param version the version of the wfs request that is contained in the query paramaeter
*/
public static void changePropertyNames(final Element query, final Collection<String> properties, String version) {
if (version == null) {
logger.error("version string is null. Try to use version 1.1.0", new Exception());
version = "1.1.0";
}
if (!(version.equals("1.0.0") || version.equals("1.1.0"))) {
// NOI18N
logger.error(// NOI18N
"unknown wfs version: " + version + // NOI18N
". Try to handle this version like version 1.1.0");
}
query.getChild(QUERY, WFS).removeChildren(PROPERTY_NAME, WFS);
final Collection<Content> propertyElements = new ArrayList<Content>();
for (final String s : properties) {
final Element tmp = new Element(PROPERTY_NAME, WFS);
tmp.setText(s);
propertyElements.add(tmp);
}
if (!propertyElements.isEmpty()) {
query.getChild(QUERY, WFS).addContent(0, propertyElements);
}
}Example 63
| Project: com.idega.block.pdf-master File: PDFGeneratorBean.java View source code |
private org.jdom.Document getDocumentWithModifiedTags(org.jdom.Document document) {
List<String> expectedValues = null;
List<Element> needless = new ArrayList<Element>();
// <div>
List<Element> divs = getDocumentElements(TAG_DIV, document);
if (!ListUtil.isEmpty(divs)) {
expectedValues = ListUtil.convertStringArrayToList(new String[] { "deselected-case" });
List<String> buttonAreaClassValue = ListUtil.convertStringArrayToList(new String[] { "fbc_button_area" });
List<String> errorsClassValue = ListUtil.convertStringArrayToList(new String[] { "xformErrors" });
List<String> displayNoneAttributeValue = ListUtil.convertStringArrayToList(new String[] { ATTRIBUTE_VALUE_DISPLAY_NONE });
for (Element div : divs) {
if (doElementHasAttribute(div, ATTRIBUTE_CLASS, buttonAreaClassValue)) {
needless.add(div);
}
if (doElementHasAttribute(div, ATTRIBUTE_CLASS, errorsClassValue)) {
needless.add(div);
}
if (doElementHasAttribute(div, ATTRIBUTE_STYLE, displayNoneAttributeValue)) {
needless.add(div);
}
}
}
// <legend>
List<Element> legends = getDocumentElements("legend", document);
if (!ListUtil.isEmpty(legends)) {
expectedValues = ListUtil.convertStringArrayToList(new String[] { "label" });
for (Element legend : legends) {
if (doElementHasAttribute(legend, ATTRIBUTE_CLASS, expectedValues)) {
needless.add(legend);
}
}
}
// <span>
List<Element> spans = getDocumentElements("span", document);
if (!ListUtil.isEmpty(spans)) {
expectedValues = ListUtil.convertStringArrayToList(new String[] { "help-text" });
for (Element span : spans) {
if (doElementHasAttribute(span, ATTRIBUTE_CLASS, expectedValues)) {
needless.add(span);
} else if (doElementHasAttribute(span, ATTRIBUTE_CLASS, Arrays.asList("selector-prototype"))) {
needless.add(span);
} else if (doElementHasAttribute(span, ATTRIBUTE_CLASS, Arrays.asList("alert"))) {
needless.add(span);
} else if (doElementHasAttribute(span, ATTRIBUTE_CLASS, Arrays.asList("required-symbol"))) {
needless.add(span);
}
}
}
// <textarea>
List<Element> textareas = getDocumentElements("textarea", document);
if (!ListUtil.isEmpty(textareas)) {
for (Element textarea : textareas) {
textarea.setName(TAG_DIV);
textarea.setAttribute(new Attribute(ATTRIBUTE_CLASS, "textAreaReplacementForPDFDocument"));
String originalText = textarea.getTextNormalize();
if (StringUtil.isEmpty(originalText)) {
textarea.setText(CoreConstants.MINUS);
} else {
String text = "<div>".concat(originalText).concat("</div>");
while (text.indexOf("src=\"../") != -1) {
text = StringHandler.replace(text, "../", CoreConstants.EMPTY);
}
text = StringHandler.replace(text, "<br data-mce-bogus=\"1\">", CoreConstants.EMPTY);
text = StringHandler.replace(text, "<br mce-bogus=\"1\">", CoreConstants.EMPTY);
text = StringHandler.replace(text, "<br mce_bogus=\"1\">", CoreConstants.EMPTY);
while (text.indexOf("<br>") != -1) {
text = StringHandler.replace(text, "<br>", CoreConstants.EMPTY);
}
org.jdom.Document textAreaContent = XmlUtil.getJDOMXMLDocument(text);
if (textAreaContent != null) {
try {
@SuppressWarnings("unchecked") List<Content> clonedContent = textAreaContent.cloneContent();
textarea.removeContent();
textarea.setContent(clonedContent);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Error setting new content for ex-textarea element: " + text, e);
textarea.setText(originalText);
}
}
}
}
}
// Links
List<Element> links = getDocumentElements("a", document);
if (!ListUtil.isEmpty(links)) {
for (Element link : links) {
if (doElementHasAttribute(link, "name", Arrays.asList("chibaform-head")) && ListUtil.isEmpty(link.getChildren())) {
needless.add(link);
} else if (doElementHasAttribute(link, ATTRIBUTE_CLASS, Arrays.asList("help-icon"))) {
needless.add(link);
}
}
}
// Scripts
List<Element> scripts = getDocumentElements("script", document);
if (!ListUtil.isEmpty(scripts)) {
needless.addAll(scripts);
}
// <iframes>
List<Element> frames = getDocumentElements("iframe", document);
if (!ListUtil.isEmpty(frames)) {
for (Element frame : frames) {
if (ListUtil.isEmpty(frame.getChildren())) {
needless.add(frame);
}
}
}
// <select>
List<Element> selects = getDocumentElements("select", document);
if (!ListUtil.isEmpty(selects)) {
Locale locale = null;
IWContext iwc = CoreUtil.getIWContext();
if (iwc != null) {
locale = iwc.getCurrentLocale();
}
if (locale == null) {
locale = Locale.ENGLISH;
}
IWResourceBundle iwrb = null;
try {
iwrb = IWMainApplication.getDefaultIWMainApplication().getBundle(CoreConstants.CORE_IW_BUNDLE_IDENTIFIER).getResourceBundle(locale);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Error getting resources bundle by locale: " + locale, e);
}
String defaultLabel = "None of the options selected";
for (Element select : selects) {
if (doElementHasAttribute(select, ATTRIBUTE_CLASS, Arrays.asList("selector-prototype"))) {
needless.add(select);
} else {
Map<String, List<Element>> allOptions = getSelectOptions(select);
if (allOptions != null && !ListUtil.isEmpty(allOptions.values())) {
for (List<Element> options : allOptions.values()) {
// Getting values for selected options
Element option = null;
List<String> selectedOptionsValues = new ArrayList<String>();
for (Iterator<Element> optionsIter = options.iterator(); optionsIter.hasNext(); ) {
option = optionsIter.next();
if (doElementHasAttribute(option, "selected", Arrays.asList("selected"))) {
selectedOptionsValues.add(option.getTextNormalize());
}
}
if (ListUtil.isEmpty(selectedOptionsValues)) {
selectedOptionsValues.add(iwrb == null ? defaultLabel : iwrb.getLocalizedString("pdf_generator.none_of_options_selected", defaultLabel));
}
select.setName(TAG_DIV);
select.setAttribute(new Attribute(ATTRIBUTE_CLASS, "selectDropdownReplacementForPDFDocument"));
if (doElementHasAttribute(select, ATTRIBUTE_STYLE, Arrays.asList(ATTRIBUTE_VALUE_DISPLAY_NONE))) {
select.removeAttribute(ATTRIBUTE_STYLE);
}
Element list = new Element("ul");
select.setContent(Arrays.asList(list));
Collection<Element> listItems = new ArrayList<Element>(selectedOptionsValues.size());
for (String value : selectedOptionsValues) {
Element listItem = new Element("li");
listItem.setText(value);
listItems.add(listItem);
}
list.setContent(listItems);
}
}
}
}
}
selects = getDocumentElements("select", document);
if (!ListUtil.isEmpty(selects)) {
// Removing empty selects
needless.addAll(selects);
}
for (Iterator<Element> needlessIter = needless.iterator(); needlessIter.hasNext(); ) {
needlessIter.next().detach();
}
return document;
}Example 64
| Project: compass-fork-master File: StAXBuilder.java View source code |
/**
* This takes a <code>XMLStreamReader</code> and builds up
* a JDOM tree. Recursion has been eliminated by using nodes'
* parent/child relationship; this improves performance somewhat
* (classic recursion-by-iteration-and-explicit stack transformation)
*
* @param f Node factory to use for creating JDOM nodes
* @param r Stream reader to use for reading the document from which
* to build the tree
* @param doc JDOM <code>Document</code> being built.
* @param tmod Text modifier to use for modifying content of text
* nodes (CHARACTERS, not CDATA), if any; null if no modifications
* are needed (modifier is usually used for trimming unnecessary
* but non-ignorable white space).
*/
protected void buildTree(JDOMFactory f, XMLStreamReader r, Document doc, StAXTextModifier tmod) throws XMLStreamException {
// At top level
Element current = null;
/* Only relevant when trying to trim indentation. But if so, let's
* just always allow modifications in prolog/epilog.
*/
boolean allowTextMods = (tmod != null);
int evtType = XMLStreamConstants.START_DOCUMENT;
main_loop: while (true) {
int prevEvent = evtType;
evtType = r.next();
/* 11-Dec-2004, TSa: We may want to trim (indentation) white
* space... and it's easiest to do as a completely separate
* piece of logic, before the main switch.
*/
if (allowTextMods) {
// Ok; did we get CHARACTERS to potentially modify?
if (evtType == XMLStreamConstants.CHARACTERS) {
// Mayhaps we could be interested in modifying it?
if (tmod.possiblyModifyText(r, prevEvent)) {
/* Need to get text before iterating to see the
* following event (as that'll lose it)
*/
String txt = r.getText();
evtType = r.next();
// So how should the text be modified if at all?
txt = tmod.textToIncludeBetween(r, prevEvent, evtType, txt);
// Need to output if it's non-empty text, then:
if (txt != null && txt.length() > 0) {
/* See discussion below for CHARACTERS case; basically
* we apparently can't add anything in epilog/prolog,
* not even white space.
*/
if (current != null) {
f.addContent(current, f.text(txt));
}
}
prevEvent = XMLStreamConstants.CHARACTERS;
// Ok, let's fall down to handle new current event
}
}
// And then can just fall back to the regular handling
}
Content child;
switch(evtType) {
case XMLStreamConstants.CDATA:
child = f.cdata(r.getText());
break;
case XMLStreamConstants.SPACE:
if (cfgIgnoreWS) {
continue main_loop;
}
case XMLStreamConstants.CHARACTERS:
/* Small complication: although (ignorable) white space
* is allowed in prolog/epilog, and StAX may report such
* event, JDOM barfs if trying to add it. Thus, let's just
* ignore all textual stuff outside the tree:
*/
if (current == null) {
continue main_loop;
}
child = f.text(r.getText());
break;
case XMLStreamConstants.COMMENT:
child = f.comment(r.getText());
break;
case XMLStreamConstants.END_DOCUMENT:
break main_loop;
case XMLStreamConstants.END_ELEMENT:
current = current.getParentElement();
if (tmod != null) {
allowTextMods = tmod.allowModificationsAfter(r, evtType);
}
continue main_loop;
case XMLStreamConstants.ENTITY_DECLARATION:
case XMLStreamConstants.NOTATION_DECLARATION:
/* Shouldn't really get these, but maybe some stream readers
* do provide the info. If so, better ignore it -- DTD event
* should have most/all we need.
*/
continue main_loop;
case XMLStreamConstants.ENTITY_REFERENCE:
child = f.entityRef(r.getLocalName());
break;
case XMLStreamConstants.PROCESSING_INSTRUCTION:
child = f.processingInstruction(r.getPITarget(), r.getPIData());
break;
case XMLStreamConstants.START_ELEMENT:
// Ok, need to add a new element...
{
Element newElem = null;
String nsURI = r.getNamespaceURI();
// needed for special handling of elem's namespace
String elemPrefix = r.getPrefix();
String ln = r.getLocalName();
if (nsURI == null || nsURI.length() == 0) {
if (elemPrefix == null || elemPrefix.length() == 0) {
newElem = f.element(ln);
} else {
/* Happens when a prefix is bound to the default
* (empty) namespace...
*/
newElem = f.element(ln, elemPrefix, "");
}
} else {
newElem = f.element(ln, elemPrefix, nsURI);
}
/* Let's add element right away (probably have to do
* it to bind attribute namespaces, too)
*/
if (current == null) {
// at root
doc.setRootElement(newElem);
} else {
f.addContent(current, newElem);
}
// Any declared namespaces?
for (int i = 0, len = r.getNamespaceCount(); i < len; ++i) {
String prefix = r.getNamespacePrefix(i);
if (prefix == null) {
prefix = "";
}
Namespace ns = Namespace.getNamespace(prefix, r.getNamespaceURI(i));
// JDOM has special handling for element's "own" ns:
if (prefix.equals(elemPrefix)) {
// already set by when it was constructed...
;
} else {
f.addNamespaceDeclaration(newElem, ns);
}
}
// And then the attributes:
for (int i = 0, len = r.getAttributeCount(); i < len; ++i) {
String prefix = r.getAttributePrefix(i);
Namespace ns;
if (prefix == null || prefix.length() == 0) {
// Attribute not in any namespace
ns = Namespace.NO_NAMESPACE;
} else {
ns = newElem.getNamespace(prefix);
}
Attribute attr = f.attribute(r.getAttributeLocalName(i), r.getAttributeValue(i), resolveAttrType(r.getAttributeType(i)), ns);
f.setAttribute(newElem, attr);
}
// And then 'push' new element...
current = newElem;
}
if (tmod != null) {
allowTextMods = tmod.allowModificationsAfter(r, evtType);
}
// Already added the element, can continue
continue main_loop;
case XMLStreamConstants.START_DOCUMENT:
/* For now, let it pass: maybe some (broken) readers pass
* that info as first event in beginning of doc?
*/
continue main_loop;
case XMLStreamConstants.DTD:
// TBI
continue main_loop;
//case XMLStreamConstants.NAMESPACE:
default:
throw new XMLStreamException("Unrecognized iterator event type: " + r.getEventType() + "; should not receive such types (broken stream reader?)");
}
if (child != null) {
if (current == null) {
f.addContent(doc, child);
} else {
f.addContent(current, child);
}
}
}
}Example 65
| Project: CORISCO2-master File: SimpleHTMLFragment.java View source code |
/** * Remove the given content from the Element. * * If the content is an element then render it as text and include it's * children in the parent. * * @param content * The DOM Content to be removed. */ private void removeContent(Content content) { if (content instanceof Element) { // If it's an element replace the content with a text node. Element element = (Element) content; if (element.getContent().size() == 0) { // The element contains nothing, we can use shorthand notation // for it. String replacement = "<" + element.getName(); @SuppressWarnings("unchecked") // This cast is correct List<Attribute> attributes = element.getAttributes(); for (Attribute attribute : attributes) { replacement += " " + attribute.getName() + "=\"" + attribute.getValue() + "\""; } replacement += "/>"; Element parent = element.getParentElement(); int index = parent.indexOf(element); parent.setContent(index, new Text(replacement)); } else { // The element contains data String prepend = "<" + element.getName(); @SuppressWarnings("unchecked") // This cast is correct List<Attribute> attributes = element.getAttributes(); for (Attribute attribute : attributes) { prepend += " " + attribute.getName() + "=\"" + attribute.getValue() + "\""; } prepend += ">"; String postpend = "</" + element.getName() + ">"; Element parent = element.getParentElement(); int index = parent.indexOf(element); parent.addContent(index, new Text(postpend)); parent.addContent(index, element.removeContent()); parent.addContent(index, new Text(prepend)); parent.removeContent(element); } } else { // If it's not an element just remove the content from the document. Element parent = content.getParentElement(); parent.removeContent(content); } }
Example 66
| Project: dlibrary-master File: METSManifest.java View source code |
/**
* Return contents of *md element as List of XML Element objects.
* Gets content, dereferencing mdRef if necessary, or decoding and parsing
* a binData that contains XML.
* @return contents of metadata section, or empty list if no XML content is available.
* @throws MetadataValidationException if METS is invalid, or there is an error parsing the XML.
*/
public List<Element> getMdContentAsXml(Element mdSec, Mdref callback) throws MetadataValidationException, PackageValidationException, IOException, SQLException, AuthorizeException {
try {
// XXX sanity check: if this has more than one child, consider it
// an error since we cannot deal with more than one mdRef|mdWrap
// child. This may be considered a bug and need to be fixed,
// so it's best to bring it to the attention of users.
List mdc = mdSec.getChildren();
if (mdc.size() > 1) {
// XXX scaffolding for debugging diagnosis; at least one
// XML parser stupidly includes newlines in prettyprinting
// as text content objects..
String id = mdSec.getAttributeValue("ID");
StringBuffer sb = new StringBuffer();
for (Iterator mi = mdc.iterator(); mi.hasNext(); ) {
sb.append(", ").append(((Content) mi.next()).toString());
}
throw new MetadataValidationException("Cannot parse METS with " + mdSec.getQualifiedName() + " element that contains more than one child, size=" + String.valueOf(mdc.size()) + ", ID=" + id + "Kids=" + sb.toString());
}
Element mdRef = null;
Element mdWrap = mdSec.getChild("mdWrap", metsNS);
if (mdWrap != null) {
Element xmlData = mdWrap.getChild("xmlData", metsNS);
if (xmlData == null) {
Element bin = mdWrap.getChild("binData", metsNS);
if (bin == null) {
throw new MetadataValidationException("Invalid METS Manifest: mdWrap element with neither xmlData nor binData child.");
} else // if binData is actually XML, return it; otherwise ignore.
{
String mimeType = mdWrap.getAttributeValue("MIMETYPE");
if (mimeType != null && mimeType.equalsIgnoreCase("text/xml")) {
byte value[] = Base64.decodeBase64(bin.getText().getBytes());
Document mdd = parser.build(new ByteArrayInputStream(value));
List<Element> result = new ArrayList<Element>(1);
result.add(mdd.getRootElement());
return result;
} else {
log.warn("Ignoring binData section because MIMETYPE is not XML, but: " + mimeType);
return new ArrayList<Element>(0);
}
}
} else {
return xmlData.getChildren();
}
} else {
mdRef = mdSec.getChild("mdRef", metsNS);
if (mdRef != null) {
String mimeType = mdRef.getAttributeValue("MIMETYPE");
if (mimeType != null && mimeType.equalsIgnoreCase("text/xml")) {
Document mdd = parser.build(callback.getInputStream(mdRef));
List<Element> result = new ArrayList<Element>(1);
result.add(mdd.getRootElement());
return result;
} else {
log.warn("Ignoring mdRef section because MIMETYPE is not XML, but: " + mimeType);
return new ArrayList<Element>(0);
}
} else {
throw new MetadataValidationException("Invalid METS Manifest: ?mdSec element with neither mdRef nor mdWrap child.");
}
}
} catch (JDOMException je) {
throw new MetadataValidationException("Error parsing or validating metadata section in mdRef or binData within " + mdSec.toString(), je);
}
}Example 67
| Project: DSpace-SVN-Deprecated-master File: METSManifest.java View source code |
/**
* Return contents of *md element as List of XML Element objects.
* Gets content, dereferencing mdRef if necessary, or decoding and parsing
* a binData that contains XML.
* @return contents of metadata section, or empty list if no XML content is available.
* @throws MetadataValidationException if METS is invalid, or there is an error parsing the XML.
*/
public List<Element> getMdContentAsXml(Element mdSec, Mdref callback) throws MetadataValidationException, PackageValidationException, IOException, SQLException, AuthorizeException {
try {
// XXX sanity check: if this has more than one child, consider it
// an error since we cannot deal with more than one mdRef|mdWrap
// child. This may be considered a bug and need to be fixed,
// so it's best to bring it to the attention of users.
List mdc = mdSec.getChildren();
if (mdc.size() > 1) {
// XXX scaffolding for debugging diagnosis; at least one
// XML parser stupidly includes newlines in prettyprinting
// as text content objects..
String id = mdSec.getAttributeValue("ID");
StringBuffer sb = new StringBuffer();
for (Iterator mi = mdc.iterator(); mi.hasNext(); ) {
sb.append(", ").append(((Content) mi.next()).toString());
}
throw new MetadataValidationException("Cannot parse METS with " + mdSec.getQualifiedName() + " element that contains more than one child, size=" + String.valueOf(mdc.size()) + ", ID=" + id + "Kids=" + sb.toString());
}
Element mdRef = null;
Element mdWrap = mdSec.getChild("mdWrap", metsNS);
if (mdWrap != null) {
Element xmlData = mdWrap.getChild("xmlData", metsNS);
if (xmlData == null) {
Element bin = mdWrap.getChild("binData", metsNS);
if (bin == null) {
throw new MetadataValidationException("Invalid METS Manifest: mdWrap element with neither xmlData nor binData child.");
} else // if binData is actually XML, return it; otherwise ignore.
{
String mimeType = mdWrap.getAttributeValue("MIMETYPE");
if (mimeType != null && mimeType.equalsIgnoreCase("text/xml")) {
byte value[] = Base64.decodeBase64(bin.getText().getBytes());
Document mdd = parser.build(new ByteArrayInputStream(value));
List<Element> result = new ArrayList<Element>(1);
result.add(mdd.getRootElement());
return result;
} else {
log.warn("Ignoring binData section because MIMETYPE is not XML, but: " + mimeType);
return new ArrayList<Element>(0);
}
}
} else {
return xmlData.getChildren();
}
} else {
mdRef = mdSec.getChild("mdRef", metsNS);
if (mdRef != null) {
String mimeType = mdRef.getAttributeValue("MIMETYPE");
if (mimeType != null && mimeType.equalsIgnoreCase("text/xml")) {
Document mdd = parser.build(callback.getInputStream(mdRef));
List<Element> result = new ArrayList<Element>(1);
result.add(mdd.getRootElement());
return result;
} else {
log.warn("Ignoring mdRef section because MIMETYPE is not XML, but: " + mimeType);
return new ArrayList<Element>(0);
}
} else {
throw new MetadataValidationException("Invalid METS Manifest: ?mdSec element with neither mdRef nor mdWrap child.");
}
}
} catch (JDOMException je) {
throw new MetadataValidationException("Error parsing or validating metadata section in mdRef or binData within " + mdSec.toString(), je);
}
}Example 68
| Project: elastic-compass-master File: StAXBuilder.java View source code |
/**
* This takes a <code>XMLStreamReader</code> and builds up
* a JDOM tree. Recursion has been eliminated by using nodes'
* parent/child relationship; this improves performance somewhat
* (classic recursion-by-iteration-and-explicit stack transformation)
*
* @param f Node factory to use for creating JDOM nodes
* @param r Stream reader to use for reading the document from which
* to build the tree
* @param doc JDOM <code>Document</code> being built.
* @param tmod Text modifier to use for modifying content of text
* nodes (CHARACTERS, not CDATA), if any; null if no modifications
* are needed (modifier is usually used for trimming unnecessary
* but non-ignorable white space).
*/
protected void buildTree(JDOMFactory f, XMLStreamReader r, Document doc, StAXTextModifier tmod) throws XMLStreamException {
// At top level
Element current = null;
/* Only relevant when trying to trim indentation. But if so, let's
* just always allow modifications in prolog/epilog.
*/
boolean allowTextMods = (tmod != null);
int evtType = XMLStreamConstants.START_DOCUMENT;
main_loop: while (true) {
int prevEvent = evtType;
evtType = r.next();
/* 11-Dec-2004, TSa: We may want to trim (indentation) white
* space... and it's easiest to do as a completely separate
* piece of logic, before the main switch.
*/
if (allowTextMods) {
// Ok; did we get CHARACTERS to potentially modify?
if (evtType == XMLStreamConstants.CHARACTERS) {
// Mayhaps we could be interested in modifying it?
if (tmod.possiblyModifyText(r, prevEvent)) {
/* Need to get text before iterating to see the
* following event (as that'll lose it)
*/
String txt = r.getText();
evtType = r.next();
// So how should the text be modified if at all?
txt = tmod.textToIncludeBetween(r, prevEvent, evtType, txt);
// Need to output if it's non-empty text, then:
if (txt != null && txt.length() > 0) {
/* See discussion below for CHARACTERS case; basically
* we apparently can't add anything in epilog/prolog,
* not even white space.
*/
if (current != null) {
f.addContent(current, f.text(txt));
}
}
prevEvent = XMLStreamConstants.CHARACTERS;
// Ok, let's fall down to handle new current event
}
}
// And then can just fall back to the regular handling
}
Content child;
switch(evtType) {
case XMLStreamConstants.CDATA:
child = f.cdata(r.getText());
break;
case XMLStreamConstants.SPACE:
if (cfgIgnoreWS) {
continue main_loop;
}
case XMLStreamConstants.CHARACTERS:
/* Small complication: although (ignorable) white space
* is allowed in prolog/epilog, and StAX may report such
* event, JDOM barfs if trying to add it. Thus, let's just
* ignore all textual stuff outside the tree:
*/
if (current == null) {
continue main_loop;
}
child = f.text(r.getText());
break;
case XMLStreamConstants.COMMENT:
child = f.comment(r.getText());
break;
case XMLStreamConstants.END_DOCUMENT:
break main_loop;
case XMLStreamConstants.END_ELEMENT:
current = current.getParentElement();
if (tmod != null) {
allowTextMods = tmod.allowModificationsAfter(r, evtType);
}
continue main_loop;
case XMLStreamConstants.ENTITY_DECLARATION:
case XMLStreamConstants.NOTATION_DECLARATION:
/* Shouldn't really get these, but maybe some stream readers
* do provide the info. If so, better ignore it -- DTD event
* should have most/all we need.
*/
continue main_loop;
case XMLStreamConstants.ENTITY_REFERENCE:
child = f.entityRef(r.getLocalName());
break;
case XMLStreamConstants.PROCESSING_INSTRUCTION:
child = f.processingInstruction(r.getPITarget(), r.getPIData());
break;
case XMLStreamConstants.START_ELEMENT:
// Ok, need to add a new element...
{
Element newElem = null;
String nsURI = r.getNamespaceURI();
// needed for special handling of elem's namespace
String elemPrefix = r.getPrefix();
String ln = r.getLocalName();
if (nsURI == null || nsURI.length() == 0) {
if (elemPrefix == null || elemPrefix.length() == 0) {
newElem = f.element(ln);
} else {
/* Happens when a prefix is bound to the default
* (empty) namespace...
*/
newElem = f.element(ln, elemPrefix, "");
}
} else {
newElem = f.element(ln, elemPrefix, nsURI);
}
/* Let's add element right away (probably have to do
* it to bind attribute namespaces, too)
*/
if (current == null) {
// at root
doc.setRootElement(newElem);
} else {
f.addContent(current, newElem);
}
// Any declared namespaces?
for (int i = 0, len = r.getNamespaceCount(); i < len; ++i) {
String prefix = r.getNamespacePrefix(i);
if (prefix == null) {
prefix = "";
}
Namespace ns = Namespace.getNamespace(prefix, r.getNamespaceURI(i));
// JDOM has special handling for element's "own" ns:
if (prefix.equals(elemPrefix)) {
// already set by when it was constructed...
;
} else {
f.addNamespaceDeclaration(newElem, ns);
}
}
// And then the attributes:
for (int i = 0, len = r.getAttributeCount(); i < len; ++i) {
String prefix = r.getAttributePrefix(i);
Namespace ns;
if (prefix == null || prefix.length() == 0) {
// Attribute not in any namespace
ns = Namespace.NO_NAMESPACE;
} else {
ns = newElem.getNamespace(prefix);
}
Attribute attr = f.attribute(r.getAttributeLocalName(i), r.getAttributeValue(i), resolveAttrType(r.getAttributeType(i)), ns);
f.setAttribute(newElem, attr);
}
// And then 'push' new element...
current = newElem;
}
if (tmod != null) {
allowTextMods = tmod.allowModificationsAfter(r, evtType);
}
// Already added the element, can continue
continue main_loop;
case XMLStreamConstants.START_DOCUMENT:
/* For now, let it pass: maybe some (broken) readers pass
* that info as first event in beginning of doc?
*/
continue main_loop;
case XMLStreamConstants.DTD:
// TBI
continue main_loop;
//case XMLStreamConstants.NAMESPACE:
default:
throw new XMLStreamException("Unrecognized iterator event type: " + r.getEventType() + "; should not receive such types (broken stream reader?)");
}
if (child != null) {
if (current == null) {
f.addContent(doc, child);
} else {
f.addContent(current, child);
}
}
}
}Example 69
| Project: vtechworks-master File: METSManifest.java View source code |
/**
* Return contents of *md element as List of XML Element objects.
* Gets content, dereferencing mdRef if necessary, or decoding and parsing
* a binData that contains XML.
* @return contents of metadata section, or empty list if no XML content is available.
* @throws MetadataValidationException if METS is invalid, or there is an error parsing the XML.
*/
public List<Element> getMdContentAsXml(Element mdSec, Mdref callback) throws MetadataValidationException, PackageValidationException, IOException, SQLException, AuthorizeException {
try {
// XXX sanity check: if this has more than one child, consider it
// an error since we cannot deal with more than one mdRef|mdWrap
// child. This may be considered a bug and need to be fixed,
// so it's best to bring it to the attention of users.
List mdc = mdSec.getChildren();
if (mdc.size() > 1) {
// XXX scaffolding for debugging diagnosis; at least one
// XML parser stupidly includes newlines in prettyprinting
// as text content objects..
String id = mdSec.getAttributeValue("ID");
StringBuffer sb = new StringBuffer();
for (Iterator mi = mdc.iterator(); mi.hasNext(); ) {
sb.append(", ").append(((Content) mi.next()).toString());
}
throw new MetadataValidationException("Cannot parse METS with " + mdSec.getQualifiedName() + " element that contains more than one child, size=" + String.valueOf(mdc.size()) + ", ID=" + id + "Kids=" + sb.toString());
}
Element mdRef = null;
Element mdWrap = mdSec.getChild("mdWrap", metsNS);
if (mdWrap != null) {
Element xmlData = mdWrap.getChild("xmlData", metsNS);
if (xmlData == null) {
Element bin = mdWrap.getChild("binData", metsNS);
if (bin == null) {
throw new MetadataValidationException("Invalid METS Manifest: mdWrap element with neither xmlData nor binData child.");
} else // if binData is actually XML, return it; otherwise ignore.
{
String mimeType = mdWrap.getAttributeValue("MIMETYPE");
if (mimeType != null && mimeType.equalsIgnoreCase("text/xml")) {
byte value[] = Base64.decodeBase64(bin.getText().getBytes());
Document mdd = parser.build(new ByteArrayInputStream(value));
List<Element> result = new ArrayList<Element>(1);
result.add(mdd.getRootElement());
return result;
} else {
log.warn("Ignoring binData section because MIMETYPE is not XML, but: " + mimeType);
return new ArrayList<Element>(0);
}
}
} else {
return xmlData.getChildren();
}
} else {
mdRef = mdSec.getChild("mdRef", metsNS);
if (mdRef != null) {
String mimeType = mdRef.getAttributeValue("MIMETYPE");
if (mimeType != null && mimeType.equalsIgnoreCase("text/xml")) {
Document mdd = parser.build(callback.getInputStream(mdRef));
List<Element> result = new ArrayList<Element>(1);
result.add(mdd.getRootElement());
return result;
} else {
log.warn("Ignoring mdRef section because MIMETYPE is not XML, but: " + mimeType);
return new ArrayList<Element>(0);
}
} else {
throw new MetadataValidationException("Invalid METS Manifest: ?mdSec element with neither mdRef nor mdWrap child.");
}
}
} catch (JDOMException je) {
throw new MetadataValidationException("Error parsing or validating metadata section in mdRef or binData within " + mdSec.toString(), je);
}
}Example 70
| Project: modello-master File: JDOMWriterGenerator.java View source code |
private void generateJDOMWriter() throws ModelloException, IOException {
Model objectModel = getModel();
String packageName = objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.jdom";
String marshallerName = getFileName("JDOMWriter");
JSourceWriter sourceWriter = newJSourceWriter(packageName, marshallerName);
JClass jClass = new JClass(packageName + '.' + marshallerName);
initHeader(jClass);
suppressAllWarnings(objectModel, jClass);
// -------------------------------------------------------------
// imports now
// -------------------------------------------------------------
jClass.addImport("java.io.OutputStream");
jClass.addImport("java.io.OutputStreamWriter");
jClass.addImport("java.io.Writer");
jClass.addImport("java.text.DateFormat");
jClass.addImport("java.util.ArrayList");
jClass.addImport("java.util.Collection");
jClass.addImport("java.util.Iterator");
jClass.addImport("java.util.List");
jClass.addImport("java.util.ListIterator");
jClass.addImport("java.util.Locale");
jClass.addImport("java.util.Map");
jClass.addImport("java.util.Properties");
jClass.addImport("org.jdom.Content");
jClass.addImport("org.jdom.DefaultJDOMFactory");
jClass.addImport("org.jdom.Document");
jClass.addImport("org.jdom.Element");
jClass.addImport("org.jdom.Text");
jClass.addImport("org.jdom.output.Format");
jClass.addImport("org.jdom.output.XMLOutputter");
addModelImports(jClass, null);
jClass.addField(new JField(new JClass("DefaultJDOMFactory"), "factory"));
jClass.addField(new JField(new JClass("String"), "lineSeparator"));
createCounter(jClass);
// constructor --
JConstructor constructor = jClass.createConstructor();
JSourceCode constCode = constructor.getSourceCode();
constCode.add("factory = new DefaultJDOMFactory();");
constCode.add("lineSeparator = \"\\n\";");
String root = objectModel.getRoot(getGeneratedVersion());
ModelClass rootClass = objectModel.getClass(root, getGeneratedVersion());
String rootElement = resolveTagName(rootClass);
// the public global write method..
jClass.addMethod(generateWriteModel(root, rootElement));
jClass.addMethod(generateWriteModel2(root, rootElement));
jClass.addMethod(generateWriteModel3(root, rootElement));
// the private utility classes;
jClass.addMethods(generateUtilityMethods());
writeAllClasses(objectModel, jClass, rootClass);
if (requiresDomSupport) {
jClass.addImport("org.codehaus.plexus.util.xml.Xpp3Dom");
jClass.addMethods(generateDomMethods());
}
jClass.print(sourceWriter);
sourceWriter.close();
}Example 71
| Project: MPS-master File: XmlConverter.java View source code |
private static SNode convertElement(Element elem) {
SNode result = SConceptOperations.createNewNode(MetaAdapterFactory.getConcept(0x479c7a8c02f943b5L, 0x9139d910cb22f298L, 0x5c842a42c54b10b2L, "jetbrains.mps.core.xml.structure.XmlElement"));
String namespacePrefix = elem.getNamespacePrefix();
SPropertyOperations.set(result, MetaAdapterFactory.getProperty(0x479c7a8c02f943b5L, 0x9139d910cb22f298L, 0x5c842a42c54b10b2L, 0x5c842a42c54b10b6L, "tagName"), ((namespacePrefix == null || namespacePrefix.length() == 0) ? elem.getName() : namespacePrefix + ":" + elem.getName()));
for (Attribute a : ListSequence.fromList((List<Attribute>) elem.getAttributes())) {
ListSequence.fromList(SLinkOperations.getChildren(result, MetaAdapterFactory.getContainmentLink(0x479c7a8c02f943b5L, 0x9139d910cb22f298L, 0x5c842a42c54b10b2L, 0x5c842a42c54b10b5L, "attributes"))).addElement(convertAttribute(a));
}
List<Namespace> additionalNamespaces = (List<Namespace>) elem.getAdditionalNamespaces();
for (Namespace ns : ListSequence.fromList(additionalNamespaces)) {
ListSequence.fromList(SLinkOperations.getChildren(result, MetaAdapterFactory.getContainmentLink(0x479c7a8c02f943b5L, 0x9139d910cb22f298L, 0x5c842a42c54b10b2L, 0x5c842a42c54b10b5L, "attributes"))).addElement(createXmlAttribute_h7fa2c_a0a0a5a3("xmlns:" + ns.getPrefix(), convertAttributeText(ns.getURI())));
}
List<Content> list = (List<Content>) elem.getContent();
Content[] contents = ListSequence.fromList(list).toGenericArray(Content.class);
for (int i = 0; i < contents.length; i++) {
Iterable<SNode> content = convertContent((i > 0 ? contents[i - 1] : null), contents[i], (i + 1 < contents.length ? contents[i + 1] : null));
if (content != null) {
ListSequence.fromList(SLinkOperations.getChildren(result, MetaAdapterFactory.getContainmentLink(0x479c7a8c02f943b5L, 0x9139d910cb22f298L, 0x5c842a42c54b10b2L, 0x16838b3fce9a4922L, "content"))).addSequence(Sequence.fromIterable(content));
}
}
SPropertyOperations.set(result, MetaAdapterFactory.getProperty(0x479c7a8c02f943b5L, 0x9139d910cb22f298L, 0x5c842a42c54b10b2L, 0x61218fae7b61b5d5L, "shortEmptyNotation"), "" + (elem.getContentSize() == 0));
return result;
}Example 72
| Project: DSpace-master File: METSManifest.java View source code |
/**
* Return contents of *md element as List of XML Element objects.
* Gets content, dereferencing mdRef if necessary, or decoding and parsing
* a binData that contains XML.
* @param mdSec mdSec element
* @param callback mdref callback
* @return contents of metadata section, or empty list if no XML content is available.
* @throws MetadataValidationException if METS is invalid, or there is an error parsing the XML.
* @throws PackageValidationException if invalid package
* @throws IOException if IO error
* @throws SQLException if database error
* @throws AuthorizeException if authorization error
*/
public List<Element> getMdContentAsXml(Element mdSec, Mdref callback) throws MetadataValidationException, PackageValidationException, IOException, SQLException, AuthorizeException {
try {
// XXX sanity check: if this has more than one child, consider it
// an error since we cannot deal with more than one mdRef|mdWrap
// child. This may be considered a bug and need to be fixed,
// so it's best to bring it to the attention of users.
List mdc = mdSec.getChildren();
if (mdc.size() > 1) {
// XXX scaffolding for debugging diagnosis; at least one
// XML parser stupidly includes newlines in prettyprinting
// as text content objects..
String id = mdSec.getAttributeValue("ID");
StringBuffer sb = new StringBuffer();
for (Iterator mi = mdc.iterator(); mi.hasNext(); ) {
sb.append(", ").append(((Content) mi.next()).toString());
}
throw new MetadataValidationException("Cannot parse METS with " + mdSec.getQualifiedName() + " element that contains more than one child, size=" + String.valueOf(mdc.size()) + ", ID=" + id + "Kids=" + sb.toString());
}
Element mdRef = null;
Element mdWrap = mdSec.getChild("mdWrap", metsNS);
if (mdWrap != null) {
Element xmlData = mdWrap.getChild("xmlData", metsNS);
if (xmlData == null) {
Element bin = mdWrap.getChild("binData", metsNS);
if (bin == null) {
throw new MetadataValidationException("Invalid METS Manifest: mdWrap element with neither xmlData nor binData child.");
} else // if binData is actually XML, return it; otherwise ignore.
{
String mimeType = mdWrap.getAttributeValue("MIMETYPE");
if (mimeType != null && mimeType.equalsIgnoreCase("text/xml")) {
byte value[] = Base64.decodeBase64(bin.getText().getBytes());
Document mdd = parser.build(new ByteArrayInputStream(value));
List<Element> result = new ArrayList<Element>(1);
result.add(mdd.getRootElement());
return result;
} else {
log.warn("Ignoring binData section because MIMETYPE is not XML, but: " + mimeType);
return new ArrayList<Element>(0);
}
}
} else {
return xmlData.getChildren();
}
} else {
mdRef = mdSec.getChild("mdRef", metsNS);
if (mdRef != null) {
String mimeType = mdRef.getAttributeValue("MIMETYPE");
if (mimeType != null && mimeType.equalsIgnoreCase("text/xml")) {
Document mdd = parser.build(callback.getInputStream(mdRef));
List<Element> result = new ArrayList<Element>(1);
result.add(mdd.getRootElement());
return result;
} else {
log.warn("Ignoring mdRef section because MIMETYPE is not XML, but: " + mimeType);
return new ArrayList<Element>(0);
}
} else {
throw new MetadataValidationException("Invalid METS Manifest: ?mdSec element with neither mdRef nor mdWrap child.");
}
}
} catch (JDOMException je) {
throw new MetadataValidationException("Error parsing or validating metadata section in mdRef or binData within " + mdSec.toString(), je);
}
}Example 73
| Project: felix-master File: MavenJDOMWriter.java View source code |
// -- void updateDistributionManagement(DistributionManagement, String, Counter, Element)
/**
* Method updateElement
*
* @param counter
* @param shouldExist
* @param name
* @param parent
*/
protected Element updateElement(Counter counter, Element parent, String name, boolean shouldExist) {
Element element = parent.getChild(name, parent.getNamespace());
if (element != null && shouldExist) {
counter.increaseCount();
}
if (element == null && shouldExist) {
element = factory.element(name, parent.getNamespace());
insertAtPreferredLocation(parent, element, counter);
counter.increaseCount();
}
if (!shouldExist && element != null) {
int index = parent.indexOf(element);
if (index > 0) {
Content previous = parent.getContent(index - 1);
if (previous instanceof Text) {
Text txt = (Text) previous;
if (txt.getTextTrim().length() == 0) {
parent.removeContent(txt);
}
}
}
parent.removeContent(element);
}
return element;
}Example 74
| Project: Maven-Archetype-master File: MavenJDOMWriter.java View source code |
// -- void updateDistributionManagement(DistributionManagement, String, Counter, Element)
/**
* Method updateElement.
*
* @param counter
* @param shouldExist
* @param name
* @param parent
*/
protected Element updateElement(Counter counter, Element parent, String name, boolean shouldExist) {
Element element = parent.getChild(name, parent.getNamespace());
if ((element != null) && shouldExist) {
counter.increaseCount();
}
if ((element == null) && shouldExist) {
element = factory.element(name, parent.getNamespace());
insertAtPreferredLocation(parent, element, counter);
counter.increaseCount();
}
if (!shouldExist && (element != null)) {
int index = parent.indexOf(element);
if (index > 0) {
Content previous = parent.getContent(index - 1);
if (previous instanceof Text) {
Text txt = (Text) previous;
if (txt.getTextTrim().length() == 0) {
parent.removeContent(txt);
}
}
}
parent.removeContent(element);
}
return element;
}Example 75
| Project: com.idega.content-master File: ThemeChangerBean.java View source code |
private Collection<Element> getExpandRegion() {
Collection<Element> c = new ArrayList<Element>();
// Region
Element region = new Element("div");
String regionName = "idegaThemeExpandRegion";
region.setAttribute("id", regionName);
Collection<Content> regionContent = new ArrayList<Content>();
regionContent.addAll(getCommentsCollection(regionName));
// Expander
Element expander = new Element("div");
expander.setText("idegaTheme");
expander.setAttribute("style", new StringBuffer("height:").append(THEME_HEIGHT).append("px;visibility:hidden").toString());
regionContent.add(expander);
region.addContent(regionContent);
c.add(region);
return c;
}Example 76
| Project: integrity-master File: XmlWriterTestCallback.java View source code |
/**
* Parses a comment into a list of {@link Content} elements. This takes care of URLs embedded in the comment.
*
* @param aCommment
* the a commment
* @return the list
*/
protected List<Content> parseComment(String aCommment) {
List<Content> tempList = new ArrayList<Content>();
tempList.add(new Text(aCommment));
outer: while (true) {
int i;
for (i = 0; i < tempList.size(); i++) {
Content tempElement = tempList.get(i);
if (tempElement instanceof Text) {
List<Content> tempInnerList = detectMarkdownURLs(((Text) tempElement).getText());
if (tempInnerList.size() > 1) {
tempList.remove(i);
tempList.addAll(i, tempInnerList);
break;
}
tempInnerList = detectSimpleURLs(((Text) tempElement).getText());
if (tempInnerList.size() > 1 || (tempInnerList.size() == 1 && !(tempInnerList.get(0) instanceof Text))) {
tempList.remove(i);
tempList.addAll(i, tempInnerList);
break;
}
}
}
if (i >= tempList.size()) {
break outer;
}
}
return tempList;
}Example 77
| Project: Zettelkasten-master File: DesktopData.java View source code |
/**
* This method retrieves the element of a modified entry. the modified
* entries' content is stored in a separated XML-Document (see
* {@link #modifiedEntries modifiedEntries}. each element of this document
* has a timestamp-attribute that equals the timestamp-attribute of an entry
* in the {@link #desktop desktop}-Document.
* <br><br>
* So, by passing a {@code timestamp} value, this method searches whether we
* have any modified entry that has the same timestamp-attribut, and if so,
* it returns that element which was modified (and thus differs from an
* entry's content as it is stored in the original database).
*
* @param timestamp the timestamp which should match the requested entry's
* timestamp-attribute
* @return the modified entry as element, or {@code null} if no entry was
* found.
*/
private Element retrieveModifiedEntryElementFromTimestamp(String timestamp) {
// retrieve all elements
List<Content> elementList = modifiedEntries.getRootElement().getContent();
// when we have any content, go on...
if (elementList.size() > 0) {
for (Content elementList1 : elementList) {
// retrieve each single element
Element e = (Element) elementList1;
// retrieve timestamp-attribute
String att = e.getAttributeValue(ATTR_TIMESTAMP);
// compare timestamp-attribute-value to timestamp-parameter
if (att != null && att.equals(timestamp)) {
// if they match, return that element
return e;
}
}
}
// else return null
return null;
}Example 78
| Project: geoserver-manager-master File: XmlElement.java View source code |
protected void add(final String nodename, final Content nodetext) {
final Element el = new Element(nodename);
el.setContent(nodetext);
this.addContent(el);
}Example 79
| Project: gocd-master File: GoControlLog.java View source code |
public void addContent(Content newContent) {
buildLog.addContent(newContent);
}Example 80
| Project: cruisecontrol-master File: Log.java View source code |
@SkipDoc
public void addContent(final Content newContent) {
buildLog.addContent(newContent);
}