How to replace <w:sdt> Xml in Word Doc using Apache POI as XWPFSDT and XWPFSDTContent object is read-only - apache-poi

In previous code we would use XWPFSParagraph and Runs to find Merge Tokens that we would replace with data in our database. However, now we need to use Content Controls and do the same thing. The problem with Paragraph and Runs is that Content controls do not appear as a single run, like a Merge Token would. And we need to get the content control title to act like a Merge Token name would be so we know where to find the data in the database, and then replace it in the document. In Content Controls we wouldn't be replacing the Content Control with the data from the db, but we would have to set the Text value in the <w:sdtContentControl> with that data.
I thought about converting the <x:sdt> object into the xml text, but then it is now removed from the Poi object because it is now a string on its own.
So I was thinking of finding the <x:sdt> and fully replacing it with a new one where each part of it would be the same except the part in the <w:sdtContentControl> section. Is this possible? Any recommendations on how to use Poi to "modify" the sdt we get from the Word doc?

XWPFSDT as well as XWPFSDTCell are in experimental state up to now. They don't even have access to their underlying CTSdtBlock, CTSdtRun and CTSdtCell classes. I don't know why. So extending them to provide writing into the CTSdtBlock, CTSdtRun or CTSdtCell is not possible. If that is the need, then a new class is needed which can be created from any kind of Word SDT content control object. This class SDTContentControl could look like so:
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentBlock;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentCell;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.impl.values.XmlObjectBase;
import javax.xml.namespace.QName;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class SDTContentControl {
private XmlObject object = null;
public SDTContentControl(XmlObject object) {
this.object = object;
}
public String getTitle() {
if (this.object instanceof CTSdtBlock) {
CTSdtBlock ctSdtBlock = (CTSdtBlock)this.object;
if (ctSdtBlock.isSetSdtPr()) {
if (ctSdtBlock.getSdtPr().isSetAlias()) {
return ctSdtBlock.getSdtPr().getAlias().getVal();
}
}
} else if (this.object instanceof CTSdtRun) {
CTSdtRun ctSdtRun = (CTSdtRun)this.object;
if (ctSdtRun.isSetSdtPr()) {
if (ctSdtRun.getSdtPr().isSetAlias()) {
return ctSdtRun.getSdtPr().getAlias().getVal();
}
}
} else if (this.object instanceof CTSdtCell) {
CTSdtCell ctSdtCell = (CTSdtCell)this.object;
if (ctSdtCell.isSetSdtPr()) {
if (ctSdtCell.getSdtPr().isSetAlias()) {
return ctSdtCell.getSdtPr().getAlias().getVal();
}
}
}
return null;
}
public String getTag() {
if (this.object instanceof CTSdtBlock) {
CTSdtBlock ctSdtBlock = (CTSdtBlock)this.object;
if (ctSdtBlock.isSetSdtPr()) {
if (ctSdtBlock.getSdtPr().isSetTag()) {
return ctSdtBlock.getSdtPr().getTag().getVal();
}
}
} else if (this.object instanceof CTSdtRun) {
CTSdtRun ctSdtRun = (CTSdtRun)this.object;
if (ctSdtRun.isSetSdtPr()) {
if (ctSdtRun.getSdtPr().isSetTag()) {
return ctSdtRun.getSdtPr().getTag().getVal();
}
}
} else if (this.object instanceof CTSdtCell) {
CTSdtCell ctSdtCell = (CTSdtCell)this.object;
if (ctSdtCell.isSetSdtPr()) {
if (ctSdtCell.getSdtPr().isSetTag()) {
return ctSdtCell.getSdtPr().getTag().getVal();
}
}
}
return null;
}
public String getContentText() {
XmlObject[] sdtContents = this.object.selectPath(
"declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' "
+".//w:sdtContent");
for (XmlObject sdtContent : sdtContents) {
if (sdtContent instanceof XmlObjectBase) {
return ((XmlObjectBase)sdtContent).getStringValue();
}
}
return null;
}
public void setContent(String text) {
if (this.object instanceof CTSdtBlock) {
CTSdtBlock ctSdtBlock = (CTSdtBlock)this.object;
if (ctSdtBlock.isSetSdtContent()) {
CTSdtContentBlock sdtContentBlock = ctSdtBlock.getSdtContent();
CTP ctP = sdtContentBlock.getPArray(0); if (ctP == null) ctP = CTP.Factory.newInstance();
for (int r = ctP.getRList().size()-1; r >= 0 ; r--) ctP.removeR(r);
CTR ctR = ctP.addNewR();
if (ctSdtBlock.isSetSdtPr()) {
if (ctSdtBlock.getSdtPr().isSetRPr()) {
ctR.setRPr(ctSdtBlock.getSdtPr().getRPr());
}
}
CTText ctText = ctR.addNewT();
ctText.setStringValue(text);
sdtContentBlock.setPArray(new CTP[]{ctP});
}
} else if (this.object instanceof CTSdtRun) {
CTSdtRun ctSdtRun = (CTSdtRun)this.object;
if (ctSdtRun.isSetSdtContent()) {
CTSdtContentRun sdtContentRun = ctSdtRun.getSdtContent();
CTR ctR = CTR.Factory.newInstance();
if (ctSdtRun.isSetSdtPr()) {
if (ctSdtRun.getSdtPr().isSetRPr()) {
ctR.setRPr(ctSdtRun.getSdtPr().getRPr());
}
}
CTText ctText = ctR.addNewT();
ctText.setStringValue(text);
sdtContentRun.setRArray(new CTR[]{ctR});
}
} else if (this.object instanceof CTSdtCell) {
CTSdtCell ctSdtCell = (CTSdtCell)this.object;
if (ctSdtCell.isSetSdtContent()) {
CTSdtContentCell sdtContentCell = ctSdtCell.getSdtContent();
for (int c = 0; c < sdtContentCell.getTcList().size(); c++) {
CTTc ctTc = sdtContentCell.getTcList().get(c);
CTP ctP = ctTc.getPArray(0); if (ctP == null) ctP = CTP.Factory.newInstance();
for (int r = ctP.getRList().size()-1; r >= 0 ; r--) ctP.removeR(r);
CTR ctR = ctP.addNewR();
if (ctSdtCell.isSetSdtPr()) {
if (ctSdtCell.getSdtPr().isSetRPr()) {
ctR.setRPr(ctSdtCell.getSdtPr().getRPr());
}
}
CTText ctText = ctR.addNewT();
ctText.setStringValue(text);
ctTc.setPArray(new CTP[]{ctP});
}
}
}
}
public void setContent(Calendar calendar) {
String dateFormat = "yyyy-MM-dd";
if (this.object instanceof CTSdtBlock) {
CTSdtBlock ctSdtBlock = (CTSdtBlock)this.object;
if (ctSdtBlock.isSetSdtPr()) {
if (ctSdtBlock.getSdtPr().isSetDate()) {
if (ctSdtBlock.getSdtPr().getDate().isSetDateFormat()) {
dateFormat = ctSdtBlock.getSdtPr().getDate().getDateFormat().getVal();
}
ctSdtBlock.getSdtPr().getDate().setFullDate(calendar);
}
}
} else if (this.object instanceof CTSdtRun) {
CTSdtRun ctSdtRun = (CTSdtRun)this.object;
if (ctSdtRun.isSetSdtPr()) {
if (ctSdtRun.getSdtPr().isSetDate()) {
if (ctSdtRun.getSdtPr().getDate().isSetDateFormat()) {
dateFormat = ctSdtRun.getSdtPr().getDate().getDateFormat().getVal();
}
ctSdtRun.getSdtPr().getDate().setFullDate(calendar);
}
}
} else if (this.object instanceof CTSdtCell) {
CTSdtCell ctSdtCell = (CTSdtCell)this.object;
if (ctSdtCell.isSetSdtPr()) {
if (ctSdtCell.getSdtPr().isSetDate()) {
if (ctSdtCell.getSdtPr().getDate().isSetDateFormat()) {
dateFormat = ctSdtCell.getSdtPr().getDate().getDateFormat().getVal();
}
ctSdtCell.getSdtPr().getDate().setFullDate(calendar);
}
}
}
SimpleDateFormat simpledDateFormat = new SimpleDateFormat(dateFormat);
String text = simpledDateFormat.format(calendar.getTime());
this.setContent(text);
}
public void setContent(BigDecimal value) {
DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");
String text = decimalFormat.format(value.doubleValue());
this.setContent(text);
}
public void setContent(Object content) {
if (content instanceof String) {
this.setContent((String)content);
} else if (content instanceof Calendar) {
this.setContent((Calendar)content);
} else if (content instanceof BigDecimal) {
this.setContent((BigDecimal)content);
//} else if (content instanceof ...) {
//ToDo
} else {
this.setContent(String.valueOf(content));
}
}
}
A list of all SDT content control objects can be created from a XWPFDocument like so:
...
/*modifiers*/ List<SDTContentControl> extractSDTsFromBody(XWPFDocument document) {
SDTContentControl sdt;
XmlCursor xmlcursor = document.getDocument().getBody().newCursor();
QName qnameSdt = new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "sdt", "w");
List<SDTContentControl> allsdts = new ArrayList<SDTContentControl>();
while (xmlcursor.hasNextToken()) {
XmlCursor.TokenType tokentype = xmlcursor.toNextToken();
if (tokentype.isStart()) {
if (qnameSdt.equals(xmlcursor.getName())) {
if (xmlcursor.getObject() instanceof XmlObject) {
sdt = new SDTContentControl((XmlObject)xmlcursor.getObject());
allsdts.add(sdt);
}
}
}
}
return allsdts;
}
...
The SDTContentControl provides methods to get the content control title, the content control tag and the content control text content. It also provides a method to set the content control content from any kind of Object.
Complete example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import java.util.List;
import java.util.ArrayList;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import javax.xml.namespace.QName;
import java.util.GregorianCalendar;
import java.math.BigDecimal;
public class WordFillContentControls {
private static List<SDTContentControl> extractSDTsFromBody(XWPFDocument document) {
SDTContentControl sdt;
XmlCursor xmlcursor = document.getDocument().getBody().newCursor();
QName qnameSdt = new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "sdt", "w");
List<SDTContentControl> allsdts = new ArrayList<SDTContentControl>();
while (xmlcursor.hasNextToken()) {
XmlCursor.TokenType tokentype = xmlcursor.toNextToken();
if (tokentype.isStart()) {
if (qnameSdt.equals(xmlcursor.getName())) {
if (xmlcursor.getObject() instanceof XmlObject) {
sdt = new SDTContentControl((XmlObject)xmlcursor.getObject());
allsdts.add(sdt);
}
}
}
}
return allsdts;
}
public static void main(String[] args) throws Exception {
String[] contentControlTags = new String[]{
"NameTag", "GenderTag", "DateTag", "AmountTag",
"DescriptionTag", "Col1Tag", "Col2Tag",
"Col1DateTag", "Col2ChooseTag"
};
Object[] contents = new Object[]{
"Axel Richter", "male", new GregorianCalendar(2022, 0, 1), BigDecimal.valueOf(1234.56),
"Lorem ipsum semit dolor ... dolor semit ...", "Blah blah", "Blubb blubb",
new GregorianCalendar(1964, 11, 21), "My choice"
};
XWPFDocument document = new XWPFDocument(new FileInputStream("./WordFormContentControl.docx"));
List<SDTContentControl> allsdts = extractSDTsFromBody(document);
for (SDTContentControl sdt : allsdts) {
//System.out.println(sdt);
String title = sdt.getTitle();
String tag = sdt.getTag();
String content = sdt.getContentText();
System.out.println(title + ": " + tag + ": " + content);
for (int i = 0; i < contentControlTags.length; i++) {
String tagToReplace = contentControlTags[i];
if (tagToReplace.equals(tag)) {
Object contentO = contents[i];
sdt.setContent(contentO);
}
}
}
allsdts = extractSDTsFromBody(document);
for (SDTContentControl sdt : allsdts) {
String title = sdt.getTitle();
String tag = sdt.getTag();
String content = sdt.getContentText();
System.out.println(title + ": " + tag + ": " + content);
}
FileOutputStream out = new FileOutputStream("./WordFormContentControlResult.docx");
document.write(out);
out.close();
document.close();
}
}

