read xml from jsp - java

lets say i have an xml file "path.xml" that goes like this:
<paths>
<path id="first">
<url>http://blablabla</url>
</path>
<path id="second">
<url>http://blablabla</url>
</path>
</paths>
i have a jsp file from which i want to read url based on the id.
for example:
i want to write in the jsp file some java code like:String path = get from xml file the "url", where path id = "second".
how is this done in jsp? i am not very experienced with Dom parsing in jsp
thanks a lot:)

You could use XML Tag Library
:
<x:parse doc="path.xml" var="doc" scope="application"/>
<x:out select="$doc/paths/path[id='second']/url"/>

First off, you shouldn't be writing scriptlets in your JSP to perform a processing like this. That should reside in your Java file, not JSP file.
To parse XML with Java, there are tons of examples you will find by just Googling around. Here's one to get you started: http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html

Related

how can i get a matching string from a xml file using <getxmlproperties> tag using ant and replace the matched string in other xml file

My requirement is to match following tag in data.xml file and replace the content in display.xml file using in ant
data.xml
--------
<data>123456789</data>
display.xml
-----------
<data>abcdefg</data
I need to match the content in data.xml file and replace the it in display.xml file.
my final output should be like:
data.xml
--------
<data>123456789</data>
display.xml
-----------
<data>123456789</data>
How can i solve this Issue? Thanks in advance
I did not find any Ant task named GetXmlProperties, but I think you may have thought about this one, XmlProperty, which composes a sequence of properties from parsing an XML document.
Two ways, to achieve what you want, come to my mind (there may be more):
The most primitive would be to just use the XmlProperty task to retreive the value in question and use a crude Replace task on the destination file, doing a simple string replace, by handling the destination as a plain text file, instead of caring for the XML logic in it. However, doing string match and replace with XML data is no fun and error prone.
Thus I propose a second approach, which is to use the XmlTask, as per the following example. Adding a prefix xml to our newly parsed properties makes it easier to distinguish them from the rest. For demo purposes we also let the build process log all the new properties under the xml prefix to the console by using the EchoProperties task.
<project name="SO63816092" default="default">
<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask" />
<xmlproperty file="data.xml" prefix="xml" />
<echoproperties prefix="xml"/>
<target name="default">
<xmltask source="display.xml" dest="display.xml" failWithoutMatch="true">
<replace path="//data/text()" withText="${xml.data}" />
</xmltask>
</target>
</project>
Using the second approach, while using the following input file data.xml:
<?xml version="1.0" encoding="UTF-8"?>
<data>123456789</data>
and the following destination file display.xml:
<?xml version="1.0" encoding="UTF-8"?>
<data>abcdefg</data>
I can successfully accomplish what you ask for and get display.xml to become:
<?xml version="1.0" encoding="UTF-8"?>
<data>123456789</data>
Just remember to place the XmlTask Java jar in the current classpath for your Ant process and note, that you may need to change the XPath expression, we use, //data/text(), to something more refined, should your document structure demand it, because the way, it is now, it would replace the value for all data elements it finds, throughout the whole display.xml document.

How to split xml to header and items using smooks?

