/** * * @param atts * @param attribute * @param metadata * @param namespace * @param type * @return */ protected Object setMetadataXML(Element atts, String attribute, String metadata, Namespace namespace, Class<?> type) { Element o=atts.getChild(attribute, namespace); String value=null; Object val=null; if((atts != null) && (o != null)){ value=o.getText(); if(type==String.class){ val=value; setMetadata(metadata,(String)value); }else if(type==Integer.class){ val=Integer.parseInt(value); setMetadata(metadata, val); }else if(type==Double.class){ val=Double.parseDouble(value); setMetadata(metadata, val); }else if(type==Float.class){ val=Float.parseFloat(value); setMetadata(metadata, val); } } return val; }
private Content parseContent(Element e) { String value = null; String src = e.getAttributeValue("src");//getAtomNamespace()); DONT KNOW WHY DOESN'T WORK String type = e.getAttributeValue("type");//getAtomNamespace()); DONT KNOW WHY DOESN'T WORK type = (type!=null) ? type : Content.TEXT; if (type.equals(Content.TEXT)) { // do nothing XML Parser took care of this value = e.getText(); } else if (type.equals(Content.HTML)) { value = e.getText(); } else if (type.equals(Content.XHTML)) { XMLOutputter outputter = new XMLOutputter(); List eContent = e.getContent(); Iterator i = eContent.iterator(); while (i.hasNext()) { org.jdom.Content c = (org.jdom.Content) i.next(); if (c instanceof Element) { Element eC = (Element) c; if (eC.getNamespace().equals(getAtomNamespace())) { ((Element)c).setNamespace(Namespace.NO_NAMESPACE); } } } value = outputter.outputString(eContent); } Content content = new Content(); content.setSrc(src); content.setType(type); content.setValue(value); return content; }
public boolean isMyType(Document document) { boolean ok = false; Element rssRoot = document.getRootElement(); Namespace defaultNS = rssRoot.getNamespace(); List additionalNSs = rssRoot.getAdditionalNamespaces(); ok = defaultNS!=null && defaultNS.equals(getRDFNamespace()); if (ok) { if (additionalNSs==null) { ok = false; } else { ok = false; for (int i=0;!ok && i<additionalNSs.size();i++) { ok = getRSSNamespace().equals(additionalNSs.get(i)); } } } return ok; }
/** * Indicates if a JDom document is an RSS instance that can be parsed with the parser. * <p/> * It checks for RDF ("http://www.w3.org/1999/02/22-rdf-syntax-ns#") and * RSS ("http://purl.org/rss/1.0/") namespaces being defined in the root element. * * @param document document to check if it can be parsed with this parser implementation. * @return <b>true</b> if the document is RSS1., <b>false</b> otherwise. */ public boolean isMyType(Document document) { boolean ok = false; Element rssRoot = document.getRootElement(); Namespace defaultNS = rssRoot.getNamespace(); List additionalNSs = rssRoot.getAdditionalNamespaces(); ok = defaultNS!=null && defaultNS.equals(getRDFNamespace()); if (ok) { if (additionalNSs==null) { ok = false; } else { ok = false; for (int i=0;!ok && i<additionalNSs.size();i++) { ok = getRSSNamespace().equals(additionalNSs.get(i)); } } } return ok; }
private Content parseContent(Element e) { String value = null; String type = e.getAttributeValue("type");//getAtomNamespace()); DONT KNOW WHY DOESN'T WORK type = (type!=null) ? type : "text/plain"; String mode = e.getAttributeValue("mode");//getAtomNamespace())); DONT KNOW WHY DOESN'T WORK if (mode == null) { mode = Content.XML; // default to xml content } if (mode.equals(Content.ESCAPED)) { // do nothing XML Parser took care of this value = e.getText(); } else if (mode.equals(Content.BASE64)) { value = Base64.decode(e.getText()); } else if (mode.equals(Content.XML)) { XMLOutputter outputter = new XMLOutputter(); List eContent = e.getContent(); Iterator i = eContent.iterator(); while (i.hasNext()) { org.jdom.Content c = (org.jdom.Content) i.next(); if (c instanceof Element) { Element eC = (Element) c; if (eC.getNamespace().equals(getAtomNamespace())) { ((Element)c).setNamespace(Namespace.NO_NAMESPACE); } } } value = outputter.outputString(eContent); } Content content = new Content(); content.setType(type); content.setMode(mode); content.setValue(value); return content; }
/** * @param t_objdb * @param string * @throws IOException * @throws SQLException */ public void export(DBInterface a_objDB, String a_strFileName) throws IOException, SQLException { this.m_objDB = a_objDB; // Erzeugung eines XML-Dokuments Document t_objDocument = new Document(); // Erzeugung des Root-XML-Elements Element t_objRoot = new Element("defaults"); Namespace xsiNS = Namespace.getNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance"); t_objRoot.addNamespaceDeclaration(xsiNS); this.exportResidues(t_objRoot); this.exportPersubstitutions(t_objRoot); this.exportIons(t_objRoot); this.exportDericatisation(t_objRoot); this.exportMolecules(t_objRoot); // Und jetzt haengen wir noch das Root-Element an das Dokument t_objDocument.setRootElement(t_objRoot); // Damit das XML-Dokument schoen formattiert wird holen wir uns ein Format Format t_objFormat = Format.getPrettyFormat(); t_objFormat.setEncoding("iso-8859-1"); // Erzeugung eines XMLOutputters dem wir gleich unser Format mitgeben XMLOutputter t_objExportXML = new XMLOutputter(t_objFormat); // Schreiben der XML-Datei in einen String FileWriter t_objWriter = new FileWriter(a_strFileName); t_objExportXML.output(t_objDocument, t_objWriter ); }
private LyricsInfo parseSearchResult(String xml) throws Exception { SAXBuilder builder = new SAXBuilder(); Document document = builder.build(new StringReader(xml)); Element root = document.getRootElement(); Namespace ns = root.getNamespace(); String lyric = StringUtils.trimToNull(root.getChildText("Lyric", ns)); String song = root.getChildText("LyricSong", ns); String artist = root.getChildText("LyricArtist", ns); return new LyricsInfo(lyric, artist, song); }
private String getITunesElement(Element element, String childName) { for (Namespace ns : ITUNES_NAMESPACES) { String value = element.getChildTextTrim(childName, ns); if (value != null) { return value; } } return null; }
private String getITunesAttribute(Element element, String childName, String attributeName) { for (Namespace ns : ITUNES_NAMESPACES) { Element elem = element.getChild(childName, ns); if (elem != null) { return StringUtils.trimToNull(elem.getAttributeValue(attributeName)); } } return null; }
/** This method creates an AnnotationSchema object fom an org.jdom.Element * @param anElement is an XSchema element element */ private void createAnnotationSchemaObject(org.jdom.Element anElement, Namespace namespace){ // Get the value of the name attribute. If this attribute doesn't exists // then it will receive a default one. annotationName = anElement.getAttributeValue("name"); if (annotationName == null) annotationName = "UnknownElement"; // See if this element has a complexType element inside it org.jdom.Element complexTypeElement = anElement.getChild("complexType", namespace); if (complexTypeElement != null){ List<?> complexTypeCildrenList = complexTypeElement.getChildren("attribute", namespace); Iterator<?> complexTypeCildrenIterator = complexTypeCildrenList.iterator(); if (complexTypeCildrenIterator.hasNext()) featureSchemaSet = new LinkedHashSet<FeatureSchema>(); while (complexTypeCildrenIterator.hasNext()) { org.jdom.Element childElement = (org.jdom.Element) complexTypeCildrenIterator.next(); createAndAddFeatureSchemaObject(childElement, namespace); }// end while }// end if }
/** Use xml:base attributes at feed and entry level to resolve relative links */ private String resolveURI(URL baseURI, Parent parent, String url) { url = (url.equals(".") || url.equals("./")) ? "" : url; if (isRelativeURI(url) && parent != null && parent instanceof Element) { Attribute baseAtt = ((Element)parent).getAttribute("base", Namespace.XML_NAMESPACE); String xmlBase = (baseAtt == null) ? "" : baseAtt.getValue(); if (!isRelativeURI(xmlBase) && !xmlBase.endsWith("/")) { xmlBase = xmlBase.substring(0, xmlBase.lastIndexOf("/")+1); } return resolveURI(baseURI, parent.getParent(), xmlBase + url); } else if (isRelativeURI(url) && parent == null) { return baseURI + url; } else if (baseURI != null && url.startsWith("/")) { String hostURI = baseURI.getProtocol() + "://" + baseURI.getHost(); if (baseURI.getPort() != baseURI.getDefaultPort()) { hostURI = hostURI + ":" + baseURI.getPort(); } return hostURI + url; } return url; }
protected BaseWireFeedGenerator(String type) { _type = type; _feedModuleGenerators = new ModuleGenerators(type+FEED_MODULE_GENERATORS_POSFIX_KEY); _itemModuleGenerators = new ModuleGenerators(type+ITEM_MODULE_GENERATORS_POSFIX_KEY); Set allModuleNamespaces = new HashSet(); Iterator i = _feedModuleGenerators.getAllNamespaces().iterator(); while (i.hasNext()) { allModuleNamespaces.add(i.next()); } i = _itemModuleGenerators.getAllNamespaces().iterator(); while (i.hasNext()) { allModuleNamespaces.add(i.next()); } _allModuleNamespaces = new Namespace[allModuleNamespaces.size()]; allModuleNamespaces.toArray(_allModuleNamespaces); }
protected Element createRootElement(Feed feed) { Element root = new Element("feed",getFeedNamespace()); root.addNamespaceDeclaration(getFeedNamespace()); //Attribute version = new Attribute("version", getVersion()); //root.setAttribute(version); if (feed.getXmlBase() != null) { root.setAttribute("base", feed.getXmlBase(), Namespace.XML_NAMESPACE); } generateModuleNamespaceDefs(root); return root; }
private boolean hasElementsFrom(Element root,Namespace namespace) { boolean itHas = false; List children = root.getChildren(); for (int i=0;!itHas && i<children.size();i++) { Element child = (Element) children.get(i); itHas = namespace.equals(child.getNamespace()); } return itHas; }
public boolean isMyType(Document document) { Element rssRoot = document.getRootElement(); Namespace defaultNS = rssRoot.getNamespace(); boolean ok = defaultNS!=null && defaultNS.equals(getRSSNamespace()); if (ok) { ok = super.isMyType(document); } return ok; }
public static void write( Writer w, Model newModel, boolean namespaceDeclaration ) throws IOException { Element root = new Element( "project" ); if ( namespaceDeclaration ) { String modelVersion = newModel.getModelVersion(); Namespace pomNamespace = Namespace.getNamespace( "", "http://maven.apache.org/POM/" + modelVersion ); root.setNamespace( pomNamespace ); Namespace xsiNamespace = Namespace.getNamespace( "xsi", "http://www.w3.org/2001/XMLSchema-instance" ); root.addNamespaceDeclaration( xsiNamespace ); if ( root.getAttribute( "schemaLocation", xsiNamespace ) == null ) { root.setAttribute( "schemaLocation", "http://maven.apache.org/POM/" + modelVersion + " http://maven.apache.org/maven-v" + modelVersion.replace( '.', '_' ) + ".xsd", xsiNamespace ); } } Document doc = new Document( root ); MavenJDOMWriter writer = new MavenJDOMWriter(); String encoding = newModel.getModelEncoding() != null ? newModel.getModelEncoding() : "UTF-8"; Format format = Format.getPrettyFormat().setEncoding( encoding ); writer.write( newModel, doc, w, format ); }
protected void mapBiopax(PathwayElement o, Element e) throws ConverterException { //this method clones all content, //getContent will leave them attached to the parent, which we don't want //We can safely remove them, since the JDOM element isn't used anymore after this method Element root = new Element("RDF", GpmlFormat.RDF); root.addNamespaceDeclaration(GpmlFormat.RDFS); root.addNamespaceDeclaration(GpmlFormat.RDF); root.addNamespaceDeclaration(GpmlFormat.OWL); root.addNamespaceDeclaration(GpmlFormat.BIOPAX); root.setAttribute(new Attribute("base", getGpmlNamespace().getURI() + "#", Namespace.XML_NAMESPACE)); //Element owl = new Element("Ontology", OWL); //owl.setAttribute(new Attribute("about", "", RDF)); //Element imp = new Element("imports", OWL); //imp.setAttribute(new Attribute("resource", BIOPAX.getURI(), RDF)); //owl.addContent(imp); //root.addContent(owl); root.addContent(e.cloneContent()); Document bp = new Document(root); updateBiopaxNamespace(root); ((BiopaxElement)o).setBiopax(bp); }
protected void mapBiopax(PathwayElement o, Element e) throws ConverterException { //this method clones all content, //getContent will leave them attached to the parent, which we don't want //We can safely remove them, since the JDOM element isn't used anymore after this method Element root = new Element("RDF", GpmlFormat.RDF); root.addNamespaceDeclaration(GpmlFormat.RDFS); root.addNamespaceDeclaration(GpmlFormat.RDF); root.addNamespaceDeclaration(GpmlFormat.OWL); root.addNamespaceDeclaration(GpmlFormat.BIOPAX); root.setAttribute(new Attribute("base", getGpmlNamespace().getURI() + "#", Namespace.XML_NAMESPACE)); //Element owl = new Element("Ontology", OWL); //owl.setAttribute(new Attribute("about", "", RDF)); //Element imp = new Element("imports", OWL); //imp.setAttribute(new Attribute("resource", BIOPAX.getURI(), RDF)); //owl.addContent(imp); //root.addContent(owl); root.addContent(e.cloneContent()); Document bp = new Document(root); ((BiopaxElement)o).setBiopax(bp); }
public static String extractEPName(final Element extensionElement) { String epName = extensionElement.getAttributeValue("point"); if (epName == null) { final Element parentElement = extensionElement.getParentElement(); final String ns = parentElement != null ? parentElement.getAttributeValue("defaultExtensionNs"):null; if (ns != null) { epName = ns + '.' + extensionElement.getName(); } else { Namespace namespace = extensionElement.getNamespace(); epName = namespace.getURI() + '.' + extensionElement.getName(); } } return epName; }
public org.jdom.Element toElement(Namespace ns) { org.jdom.Element el = new org.jdom.Element(NAME_ELEM,ns); el.setAttribute(ID_ELEM,String.valueOf(ID)); el.setAttribute(EIID_ELEM, buildEiidString()); el.setAttribute(OFFSET_ELEM,String.valueOf(index)); el.setAttribute(STRING_ELEM,string()); el.setAttribute(TENSE_ELEM,tense.toString()); el.setAttribute(ASPECT_ELEM,aspect.toString()); el.setAttribute(CLASS_ELEM,theclass.toString()); el.setAttribute(POL_ELEM,polarity.toString()); el.setAttribute(MODAL_ELEM,modality); el.setAttribute(HAPPENED_ELEM,happened); el.setAttribute(LOWER_DURATION_ELEM,lowerDuration); el.setAttribute(UPPER_DURATION_ELEM,upperDuration); return el; }
@Test public void testConvertFullNestedInOAI() throws Exception { SAXBuilder builder = new SAXBuilder(); builder.setValidation(false); builder.setFeature("http://xml.org/sax/features/validation", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); InputStreamReader testIS = new InputStreamReader(ClassLoader.class.getResourceAsStream(testXmlNestedInOAI), "UTF-8"); Document document = builder.build(testIS); Element sourceDocument = document.getRootElement(); String testText = NlmToDocumentTextConverter.getDocumentText(sourceDocument, Namespace.getNamespace("http://www.openarchives.org/OAI/2.0/")); testIS.close(); InputStream expectedIS = ClassLoader.class.getResourceAsStream(testTxtNestedInOAI); String expectedText = IOUtils.toString(expectedIS, "UTF-8").replaceAll(System.getProperty("line.separator"), "\n"); expectedIS.close(); assertEquals(expectedText, testText); }
/** * Create a new <events> element in a single sentence. Fill it with the given events. */ public void addEvents(String docname, int sid, List<TextEvent> events) { docname = stripFile(docname); Namespace ns = Namespace.getNamespace(INFO_NS); Element mainfile = getFileElement(docname); // Check each sentence entry List<Element> children = mainfile.getChildren(ENTRY_ELEM,ns); Element targetSentenceElement = children.get(sid); // Add the events vector if( events != null ) { Element eventsElem = targetSentenceElement.getChild(EVENTS_ELEM,ns); if( eventsElem == null ) { eventsElem = new Element(EVENTS_ELEM,ns); targetSentenceElement.addContent(eventsElem); } for( TextEvent te : events ) eventsElem.addContent(te.toElement(ns)); } }
/** * Adds a list of tlinks to the XML file * @param tlinks Vector of TLink objects */ public void addTlinks(String file, List<TLink> tlinks) { file = stripFile(file); Namespace ns = Namespace.getNamespace(INFO_NS); Element root = jdomDoc.getRootElement(); // Find the file's Element Element mainfile = getFileElement(file); // Create a new file Element if we need to if( mainfile == null ) { System.out.println("InfoFile addTlinks new file = " + mainfile); mainfile = new Element(FILE_ELEM,ns); mainfile.setAttribute(FILENAME_ELEM,file); root.addContent(mainfile); } // Check for duplicates as we add for( TLink tlink : tlinks ) mainfile.addContent(tlink.toElement(ns)); }
/** * @return A Vector of all TLink objects (event-event and event-time) */ public Vector<TLink> getTlinks(String file, boolean noclosures) { file = stripFile(file); Namespace ns = Namespace.getNamespace(INFO_NS); Element mainfile = getFileElement(file); Vector<TLink> tlinks = new Vector<TLink>(); if( mainfile != null ) { List children = mainfile.getChildren(TLink.TLINK_ELEM,ns); for( Object obj : children ) { if( noclosures ) { // don't add closed links TLink link = tlinkFromElement((Element)obj); if( !link.isFromClosure() ) tlinks.add(link); } // add all links else tlinks.add(tlinkFromElement((Element)obj)); } } return tlinks; }
/** * @return A list of lists. * This is a list of sentences, each sentence is a list of CoreLabels with character information. */ public List<List<CoreLabel>> getTokens(String file) { file = stripFile(file); Namespace ns = Namespace.getNamespace(INFO_NS); Element mainfile = getFileElement(file); if( mainfile == null ) { System.err.println("Can't find file " + file + " in document."); return null; } List<List<CoreLabel>> tokens = new ArrayList<List<CoreLabel>>(); // Get each sentence entry. List<Element> children = mainfile.getChildren(ENTRY_ELEM,ns); for( Element obj : children ) { // Get the <tokens> element. Element ev = obj.getChild(TOKENS_ELEM,ns); String text = ev.getText(); // Map the string to CoreLabel objects. tokens.add(stringToCoreLabels(text)); } return tokens; }
/** * @return A Vector of TLink objects Event-Event, no Event-Time links */ public Vector<TLink> getTlinksOfType(String file, String type) { file = stripFile(file); Namespace ns = Namespace.getNamespace(INFO_NS); Element mainfile = getFileElement(file); if( mainfile == null ) { System.err.println("Can't find file " + file + " in document."); return null; } List children = mainfile.getChildren(TLink.TLINK_ELEM,ns); Vector<TLink> tlinks = new Vector<TLink>(); for( Object obj : children ) { Element el = (Element)obj; // return TLinks based on their type (e.g. event-event) // if( el.getAttributeValue(EventTimeLink.TIME_TLINK_ATT) == null ) if( el.getAttributeValue(TLink.TLINK_TYPE_ATT).equals(type) ) tlinks.add(new TLink(el)); } return tlinks; }
/** * Adds a list of TIMEX tags to the XML file * @param timexes Vector of Timex objects */ public void addTimexes(String file, Collection<Timex> timexes) { file = stripFile(file); Namespace ns = Namespace.getNamespace(INFO_NS); Element root = jdomDoc.getRootElement(); // Find the file's Element Element mainfile = getFileElement(file); // Create a new file Element if we need to if( mainfile == null ) { mainfile = new Element(FILE_ELEM,ns); mainfile.setAttribute(FILENAME_ELEM,file); root.addContent(mainfile); } for( Timex timex : timexes ) mainfile.addContent(timex.toElement(ns)); }
public List parseModules(Element root) { List parsers = getPlugins(); List modules = null; for (int i=0;i<parsers.size();i++) { ModuleParser parser = (ModuleParser) parsers.get(i); String namespaceUri = parser.getNamespaceUri(); Namespace namespace = Namespace.getNamespace(namespaceUri); if (hasElementsFrom(root, namespace)) { Module module = parser.parse(root); if (module != null) { if (modules == null) { modules = new ArrayList(); } modules.add(module); } } } return modules; }
/** * @return A file Element for an event in a sentence. */ private Element getEventElement(String filename, String eventID) { Namespace ns = Namespace.getNamespace(INFO_NS); Element fileobj = getFileElement(filename); // Check each sentence entry. List<Element> sentenceElements = fileobj.getChildren(ENTRY_ELEM, ns); for( Element obj : sentenceElements ) { Element ev = obj.getChild(EVENTS_ELEM,ns); // Check each event in this sentence. List<Element> localevents = ev.getChildren(TextEvent.NAME_ELEM, ns); for( Element child : localevents ) if( child.getAttributeValue(TextEvent.ID_ELEM).equalsIgnoreCase(eventID) ) return child; } return null; }
public void parseContent(DefaultHandler the_handler, CartridgeLoader the_cartridge, Element the_resource, boolean isProtected) throws ParseException { try { //ok, so we're looking at a discussion topic here... Element blti = getXML(the_cartridge, ((Element)the_resource.getChildren(FILE, the_handler.getNs().cc_ns()).get(0)).getAttributeValue(HREF)); log.info("blti="+blti); Namespace topicNs = the_handler.getNs().blti_ns(); the_handler.startLti(blti.getChildText(TITLE, topicNs), blti.getChild(TEXT, topicNs).getAttributeValue(TEXTTYPE), blti.getChildText(TEXT, topicNs), isProtected); the_handler.setLtiXml(blti); the_handler.endLti(); } catch (IOException e) { throw new ParseException(e); } }
/** * <p> * This returns the number of elements that are descendents of this element * and belonging to the specified Namespace. The resulting count excludes the * specified parent Element. * </p> * @param parent the JDOM <code>Element</code> to use as the root for a count. * @param ns the Namespace to match * @return the number of JDOM <code>Element</code>s nested within the parent */ public static int getDescendentCount( Element parent, final Namespace ns ) { if(parent == null){ ArgCheck.isNotNull(parent,CorePlugin.Util.getString("JdomHelper.The_JDOM_Element_reference_may_not_be_null_25")); //$NON-NLS-1$ } XMLVisitor visitor = new XMLVisitor() { public void visit( Object obj ) { if( ((Element)obj).getNamespace().equals(ns) ) { count++; } } }; levelOrderTraversal( parent, visitor); return visitor.count; }
/** * Get the best content value for a JDOM object. For elements, the content text is returned. * For attributes, the attribute value is returned. For namespaces, the URI is returned. Etc... * @param jdomObject JDOM object such as Element, Attribute, Text, Namespace, Comment, ProcessingInstruction, String * @return Content value for the specified JDOM object * @since 4.2 */ public static String getContentValue( Object jdomObject ) { if(jdomObject == null) { return null; } else if(jdomObject instanceof String) { return (String)jdomObject; } else if(jdomObject instanceof Element) { return ((Element)jdomObject).getText(); } else if(jdomObject instanceof Attribute) { return ((Attribute)jdomObject).getValue(); } else if(jdomObject instanceof Text) { return ((Text)jdomObject).getValue(); } else if(jdomObject instanceof Namespace) { return ((Namespace)jdomObject).getURI(); } else if(jdomObject instanceof Comment) { return ((Comment)jdomObject).getText(); } else if(jdomObject instanceof ProcessingInstruction) { return ((ProcessingInstruction)jdomObject).getData(); } // Default return jdomObject.toString(); }
/** * Converts a <code>Filter</code> to an XML element. * * @param filter * the <code>Filter</code> to serialize * @param namespace * the <code>Namespace</code> to use when constructing the * <code>Element</code> * @return an XML serialization of the <code>Filter</code> */ public static Element filterToElement(Filter filter, Namespace namespace) { Element filterElement = new Element(FILTER_ELEMENT, namespace); filterElement.setAttribute(NAME_ATTRIBUTE, filter.getName()); String value = filter.getValue(); if (filter.isBoolean()) { if ("excluded".equalsIgnoreCase(value)) { filterElement.setAttribute("excluded", "1"); } else { filterElement.setAttribute("excluded", "0"); } } else { if (value == null) { filterElement.setAttribute("value", ""); } else { filterElement.setAttribute("value", value); } } if (filter.isList()) { filterElement.setAttribute("list", "true"); } return filterElement; }
/** * Creates a <code>Query</code> from an XML element. * * @param element * the <code>Element</code> to deserialize * @param namespace * the <code>Namespace</code> containing the * <code>Element</code> * @return a deserialized <code>Query</code> */ public static Query elementToQuery(Element element, Namespace namespace) { String virtualSchema = element.getAttributeValue(SCHEMA_ATTRIBUTE); int count = Integer.parseInt(element.getAttributeValue(COUNT_ATTRIBUTE)); String version = element.getAttributeValue(VERSION_ATTRIBUTE); String formatter = element.getAttributeValue(FORMATTER_ATTRIBUTE); String requestId = element.getAttributeValue(REQUEST_ID_ATTRIBUTE); Query query = new Query(virtualSchema, count, version, requestId); query.setFormatter(formatter); String uniqueRows = element.getAttributeValue(UNIQUE_ROWS_ATTRIBUTE); if (uniqueRows != null) { query.setUniqueRows(Integer.parseInt(uniqueRows)); } List<Element> datasets = element.getChildren(DATASET_ELEMENT, namespace); for (Element datasetElement : datasets) { query.addDataset(elementToDataset(datasetElement, namespace)); } List<Element> links = element.getChildren(LINK_ELEMENT, namespace); for (Element linkElement : links) { query.addLink(elementToLink(linkElement)); } return query; }
/** * Provides article element as root element or nested inside oai record. * * @param source * @param oaiNamespace * @return article root element or child of oai:metadata element. */ private static Element getArticleElement(Element source, Namespace oaiNamespace) { Element metadata = source.getChild("metadata", oaiNamespace); if (metadata != null) { Element article = metadata.getChild("article"); if (article != null) { return article; } else { throw new RuntimeException("unexpected NLM record contents: " + "article element was not found inside OAI metadata element! Record dump: " + new XMLOutputter().outputString(source)); } } else { // source element is not wrapped with oai:metadata element return source; } }
/** * Converts a <code>MartDataset</code> to an XML element. * * @param dataset * the <code>MartDataset</code> to serialize * @param namespace * the <code>Namespace</code> to use when constructing the * <code>Element</code> * @return an XML serialization of the <code>MartDataset</code> */ public static Element datasetToElement(MartDataset dataset, Namespace namespace) { Element element = new Element(MART_DATASET_ELEMENT, namespace); element.setAttribute(DISPLAY_NAME_ATTRIBUTE, dataset.getDisplayName()); element.setAttribute(NAME_ATTRIBUTE, dataset.getName()); element.setAttribute(TYPE_ATTRIBUTE, dataset.getType()); element.setAttribute(INITIAL_BATCH_SIZE_ATTRIBUTE, String .valueOf(dataset.getInitialBatchSize())); element.setAttribute(MAXIMUM_BATCH_SIZE_ATTRIBUTE, String .valueOf(dataset.getMaximumBatchSize())); element.setAttribute(VISIBLE_ATTRIBUTE, String.valueOf(dataset .isVisible())); if (dataset.getInterface() != null) { element.setAttribute(INTERFACE_ATTRIBUTE, dataset.getInterface()); } if (dataset.getModified() != null) { element.setAttribute(MODIFIED_ATTRIBUTE, dataset.getModified()); } element.addContent(locationToElement(dataset.getMartURLLocation(), namespace)); return element; }
/** * Creates a <code>MartDataset</code> from an XML element. * * @param element * the <code>Element</code> to deserialize * @param namespace * the <code>Namespace</code> containing the * <code>Element</code> * @return a deserialized <code>MartDataset</code> */ public static MartDataset elementToDataset(Element element, Namespace namespace) { MartDataset dataset = new MartDataset(); dataset.setDisplayName(element .getAttributeValue(DISPLAY_NAME_ATTRIBUTE)); dataset.setName(element.getAttributeValue(NAME_ATTRIBUTE)); dataset.setType(element.getAttributeValue(TYPE_ATTRIBUTE)); dataset.setInitialBatchSize(Long.parseLong(element .getAttributeValue(INITIAL_BATCH_SIZE_ATTRIBUTE))); dataset.setMaximumBatchSize(Long.parseLong(element .getAttributeValue(MAXIMUM_BATCH_SIZE_ATTRIBUTE))); dataset.setVisible(Boolean.getBoolean(element .getAttributeValue(VISIBLE_ATTRIBUTE))); dataset.setInterface(element.getAttributeValue(INTERFACE_ATTRIBUTE)); dataset.setModified(element.getAttributeValue(MODIFIED_ATTRIBUTE)); dataset.setMartURLLocation(elementToLocation(element.getChild( MART_URL_LOCATION_ELEMENT, namespace))); return dataset; }
/** * Converts a <code>MartQuery</code> to an XML element. * * @param martQuery * the <code>MartQuery</code> to serialize * @param namespace * the <code>Namespace</code> to use when constructing the * <code>Element</code> * @return an XML serialization of the <code>MartQuery</code> */ public static Element martQueryToElement(MartQuery martQuery, Namespace namespace) { Element element = new Element(MART_QUERY_ELEMENT, namespace); element.addContent(martServiceToElement(martQuery.getMartService(), namespace)); element.addContent(datasetToElement(martQuery.getMartDataset(), namespace)); element.addContent(QueryXMLHandler.queryToElement(martQuery.getQuery(), namespace)); Set linkedDatasets = martQuery.getLinkedDatasets(); if (linkedDatasets.size() > 0) { Element linksElement = new Element(LINKED_DATASETS_ELEMENT, namespace); for (Iterator iter = linkedDatasets.iterator(); iter.hasNext();) { String datasetName = (String) iter.next(); Element datasetElement = new Element(LINKED_DATASETS_ELEMENT, namespace); datasetElement.setAttribute(NAME_ATTRIBUTE, datasetName); datasetElement.setAttribute(LINK_ATTRIBUTE, martQuery .getLink(datasetName)); linksElement.addContent(datasetElement); } element.addContent(linksElement); } return element; }
private static void populateElement(Element element, TypeDescriptor descriptor) { element.setAttribute("optional", String .valueOf(descriptor.isOptional())); element.setAttribute("unbounded", String.valueOf(descriptor .isUnbounded())); if (descriptor instanceof ArrayTypeDescriptor) { element.setAttribute("wrapped", String .valueOf(((ArrayTypeDescriptor) descriptor).isWrapped())); } element.setAttribute("typename", descriptor.getType()); element.setAttribute("name", descriptor.getName() == null ? "" : descriptor.getName()); element.setAttribute("qname", descriptor.getQname().toString()); if (descriptor.getDocumentation() != null){ Element annotationElement = new Element("annotation", Namespace.getNamespace("xsd", "http://www.w3.org/2001/XMLSchema")); Element documentationElemenet = new Element("documentation", Namespace.getNamespace("xsd", "http://www.w3.org/2001/XMLSchema")); documentationElemenet.setText(descriptor.getDocumentation()); annotationElement.addContent(documentationElemenet); element.addContent(annotationElement); } }