Reneder XML on browser using Binary Stream - java

I have one xml file in JCR, I want to render this XML over browser via servlet. Below is the code I am using :
String path = "/content/geometrixx/en/sitemap.xml/jcr:content";
if(session.nodeExists(path)) {
Node node = session.getNode(path);
InputStream inputStream = node.getProperty("jcr:data").getBinary().getStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while (result != -1) {
byte b = (byte) result;
buf.write(b);
result = bis.read();
}
out.print(buf.toString());
}
But in this way only string gets printed over browser means values of tags not the whole XML. How can I render whole XML to browser.

Related

How to get Java Resource file into byte[]?

I have a Java program that needs to read a file from a resource within the JAR and it only takes it through byte[]. My problem is converting the resource file from a folder within the project (i.e. tools/test.txt) into byte[]. I have tried the following (gave an "undefined for type" error):
final byte[] temp = new File("tools/test.txt").getBytes();
Another method I tried resulted in not being able to find the file:
FileOutputStream fos = new FileOutputStream("tools/test.txt");
byte[] myByteArray = null;
fos.write(myByteArray);
fos.close();
System.out.println("Results = " + myByteArray);
And lastly using Inputstream and BufferedReader. This actually gave the content of the file when running the program from Eclipse, but came out as null when running it as a jar (I am assuming that it is also not reading the file).
InputStream is = null;
BufferedReader br = null;
String line;
ArrayList list = new ArrayList();
try {
is = Main.class.getResourceAsStream("tools/test.txt");
br = new BufferedReader(new InputStreamReader(is));
while (null != (line = br.readLine())) {
list.add(line);
System.out.println("Output:" + line);
}
while (null == (line = br.readLine())) {
System.out.println("Error loading file:" + line);
}
}
catch (Exception ef) {
ef.printStackTrace();
System.out.println("Output:" + ef);
}
So my question is, if I have a folder named "tools" and have a file called "test.txt", what code would I use to turn it into byte[] and still work when compiled into a Jar file?
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream in = Main.class.getResourceAsStream("/tools/test.txt");
byte[] buffer = new byte[4096];
for (;;) {
int nread = in.read(buffer);
if (nread <= 0) {
break;
}
baos.write(buffer, 0, nread);
}
byte[] data = baos.toByteArray();
String text = new String(data, "Windows-1252");
Byte[] asByteObjects = new Byte[data.length];
for (int i # 0; i < data.length: ++i) {
asByteObjects[i] = data[i];
}
Without the heading slash the path would be relative to the package of the class. A ByteArrayOutputStream serves to collect for a byte[].
If the bytes represent text is some encoding, one can turn it into a String. Here with Windows Latin-1.
have you tried Scanner.nextByte()? make a new scanner with the file you want to parse as the input and use a for loop to create your array.

Not able to process big file inside a zip file using ZipInputStream

I am having a below mentioned java class which extracts a zip, and one by one convert its content to string and print to console.
Problem is, when the file present inside the zip is big ~80KB. Entire content is not getting displayed (only 3/4 of the data is getting converted to string and displayed in console).
Secondly below mentioned code is introducing null/space in between and also if the file size is small ~1KB
what is wrong in below mentioned code.
public static void main(String[] args) throws Exception {
byte[] buf = new byte[1024];
final int BUFFER = 1024;
String fName = "c:\\DOC00001.zip";
ZipInputStream zinstream = new ZipInputStream(
new FileInputStream(fName));
ZipEntry zentry = zinstream.getNextEntry();
while (zentry != null) {
byte data[] = new byte[BUFFER];
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((zinstream.read(data, 0, BUFFER)) != -1) {
out.write(data);
}
InputStream is = new ByteArrayInputStream(out.toByteArray());
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
String response = writer.toString();
System.out.println(response);
zentry = zinstream.getNextEntry();
}
zinstream.close();
}
The read method is not guaranteed to read a full buffer; the number of bytes that have been read is returned. The correct way to extract data from a zip file, or any InputStream in general, would be:
byte[] data = new byte[BUFFER];
ByteArrayOutputStream out = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = zinstream.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, bytesRead);
}
Or, since you are already using IOUtils,
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(zinstream, out);
Or, given that you write to a ByteArrayOutputStream only to later write to a String, you can skip the ByteArrayOutputStream entirely:
while (zentry != null) {
StringWriter writer = new StringWriter();
IOUtils.copy(zinstream, writer, "UTF-8");
String response = writer.toString();
System.out.println(response);
zentry = zinstream.getNextEntry();
}

images courrupted

I am creating httpServer and I have done writing file server part.
But I am having problems when I download images.
FileInputStream fis = new FileInputStream(file_path);
output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int n = 0;
while (-1 != (n = fis.read(buffer))) {
output.write(buffer, 0, n);
}
data = output.toByteArray();
body = new String(data);
return body
I return the body of response to my original method.
// body is return value from above code, header is also another String return value from
// makeHeader method
String response = header + body;
byte[] Response = null;
try{
Response = response.getBytes("US-ASCII");
}catch (UnsupportedEncodingException e) {}
return Response
My server is working when it comes to text files, .html, .css but not with images.
Can you please point me out what did I do wrong
If you mix text and binary you are sure to corrupt the data. For example US-ASCII is only 7 bit and any byte with the top bit set will be corrupted.
You should attempt to send the image without using String or text to avoid corruption.

How to get a binary file from a remote php script response?

I'm calling a script that gives me a binary file (12345.cl), with binary data. The script is done, and it's working, if I paste it on the navigator I get the binary file.
Now I have a problem: How I transform the response of the script into a binary resource to use it in my app?
For the moment, i have this code:
public void decodeStream( String mURL ){
BufferedInputStream bis = new BufferedInputStream(new URL(mURL).openStream(), BUFFER_IO_SIZE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos, BUFFER_IO_SIZE);
copy(bis, bos);
bos.flush();
Then, I have a BufferedOutputStream with the response, but I don't know how to transform it into a binary resource to use it
I need to obtain a datainputstream with the file but I don't know how to achieve it
You can use following code:
public void decodeStream( String mURL, String ofile ) throws Exception {
InputStream in = null;
FileOutputStream out = null;
try {
URL url = new URL(mURL);
URLConnection urlConn = url.openConnection();
in = urlConn.getInputStream();
out = new FileOutputStream(ofile);
int c;
byte[] b = new byte[1024];
while ((c = in.read(b)) != -1)
out.write(b, 0, c);
} finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
}

How do I get the InputStream of decompressed data from an InputStream of GZIPed data?

I call a service which returns a gzipped file. I have the data as an InputStream (courtesy of javax.activation.DataHandler.getInputStream();) from the response.
What I would like to do is, without writing anything to disk, get an InputStream of the decompressed data in the file that is in the archive. The compressed file in this case is an xml document that I am trying to unmarshal using javax.xml.bind.Unmarshaller which takes an InputStream.
I'm currently trying to write the InputStream to an OutputStream (decompressing the data) and then I'll need to write it back to an InputStream. It's not working yet so I thought I would see if there was a better (I would hope so) approach.
I can write the initial InputStream to disk and get a gz file, and then read that file, get the compressed file out of it and go from there but I'd rather keep it all in memory is possible.
Update 1: Here is my current (not working - get a "Not in GZIP format" exception):
ByteArrayInputStream xmlInput = null;
try {
InputStream in = dh.getInputStream(); //dh is a javax.activation.DataHandler
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int bytes_read = 0;
byte[] dataBuf = new byte[4096];
while ((bytes_read = bis.read(dataBuf)) != -1) {
bo.write(dataBuf, 0, bytes_read);
}
ByteArrayInputStream bin = new ByteArrayInputStream(bo.toByteArray());
GZIPInputStream gzipInput = new GZIPInputStream(bin);
ByteArrayOutputStream out = new ByteArrayOutputStream();
dataBuf = new byte[4096];;
bytes_read = 0;
while ((bytes_read = gzipInput.read(dataBuf)) > 0) {
out.write(dataBuf, 0, bytes_read);
}
xmlInput = new ByteArrayInputStream(out.toByteArray());
If instead of writing to a ByteArrayOutputStream I write to a FileOutputStream the first time around I get a compressed file (which I can manually open to get the xml file within) and the service (eBay) says it should be a gzip file so I'm not sure why I get a "Not in GZIP format" error.
Update 2: I tried something a little different - same error ("Not in GZIP format"). Wow, I just tried to end that parenthesis with a semi-colon. Anyways, here is my second attempt, which still does not work:
ByteArrayInputStream xmlInput = null;
try {
GZIPInputStream gzipInput = new GZIPInputStream(dh.getInputStream());
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int bytes_read = 0;
byte[] dataBuf = new byte[4096];
while ((bytes_read = gzipInput.read(dataBuf)) != -1) {
bo.write(dataBuf, 0, bytes_read);
}
xmlInput = new ByteArrayInputStream(bo.toByteArray());
Decorate the input stream with a GZIPInputStream.
InputStream decompressed = new GZIPInputStream(compressed);
The following code should work. Keep in mind you'll have to handle exceptions properly.
OutputStream out = null;
InputStream in = null;
try {
out = /* some output stream */;
in = new java.util.GZIPInputStream(/*some stream*/);
byte[] buffer = new byte[4096];
int c = 0;
while (( c = in.read(buffer, 0, 4096)) > 0) {
out.write(buffer, 0, c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
Take a look at GZIPInputStream. Here's an example; the class handles this very transparently, it's almost no work to use.

Categories

Resources