How to display images from database in JSF - java

I have images that are stored in the database as a BLOB. Now I can display them in my jsf pages using Richfaces mediaOutput tag.
Is it possible for images to have path like "/images/image.jpg" while images are stored in the database.
While searching for an answer I came around something like this:
#GET
#Path("/files/{filename}")
#Produces(MediaType.WILDCARD)
Best regards,
Ilya Sidorovich

You could write a servlet picking up every request to /image/* or something that suits you.
And in your servlet you retrieve the correct data from your database via request parameters.
And you write out the data via
response.getOutputStream().write(content);
(content being the bytearray of you image)

Thank you roel and BalusC!
If anyone comes around this issue, here is what you can do.
package org.gicm.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.inject.Inject;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import org.gicm.cms.CMSDao;
import org.gicm.model.UploadedImage;
#WebServlet("/images/*")
public class TestServlet extends HttpServlet {
#Inject
private CMSDao cms;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String imageId = String.valueOf(request.getPathInfo().substring(1)); // Gets string that goes after "/images/".
UploadedImage image = cms.findImage(imageId); // Get Image from DB.
response.setHeader("Content-Type", getServletContext().getMimeType(image.getName()));
response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(image.getData()); // Creates buffered input stream.
output = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[8192];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
}
}

Related

Huge white space after header in PDF using Flying Saucer

I am trying to export an HTML page into a PDF using Flying Saucer. For some reason, the pages have a large white space after the header (id = "divTemplateHeaderPage1") divisions.
The jsFiddle link to my HTML code that is being used by PDF renderer: https://jsfiddle.net/Sparks245/uhxqdta6/.
Below is the Java code used for rendering the PDF (Test.html is the same HTML code in the fiddle) and rendering only one page.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.HTTP;
import org.json.JSONException;
import org.json.*;
import org.json.simple.JSONArray;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.*;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.DocumentException;
import com.lowagie.text.List;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
#WebServlet("/PLPDFExport")
public class PLPDFExport extends HttpServlet
{
//Option for Serialization
private static final long serialVersionUID = 1L;
public PLPDFExport()
{
super();
}
//Get method
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException
{
}
//Post method
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException
{
StringBuffer jb = new StringBuffer();
String line = null;
int Pages;
String[] newArray = null;
try
{
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
{ jb.append(line);
}
} catch (Exception e) { /*report an error*/ }
try
{
JSONObject obj = new JSONObject(jb.toString());
Pages = obj.getInt("Pages");
newArray = new String[1];
for(int cnt = 1; cnt <= 1; cnt++)
{
StringBuffer buf = new StringBuffer();
String base = "C:/Users/Sparks/Desktop/";
buf.append(readFile(base + "Test.html"));
newArray[0] = buf.toString();
}
}
catch (JSONException e)
{
// crash and burn
throw new IOException("Error parsing JSON request string");
}
//Get the parameters
OutputStream os = null;
try {
final File outputFile = File.createTempFile("FlyingSacuer.PDFRenderToMultiplePages", ".pdf");
os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
// we need to create the target PDF
// we'll create one page per input string, but we call layout for the first
renderer.setScaleToFit(true);
renderer.isScaleToFit();
renderer.setDocumentFromString(newArray[0]);
renderer.layout();
try {
renderer.createPDF(os, false);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// each page after the first we add using layout() followed by writeNextDocument()
for (int i = 1; i < newArray.length; i++) {
renderer.setScaleToFit(true);
renderer.isScaleToFit();
renderer.setDocumentFromString(newArray[i]);
renderer.layout();
try {
renderer.writeNextDocument();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// complete the PDF
renderer.finishPDF();
System.out.println("PDF Downloaded to " + outputFile );
System.out.println(newArray[0]);
}
finally {
if (os != null) {
try {
os.close();
} catch (IOException e) { /*ignore*/ }
}
}
//Return
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("File Uploaded");
}
String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
}
The link for exported PDF: https://drive.google.com/file/d/13CmlJK0ZDLolt7C3yLN2k4uJqV3TX-4B/view?usp=sharing
I tried adding css properties like page-break-inside: avoid to the header divisions but it didn't work. Also I tried adding absolute positions and top margins to the body division (id = "divTemplateBodyPage1") just below the header div, but the white space continues to exist.
Any suggestions would be helpful.
Please take a look at the metadata of your PDF:
You are using an old third party tool that is not endorsed by iText Group, and that uses iText 2.1.7, a version of iText dating from 2009 that should no longer be used.
It would probably have been OK to complain and to write "My code isn't working" about 7 years ago, but if you would use the most recent version of iText, the result of converting your HTML to PDF would look like this:
I only needed a single line of code to get this result:
HtmlConverter.convertToPdf(new File(src), new File(dest));
In this line src is the path the the source HTML and dest is the path to the resulting PDF.
I only had to apply one minor change to your HTML. I change the #page properties like this:
#page {
size: 27cm 38cm;
margin: 0.2cm;
}
If I hadn't changed this part of the CSS, the page size would have been A4, and in that case, not all the content would have fitted the page. I also added a small margin because I didn't like the fact that the border was sticking to close to the sides of the page.
Morale: don't use old versions of libraries! Download the latest version of iText and the pdfHTML add-on. You need iText 7 core and the pdfHTML add-on. You might also want to read the HTML to PDF tutorial.

Read HTTP POST from mobile in java

I have iOS Swift code, which sends a POST request to server. If i send this code directly to apple server i get response back with proper data. But when i send this to my server, server could not get the body of the HTTP POST.
I have no idea whether this issue is related to client side or server side.
Here is the Swift code.
func validateReceipt(completion : (status : Bool) -> ()) {
let receiptUrl = NSBundle.mainBundle().appStoreReceiptURL!
if NSFileManager.defaultManager().fileExistsAtPath(receiptUrl.path!)
{
if let receipt : NSData = NSData(contentsOfURL: receiptUrl)
{
let receiptdata: NSString = receipt.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithLineFeed)
let dict = ["receipt-data" : receiptdata]
let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0))
let request = NSMutableURLRequest(URL: NSURL(string: ReceiptURL.MAIN_SERVER.rawValue)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.HTTPBody = jsonData
let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
if let dataR = data
{
self.handleData(dataR, completion: { status in
completion(status: status)
})
}
})
task.resume()
}
else
{
completion(status: false)
}
}
else
{
completion(status: false)
}
}
and here is my Java code in server side, there are two Java classes which take care of this
MyRequestWrapper.Java
package webservice;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class MyRequestWrapper extends HttpServletRequestWrapper {
private final String body;
public MyRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[100000];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
}
#Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
return servletInputStream;
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
public String getBody() {
return this.body;
}
}
And here is the another class.
GetResult.Java
package webservice;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
#Path("/service")
public class GetResult {
static Logger logger = Logger.getLogger(GetResult.class);
// #Produces("application/json; charset=UTF-8")
//#Produces("text/plain")
#POST
#Produces (MediaType.APPLICATION_JSON)
public Response inapp(#Context HttpServletRequest request,
#Context HttpServletResponse response) throws Exception {
System.out.println("response===" + response);
System.out.println("Request-Header===" + request.getHeader("receipt-data"));
System.out.println("Request===" + request.getParameter("receipt-data"));
// System.out.println("Request==="+request.getReader());
// reader(request,response);
// getBody(request);
doFilter(request,response);
String result = "";
result = " " /* jsonObject */;
return Response.status(200).entity(result).build();
}
We could get the client IP and client Port from this request but unable to get the body. In production also we could not get the body. Some Java developers told me that you cant directly get the raw bytes in Java, i don't know about this.
Somebody please take a look at this, and tell me what i am doing wrong.
You may have to explicitly set the content type of the input post body you send to the server. This can be achieved as follows:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
Set the content type after setting the http method and son data to the request object( NSMutableURLRequest object)
This may help you!
Edited:
Actually the header field name is "Content-Type".

Java Servlet: Pick files to download

I'm pretty new to Java Servlets/Apache Tomcat/etc but I was able to find some handy resources on how I can implement Download and Upload functionality.
When the user wants to upload a file, they click the button, and they are prompted to select a file. However, when they want to download a file, they only have the choice of just the one file (specified in the servlet).
So, my question is: Is there a way to list out the directory somehow that would let the user pick a particular file, and then download that file?
Below is my code if you need a point of reference:
NOTE: This code works, I just want to know how I can expand on it with the desired effect I want.
package testPackage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet
{
private static final String absFilePath = "/test/files/download/test.txt";
private static final String relFilePath = "/files/download/test.txt";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//Quick switch to determine what type of path to user
boolean useAbsolute = false; //Defaults to relative
//Initialize a new File
File downloadFile = new File("");
//Check if we want to use the absolute file path
if(useAbsolute)
{
//Read the input file from the absolute path
downloadFile = new File(absFilePath);
}
//Otherwise, we are using relative
else
{
//Read the input file from the relative path
String relativePath = getServletContext().getRealPath(relFilePath);
downloadFile = new File(relativePath);
//System.out.println("Relative Path: " + relativePath);
}
//Open up the FileInputStream
FileInputStream inputStream = new FileInputStream(downloadFile);
//Obtain the Servlet Context
ServletContext context = getServletContext();
//Get the MIME type of the file
String mimeType = context.getMimeType(absFilePath);
//If we don't get a type, default to binary
if(mimeType == null)
{
//Set to binary type if the MIME mapping is not found
mimeType = "application/octet-stream";
}
//Just some logging
System.out.println("MIME Type: " + mimeType);
//Modify Servlet Response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
//Set the header key/value
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);
//Obtain the response output stream
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
//While there are bytes to write
while((bytesRead = inputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, bytesRead);
}
//Close the streams
inputStream.close();
outputStream.close();
}
}

Converting DICOM image to jpeg image

My code is
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.dcm4che2.imageio.plugins.dcm.DicomImageReadParam;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class DicomToJpeg {
public static void main(String args[]) throws IOException, Exception
{
dicomToJpeg("d:/F74AFBC7");
}
public static void dicomToJpeg(String args) throws IOException, Exception {
// TODO Auto-generated method stub
try
{
File myDicomFile = new File(args);
BufferedImage myJpegImage = null;
Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
ImageReader reader = (ImageReader) iter.next();
DicomImageReadParam param = null;
try{
param = (DicomImageReadParam) reader.getDefaultReadParam();
}
catch (Exception e) {
e.printStackTrace();
}
ImageInputStream iis=ImageIO.createImageInputStream(myDicomFile);
reader.setInput(iis, false);
myJpegImage = reader.read(0, param);
iis.close();
if (myJpegImage == null) {
System.out.println("\nError: couldn't read dicom image!");
return;
}
File myJpegFile = new File("d:/demo.jpg");
OutputStream output = new BufferedOutputStream(new FileOutputStream(myJpegFile));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
encoder.encode(myJpegImage);
System.out.println("Image Create successufully");
output.close();
}
catch(IOException e){
System.out.println("\nError: couldn't read dicom image!"+ e.getMessage());
return;
}
}
}
When i execute in java project using eclipse it work fine...
But when i execute using web application and in this i call it from controller page like
DicomToJpeg.dicomToJpeg("d:/F74AFBC7");
then it gives error like...
java.util.NoSuchElementException
at javax.imageio.spi.FilterIterator.next(Unknown Source)
at javax.imageio.ImageIO$ImageReaderIterator.next(Unknown Source)
at javax.imageio.ImageIO$ImageReaderIterator.next(Unknown Source)
at com.lifecare.controller.DicomToJpeg.dicomToJpeg(DicomToJpeg.java:32)
How to solve this error please help me....
The javadoc to ImageIO.getImageREadersByFormatName says:
Returns an Iterator containing all currently registered ImageReaders
that claim to be able to decode the named format.
If you access the iterator without checking if it has an element, you will get an exception.
Since it runs in you IDE and not on the server, you may have a look if the image readers for the DICOM is in the application's classpath on the server.
However, I would also like to know how do you call the above class. Is it from a servlet?
I solved it by calling ImageIO.scanForPlugins() before ImageIO.getImageReadersByFormatName()
ImageIO.scanForPlugins()
Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
ImageReader reader = (ImageReader) iter.next();
This works perfectly on servlets
Try like this
BufferImage bi = ImageIO.read(dcm file name with path);
ImageIO.write(enter pathname with filename, format);

Servlet java, server side, send a string as a new txt file

I have a Java web app. The user is able to upload a file (via POST request), and then the servlet will execute some code on this file. The output of this code is a string.
How to return a file to the user, without create one on the server side? Is that possible?
yes,
you have to set content disposition header then write the stream to response.
Try to use that code
package com.hainasoft.web;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet {
static final long serialVersionUID = 1L;
private static final int BUFSIZE = 4096;
private String filePath;
public void init() {
// the file data.xls is under web application folder
filePath = getServletContext().getRealPath("") + File.separator + "data.xls";
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
File file = new File(filePath);
int length = 0;
ServletOutputStream outStream = response.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType(filePath);
// sets response content type
if (mimetype == null) {
mimetype = "application/octet-stream";
}
response.setContentType(mimetype);
response.setContentLength((int)file.length());
String fileName = (new File(filePath)).getName();
// sets HTTP header
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
byte[] byteBuffer = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(file));
// reads the file's bytes and writes them to the response stream
while ((in != null) && ((length = in.read(byteBuffer)) != -1))
{
outStream.write(byteBuffer,0,length);
}
in.close();
outStream.close();
}
}
it is important to set the myme type
mimetype = "application/octet-stream";
and with this you set a download dialog to the user
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
I have retrieved all that information from
http://www.java-forums.org/blogs/servlet/668-how-write-servlet-sends-file-user-download.html
so take a look in it for more accurate information.

Categories