I have a xml file roughly like this:
<batch>
<header>
<headerStuff />
</header>
<contents>
<timestamp />
<invoices>
<invoice>
<invoiceStuff />
</invoice>
<!-- Insert 1000 invoice elements here -->
</invoices>
</contents>
</batch>
I would like to split that file to 1000 files with the same headerStuff and only one invoice. Smooks documentation is very proud of the possibilities of transformations, but unfortunately I don't want to do those.
The only way I've figured how to do this is to repeat the whole structure in freemarker. But that feels like repeating the structure unnecessarily. The header has like 30 different tags so there would be lots of work involved also.
What I currently have is this:
<?xml version="1.0" encoding="UTF-8"?>
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
xmlns:calc="http://www.milyn.org/xsd/smooks/calc-1.1.xsd"
xmlns:frag="http://www.milyn.org/xsd/smooks/fragment-routing-1.2.xsd"
xmlns:file="http://www.milyn.org/xsd/smooks/file-routing-1.1.xsd">
<params>
<param name="stream.filter.type">SAX</param>
</params>
<frag:serialize fragment="INVOICE" bindTo="invoiceBean" />
<calc:counter countOnElement="INVOICE" beanId="split_calc" start="1" />
<file:outputStream openOnElement="INVOICE" resourceName="invoiceSplitStream">
<file:fileNamePattern>invoice-${split_calc}.xml</file:fileNamePattern>
<file:destinationDirectoryPattern>target/invoices</file:destinationDirectoryPattern>
<file:highWaterMark mark="10"/>
</file:outputStream>
<resource-config selector="INVOICE">
<resource>org.milyn.routing.io.OutputStreamRouter</resource>
<param name="beanId">invoiceBean</param>
<param name="resourceName">invoiceSplitStream</param>
<param name="visitAfter">true</param>
</resource-config>
</smooks-resource-list>
That creates files for each invoice tag, but I don't know how to continue from there to get the header also in the file.
EDIT:
The solution has to use Smooks. We use it in an application as a generic splitter and just create different smooks configuration files for different types of input files.
I just started with Smooks myself. However... your problem sounds identical to this: http://www.smooks.org/mediawiki/index.php?title=V1.5:Smooks_v1.5_User_Guide#Routing_to_File
You will have to provide the output FTL format in whole, that's the downside of using a general purpose tool I guess. Data mapping often includes a lot of what feels like redundancy, one way around this is to leverage convention but that has to be built into the framework.
I don't know smooks, but the simplest solution (with poor performance) would be (to create the Nth file):
copy the whole xml structure
delete all the invoice tags but the Nth one
I don't know how to do that in smooks, that only an idea. In this case you don't need to duplicate the structure of the xml in a freemarker template.

xsl loading image to get metadata

i would like to load an image to get the metadata. my code is like this :
the value of "url" is like this : "http:\localhost:8080\mypics\pic1.jpg"
<xsl:call-template name="mypic">
<xsl:with-param name="metadata" select="document($url)/metadata"/>
</xsl:call-template>
i get this exception : ID systÞme inconnu; Ligne #47; Colonne #38; Unable to load the requested document : C:\http:\localhost:8080\mypics\pic1.jpg (the specific path was not found)
Thanks for help.
The value of $url should be
http://localhost:8080/mypics/pic1.jpg
Update
According to this documentation you need to specify an URI and the resource at that URI has to be of xml type. I strongly doubt, that you can handle images with this expression. The document() function is used to access (xml-)nodes in external documents.
I guess, the backslashes made the processor believe the string was pointing to a file resource, relative to C:\.
i would like to load an image to get the metadata. my code is like
this : the value of "url" is like this :
"http:\localhost:8080\mypics\pic1.jpg"
In XSLT you cant load a file unless it contains a well-formed XML document, or just text (not binary).
In an XSLT transformation only XML documents (with the document() function) or text files (with the XSLT 2.0 unparsed-text()) function can be loaded.
I assume that there is no native XSLT way to do this as I guess Dimitrie would have shown us one if existed.
The alternative is to drop out to Java. Write your own extension function in Java and call it from your XSLT. This link shows how this can be done:
http://www.redstream.nl/2011/03/29/xslt-2-0-and-java-extensions/

how to get full path from file type in JSP?

i written some code in JSP like this--
<input type="file" name="imagename" >
and in servlet i am retrieving 'imagename' value. But it is giving the name of the image instead of full path. My servlet code is like this:
String imagename = request.getParameter("imagename");
and i dont want to use javascript. any ideas? Thanks in advance
Maybe you should checkout this question: How to get the file path from HTML input form in Firefox 3
There is little to no reason why server should have to know full file path. If you want to upload a file, you'll need to use an appropriate library like Apache Commons FileUpload and transfer the file using.
<form action="upload-script-url" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
Apache Commons FileUpload will then accept and transform encoded file into a usable form.
Otherwise you'll need to use JavaScript to get that path.
Assuming that you are trying to upload a file to your server, please note that file uploads are a little more than what you are trying to do - do not expect that if you have a "file" input type in a form, on submission the file just reaches your sever, with no effort. There is a certain procedure to do that.
This article might e a good reference : http://www.cs.tut.fi/~jkorpela/forms/file.html
For Java, use Apache's commons-fileupload : http://commons.apache.org/fileupload/
imagename contains the variable you pass to the servlet... the actual HTTP request parameter. If you want the full path, be sure that the program that is calling your HTTP page is passing the full path instead of just the image name.