Related

How to change the content of the table in the Text box of docX file

How to change the content of the table in the Text box of docX file?When xmlcursor.getobject () instanceof XmlAnyTypeImpl is instanceof XmlAnyTypeImpl, I cannot change the contents of the table in the text box. How can I change the contents of the table in the text box?Here's my code, but he can't change it properly。
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl;
import org.apache.xmlbeans.XmlCursor;
import javax.xml.namespace.QName;
import java.util.List;
import java.util.ArrayList;
public class WordReadAllTables {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument(new FileInputStream(System.getProperty("user.dir") + "\\template\\" + "test.docx"));
CTBody ctbody = document.getDocument().getBody();
XmlCursor xmlcursor = ctbody.newCursor();
QName qnameTbl = new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "tbl", "w");
QName qnameFallback = new QName("http://schemas.openxmlformats.org/markup-compatibility/2006", "Fallback", "mc");
List<CTTbl> allCTTbls = new ArrayList<CTTbl>();
while (xmlcursor.hasNextToken()) {
XmlCursor.TokenType tokentype = xmlcursor.toNextToken();
if (tokentype.isStart()) {
if (qnameTbl.equals(xmlcursor.getName())) {
if (xmlcursor.getObject() instanceof CTTbl) {
allCTTbls.add((CTTbl) xmlcursor.getObject());
} else if (xmlcursor.getObject() instanceof XmlAnyTypeImpl) {
allCTTbls.add(CTTbl.Factory.parse(xmlcursor.getObject().toString()));
}
} else if (qnameFallback.equals(xmlcursor.getName())) {
xmlcursor.toEndToken();
}
}
}
for (CTTbl cTTbl : allCTTbls) {
StringBuffer tableHTML = new StringBuffer();
tableHTML.append("<table>\n");
for (CTRow cTRow : cTTbl.getTrList()) {
for (CTTc cTTc : cTRow.getTcList()) {
for (CTP cTP : cTTc.getPList()) {
for (CTR cTR : cTP.getRList()) {
for (CTText cTText : cTR.getTList()) {
tableHTML.append(cTText.getStringValue() + "-");
if (cTText.getStringValue().contains("select")) {
cTText.setStringValue("1111");
}
}
}
}
}
}
}
FileOutputStream stream = new FileOutputStream(new File("D://aa.docx"));
document.write(stream);
stream.close();
document.close();
}
}

