Append data to already existing Sitemap.xml file - java

I have created sitemap using the com.redfin.sitemapgenerator jar, now I want to add nodes i.e the urls in the urlset at run time, I have checked that the sitemap already exists or not but now I am unable to append to the already existing sitemap.xml file.`public String searchforques()
throws IllegalArgumentException {
// TODO Auto-generated method stub
System.out.println("calledd");
WebSitemapGenerator sitemapGenerator = null;
WebSitemapUrl sitemapUrl = null;
File file=new File("C:\\sitemap\\sitemap.xml");
try {
if(!file.exists())
{
sitemapGenerator = WebSitemapGenerator
.builder("http://www.testing.com", new File("C:\\sitemap"))
.gzip(false).build();
/*------------------------------------------*/
try {
sitemapUrl = new WebSitemapUrl.Options(
"http://www.testing.com/#!dashboard1")
.lastMod(new Date()).priority(1.0)
.changeFreq(ChangeFreq.HOURLY).build();
System.out.println("-----------");
System.out.println("sitemapUrl :: "+sitemapUrl.getUrl());
sitemapGenerator.addUrl(sitemapUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/****************/
}
else
{
System.out.println("file already exist");
sitemapGenerator = WebSitemapGenerator
.builder("http://www.testing.com", file)
.gzip(false).build();
try {
sitemapGenerator
.addUrl("http://www.testing.com/#!ques");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("sitemapGenerator :: "+sitemapGenerator);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sitemapGenerator.write();
// this will configure the URL with lastmod=now, priority=1.0,
// changefreq=hourly
// You can add any number of urls here
return "";
}
But my else part is not working it directly goes to server fail.
I am working on java with gwt.
So, any one could help to add dynamically the nodes(urls) in the urlset at runtime.

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
File file=new File("war/abc.xml"); //local war
String val=null;
if(!file.exists())
{
val= "not exist";
try {
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document document = docBuilder.newDocument();
Element rootElement = document.createElement("urlset");
rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
document.appendChild(rootElement);
Element url = document.createElement("url");
Element loc = document.createElement("loc");
loc.appendChild(document.createTextNode(urllink));
url.appendChild(loc);
Element lastmod = document.createElement("lastmod");
lastmod.appendChild(document.createTextNode(dateText));
url.appendChild(lastmod);
Element changefreq = document.createElement("changefreq");
changefreq.appendChild(document.createTextNode("always"));
url.appendChild(changefreq);
Element priority = document.createElement("priority");
priority.appendChild(document.createTextNode("1.0"));
url.appendChild(priority);
rootElement.appendChild(url);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try
{
transformer = transformerFactory.newTransformer();
}
catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(file);
// Output to console for testing
//StreamResult result = new StreamResult(System.out);
try
{
transformer.transform(source, result);
}
catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File saved!");
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
System.out.println("file already exist append ");
val="file already exist append ";
DocumentBuilder documentBuilder = null;
try {
documentBuilder = docFactory.newDocumentBuilder();
} catch (ParserConfigurationException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Document document = null;
try {
document = documentBuilder.parse(file);
document.normalize();
} catch (SAXException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Element rootElement = document.getDocumentElement();
Element url = document.createElement("url");
Element loc = document.createElement("loc");
loc.appendChild(document.createTextNode(urllink));
url.appendChild(loc);
Element lastmod = document.createElement("lastmod");
lastmod.appendChild(document.createTextNode(dateText));
url.appendChild(lastmod);
Element changefreq = document.createElement("changefreq");
changefreq.appendChild(document.createTextNode("always"));
url.appendChild(changefreq);
Element priority = document.createElement("priority");
priority.appendChild(document.createTextNode("1.0"));
url.appendChild(priority);
rootElement.appendChild(url);
DOMSource source = new DOMSource(document);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StreamResult result = new StreamResult(file);
System.out.println("result :: "+result.toString());
try {
transformer.transform(source, result);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

Why am I getting InvocationTargetException at ClassLoaders.callStaticFunction Java Eclipse? [duplicate]

I have created a program to convert text to xml by using ReverseXSL API.
This program is to be executed by an application by calling static method (static int transformXSL).
I am able to execute and produce output with running from Eclipse. However, When I ran program (jar) by using application it stuck somewhere and I couldnt find anything.
Then, I debugged by "Debug as...-> Remote Java Application" in Eclipse from Application and found "InvocationTargetException" at ClassLoaders.callStaticFunction.
Below Static method is called by application.
public class MyTest4 {
public MyTest4()
{
}
public static int transformXSL(String defFile, String inputFile, String XSLFile, String OutputFile) {
System.out.println("Dheeraj's method is called");
// start time
FileWriter fw=null;
try {
fw = new FileWriter("D://Countime.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedWriter output=new BufferedWriter(fw);
DateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dt= new Date();
System.out.println("Date is calculated");
try {
output.write("Start Time:"+sd.format(dt).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sd.format(dt));
FileReader myDEFReader=null, myXSLReader=null;
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t=null;
FileInputStream inStream = null;
ByteArrayOutputStream outStream = null;
// Step 1:
//instantiate a transformer with the specified DEF and XSLT
if (new File(defFile).canRead())
{
try {
myDEFReader = new FileReader(defFile);
System.out.println("Definition file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else myDEFReader = null;
if (new File(XSLFile).canRead())
try {
myXSLReader = new FileReader(XSLFile);
System.out.println("XSL file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
else myXSLReader = null;
try {
t = tf.newTransformer(myDEFReader, myXSLReader);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Step 1: DEF AND XSLT Transformation completed");
// Step 2:
// Read Input data
try {
inStream = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
outStream = new ByteArrayOutputStream();
System.out.println("Step 2: Reading Input file: completed");
// Step 3:
// Transform Input
try {
try (BufferedReader br = new BufferedReader(new FileReader("D://2.txt"))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("Content: "+line);
}
}
System.out.println("File: "+inputFile.toString());
System.out.println("\n content: \n"+ inStream.toString());
System.out.println("Calling Transform Function");
t.transform(inStream, outStream);
System.out.println("Transformation is called");
outStream.close();
try(OutputStream outputStream = new FileOutputStream(OutputFile)) {
outStream.writeTo(outputStream);
System.out.println("Outstream is generated; Output file is creating");
}
System.out.println(outStream.toString());
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (javax.xml.transform.TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output file is created");
// End time
Date dt2= new Date();
System.out.println(sd.format(dt2));
System.out.println("End time:"+dt2.toString());
try {
output.append("End Time:"+sd.format(dt2).toString());
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}

Convert an XML String to CSV file (Java) -> CSV Result is empty

I need help understanding why the XML String does not convert into a CSV file. Why is the CSV Resut always empty?
Here is an example of a Java Code
public class transformCSV_1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String xmlData = new String(
"<?xml version=\"1.0\"?><PurchaseOrder xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://localhost:8080/source/schemas/poSource/xsd/purchaseOrder.xsd\"><Reference>SBELL-2002100912333601PDT</Reference><Actions><Action><User>SVOLLMAN</User></Action></Actions><Requestor>Sarah J. Bell</Requestor><User>SBELL</User><CostCenter>S30</CostCenter><ShippingInstructions><name>Sarah J. Bell</name><address>400 Oracle Parkway Redwood Shores CA 94065 USA</address><telephone>650 506 7400</telephone></ShippingInstructions><SpecialInstructions>Air Mail</SpecialInstructions><LineItems><LineItem ItemNumber=\"1\"><Description>A Night to Remember</Description><Part Id=\"715515009058\" UnitPrice=\"39.95\" Quantity=\"2\"/></LineItem><LineItem ItemNumber=\"2\"><Description>The Unbearable Lightness Of Being</Description><Part Id=\"37429140222\" UnitPrice=\"29.95\" Quantity=\"2\"/></LineItem><LineItem ItemNumber=\"3\"><Description>Sisters</Description><Part Id=\"715515011020\" UnitPrice=\"29.95\" Quantity=\"4\"/></LineItem></LineItems></PurchaseOrder>");
String stylesheet = new String(
"<?xml version=\"1.0\" encoding=\"utf-8\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:output method=\"text\" /><xsl:variable name=\"delimiter\" select=\"','\" /><!-- define an array containing the fields we are interested in --><xsl:variable name=\"fieldArray\"><field>Reference</field><field>User</field><field>Reject</field><field>Requestor</field></xsl:variable><xsl:param name=\"fields\" select=\"document('')/*/xsl:variable[#name='fieldArray']/*\" /><xsl:template match=\"/\"><!-- output the header row --><xsl:for-each select=\"$fields\"><xsl:if test=\"position() != 1\"><xsl:value-of select=\"$delimiter\"/></xsl:if><xsl:value-of select=\".\" /></xsl:for-each><!-- output newline --><xsl:text>
</xsl:text><xsl:apply-templates select=\"PurchaseOrder\"/></xsl:template><xsl:template match=\"PurchaseOrder\"><xsl:variable name=\"currNode\" select=\".\" /><!-- output the data row --><!-- loop over the field names and find the value of each one in the xml --><xsl:for-each select=\"$fields\"><xsl:if test=\"position() != 1\"><xsl:value-of select=\"$delimiter\"/></xsl:if><xsl:value-of select=\"$currNode/*[name() = current()]\" /></xsl:for-each><!-- output newline --><xsl:text>
</xsl:text></xsl:template></xsl:stylesheet>");
InputStream xmlSource = new ByteArrayInputStream(
xmlData.getBytes("UTF-8"));
InputStream styleSource = new ByteArrayInputStream(
stylesheet.getBytes("UTF-8"));
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlSource);
StreamSource stylesource = new StreamSource(styleSource);
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(stylesource);
Source source = new DOMSource(document);
Result outputTarget = new StreamResult(new File("src/resultI.csv"));
transformer.transform(source, outputTarget);
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Best way is to use XSLT to "transform" the XML to CSV --> Can someone give me hint?
Consider to load the XSLT code from a file or URI (instead of from a string) as otherwise your approach of doing <xsl:param name="fields" select="document('')/*/xsl:variable[#name='fieldArray']/*" /> where document('') tries to pull in the XSLT code again is likely to fail, unless you set up a special resolver.

Java parse XML string

I have an string which I am attempting to extract values from, for convenience I thought that converting the string to a Document and then parsing the xml would be the best way to do this but I am running into all sorts of problems! The string looks like:
<Messagexxx>
<Unit>
<contact>0</contact>
<text>Test Content</text>
<date>09-Sep-14 13:56</date>
<subject>Test Title</subject>
</Unit>
</Messagexxx>
Can someone point me in the correct way to achieve my goal of reading the values from the tags .
I have attempted using the following snippet but I all the values in the array are
null! Document xml = null; Node T = null; try { xml = stringToDom(message); T = xml.getLastChild(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(xml.getFirstChild() != null){ }
When you write your string to a text file, you can first parse it:
private Document parse(String filename){
Document doc = null;
try {
DOMParser parser = new DOMParser();
parser.parse(filename);
doc = parser.getDocument();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return doc;
}
and then you read all text elements out of this document:
public void extract (Document doc){
Node root = doc.getDocumentElement();
for (int i = 0; i< root .getChildNodes().getLength(); i++){
Node child = root.getChildNodes().item(i);
System.out.println(child.getTextContent());
}
}
Use JAXB lib : https://jaxb.java.net/
Create your model from your XML and to read :
JAXBContext jaxbContext = JAXBContext.newInstance(YourModel.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader("xml string here");
YourModel yourModel= (Person) unmarshaller.unmarshal(reader);
After your can use the object "YourModel" to read your value.
This is a very simple way to get node values when you know the node names, and they don't repeat:
String getXmlNodeValue(String xmlString, String nodeName){
int start = xmlString.indexOf("<"+nodeName+">") + nodeName.length() + 2;
int end = xmlString.indexOf("</"+nodeName+">");
return xmlString.substring(start, end);
}

How can I put the value from an XML file into an array list in another class in java?

I am reading in an XML file, and trying to return the values in another class using Java. In the XML Reader I read in the values from the XML file. I'm not quite sure how to do this. Any help would be appreciated.
public class XMLReader {
public static List<String> load()
{
try{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("C:/adapters.xml"));
doc.normalize();
NodeList rootNodes = doc.getElementsByTagName("adapters");
Node rootNode = rootNodes.item(0);
Element rootElement = (Element) rootNode;
NodeList adaptersList = rootElement.getElementsByTagName("class");
for(int i=0; i<adaptersList.getLength(); i++){
Node theAdapter = adaptersList.item(i);
Element adpElement = (Element) theAdapter;
System.out.println("This is: " + adpElement.getTextContent());
}
}catch(ParserConfigurationException e){
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public class AdapterLoader {
public static List<AbstractAdapter> loadAllAdapters()
{
List<AbstractAdapter> allAdapters = new ArrayList<AbstractAdapter>();
List<String> adapterClasses = XMLReader.load();
for (String className : adapterClasses)
{
try {
Class adapters = Class.forName(className);
AbstractAdapter adp = (AbstractAdapter) adapters.newInstance();
allAdapters.add(adp);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return allAdapters;
}
}
Instead of printing it to console
System.out.println("This is: " + adpElement.getTextContent());
add this to a List and return that instead of
return null;

Redirecting Error/Exception to HTML page

Needs to redirect the error and exceptions which i found in the catch block to .html page
This is my code now i want if anytime any file not found excpetion will come then it should redirect to .html page or borwser
public class XmlToHtml {
public static void main(String[] args) {
if (args.length == 3 && args.length !=0) {
String dataXML = args[0];
String inputXSL = args[1];
String outputHTML = args[2];
XmlToHtml xmltoHtml = new XmlToHtml();
try {
xmltoHtml.transform(dataXML, inputXSL, outputHTML);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
System.out.println("TransformerConfigurationException" + e);
} catch (TransformerException e) {
e.printStackTrace();
System.out.println("TransformerException" + e);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("FileNotFoundException" + e);
}
} else {
System.err.println("Wrong Input");
System.err
.println("Please Enter in the follwing format : Data.xml Input.xsl Output.html");
}
}
public void transform(String dataXML, String inputXSL, String outputHTML)
throws FileNotFoundException, TransformerException,
TransformerConfigurationException {
TransformerFactory tFactory = TransformerFactory.newInstance();
Source xslDoc = new StreamSource(inputXSL);
Source xmlDoc = new StreamSource(dataXML);
OutputStream htmlDoc = new FileOutputStream(outputHTML);
Transformer transformer = tFactory.newTransformer(xslDoc);
transformer.transform(xmlDoc, new StreamResult(htmlDoc));
Desktop dk = Desktop.getDesktop();
try {
dk.open(new File(outputHTML));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories