I am trying to write a java program that reads in an XML file and returns various elements of interest to the user. I am having some issues getting it to compile and I have created a test class in order for it to be displayed properly. This is what I have thus far.
EDIT: The Bolded Line in the test class is giving me problems. The error is cannot convert from String to Resources.
public class T_Resources {
public static void main(String[] args) {
Resources resources = ResourceImporter.importResourcesFromXML("http://free1.ed.gov/xml/gemexport.xml");
displayResources(resources);
}
private static void displayResources(Resources resources) {
Subject[] subjects;
**Resources resource = resources.getTitle();**
System.out.println(resource.getTitle());
System.out.println(resource.getDescription());
System.out.println(resource.getIdentifier());
subjects = resource.getSubjects();
for (int i=0; i < subjects.length; ++i) {
System.out.println(subjects[i].getCategory() + " :: " + subjects[i].getSubcategory());
}
System.out.println();
}
}
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ResourceImporter {
// This operation loads the XML document specified by the document location, which can a file or a URL,
// and returns a reference to the document. If the operation cannot successfully load the document
// the operation returns the null reference.
//
private static Document loadXMLDocument(String documentLocation) {
// The XML document.
//
Document documentIn = null;
// The parser that reads in an XML files.
//
DocumentBuilder parser = null;
// Pull the document
//
try {
// Obtain a document parser.
//
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
parser = builderFactory.newDocumentBuilder();
documentIn = parser.parse(documentLocation);
} catch (ParserConfigurationException p) {
System.out.println("Error creating parser.");
System.out.println(" " + p.getMessage());
} catch (SAXException s) {
System.out.println("Document is not well formed.");
System.out.println(" " + s.getMessage());
} catch (IOException i) {
System.out.println("Error accessing the file.");
System.out.println(" " + i.getMessage());
} catch (Exception e) {
System.out.println("Unknown error occurred.");
System.out.println(" " + e.getMessage());
}
return documentIn;
}
public static Resources importResourcesFromXML(String documentLocation) {
Resources resource = new Resources();
Document doc;
Element resourceElement;
Element titleElement;
String title;
Element descriptionElement;
String description;
Element identifierElement;
String identifiers;
Element urlElement;
String url;
NodeList subjectList;
Element subjectElement;
String subjects;
Element categoryElement;
String category;
Element subcategoryElement;
String subcategory;
doc = loadXMLDocument(documentLocation);
resourceElement = (Element)doc.getElementsByTagName("resource").item(0);
if (resourceElement != null) {
titleElement = (Element)resourceElement.getElementsByTagName("title").item(0);
resource.setTitle( titleElement == null ? "unknown" : titleElement.getTextContent() );
descriptionElement = (Element)resourceElement.getElementsByTagName("description").item(0);
resource.setDescription( descriptionElement == null ? "unknown" : descriptionElement.getTextContent() );
identifierElement = (Element)resourceElement.getElementsByTagName("identifier").item(0);
if (identifierElement != null) {
Identifier identifier = new Identifier();
urlElement = (Element)identifierElement.getElementsByTagName("url").item(0);
identifier.setURL( urlElement == null ? "unknown" : urlElement.getTextContent() );
subjectElement = (Element)resourceElement.getElementsByTagName("subjects").item(0);
if (subjectElement != null) {
subjectList = subjectElement.getElementsByTagName("subject");
for (int i=0; i < subjectList.getLength(); ++i) {
Subject subject = new Subject();
subjectElement = (Element)subjectList.item(i);
categoryElement = (Element)subjectElement.getElementsByTagName("category").item(0);
subject.setCategory( categoryElement == null ? "unknown" : categoryElement.getTextContent() );
subcategoryElement = (Element)subjectElement.getElementsByTagName("subcategory").item(0);
subject.setSubcategory( subcategoryElement == null ? "unknown" :subcategoryElement.getTextContent() );
resource.addSubject(subject);
}
}
}
}
return resource;
}
}
public class Resources {
private static final int MAX_SUBJECTS = 20;
private String title;
private String description;
private Identifier identifier;
private Subject[] subjects;
private int subjectCount;
public Resources() {
title = "unknown title";
description = "unknown description";
identifier = null;
subjects = new Subject[MAX_SUBJECTS];
subjectCount = 0;
}
public void setTitle(String newTitle) {
title = newTitle;
}
public String getTitle() {
return title;
}
public void setDescription(String newDescription) {
description = newDescription;
}
public String getDescription() {
return description;
}
public void setIdentifier(Identifier newIdentifier) {
identifier = newIdentifier;
}
public Identifier getIdentifier() {
return identifier;
}
public void addSubject(Subject newSubject) {
subjects[subjectCount++] = newSubject;
}
public Subject[] getSubjects() {
Subject[] result = new Subject[subjectCount];
System.arraycopy(subjects, 0, result, 0, subjectCount);
return result;
}
}
public class Subject {
private String category;
private String subcategory;
public Subject() {
String category = "unknown";
String subcategory = "unknown";
}
public Subject(Subject subject) {
category = subject.category;
subcategory = subject.subcategory;
}
public void setCategory(String newCategory) {
category = (newCategory == null) ? "unknown" : newCategory;
}
public String getCategory() {
return category;
}
public void setSubcategory(String newSubcategory) {
subcategory = newSubcategory;
}
public String getSubcategory() {
return subcategory;
}
}
public class Identifier {
private String url;
public Identifier() {
url = "unknown";
}
public void setURL(String newURL) {
url = newURL;
}
public String getURL() {
return url;
}
}
The error lies in here:
private static void displayResources(Resources resources) {
Subject[] subjects;
// DELETE THIS
// **Resources resource = resources.getTitle();**
// RENAME 'resource' to 'resources', or just change the method parameter above...
System.out.println(resources.getTitle());
//System.out.println(resource.getTitle());
System.out.println(resources.getDescription());
//System.out.println(resource.getDescription());
System.out.println(resources.getIdentifier());
//System.out.println(resource.getIdentifier());
....
You pass a Resources Object, and normally you would want to work directly with it?
Currently this just seems borked here, all the other code works, I tested and get fancy console outputs.
EDIT: (Answering a comment below this post.)
In ResourceImporter.java add line following the comment below:
if (resourceElement != null) {
titleElement = (Element)resourceElement.getElementsByTagName("title").item(0);
resource.setTitle( titleElement == null ? "unknown" : titleElement.getTextContent() );
descriptionElement = (Element)resourceElement.getElementsByTagName("description").item(0);
resource.setDescription( descriptionElement == null ? "unknown" : descriptionElement.getTextContent() );
identifierElement = (Element)resourceElement.getElementsByTagName("identifier").item(0);
if (identifierElement != null) {
Identifier identifier = new Identifier();
urlElement = (Element)identifierElement.getElementsByTagName("url").item(0);
identifier.setURL( urlElement == null ? "unknown" : urlElement.getTextContent() );
// ADDED THIS LINE HERE
resource.setIdentifier(identifier);
subjectElement = (Element)resourceElement.getElementsByTagName("subjects").item(0);
if (subjectElement != null) {
subjectList = subjectElement.getElementsByTagName("subject");
....
You may also want to use this line for your syso's in the helper method being used in the main method: System.out.println(resources.getIdentifier().getURL());, otherwise you will get uninterpretable information.
I'd change
private static void displayResources(Resources resources)
to
private static void displayResources(Resources resource)
(notice I removed the 's'), and remove your bold line.
As stated by JB Nizet, your method returns a String when you want the Resources that is passed to your static method.
The getTitle() method is declared as
public String getTitle()
But you're assigning its result to a variabe of type Resources:
Resources resource = resources.getTitle();
That obviously can't work, hence the error, which is quite self-explanatory:
cannot convert from String to Resources
You probably want
String title = resources.getTitle();
instead.
Related
I have a simple Spring application (front-end application) that loads files into the Alfresco repository. If the file already exists, its new version is not created.
Repository web script is presented below:
public class CustomFileUploader extends DeclarativeWebScript {
private static final String FIRM_DOC =
"{http://www.firm.com/model/content/1.0}someDoc";
private static final String FIRM_DOC_FOLDER =
"workspace://SpacesStore/8caf07c3-6aa9-4a41-bd63-404cb3e3ef0f";
private FirmFile firmFile;
private FileFolderService fileFolderService;
private ContentService contentService;
protected Map<String, Object> executeImpl(WebScriptRequest req,
Status status) {
retrievePostRequestParams(req);
writeContent();
return null;
}
private void retrievePostRequestParams(WebScriptRequest req) {
FormData formData = (FormData) req.parseContent();
FormData.FormField[] fields = formData.getFields();
for(FormData.FormField field : fields) {
String fieldName = field.getName();
String fieldValue = field.getValue();
if(fieldName.equalsIgnoreCase("firm_file")
&& field.getIsFile()) {
String fileName = field.getFilename();
Content fileContent = field.getContent();
String fileMimetype = field.getMimetype();
firmFile = new FirmFile(fileName, fileContent,
fileMimetype, FIRM_DOC);
}
}
}
private void writeContent() {
try {
NodeRef parentNodeRef = new NodeRef(FIRM_DOC_FOLDER);
NodeRef fileNodeRef = createFileNode(parentNodeRef,
firmFile.getFileName());
ContentWriter contentWriter = contentService.getWriter(fileNodeRef,
ContentModel.PROP_CONTENT, true);
contentWriter.setMimetype(firmFile.getFileMimetype());
contentWriter.putContent(firmFile.getFileContent().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
private NodeRef createFileNode(NodeRef parentNode, String fileName) {
try {
QName contentQName = QName.createQName(FIRM_DOC);
FileInfo fileInfo = fileFolderService.create(parentNode,
fileName, contentQName);
return fileInfo.getNodeRef();
} catch (Exception e) {
e.printStackTrace();
}
}
public FileFolderService getFileFolderService() {
return fileFolderService;
}
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
public ContentService getContentService() {
return contentService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
}
How to create a new version of a file with the same name by using Java-backed WebScript?
Does this solution correct?
Check if the file exists by using Lucene search: TYPE:"firm:doc" AND #cm\:name:contract.png; (for example) If exists, increment the property cm:versionLabel and create a new version of Node with all the properties (Actually, need to iterate through all the ResultSet and find NodeRef with max value of cm:versionLabel then increment it and create a new Node). Is there more elegant solution?
The solution can be represented as follows:
public class CustomFileUploader extends DeclarativeWebScript {
private static final String FIRM_DOC = "{http://www.firm.com/model/content/1.0}doc";
private static final String FIRM_DOC_FOLDER = "workspace://SpacesStore/8caf07c3-6aa9-4a41-bd63-404cb3e3ef0f";
private FileFolderService fileFolderService;
private ContentService contentService;
private NodeService nodeService;
private SearchService searchService;
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
processUpload(req);
return null;
}
private void writeContent(NodeRef node, FirmFile firmFile) {
try {
ContentWriter contentWriter = contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
contentWriter.setMimetype(firmFile.getFileMimetype());
contentWriter.putContent(firmFile.getFileContent().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
private NodeRef checkIfNodeExists(String fileName) {
StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE/*LANGUAGE_FTS_ALFRESCO*/,
"TYPE:\"firm:doc\" AND #cm\\:name:" + fileName.replaceAll(" ", "\\ ")+ "");
int len = resultSet.length();
if(len == 0) {
return null;
}
NodeRef node = resultSet.getNodeRef(0);
return node;
}
private NodeRef createNewNode(FirmFile firmFile) {
NodeRef parent = new NodeRef(FIRM_DOC_FOLDER);
NodeRef node = createFileNode(parent, firmFile.getFileName());
return node;
}
private void processUpload(WebScriptRequest req) {
FormData formData = (FormData) req.parseContent();
FormData.FormField[] fields = formData.getFields();
for(FormData.FormField field : fields) {
String fieldName = field.getName();
if(fieldName.equalsIgnoreCase("firm_file") && field.getIsFile()) {
String fileName = field.getFilename();
Content fileContent = field.getContent();
String fileMimetype = field.getMimetype();
NodeRef node = checkIfNodeExists(fileName);
// POJO
FirmFile firm = new FirmFile(fileName, fileContent, fileMimetype, FIRM_DOC);
if(node == null) {
node = createNewNode(firmFile);
}
writeContent(node, firmFile);
}
}
}
private NodeRef createFileNode(NodeRef parentNode, String fileName) {
try {
QName contentQName = QName.createQName(FIRM_DOC);
FileInfo fileInfo = fileFolderService.create(parentNode, fileName, contentQName);
return fileInfo.getNodeRef();
} catch (Exception e) {
e.printStackTrace();
}
}
public FileFolderService getFileFolderService() {
return fileFolderService;
}
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
public ContentService getContentService() {
return contentService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
public NodeService getNodeService() {
return nodeService;
}
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public SearchService getSearchService() {
return searchService;
}
public void setSearchService(SearchService searchService) {
this.searchService = searchService;
}
}
The content model must have a mandatory aspect cm:versionable:
<mandatory-aspects>
<aspect>cm:versionable</aspect>
</mandatory-aspects>
This question already has answers here:
How to read and write XML files?
(6 answers)
Closed 5 years ago.
Parse response from server to Object, I post to server a JSON and this is a answer :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><login_result><sctoken>a1fc912a-5c7a352b-8edf-4a54-a396-c6c5aea58c8b</sctoken><user_descr>Jan Nowak</user_descr><maps><tms><name>** MapCenterCache</name><url>http://cache2.smok.net.pl/cache_2015/element?s=%zoom%&x=%x%&y=%y%</url></tms><tms><name>OSM Mapnik</name><url>http://tile.openstreetmap.org/%zoom%/%x%/%y%.png</url></tms><tms><name>OSM****1</name><url>http://51.254.61.18:8104/tile/tilecache.cgi/1.0.0/osm_server_elte/%zoom%/%x%/%y%.png</url></tms><tms><name>*****</name><url>http://mapa.***.net.pl/tms/%zoom%/%x%/%y%.png</url></tms></maps></login_result>
The parsed Object is Root:
==================================
package ;
public class Tms
{
private String name;
private String url;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setUrl(String url){
this.url = url;
}
public String getUrl(){
return this.url;
}
}
==================================
package ;
import java.util.ArrayList;
import java.util.List;
public class Maps
{
private List<Tms> tms;
public void setTms(List<Tms> tms){
this.tms = tms;
}
public List<Tms> getTms(){
return this.tms;
}
}
==================================
package ;
public class Login_result
{
private String sctoken;
private String user_descr;
private Maps maps;
public void setSctoken(String sctoken){
this.sctoken = sctoken;
}
public String getSctoken(){
return this.sctoken;
}
public void setUser_descr(String user_descr){
this.user_descr = user_descr;
}
public String getUser_descr(){
return this.user_descr;
}
public void setMaps(Maps maps){
this.maps = maps;
}
public Maps getMaps(){
return this.maps;
}
}
==================================
package ;
public class Root
{
private Login_result login_result;
public void setLogin_result(Login_result login_result){
this.login_result = login_result;
}
public Login_result getLogin_result(){
return this.login_result;
}
}
Have a look here on how to parse XMLhttps://developer.android.com/training/basics/network-ops/xml.html
https://www.tutorialspoint.com/android/android_xml_parsers.htm
Example:
public void parseXml(){
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader( "<foo>Hello World!</foo>" ) ); // pass input whatever xml you have
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
Log.d(TAG,"Start document");
} else if(eventType == XmlPullParser.START_TAG) {
Log.d(TAG,"Start tag "+xpp.getName());
} else if(eventType == XmlPullParser.END_TAG) {
Log.d(TAG,"End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
Log.d(TAG,"Text "+xpp.getText()); // here you get the text from xml
}
eventType = xpp.next();
}
Log.d(TAG,"End document");
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I am trying to make an android application that parses pictures from online in a grid/list however Im coming up with some runtime errors.. its saying that i am parsing wrong for my FAMILY DOG BREED. Does anyone know where I am making my errors?? I know why an array would be out of bounds but i have no idea how to fix it!!
I am trying to parse http://www.dogbreedslist.info/family-dog-breeds/ this website data.. but am getting runtime errors at these sections of my
DogActivity.class
private class RetrieveDogsTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... urls) {
for (String url : urls) {
Parser parser = new Parser(url, DogsActivity.this);
Breed.Name breedName = breed.getName();
if (breedName == Breed.Name.HERDING_DOG_BREED) {
dogs.add(parser.parseProfile(new Dog(url, breedName)));
} else {
dogs.addAll(parser.parseDogsPage(breedName, DogsActivity.this));
}
}
return null;
}
Parser.class
public class Parser {
Document doc;
Context context;
Elements dogRows;
public Parser(String url, Context context) {
this.context = context;
try {
doc = Jsoup.connect(url).get();
} catch (IOException e) {
Log.e("Page", "Wrong URL or network problems", e);
}
}
public ArrayList<Dog> parseDogsPage(Breed.Name breedName, Context context) {
ArrayList<Dog> dogs = new ArrayList<>();
try {
Element dogContainer;
if (breedName == Breed.Name.FAMILY_DOG_BREED) {
dogContainer = doc.getElementsByClass("familybreed").get(0);
} else {
dogContainer = doc.getElementsByClass("toybreed").get(0);
}
Log.i("Page", "A page has been parsed successfully");
dogRows = dogContainer.getElementsByTag("a");
for (Element dogRow : dogRows) {
String dogName, dogURL;
Dog dog;
dogURL = dogRow.getElementsByTag("a").get(0).absUrl("href");
String dogThumbnailURL = dogRow.
getElementsByTag("img").get(0).absUrl("src");
if (breedName == Breed.Name.FAMILY_DOG_BREED) {
dogName = dogRow.getElementsByTag("span").get(0).text();
dog = new Dog(dogName, dogURL, dogThumbnailURL, breedName);
} else {
dogName = dogRow.getElementsByTag("strong").get(0).text();
Element details = dogContainer.getElementsByClass("details").get(0);
Elements children = details.children();
if (breedName == Breed.Name.TOY_DOG_BREED || breedName == Breed.Name.HOUND_DOG_BREED) {
String origin = children.get(1).text();
String lifespan = children.get(3).text();
dog= new Dog(dogName, origin , lifespan, dogURL, dogThumbnailURL, breedName);
} else {
//for herding
String sizetype = children.get(1).text();
dog = new Dog(dogName, sizetype, dogThumbnailURL, dogURL, breedName);
}
}
dogs.add(dog);
}
} catch (Exception e) {
Log.e("Breed activity", "Wrong parsing for " + breedName, e);
}
return dogs;
}
public Dog parseProfile(Dog dog) {
if (!dog.isDetailDataReady()) {
//coaches already read the data in the coaches page
try {
Element dogContainer = doc.getElementById("dogscontainer");
Element bioContainer = dogContainer.getElementById("biocontainer");
Element bioDetails = bioContainer.getElementById("biodetails");
dog.setOtherNames(bioDetails.getElementsByTag("h1").text());
ArrayList<Dog.Detail> dogDetails = new ArrayList<>();
Elements rows = bioDetails.getElementsByTag("tr");
for (Element row : rows) {
Elements tds = row.getElementsByTag("td");
if (dog.getBreed() == Breed.Name.WORKING_DOG_BREED ||
dog.getBreed() == Breed.Name.TERRIER_DOG_BREED ||
dog.getBreed() == Breed.Name.HERDING_DOG_BREED) {
//coaches, manager and legends use th and td
Elements ths = row.getElementsByTag("th");
dogDetails.add(new Dog.Detail(ths.get(0).text(), tds.get(0).text()));
} else {
//dogs use two tds
dogDetails.add(new Dog.Detail(tds.get(0).text(), tds.get(1).text()));
}
}
dog.setDetails(dogDetails);
Element articleText = dogContainer.getElementsByClass("dogarticletext").get(0);
Elements paragraphs = articleText.getElementsByTag("p");
String text = "";
for (Element p : paragraphs) {
text = text + "\n\n\n" + p.text();
}
dog.setArticleText(dog.getArticleText() + text);
if (dog.getBreed() == Breed.Name.WORKING_DOG_BREED ||
dog.getBreed() == Breed.Name.TERRIER_DOG_BREED ||
dog.getBreed() == Breed.Name.HERDING_DOG_BREED) {
//get main image url
dog.setMainImageURL(bioContainer.getElementsByTag("img").get(0).absUrl("src"));
if (dog.getBreed() == Breed.Name.WORKING_DOG_BREED) {
dog.setThumbnailURL(dog.getMainImageURL());
//only need first name
dog.setName(dog.getOtherNames().split(" ")[1]);
}
} else {
dog.setMainImageURL(bioContainer.getElementsByClass("mainImage").get(0).absUrl("src"));
}
} catch (Exception e) {
Log.e("Profile activity", "Wrong parsing for " + dog.getUrl(), e);
}
if (dog.getBreed() == Breed.Name.WORKING_DOG_BREED) {
dog.setBasicDataReady(true);
}
dog.setDetailDataReady(true);
}
return dog;
}
}
RetrieveDogTask:
private class RetrieveDogsTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... urls) {
for (String url : urls) {
Parser parser = new Parser(url, DogsActivity.this);
Breed.Name breedName = breed.getName();
if (breedName == Breed.Name.HERDING_DOG_BREED) {
dogs.add(parser.parseProfile(new Dog(url, breedName)));
} else {
dogs.addAll(parser.parseDogsPage(breedName, DogsActivity.this));
}
}
return null;
Logcat:
Wrong parsing for FAMILY_DOG_BREED
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at org.jsoup.select.Elements.get(Elements.java:544)
at com.example.shannon.popular.Parser.parseDogsPage(Parser.java:35)
at com.example.shannon.popular.DogsActivity$RetrieveDogsTask.doInBackground(DogsActivity.java:140)
at com.example.shannon.popular.DogsActivity$RetrieveDogsTask.doInBackground(DogsActivity.java:131)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Breed.class:
public class Breed implements Serializable {
private Name name;
private String url;
Breed(Name name, String url) {
this.name = name;
this.url = url;
}
public Name getName() {
return name;
}
public String getNameString(Context context) {
String nameString = "";
switch (name) {
case FAMILY_DOG_BREED:
nameString = context.getString(R.string.family_breed);
break;
case TOY_DOG_BREED:
nameString = context.getString(R.string.toy_breed);
break;
case HOUND_DOG_BREED:
nameString = context.getString(R.string.hound_breed);
break;
case TERRIER_DOG_BREED:
nameString = context.getString(R.string.terrier_breed);
break;
case WORKING_DOG_BREED:
nameString = context.getString(R.string.working_breed);
break;
case HERDING_DOG_BREED:
nameString = context.getString(R.string.herding_breed);
break;
}
return nameString;
}
public String getURL() {
return url;
}
public enum Name {FAMILY_DOG_BREED, TOY_DOG_BREED, HOUND_DOG_BREED, TERRIER_DOG_BREED, WORKING_DOG_BREED, HERDING_DOG_BREED}
}
You may be using a strict XML parser for a malformed HTML document. I just tried to XML-validate the URL you are parsing and it's failing because the <link> element is never closed (in strict XML, it should be ended by a </link> tag, but it's missing in that page).
This is very common for HTML pages as today's browsers tend to auto-correct these kinds of errors.
Since you use a strict XML parser, it is very likely for the parser to fail.
I suggest switching to different parser. I'd use a PULL parser (eg. http://www.xmlpull.org ) - this technique allows parsing with a lower-level of control, meaning you can easily ignore unwanted content from the HTML - like these link elements, or any others.
So you could do something like this:
XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(new BufferedReader(
new InputStreamReader(
new URL("http://.....").openConnection().getInputStream()
)
)
);
while(XmlPullParser.END_DOCUMENT != parser.next()){
if(XmlPullParser.START_TAG == parser.getEventType()){
String tagName = parser.getName();
if(parser.getAttributeCount() > 0 {
// parse attributes, if needed
}
if(parser.nextToken() == XmlPullParser.TEXT){
String tagValue = parser.getText()
}
// etc.
}
}
I have this string coming from my dataBase:
<user>
<name>John</name>
<surname>Shean</surname>
<birthdate>1/1/1111</birthdate>
<phone >(555) 444-1111</phone>
<city>NY</city>
</user>
I need to parse it and add to:
arrayList<User>.(User(name,surname,...))
It should end up looking like this:
user[1]={name="John",surname="Shena",...}
I used the following method but it isn't working right. Does anyone have a method to will do this?
public User parseList(String array) {
User user = new User();
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL u = new URL("xmldb:exist://192.168.1.71:8094/exist/xmlrpc/db/testDB/userInformation.xml");
Document doc = builder.parse(u.openStream());
NodeList nodes = doc.getElementsByTagName("user");
Element element = (Element) nodes.item(0);
user.setName(getElementValue(element, "name"));
user.setSurname(getElementValue(element, "surname"));
user.setBirthdate(getElementValue(element, "birthdate"));
user.setPhone(getElementValue(element, "phone"));
user.setCity(getElementValue(element, "city"));
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
protected String getElementValue(Element parent, String label) {
return getCharacterDataFromElement((Element) parent.getElementsByTagName(label).item(0));
}
private String getCharacterDataFromElement(Element e) {
try {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
} catch (Exception ex) {
}
return "";
}
1 - model your use class:
package com.howtodoinjava.xml.sax;
/**
* Model class. Its instances will be populated using SAX parser.
* */
public class User
{
//XML attribute id
private int id;
//XML element name
private String Name;
//XML element surname
private String SurName;
//...
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getSurName() {
return SurName;
}
public void setSurName(String SurName) {
this.SurName = SurName;
}
// [...]
#Override
public String toString() {
return this.id + ":" + this.Name + ":" +this.SurName ;
}
}
2 - Build the handler by extending DefaultParser
package com.howtodoinjava.xml.sax;
import java.util.ArrayList;
import java.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class UserParserHandler extends DefaultHandler
{
//This is the list which shall be populated while parsing the XML.
private ArrayList userList = new ArrayList();
//As we read any XML element we will push that in this stack
private Stack elementStack = new Stack();
//As we complete one user block in XML, we will push the User instance in userList
private Stack objectStack = new Stack();
public void startDocument() throws SAXException
{
//System.out.println("start of the document : ");
}
public void endDocument() throws SAXException
{
//System.out.println("end of the document document : ");
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
//Push it in element stack
this.elementStack.push(qName);
//If this is start of 'user' element then prepare a new User instance and push it in object stack
if ("user".equals(qName))
{
//New User instance
User user = new User();
//Set all required attributes in any XML element here itself
if(attributes != null && attributes.getLength() == 1)
{
user.setId(Integer.parseInt(attributes.getValue(0)));
}
this.objectStack.push(user);
}
}
public void endElement(String uri, String localName, String qName) throws SAXException
{
//Remove last added element
this.elementStack.pop();
//User instance has been constructed so pop it from object stack and push in userList
if ("user".equals(qName))
{
User object = this.objectStack.pop();
this.userList.add(object);
}
}
/**
* This will be called everytime parser encounter a value node
* */
public void characters(char[] ch, int start, int length) throws SAXException
{
String value = new String(ch, start, length).trim();
if (value.length() == 0)
{
return; // ignore white space
}
//handle the value based on to which element it belongs
if ("name".equals(currentElement()))
{
User user = (User) this.objectStack.peek();
user.setName(value);
}
else if ("surname".equals(currentElement()))
{
User user = (User) this.objectStack.peek();
user.setSurName(value);
}
}
/**
* Utility method for getting the current element in processing
* */
private String currentElement()
{
return this.elementStack.peek();
}
//Accessor for userList object
public ArrayList getUsers()
{
return userList;
}
}
3 - Write parser for xml file
package com.howtodoinjava.xml.sax;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
public class UsersXmlParser
{
public ArrayList parseXml(InputStream in)
{
//Create a empty link of users initially
ArrayList<user> users = new ArrayList</user><user>();
try
{
//Create default handler instance
UserParserHandler handler = new UserParserHandler();
//Create parser from factory
XMLReader parser = XMLReaderFactory.createXMLReader();
//Register handler with parser
parser.setContentHandler(handler);
//Create an input source from the XML input stream
InputSource source = new InputSource(in);
//parse the document
parser.parse(source);
//populate the parsed users list in above created empty list; You can return from here also.
users = handler.getUsers();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
return users;
}
}
4 - Test parser
package com.howtodoinjava.xml.sax;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class TestSaxParser
{
public static void main(String[] args) throws FileNotFoundException
{
//Locate the file OR String
File xmlFile = new File("D:/temp/sample.xml");
//Create the parser instance
UsersXmlParser parser = new UsersXmlParser();
//Parse the file Or change to parse String
ArrayList users = parser.parseXml(new FileInputStream(xmlFile));
//Verify the result
System.out.println(users);
}
}
If you want to parse XML, you can use an XML parser.
This may help you:
Java:XML Parser
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to build a plug-in that gets loaded when the Notes client (8.5.2++) loads that gets called whenever a document is opened and get the (Notes) URL of that document. What extension points and APIs do I need?
Clarification:
I do know how to get to the current document (NotesUIWorkspace.currentDocument). What I don't know is how (and when) to register a listener to get notified.
Special challenge: documents can be opened in Framesets (more than one) and documents can be opened as part of a composite page. The Frameset isn't a big concern, but the composite. If this would require to listen to any page opening and inspect it - I'm fine with that
We have solved this by getting all request of anykind of "post selection". The following Code snipped is from a sidebarplugin and is called in createViewPart():
m_Observer = new NotesSelectionObserverImpl();
NotesSelectionObservable cObservable = new NotesSelectionObservable();
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().addPostSelectionListener(cObservable);
cObservable.addObserver(this.m_Observer);
The first part of the magic is "PlattformUI ..... .addPostSelecitonListener();" On this point we register our listener, witch is als based on a observer pattern.
class NotesSelectionObserverImpl implements NotesSelectionObserver {
#Override
public void onSelectionChange(NotesSelectionContext cContext)
throws NotesException {
Database ndbCurrent = cContext.getDatabase();
Document docCurrent = cContext.getDocument();
if (ndbCurrent != null && docCurrent != null) {
String strEMail = "";
if (docCurrent.getItemValueString("Form").equals("Memo")
|| docCurrent.getItemValueString("Form")
.equals("Reply")) {
strEMail = docCurrent.getItemValueString("From");
strEMail = parseEMail(strEMail);
System.out.println("EMAIL: " + strEMail);
ContextCommand ccCurrent = new ContextCommand(strEMail,
docCurrent.getItemValueString("Subject"));
m_State.doFeedAction(false, m_Feeds.get(Activator.FEED_CONTEXT_ID), ccCurrent);
}
}
}
#Override
public void onUpdateAfterSelectionChange() {
// TODO Auto-generated method stub
}
}
The NotesSelectionObserver is a interface with the following definition:
import lotus.domino.NotesException;
public interface NotesSelectionObserver
{
void onSelectionChange(NotesSelectionContext cContext) throws NotesException;
void onUpdateAfterSelectionChange();
}
The NotesSelecitonContext is a other Interface that delivers all the information about the Selection. Here the definition:
import lotus.domino.Database;
import lotus.domino.Document;
public interface NotesSelectionContext
{
public Database getDatabase();
public Document getDocument();
public String getField();
}
So and now the last part, witch is the clue.... the NotesSelectionObservable:
import java.net.MalformedURLException;
import java.net.URL;
import java.util.StringTokenizer;
import java.util.Vector;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.NotesException;
import lotus.domino.Session;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.INullSelectionListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.progress.UIJob;
import com.ibm.csi.types.DocumentSummary;
import com.ibm.notes.java.api.util.NotesSessionJob;
import com.ibm.notes.java.ui.documents.NotesUIField;
import com.ibm.workplace.noteswc.selection.NotesApplicationInfo;
import com.ibm.workplace.noteswc.selection.NotesFieldSelection;
import com.ibm.workplace.noteswc.selection.NotesTextSelection;
public class NotesSelectionObservable implements INullSelectionListener {
public void addObserver(NotesSelectionObserver cObserver) {
if (!this.m_cObserverList.contains(cObserver))
this.m_cObserverList.add(cObserver);
}
public void removeObserver(NotesSelectionObserver cObserver) {
this.m_cObserverList.remove(cObserver);
}
public void selectionChanged(IWorkbenchPart cPart, ISelection cSelection) {
if (cSelection == null || cSelection.isEmpty())
this.clearSelection();
else if (cSelection instanceof StructuredSelection) {
Object cObj = ((StructuredSelection) cSelection).getFirstElement();
if (cObj instanceof DocumentSummary) {
DocumentSummary cSummary = (DocumentSummary) cObj;
this.setURL(cSummary.getUrl());
if (cSummary.getDocumentKey() != null)
this.setURL(cSummary.getDocumentKey().getUniqueId());
} else if (cObj instanceof NotesApplicationInfo) {
NotesApplicationInfo cInfo = (NotesApplicationInfo) cObj;
this.setURL(cInfo.getUrl());
}
if (cObj instanceof NotesFieldSelection) {
NotesUIField f = ((NotesFieldSelection)cObj).getCurrentField();
this.setField(f.getName());
}
if (cObj instanceof NotesTextSelection) {
// String strOut = ((NotesTextSelection) cObj).getText();
// System.out.println("Selektierter Text: " + strOut);
}
if (false) {
Class<? extends Object> c;
String cl = null;
for (c = cObj.getClass(); c != null; c = c.getSuperclass()) {
if (c.equals(Object.class))
break;
cl = cl != null ? cl + " : " + c.getName() : c.getName();
}
System.out.println("Type of selected object: " + cl);
}
}
if (this.m_bModified) {
this.startJob();
this.m_bModified = false;
}
}
private void clearSelection() {
this.m_strDatabaseRepID = null;
this.m_strDatabaseServer = null;
this.m_strDocumentUNID = null;
this.m_strDesginElement = null;
this.m_strField = null;
this.m_bModified = true;
}
private void setDatabase(String strRepID, String strServer) {
if (strRepID.equals(this.m_strDatabaseRepID) == false
|| (strServer != null && this.m_strDatabaseServer == null)
|| (this.m_strDatabaseServer != null && this.m_strDatabaseServer.equals(strServer) == false)) {
this.m_strDatabaseRepID = strRepID;
this.m_strDatabaseServer = strServer;
this.m_strDesginElement = null;
this.m_strDocumentUNID = null;
this.m_strField = null;
this.m_bModified = true;
}
}
private void setDesignElement(String strUNID) {
if (!strUNID.equals(this.m_strDesginElement)) {
this.m_strDesginElement = strUNID;
this.m_strDocumentUNID = null;
this.m_strField = null;
this.m_bModified = true;
}
}
private void setDocument(String strDocumentUNID) {
if (!strDocumentUNID.equals(this.m_strDocumentUNID)) {
this.m_strDocumentUNID = strDocumentUNID;
this.m_strField = null;
this.m_bModified = true;
}
}
private void setField(String strField) {
if (!strField.equals(this.m_strField)) {
this.m_strField = strField;
this.m_bModified = true;
}
}
private void setURL(String strURL) {
if (strURL == null || strURL.isEmpty())
return;
URL cURL;
try {
cURL = new URL(strURL);
} catch (MalformedURLException e) {
return;
}
if (!cURL.getProtocol().equalsIgnoreCase("notes"))
return;
StringTokenizer cToken = new StringTokenizer(cURL.getPath()
.substring(1), "/");
if (cToken.hasMoreElements())
this.setDatabase(cToken.nextToken(),
cURL.getHost().isEmpty() ? null : cURL.getHost());
else
return;
if (cToken.hasMoreElements())
this.setDesignElement(cToken.nextToken());
else
return;
if (cToken.hasMoreElements())
this.setDocument(cToken.nextToken());
}
private void startJob() {
if (this.m_strDatabaseRepID != null && this.m_cObserverList.size() > 0) {
Job cJob = new TheJob(this);
cJob.schedule();
try {
cJob.join();
for (NotesSelectionObserver o : this.m_cObserverList)
o.onUpdateAfterSelectionChange();
this.m_bModified = false;
} catch (InterruptedException e) {
return;
}
cJob = new TheUIJob(this);
cJob.schedule();
}
}
private class NotesSelectionContextImp implements NotesSelectionContext {
public Database getDatabase() {
return cDatabase;
}
public Document getDocument() {
return cDocument;
}
public String getField() {
return strField;
}
public Database cDatabase;
public Document cDocument;
public String strField;
}
private class TheJob extends NotesSessionJob {
public TheJob(NotesSelectionObservable cObservable) {
super(cObservable.getClass().getName() + ".selectionChanged()");
this.m_strRepID = cObservable.m_strDatabaseRepID;
this.m_strServer = cObservable.m_strDatabaseServer != null ? cObservable.m_strDatabaseServer
: "";
if (this.m_strServer.contains("%2F"))
this.m_strServer = this.m_strServer.replace("%2F", "/");
this.m_strDocumentUNID = cObservable.m_strDocumentUNID;
this.m_cContext.strField = cObservable.m_strField;
this.m_cObservable = cObservable;
}
protected IStatus runInNotesThread(Session cSession,
IProgressMonitor cProgress) throws NotesException {
this.m_cContext.cDatabase = cSession.getDbDirectory(this.m_strServer).openDatabaseByReplicaID(this.m_strRepID);
if (!this.m_cContext.cDatabase.isOpen()) {
this.m_cContext.cDatabase.open();
}
this.m_cContext.cDocument = this.m_strDocumentUNID != null ? this.m_cContext.cDatabase.getDocumentByUNID(this.m_strDocumentUNID)
: null;
for (NotesSelectionObserver o : this.m_cObservable.m_cObserverList)
o.onSelectionChange(this.m_cContext);
return Status.OK_STATUS;
}
private NotesSelectionContextImp m_cContext = new NotesSelectionContextImp();
private NotesSelectionObservable m_cObservable;
private String m_strRepID;
private String m_strServer;
private String m_strDocumentUNID;
}
private class TheUIJob extends UIJob {
public TheUIJob(NotesSelectionObservable cObservable) {
super(cObservable.getClass().getName() + ".selectionChanged()");
this.m_cObservable = cObservable;
}
public IStatus runInUIThread(IProgressMonitor arg0) {
for (NotesSelectionObserver o : this.m_cObservable.m_cObserverList)
o.onUpdateAfterSelectionChange();
this.m_cObservable.m_bModified = false;
return Status.OK_STATUS;
}
private NotesSelectionObservable m_cObservable;
}
private String m_strDatabaseRepID = null;
private String m_strDatabaseServer = null;
private String m_strDesginElement = null;
private String m_strDocumentUNID = null;
private String m_strField = null;
private boolean m_bModified = false;
private Vector<NotesSelectionObserver> m_cObserverList = new Vector<NotesSelectionObserver>();
}
You have also asked about the list of plugins:
org.eclipse.ui,
org.eclipse.core.runtime,
com.ibm.notes.java.api;bundle-version="1.5.1",
com.ibm.notes.java.ui;bundle-version="8.5.1",
com.ibm.csi;bundle-version="1.5.1",
com.ibm.notes.client;bundle-version="8.5.1"
We will bring this code also as a plugin to the openNTF Community. I think anybody who wants to extend the notesclient via Sidebars need to be aware on witch context a user is and wants to response to this context.