Export HTML table to Excel - using jQuery or Java

I've a HTML table on my JSP page, that I want to be exported to Excel on a button click.
What would be the best way of going about this?
(For ex., how would I do this using may be a jQuery function?)
Any code examples for demo purposes should be great.
I would recommend Apache POI, we've been using it for years, never had any problems.
Alot of examples online to get a good start, and the documentation on the site is also good: http://poi.apache.org/spreadsheet/quick-guide.html
Rather export to CSV format. It's supported by Excel as well. Exporting to a fullworthy XLS(X) format using for example Apache POI HSSF or JExcepAPI is slow and memory hogging.
Exporting to CSV is relatively simple. You can find a complete code example in this answer.
As to exporting to files using JavaScript, this is not possible without interaction of Flash or the server side. In Flash there's as far only the Downloadify library which can export to simple txt files. Further, ExtJs seems to have a CSV export library, but I can't find any feasible demo page.
You can parse the table using a library like http://jsoup.org/
After you get the data, you can store it in Excel-compatible format (CSV), or using Java Excel library for that like POI, or using JDBC to write data into Excel sheet, see this example:
Password Protected Excel File
I also spend lot of time to convert html to excel after lot of R & D i found following easiest way.
create hidden field and in that pass your html data to your servlet or controller for e.g
<form id="formexcel" action="" method="post" name="formexcel">
<input type="hidden" name="exceldata" id="exceldata" value="" />
</form>
on your button of href click call following function and pass your html data using in document.formexcel.exceldata.value and your servlet or controller in document.formstyle.action
function exportDivToExcel() {
document.formexcel.exceldata.value=$('#htmlbody').html();
$("#lblReportForPrint").html("Procurement operation review report");
document.formstyle.method='POST';
document.formstyle.action='${pageContext.servletContext.contextPath}/generateexcel';
document.formstyle.submit();
}
Now in your controller or servlet write following code
StringBuilder exceldata = new StringBuilder();
exceldata.append(request.getParameter("exceldata"));
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=\"exportexcel.xls\"");
outputStream.write(exceldata.toString().getBytes());
Excel can load CSV (comma-separated value) files, which are basically just files with everything that would go into separate Excel cells separated by comma.
I don't know enough about how jQuery can handle pushing information into a file that you would download, but it seems a jQuery library has been written that at least transforms html tables to CSV format, and it is here:
http://www.kunalbabre.com/projects/table2CSV.php
Edit (February 29, 2016):
You can use the table2csv implementation above in conjunction with FileSaver.js (which is a wrapper for the HTML5 W3C saveAs() spec).
The usage will end up looking something like:
var resultFromTable2CSV = $('#table-id').table2CSV({delivery:'value'});
var blob = new Blob([resultFromTable2CSV], {type: "text/csv;charset=utf-8"});
saveAs(blob, 'desiredFileName.csv');
Exporting to Excel file format with JQuery is impossible.
You can try with Java. There are a lot of libraries to do that.
You would have to create something on the server-side (like a servlet) to read the html and create the excel file and serve it back to the user.
You could use this library to help you do the transformation.
I can suggest you to try http://code.google.com/p/gwt-table-to-excel/, at least the server part.
I have been using the jQuery plugin table2excel. It works very well and no serverside coding is needed.
Using it is easy. Simply include jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Now include the table2excel script (Remember to change the src destination to match yours)
<script src="dist/jquery.table2excel.min.js"></script>
Now simply call the script on the table you want exportet.
$("#yourHtmTable").table2excel({
exclude: ".excludeThisClass",
name: "Worksheet Name",
filename: "SomeFile" //do not include extension
});
It's also easy to attach to a button like so:
$("button").click(function(){
$("#table2excel").table2excel({
// exclude CSS class
exclude: ".noExl",
name: "Excel Document Name"
});
});
All examples are taken directly from the authors github page and from jqueryscript.net

Categories

Resources