How can I read the schema (XSD) from Saxon after loading an XML & XSD file?

Our program displays a tree control showing the metadata structure of the XML file they are using as a datasource. So it displays all elements & attributes in use in the XML file, like this:
Employees
Employee
FirstName
LastName
Orders
Order
OrderId
For the case where the user does not pass us a XSD file, we need to walk the XML file and build up the metadata structure.
The full code for this is at SaxonQuestions.zip, TestBuildTreeWithSchema.java and is also listed below.
The below code works but it has a problem. Suppose under Employee there's an element for SpouseName. This is only populated if the employee is married. What if the sample data file I have is all unmarried employees? Then the below code does not know there's a SpouseName element.
So my question is - how can I read the schema directly, instead of using the below code. If I read the schema then I get every node & attribute including the optional ones. I also get the type. And the schema optionally has a description for each node and I get that too.
Therefore, I need to read the schema itself. How can I do that?
And secondary question - why is the type for an int BigInteger instead of Integer or Long? I see this with Employee/#EmployeeID in Southwind.xml & Southwind.xsd.
TestBuildTreeWithSample.java
import net.sf.saxon.s9api.*;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
public class TestBuildTreeWithSchema {
public static void main(String[] args) throws Exception {
XmlDatasource datasource = new XmlDatasource(
new FileInputStream(new File("files", "SouthWind.xml").getCanonicalPath()),
new FileInputStream(new File("files", "SouthWind.xsd").getCanonicalPath()));
// get the root element
XdmNode rootNode = null;
for (XdmNode node : datasource.getXmlRootNode().children()) {
if (node.getNodeKind() == XdmNodeKind.ELEMENT) {
rootNode = node;
break;
}
}
TestBuildTreeWithSchema buildTree = new TestBuildTreeWithSchema(rootNode);
Element root = buildTree.addNode();
System.out.println("Schema:");
printElement("", root);
}
private static void printElement(String indent, Element element) {
System.out.println(indent + "<" + element.name + "> (" + (element.type == null ? "null" : element.type.getSimpleName()) + ")");
indent += " ";
for (Attribute attr : element.attributes)
System.out.println(indent + "=" + attr.name + " (" + (attr.type == null ? "null" : attr.type.getSimpleName()) + ")");
for (Element child : element.children)
printElement(indent, child);
}
protected XdmItem currentNode;
public TestBuildTreeWithSchema(XdmItem currentNode) {
this.currentNode = currentNode;
}
private Element addNode() throws SaxonApiException {
String name = ((XdmNode)currentNode).getNodeName().getLocalName();
// Question:
// Is this the best way to determine that this element has data (as opposed to child elements)?
Boolean elementHasData;
try {
((XdmNode) currentNode).getTypedValue();
elementHasData = true;
} catch (Exception ex) {
elementHasData = false;
}
// Questions:
// Is this the best way to get the type of the element value?
// Why BigInteger instead of Long for int?
Class valueClass = ! elementHasData ? null : ((XdmAtomicValue)((XdmNode)currentNode).getTypedValue()).getValue().getClass();
Element element = new Element(name, valueClass, null);
// add in attributes
XdmSequenceIterator currentSequence;
if ((currentSequence = moveTo(Axis.ATTRIBUTE)) != null) {
do {
name = ((XdmNode) currentNode).getNodeName().getLocalName();
// Questions:
// Is this the best way to get the type of the attribute value?
// Why BigInteger instead of Long for int?
valueClass = ((XdmAtomicValue)((XdmNode)currentNode).getTypedValue()).getValue().getClass();
Attribute attr = new Attribute(name, valueClass, null);
element.attributes.add(attr);
} while (moveToNextInCurrentSequence(currentSequence));
moveTo(Axis.PARENT);
}
// add in children elements
if ((currentSequence = moveTo(Axis.CHILD)) != null) {
do {
Element child = addNode();
// if we don't have this, add it
Element existing = element.getChildByName(child.name);
if (existing == null)
element.children.add(child);
else
// add in any children this does not have
existing.addNewItems (child);
} while (moveToNextInCurrentSequence(currentSequence));
moveTo(Axis.PARENT);
}
return element;
}
// moves to element or attribute
private XdmSequenceIterator moveTo(Axis axis) {
XdmSequenceIterator en = ((XdmNode) currentNode).axisIterator(axis);
boolean gotIt = false;
while (en.hasNext()) {
currentNode = en.next();
if (((XdmNode) currentNode).getNodeKind() == XdmNodeKind.ELEMENT || ((XdmNode) currentNode).getNodeKind() == XdmNodeKind.ATTRIBUTE) {
gotIt = true;
break;
}
}
if (gotIt) {
if (axis == Axis.ATTRIBUTE || axis == Axis.CHILD || axis == Axis.NAMESPACE)
return en;
return null;
}
return null;
}
// moves to next element or attribute
private Boolean moveToNextInCurrentSequence(XdmSequenceIterator currentSequence)
{
if (currentSequence == null)
return false;
while (currentSequence.hasNext())
{
currentNode = currentSequence.next();
if (((XdmNode)currentNode).getNodeKind() == XdmNodeKind.ELEMENT || ((XdmNode)currentNode).getNodeKind() == XdmNodeKind.ATTRIBUTE)
return true;
}
return false;
}
static class Node {
String name;
Class type;
String description;
public Node(String name, Class type, String description) {
this.name = name;
this.type = type;
this.description = description;
}
}
static class Element extends Node {
List<Element> children;
List<Attribute> attributes;
public Element(String name, Class type, String description) {
super(name, type, description);
children = new ArrayList<>();
attributes = new ArrayList<>();
}
public Element getChildByName(String name) {
for (Element child : children) {
if (child.name.equals(name))
return child;
}
return null;
}
public void addNewItems(Element child) {
for (Attribute attrAdd : child.attributes) {
boolean haveIt = false;
for (Attribute attrExist : attributes)
if (attrExist.name.equals(attrAdd.name)) {
haveIt = true;
break;
}
if (!haveIt)
attributes.add(attrAdd);
}
for (Element elemAdd : child.children) {
Element exist = null;
for (Element elemExist : children)
if (elemExist.name.equals(elemAdd.name)) {
exist = elemExist;
break;
}
if (exist == null)
children.add(elemAdd);
else
exist.addNewItems(elemAdd);
}
}
}
static class Attribute extends Node {
public Attribute(String name, Class type, String description) {
super(name, type, description);
}
}
}
XmlDatasource.java
import com.saxonica.config.EnterpriseConfiguration;
import com.saxonica.ee.s9api.SchemaValidatorImpl;
import net.sf.saxon.Configuration;
import net.sf.saxon.lib.FeatureKeys;
import net.sf.saxon.s9api.*;
import net.sf.saxon.type.SchemaException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
public class XmlDatasource {
/** the DOM all searches are against */
private XdmNode xmlRootNode;
private XPathCompiler xPathCompiler;
/** key == the prefix; value == the uri mapped to that prefix */
private HashMap<String, String> prefixToUriMap = new HashMap<>();
/** key == the uri mapped to that prefix; value == the prefix */
private HashMap<String, String> uriToPrefixMap = new HashMap<>();
public XmlDatasource (InputStream xmlData, InputStream schemaFile) throws SAXException, SchemaException, SaxonApiException, IOException {
boolean haveSchema = schemaFile != null;
// call this before any instantiation of Saxon classes.
Configuration config = createEnterpriseConfiguration();
if (haveSchema) {
Source schemaSource = new StreamSource(schemaFile);
config.addSchemaSource(schemaSource);
}
Processor processor = new Processor(config);
DocumentBuilder doc_builder = processor.newDocumentBuilder();
XMLReader reader = createXMLReader();
InputSource xmlSource = new InputSource(xmlData);
SAXSource saxSource = new SAXSource(reader, xmlSource);
if (haveSchema) {
SchemaValidator validator = new SchemaValidatorImpl(processor);
doc_builder.setSchemaValidator(validator);
}
xmlRootNode = doc_builder.build(saxSource);
xPathCompiler = processor.newXPathCompiler();
if (haveSchema)
xPathCompiler.setSchemaAware(true);
declareNameSpaces();
}
public XdmNode getXmlRootNode() {
return xmlRootNode;
}
public XPathCompiler getxPathCompiler() {
return xPathCompiler;
}
/**
* Create a XMLReader set to disallow XXE aattacks.
* #return a safe XMLReader.
*/
public static XMLReader createXMLReader() throws SAXException {
XMLReader reader = XMLReaderFactory.createXMLReader();
// stop XXE https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#JAXP_DocumentBuilderFactory.2C_SAXParserFactory_and_DOM4J
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
return reader;
}
private void declareNameSpaces() throws SaxonApiException {
// saxon has some of their functions set up with this.
prefixToUriMap.put("saxon", "http://saxon.sf.net");
uriToPrefixMap.put("http://saxon.sf.net", "saxon");
XdmValue list = xPathCompiler.evaluate("//namespace::*", xmlRootNode);
if (list == null || list.size() == 0)
return;
for (int index=0; index<list.size(); index++) {
XdmNode node = (XdmNode) list.itemAt(index);
String prefix = node.getNodeName() == null ? "" : node.getNodeName().getLocalName();
// xml, xsd, & xsi are XML structure ones, not ones used in the XML
if (prefix.equals("xml") || prefix.equals("xsd") || prefix.equals("xsi"))
continue;
// use default prefix if prefix is empty.
if (prefix == null || prefix.isEmpty())
prefix = "def";
// this returns repeats, so if a repeat, go on to next.
if (prefixToUriMap.containsKey(prefix))
continue;
String uri = node.getStringValue();
if (uri != null && !uri.isEmpty()) {
xPathCompiler.declareNamespace(prefix, uri);
prefixToUriMap.put(prefix, uri);
uriToPrefixMap.put(uri, prefix); }
}
}
public static EnterpriseConfiguration createEnterpriseConfiguration()
{
EnterpriseConfiguration configuration = new EnterpriseConfiguration();
configuration.supplyLicenseKey(new BufferedReader(new java.io.StringReader(deobfuscate(key))));
configuration.setConfigurationProperty(FeatureKeys.SUPPRESS_XPATH_WARNINGS, Boolean.TRUE);
return configuration;
}
}
Thanks for the clarifications. I think your real goal is to find a way to parse and process an XML Schema in Java without having to treat the XSD as an ordinary XML document (it is an ordinary XML document, but processing it using the standard facilities is not easy).
On that basis, I think this thread should help: In Java, how do I parse an xml schema (xsd) to learn what's valid at a given element?
Personally, I've never found any library that does a better job than the EMF XSD model. It's complex, but comprehensive.

download XSD with all imports

I use gml (3.1.1) XSDs in XSD for my application. I want to download all gml XSDs in version 3.1.1 in for example zip file. In other words: base xsd is here and I want to download this XSD with all imports in zip file or something like zip file. Is there any application which supports that?
I've found this downloader but it doesn't works for me (I think that this application is not supporting relative paths in imports which occurs in gml.xsd 3.1.1). Any ideas?
QTAssistant's XSR (I am associated with it) has an easy to use function that allows one to automatically import and refactor XSD content as local files from all sorts of sources. In the process it'll update schema location references, etc.
I've made a simple screen capture of the steps involved in achieving a task like this which should demonstrate its usability.
Based on the solution of mschwehl, I made an improved class to achieve the fetch. It suited well with the question. See https://github.com/mfalaize/schema-fetcher
You can achieve this using SOAP UI.
Follow these steps :
Create a project using the WSDL.
Choose your interface and open in interface viewer.
Navigate to the tab 'WSDL Content'.
Use the last icon under the tab 'WSDL Content' : 'Export the entire WSDL and included/imported files to a local directory'.
select the folder where you want the XSDs to be exported to.
Note: SOAPUI will remove all relative paths and will save all XSDs to the same folder.
I have written a simple java-main that does the job and change to relative url's
package dl;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class SchemaPersister {
private static final String EXPORT_FILESYSTEM_ROOT = "C:/export/xsd";
// some caching of the http-responses
private static Map<String,String> _httpContentCache = new HashMap<String,String>();
public static void main(String[] args) {
try {
new SchemaPersister().doIt();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void doIt() throws Exception {
// // if you need an inouse-Proxy
// final String authUser = "xxxxx";
// final String authPassword = "xxxx"
//
// System.setProperty("http.proxyHost", "xxxxx");
// System.setProperty("http.proxyPort", "xxxx");
// System.setProperty("http.proxyUser", authUser);
// System.setProperty("http.proxyPassword", authPassword);
//
// Authenticator.setDefault(
// new Authenticator() {
// public PasswordAuthentication getPasswordAuthentication() {
// return new PasswordAuthentication(authUser, authPassword.toCharArray());
// }
// }
// );
//
Set <SchemaElement> allElements = new HashSet<SchemaElement>() ;
// URL url = new URL("file:/C:/xauslaender-nachrichten-administration.xsd");
URL url = new URL("http://www.osci.de/xauslaender141/xauslaender-nachrichten-bamf-abh.xsd");
allElements.add ( new SchemaElement(url));
for (SchemaElement e: allElements) {
System.out.println("processing " + e);
e.doAll();
}
System.out.println("done!");
}
class SchemaElement {
private URL _url;
private String _content;
public List <SchemaElement> _imports ;
public List <SchemaElement> _includes ;
public SchemaElement(URL url) {
this._url = url;
}
public void checkIncludesAndImportsRecursive() throws Exception {
InputStream in = new ByteArrayInputStream(downloadContent() .getBytes("UTF-8"));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(in);
List<Node> includeNodeList = null;
List<Node> importNodeList = null;
includeNodeList = getXpathAttribute(doc,"/*[local-name()='schema']/*[local-name()='include']");
_includes = new ArrayList <SchemaElement> ();
for ( Node element: includeNodeList) {
Node sl = element.getAttributes().getNamedItem("schemaLocation");
if (sl == null) {
System.out.println(_url + " defines one import but no schemaLocation");
continue;
}
String asStringAttribute = sl.getNodeValue();
URL url = buildUrl(asStringAttribute,_url);
SchemaElement tmp = new SchemaElement(url);
tmp.setSchemaLocation(asStringAttribute);
tmp.checkIncludesAndImportsRecursive();
_includes.add(tmp);
}
importNodeList = getXpathAttribute(doc,"/*[local-name()='schema']/*[local-name()='import']");
_imports = new ArrayList <SchemaElement> ();
for ( Node element: importNodeList) {
Node sl = element.getAttributes().getNamedItem("schemaLocation");
if (sl == null) {
System.out.println(_url + " defines one import but no schemaLocation");
continue;
}
String asStringAttribute = sl.getNodeValue();
URL url = buildUrl(asStringAttribute,_url);
SchemaElement tmp = new SchemaElement(url);
tmp.setSchemaLocation(asStringAttribute);
tmp.checkIncludesAndImportsRecursive();
_imports.add(tmp);
}
in.close();
}
private String schemaLocation;
private void setSchemaLocation(String schemaLocation) {
this.schemaLocation = schemaLocation;
}
// http://stackoverflow.com/questions/10159186/how-to-get-parent-url-in-java
private URL buildUrl(String asStringAttribute, URL parent) throws Exception {
if (asStringAttribute.startsWith("http")) {
return new URL(asStringAttribute);
}
if (asStringAttribute.startsWith("file")) {
return new URL(asStringAttribute);
}
// relative URL
URI parentUri = parent.toURI().getPath().endsWith("/") ? parent.toURI().resolve("..") : parent.toURI().resolve(".");
return new URL(parentUri.toURL().toString() + asStringAttribute );
}
public void doAll() throws Exception {
System.out.println("READ ELEMENTS");
checkIncludesAndImportsRecursive();
System.out.println("PRINTING DEPENDENCYS");
printRecursive(0);
System.out.println("GENERATE OUTPUT");
patchAndPersistRecursive(0);
}
public void patchAndPersistRecursive(int level) throws Exception {
File f = new File(EXPORT_FILESYSTEM_ROOT + File.separator + this.getXDSName() );
System.out.println("FILENAME: " + f.getAbsolutePath());
if (_imports.size() > 0) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("IMPORTS");
for (SchemaElement kid : _imports) {
kid.patchAndPersistRecursive(level+1);
}
}
if (_includes.size() > 0) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("INCLUDES");
for (SchemaElement kid : _includes) {
kid.patchAndPersistRecursive(level+1);
}
}
String contentTemp = downloadContent();
for (SchemaElement i : _imports ) {
if (i.isHTTP()) {
contentTemp = contentTemp.replace(
"<xs:import schemaLocation=\"" + i.getSchemaLocation() ,
"<xs:import schemaLocation=\"" + i.getXDSName() );
}
}
for (SchemaElement i : _includes ) {
if (i.isHTTP()) {
contentTemp = contentTemp.replace(
"<xs:include schemaLocation=\"" + i.getSchemaLocation(),
"<xs:include schemaLocation=\"" + i.getXDSName() );
}
}
FileOutputStream fos = new FileOutputStream(f);
fos.write(contentTemp.getBytes("UTF-8"));
fos.close();
System.out.println("File written: " + f.getAbsolutePath() );
}
public void printRecursive(int level) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(_url.toString());
if (this._imports.size() > 0) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("IMPORTS");
for (SchemaElement kid : this._imports) {
kid.printRecursive(level+1);
}
}
if (this._includes.size() > 0) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("INCLUDES");
for (SchemaElement kid : this._includes) {
kid.printRecursive(level+1);
}
}
}
String getSchemaLocation() {
return schemaLocation;
}
/**
* removes html:// and replaces / with _
* #return
*/
private String getXDSName() {
String tmp = schemaLocation;
// Root on local File-System -- just grap the last part of it
if (tmp == null) {
tmp = _url.toString().replaceFirst(".*/([^/?]+).*", "$1");
}
if ( isHTTP() ) {
tmp = tmp.replace("http://", "");
tmp = tmp.replace("/", "_");
} else {
tmp = tmp.replace("/", "_");
tmp = tmp.replace("\\", "_");
}
return tmp;
}
private boolean isHTTP() {
return _url.getProtocol().startsWith("http");
}
private String downloadContent() throws Exception {
if (_content == null) {
System.out.println("reading content from " + _url.toString());
if (_httpContentCache.containsKey(_url.toString())) {
this._content = _httpContentCache.get(_url.toString());
System.out.println("Cache hit! " + _url.toString());
} else {
System.out.println("Download " + _url.toString());
Scanner scan = new Scanner(_url.openStream(), "UTF-8");
if (isHTTP()) {
this._content = scan.useDelimiter("\\A").next();
} else {
this._content = scan.useDelimiter("\\Z").next();
}
scan.close();
if (this._content != null) {
_httpContentCache.put(_url.toString(), this._content);
}
}
}
if (_content == null) {
throw new NullPointerException("Content of " + _url.toString() + "is null ");
}
return _content;
}
private List<Node> getXpathAttribute(Document doc, String path) throws Exception {
List <Node> returnList = new ArrayList <Node> ();
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
{
XPathExpression expr = xpath.compile(path);
NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET );
for (int i = 0 ; i < nodeList.getLength(); i++) {
Node n = nodeList.item(i);
returnList.add(n);
}
}
return returnList;
}
#Override
public String toString() {
if (_url != null) {
return _url.toString();
}
return super.toString();
}
}
}
I created a python tool to recursively download XSDs with relative paths in import tags (eg: <import schemaLocation="../../../../abc)
https://github.com/n-a-t-e/xsd_download
After downloading the schema you can use xmllint to validate an XML document
I am using org.apache.xmlbeans.impl.tool.SchemaResourceManager from the xmlbeans project. This class is quick and easy to use.
for example:
SchemaResourceManager manager = new SchemaResourceManager(new File(dir));
manager.process(schemaUris, emptyArray(), false, true, true);
manager.writeCache();
This class has a main method that documents the different options available.

Blackberry - How if addElement() doesn't work?

I am a newbie of Blackberry developing application. I try to store all xml parsing data to an object, and set them to a vector.
public class XmlParser extends MainScreen {
Database d;
private HttpConnection hcon = null;
private Vector binN;
public Vector getBinN() {
return binN;
}
public void setBinN(Vector bin) {
this.binN = bin;
}
LabelField from;
LabelField ttl;
LabelField desc;
LabelField date;
public XmlParser() {
LabelField title = new LabelField("Headline News" ,LabelField.HCENTER|LabelField.USE_ALL_WIDTH);
setTitle(title);
try {
URI myURI = URI.create("file:///SDCard/Database/WebFeed.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT feed_url, feed_name FROM WebFeed");
st.prepare();
Cursor c = st.getCursor();
while (c.next()) {
Row r = c.getRow();
hcon = (HttpConnection)Connector.open(r.getString(0));
hcon.setRequestMethod(HttpConnection.GET);
hcon.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
hcon.setRequestProperty("Content-Length", "0");
hcon.setRequestProperty("Connection", "close");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.isValidating();
Document document = builder.parse(hcon.openInputStream());
Element rootElement = document.getDocumentElement();
rootElement.normalize();
NodeList list = document.getElementsByTagName("item");
int i=0;
while (i<10){
Node item = list.item(i);
if(item.getNodeType() != Node.TEXT_NODE) {
NodeList itemChilds = item.getChildNodes();
int j=0;
while (j<10){
Node detailNode = itemChilds.item(j);
if(detailNode.getNodeType() != Node.TEXT_NODE) {
if(detailNode.getNodeName().equalsIgnoreCase("title")) {
ttl = new LabelField(getNodeValue(detailNode)) {
public void paint(Graphics g) {
g.setColor(Color.BLUE);
super.paint(g);
}
};
from = new LabelField(r.getString(1), LabelField.FIELD_RIGHT|LabelField.USE_ALL_WIDTH);
ttl.setFont(Font.getDefault().derive(Font.BOLD));
from.setFont(Font.getDefault().derive(Font.BOLD));
add (from);
add (ttl);
} else if(detailNode.getNodeName().equalsIgnoreCase("description")) {
desc = new LabelField(getNodeValue(detailNode), 0, 70, USE_ALL_WIDTH);
add(desc);
} else if(detailNode.getNodeName().equalsIgnoreCase("dc:date")) {
date = new LabelField(getNodeValue(detailNode), 11, 5, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else if(detailNode.getNodeName().equalsIgnoreCase("pubDate")) {
date = new LabelField(getNodeValue(detailNode), 0, 22, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else {
System.out.println("not the node");
}
} else {
System.out.println("not text node");
}
j++;
}
}
i++;
BinNews bin = new BinNews();
bin.setProv(from.getText());
bin.setTitle(ttl.getText());
bin.setDesc(desc.getText());
bin.setDate(date.getText());
binN.addElement(bin);
}
setBinN(binN);
}
//setBinN(binN);
st.close();
d.close();
} catch (Exception e) {
add (new LabelField(e.toString(),LabelField.HCENTER|LabelField.USE_ALL_WIDTH));
System.out.println(e.toString());
}
}
public String getNodeValue(Node node) {
NodeList nodeList = node.getChildNodes();
Node childNode = nodeList.item(0);
return childNode.getNodeValue();
}
}
I try to store all data from an object called BinNews, to a vector called binN. But when I do debugging, I found that BinN has null value, because "binN.addElement(bin)" doesn't work.
Please advise.
First, you don't actually call setBinN until after the while(i < 10) loop completes. So when you say binN.addElement(bin) then binN will be null.
However your setBinN(binN) call doesn't make sense because you're passing in binN and then setting it to itself which isn't going to do anything.
What you can do is have binN = new Vector(); at the top of the constructor and then it won't be null later on. I don't think the setBinN call will be necessary later on if you're adding the BinNews objects straight to binN.

How to sort search dictionary result based on frequency in j2me

This is my dictionary format:
word Frequency
Gone 60
Goes 10
Go 30
So far the system returns words eg starting with 'g' as go30, goes10, gone60 as a list.
(alphabetically). I want to increase the accuracy of the system so that the search result is based on frequency. Words with high frequencies appear first. kindly help.
Here is the Text midlet class that reads the dictionary line by line.
public class Text extends MIDlet {
// Fields
private static final String[] DEFAULT_KEY_CODES = {
// 1
".,?!'\"1-()#/:_",
// 2
"ABC2",
// 3
"DEF3",
// 4
"GHI4",
// 5
"JKL5",
// 6
"MNO6",
// 7
"PQRS7",
// 8
"TUV8",
// 9
"WXYZ9",
};
//Initializing inner Classes
public ComposeText() {
cmdHandler = new CommandHandler();
lineVector = new Vector();
}
//Calling All InitMethods, setting Theme, Show MainForm
public void startApp() {
Display.init(this);
setTheme();
initCmd();
initMainGui();
mainFrm.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
//Initializing all the Commands
public void initCmd() {
exitCmd = new Command("Exit");
selectCmd = new Command("Ok");
cancelCmd = new Command("Cancel");
predCmd = new Command("Prediction");
sendCmd = new Command("Send");
tfPredArea = new TextField();
//check dictionary
try {
readFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//Initiating MainScreen
public void initMainGui() {
mainFrm = new Form("Compose Text");
mainFrm.setLayout(new BorderLayout());
mainFrm.setLayout(new CoordinateLayout(150, 150));
mainFrm.addCommand(exitCmd);
mainFrm.addCommand(predCmd);
mainFrm.addCommand(sendCmd);
mainFrm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == predCmd){
initPredGui();
} else if(ae.getSource() == exitCmd){
destroyApp(true);
notifyDestroyed();
}
}
});
// To : 07xxxxxxxxxx
Dimension d1 = new Dimension(130, 20);
lbTo = new Label("To:");
lbTo.setX(10);
lbTo.setY(10);
tfTo = new TextField();
tfTo.setReplaceMenu(false);
tfTo.setConstraint(TextField.NUMERIC);
tfTo.setInputModeOrder(new String[]{"123"});
tfTo.setMaxSize(13);
tfTo.setX(40);
tfTo.setY(10);
tfTo.setPreferredSize(d1);
//Message : Compose Text
Dimension d2 = new Dimension(135, 135);
lbSms = new Label("Message:");
lbSms.setX(5);
lbSms.setY(40);
tfSms = new TextField();
tfSms.setReplaceMenu(false);
tfSms.setX(40);
tfSms.setY(40);
tfSms.setPreferredSize(d2);
//add stuff
mainFrm.addComponent(lbTo);
mainFrm.addComponent(lbSms);
mainFrm.addComponent(tfTo);
mainFrm.addComponent(tfSms);
}
//Initiating FilterSelection Screen
public void initPredGui() {
predForm = new Form("Prediction on");
predForm.setLayout(new CoordinateLayout(150, 150));
predForm.addCommand(cancelCmd);
predForm.addCommand(selectCmd);
//textfied in prediction form
final Dimension d5 = new Dimension(200, 200);
tfPredArea = new TextField();
tfPredArea.setReplaceMenu(false);
tfPredArea.setX(10);
tfPredArea.setY(10);
tfPredArea.setPreferredSize(d5);
predForm.addComponent(tfPredArea);
final ListModel underlyingModel = new DefaultListModel(lineVector);
// final ListModel underlyingModel = new
DefaultListModel(tree.getAllPrefixMatches(avail));
// this is a list model that can narrow down the underlying model
final SortListModel proxyModel = new SortListModel(underlyingModel);
final List suggestion = new List(proxyModel);
tfPredArea.addDataChangeListener(new DataChangedListener() {
public void dataChanged(int type, int index) {
int len = 0;
int i = 0;
String input = tfPredArea.getText();
len = tfPredArea.getText().length();
//ensure start search character is set for each word
if (!(len == 0)) {
for (i = 0; i < len; i++) {
if (input.charAt(i) == ' ') {
k = i;
}
}
String currentInput = input.substring(k + 1, len);
proxyModel.filter(currentInput);
}
}
});
Dimension d3 = new Dimension(110, 120);
suggestion.setX(80);
suggestion.setY(80);
suggestion.setPreferredSize(d3);
predForm.addComponent(suggestion);
suggestion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String string = suggestion.getSelectedItem().toString();
if (tfPredArea.getText().charAt(0) == 0) {
tfPredArea.setText(string);
}
else if (tfPredArea.getText().length() == 0) {
tfPredArea.setText(string);
} else {
tfPredArea.setText(tfPredArea.getText() + string);
}
}
});
predForm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == addCmd) {
newDictionaryFrm.show();
} else {
mainFrm.show();
}
}
});
predForm.show();
}
//Setting Theme for All Forms
public void setTheme() {
try {
Resources r = Resources.open("/theme.res");
UIManager.getInstance().setThemeProps(r.getTheme(
r.getThemeResourceNames()[0]));
} catch (java.io.IOException e) {
System.err.println("Couldn't load the theme");
}
}
//Inner class CommandHandler
public class CommandHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
//cancelCommand from predictionForm
if (ae.getSource() == cancelCmd) {
if (edit) {
mainFrm.show();
// clearFields();
} else if (ae.getSource() == selectCmd){
tfPredList.addDataChangeListener(model);
predForm.show();
}
else{}
}
}
}
// method that reads dictionary line by line
public void readFile() throws IOException {
tree = new Trie();
InputStreamReader reader = new InputStreamReader(
getClass().getResourceAsStream("/Maa Corpus.txt-01-ngrams-Alpha.txt"));
String line = null;
// Read a single line from the file. null represents the EOF.
while ((line = readLine(reader)) != null) {
// Append to a vector to be used as a list
lineVector.addElement(line);
}
}
public String readLine(InputStreamReader reader) throws IOException {
// Test whether the end of file has been reached. If so, return null.
int readChar = reader.read();
if (readChar == -1) {
return null;
}
StringBuffer string = new StringBuffer("");
// Read until end of file or new line
while (readChar != -1 && readChar != '\n') {
// Append the read character to the string.
// This is part of the newline character
if (readChar != '\r') {
string.append((char) readChar);
}
// Read the next character
readChar = reader.read();
}
return string.toString();
}
}
}
The SortListModel Class has a filter method that gets prefix from the textfield datachangeLister
class SortListModel implements ListModel, DataChangedListener {
private ListModel underlying;
private Vector filter;
private Vector listeners = new Vector();
public SortListModel(ListModel underlying) {
this.underlying = underlying;
underlying.addDataChangedListener(this);
}
private int getFilterOffset(int index) {
if(filter == null) {
return index;
}
if(filter.size() > index) {
return ((Integer)filter.elementAt(index)).intValue();
}
return -1;
}
private int getUnderlyingOffset(int index) {
if(filter == null) {
return index;
}
return filter.indexOf(new Integer(index));
}
public void filter(String str) {
filter = new Vector();
str = str.toUpperCase();
for(int iter = 0 ; iter < underlying.getSize() ; iter++) {
String element = (String)underlying.getItemAt(iter);
if(element.toUpperCase().startsWith(str)) // suggest only if smthing
{
filter.addElement(new Integer(iter));
}
}
dataChanged(DataChangedListener.CHANGED, -1);
}
public Object getItemAt(int index) {
return underlying.getItemAt(getFilterOffset(index));
}
public int getSize() {
if(filter == null) {
return underlying.getSize();
}
return filter.size();
}
public int getSelectedIndex() {
return Math.max(0, getUnderlyingOffset(underlying.getSelectedIndex()));
}
public void setSelectedIndex(int index) {
underlying.setSelectedIndex(getFilterOffset(index));
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addElement(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeElement(l);
}
public void addSelectionListener(SelectionListener l) {
underlying.addSelectionListener(l);
}
public void removeSelectionListener(SelectionListener l) {
underlying.removeSelectionListener(l);
}
public void addItem(Object item) {
underlying.addItem(item);
}
public void removeItem(int index) {
underlying.removeItem(index);
}
public void dataChanged(int type, int index) {
if(index > -1) {
index = getUnderlyingOffset(index);
if(index < 0) {
return;
}
}
for(int iter = 0 ; iter < listeners.size() ; iter++) {
((DataChangedListener)listeners.elementAt(iter)).dataChanged(type, index);
}
}
}

Resources