Java code to generate report using BIRT - java

I have some data in the form of XML which contains few records and also created one RPT file.
So now, how can i call birt to generate report by passing XML and RPT as input parameters.
I am completely new to BIRT. Any code example wil be appreciated.

try this:BirtEngine.java:
public class BirtEngine {
private static IReportEngine birtEngine = null;
private static Properties configProps = new Properties();
private final static String configFile = "BirtConfig.properties";
public static synchronized void initBirtConfig() {
loadEngineProps();
}
public static synchronized IReportEngine getBirtEngine(ServletContext sc) {
if (birtEngine == null)
{
EngineConfig config = new EngineConfig();
if( configProps != null){
String logLevel = configProps.getProperty("logLevel");
Level level = Level.OFF;
if ("SEVERE".equalsIgnoreCase(logLevel))
{
level = Level.SEVERE;
} else if ("WARNING".equalsIgnoreCase(logLevel))
{
level = Level.WARNING;
} else if ("INFO".equalsIgnoreCase(logLevel))
{
level = Level.INFO;
} else if ("CONFIG".equalsIgnoreCase(logLevel))
{
level = Level.CONFIG;
} else if ("FINE".equalsIgnoreCase(logLevel))
{
level = Level.FINE;
} else if ("FINER".equalsIgnoreCase(logLevel))
{
level = Level.FINER;
} else if ("FINEST".equalsIgnoreCase(logLevel))
{
level = Level.FINEST;
} else if ("OFF".equalsIgnoreCase(logLevel))
{
level = Level.OFF;
}
config.setLogConfig(configProps.getProperty("logDirectory"), level);
}
config.setEngineHome("");
IPlatformContext context = new PlatformServletContext( sc );
//IPlatformContext context = new PlatformFileContext();
config.setPlatformContext( context );
//Create the report engine
//birtEngine = new ReportEngine( config );
//ReportEngine engine = new ReportEngine( null );
try
{
Platform.startup( config );
}
catch ( BirtException e )
{
e.printStackTrace( );
}
IReportEngineFactory factory = (IReportEngineFactory) Platform
.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
birtEngine = factory.createReportEngine( config );
}
return birtEngine;
}
public static synchronized void destroyBirtEngine() {
if (birtEngine == null) {
return;
}
birtEngine.destroy();
Platform.shutdown();
birtEngine = null;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
private static void loadEngineProps() {
try {
//Config File must be in classpath
ClassLoader cl = Thread.currentThread ().getContextClassLoader();
InputStream in = null;
in = cl.getResourceAsStream (configFile);
configProps.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
webreport.java:
public class WebReport extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor of the object.
*/
private IReportEngine birtReportEngine = null;
protected static Logger logger = Logger.getLogger( "org.eclipse.birt" );
public WebReport() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy();
BirtEngine.destroyBirtEngine();
}
/**
* The doGet method of the servlet. <br>
*
*/
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//get report name and launch the engine
//resp.setContentType("text/html");
//resp.setContentType( "application/pdf" );
resp.setContentType( "application/msword" );
//resp.setHeader ("Content-Disposition","inline; filename=test.pdf");
resp.setHeader("Content-disposition","attachment; filename=\"" +"test.doc" +"\"");
String reportName = req.getParameter("ReportName");
ServletContext sc = req.getSession().getServletContext();
this.birtReportEngine = BirtEngine.getBirtEngine(sc);
IReportRunnable design;
try
{
//Open report design
design = birtReportEngine.openReportDesign( sc.getRealPath("/Reports")+"/"+reportName );
//create task to run and render report
IRunAndRenderTask task = birtReportEngine.createRunAndRenderTask( design );
task.getAppContext().put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, WebReport.class.getClassLoader());
task.getAppContext().put("BIRT_VIEWER_HTTPSERVLET_REQUEST", req );
//set output options
//HTMLRenderOption options = new HTMLRenderOption();
//options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);
//options.setOutputStream(resp.getOutputStream());
//options.setImageHandler(new HTMLServerImageHandler());
//options.setBaseImageURL(req.getContextPath()+"/images");
//options.setImageDirectory(sc.getRealPath("/images"));
/*PDFRenderOption options = new PDFRenderOption();
options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);
options.setOutputStream(resp.getOutputStream());
*/
RenderOption options = new RenderOption();
options.setOutputFormat("doc");
options.setOutputStream(resp.getOutputStream());
//options.setEnableAgentStyleEngine(true);
//options.setEnableInlineStyle(true);
task.setRenderOption(options);
//run report
task.run();
task.close();
}catch (Exception e){
e.printStackTrace();
throw new ServletException( e );
}
}
/**
* The doPost method of the servlet. <br>
*
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.println(" Post Not Supported");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* #throws ServletException if an error occure
*/
public void init(ServletConfig sc) throws ServletException {
BirtEngine.initBirtConfig();
this.birtReportEngine = BirtEngine.getBirtEngine(sc.getServletContext());
}
}
birtconfigproperty:
ogDirectory=c:/temp
logLevel=FINEST

Related

HttpRequest from asp.net client to java server which has error "the request was rejected because no multipart boundary was found"

asp.net client
.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Image_Identify.aspx.cs"
Inherits="WebApplication.iva.Image_Identify" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data" method="post">
<div>
<asp:Button ID="Button_Post" runat="server" Text="submit" OnClick="Button_PostWebRequest" />
</div>
</form>
</body>
</html>
.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
namespace WebApplication.iva
{
public partial class Image_Identify : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string postUrl = "http://xxx/WebUploadHandleServlet";
string paramData = "E:\\1111.jpg";
string ret = string.Empty;
Encoding dataEncode = Encoding.UTF8;
try
{
byte[] byteArray = dataEncode.GetBytes(paramData);
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "multipart/mixed";
webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close();
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
}
}
protected void Button_PostWebRequest(object sender, EventArgs e)
{
}
}
}
java server
#WebServlet(asyncSupported = true, urlPatterns = { "/WebUploadHandleServlet" })
public class WebUploadHandleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final long MAXSize = 1024 * 1024 * 4 * 2L;// 4*2MB
private String filedir = null;// before
private String resdir = null;// after
/**
* #see HttpServlet#HttpServlet()
*/
public WebUploadHandleServlet() {
super();
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("init...");
JNIDispatcher.getInstance();
filedir = config.getServletContext().getRealPath("WEB-INF/original_images");
resdir = config.getServletContext().getRealPath("WEB-INF/result_images");
File file1 = new File(filedir);
File file2 = new File(resdir);
if (!file1.exists() && !file2.exists()) {
System.out.println("create dir");
file1.mkdir();
file2.mkdir();
System.out.println("create success");
}
System.out.println("filedir=" + filedir);
System.out.println("resdir=" + resdir);
super.init(config);
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("receive request");
double begin_time = System.currentTimeMillis();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//FileUpload upload = new FileUpload(factory);20161005
upload.setSizeMax(-1);
upload.setHeaderEncoding("utf-8");
ImageDispose disposer = new ImageDispose(filedir, resdir);
// response.setContentType("text/html");
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String respondResult = null;
String filename = null;
try {
List<FileItem> items = upload.parseRequest(request);
if (items != null && !items.isEmpty()) {
System.out.println("items size:" + items.size());
double start_time = System.currentTimeMillis();
for (FileItem fileItem : items) {
filename = fileItem.getName();
String filepath = filedir + File.separator + filename;
System.out.println("file save path:" + filepath);
InputStream inputStream = fileItem.getInputStream();
respondResult = disposer.process(inputStream, filename);
inputStream.close();
fileItem.delete();
}
double end_time = System.currentTimeMillis();
System.out.println("JNI handle" + filename + "time:" + (end_time - start_time) + "ms");
System.out.println("total time:" + (end_time - begin_time));
}
out.write(respondResult);
} catch (Exception e) {
e.printStackTrace();
out.write("文件" + filename + "upload fail:" + e.getMessage());
}
System.out.println("finish!");
}
#Override
public void destroy() {
System.out.println("release JNI...");
JNIDispatcher.getInstance().releaseJNI();
super.destroy();
}
}
I have printed the result as below.
It seems that java server has received the http request but cannot resolve.
Hope for help!

How is the JasperServer REST client path?

I'm working to make client rest service with jasperserver to generate reports. I'm using the following code to make that:
I have problem in setting server url and report path,
for server url I put http://localhost:8081/jasperserver/
and as shown in next image I put report path rest/report/mytest/my_report but I get 404 not found error in line
File remoteFile = resource.get(File.class);
So how can I get the proper report path from jasperserver?
public class App2 {
private final static String serverUrl = "http://localhost:8081
/jasperserver/";
private final static String serverUser = "jasperadmin";
private final static String serverPassword = "jasperadmin";
public static void main(String arg[]) throws Exception {
Report reporte = new Report();
reporte.setFormat("pdf");
reporte.setOutputFolder("/home/ali/images");
ClientConfig clientConfig;
Map<String, String> resourceCache=new HashMap<String, String>();
clientConfig = new DefaultApacheHttpClientConfig();
clientConfig.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
clientConfig.getProperties().put(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES, true);
ApacheHttpClient client = ApacheHttpClient.create(clientConfig);
client.addFilter(new HTTPBasicAuthFilter(serverUser, serverPassword));
String describeResourcePath = "/rest/resource" + "/mytest/my_report/";
String generateReportPath = "/rest/report" + "/mytest/my_report/" + "?RUN_OUTPUT_FORMAT=" + reporte.getFormat();
WebResource resource = null;
String resourceResponse = null;
if (resourceCache.containsKey(describeResourcePath)) {
resourceResponse = resourceCache.get(describeResourcePath);
} else {
resource = client.resource(serverUrl);
resource.accept(MediaType.APPLICATION_XML);
resourceResponse = resource.path(describeResourcePath).get(String.class);
resourceCache.put(describeResourcePath, resourceResponse);
}
Document resourceXML = parseResource(resourceResponse);
resourceXML = addParametersToResource(resourceXML, reporte);
resource = client.resource(serverUrl + generateReportPath);
resource.accept(MediaType.TEXT_XML);
System.out.println(resource);
String reportResponse = resource.put(String.class, serializetoXML(resourceXML));
String urlReport = parseReport(reportResponse);
resource = client.resource(urlReport);
System.out.println(resource);
File destFile = null;
try {
File remoteFile = resource.get(File.class);
File parentDir = new File(reporte.getOutputFolder());
destFile = File.createTempFile("report_", "." + getExtension(reporte.getFormat()), parentDir);
FileUtils.copyFile(remoteFile, destFile);
} catch (IOException e) {
throw e;
}
}
/**
*
* #return
* #throws DocumentException
*/
private static Document parseResource(String resourceAsText) throws Exception {
// LOGGER.debug("parseResource:\n" + resourceAsText);
Document document;
try {
document = DocumentHelper.parseText(resourceAsText);
} catch (DocumentException e) {
throw e;
}
return document;
}
/**
*
*/
private static String parseReport(String reportResponse) throws Exception {
String urlReport = null;
try {
Document document = DocumentHelper.parseText(reportResponse);
Node node = document.selectSingleNode("/report/uuid");
String uuid = node.getText();
node = document.selectSingleNode("/report/totalPages");
Integer totalPages = Integer.parseInt(node.getText());
if (totalPages == 0) {
throw new Exception("Error generando reporte");
}
urlReport = serverUrl + "/report/" + uuid + "?file=report";
} catch (DocumentException e) {
throw e;
}
return urlReport;
}
/**
*
* #param resource
* #param reporte
* #return
*/
private static Document addParametersToResource(Document resource, Report reporte) {
// LOGGER.debug("addParametersToResource");
Element root = resource.getRootElement();
Map<String, String> params = reporte.getParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key != null && value != null) {
root.addElement("parameter").addAttribute("name", key).addText(value);
}
}
// LOGGER.debug("resource:" + resource.asXML());
return resource;
}
/**
*
* #param aEncodingScheme
* #throws IOException
* #throws Exception
*/
private static String serializetoXML(Document resource) throws Exception {
OutputFormat outformat = OutputFormat.createCompactFormat();
ByteArrayOutputStream out = new ByteArrayOutputStream();
outformat.setEncoding("ISO-8859-1");
try {
XMLWriter writer = new XMLWriter(out, outformat);
writer.write(resource);
writer.flush();
} catch (IOException e) {
throw e;
}
return out.toString();
}
/**
*
* #param format
* #return
*/
private static String getExtension(String format) {
String ext = null;
if (format.equals(Report.FORMAT_PDF)) {
ext = "pdf";
} else if (format.equals(Report.FORMAT_EXCEL)) {
ext = "xls";
}
return ext;
}
}
I have fixed it,I need to change path
urlReport = serverUrl + "/report/" + uuid + "?file=report";
to
urlReport = serverUrl + "/rest/report/" + uuid + "?file=report";
in parseReport method
private static String parseReport(String reportResponse) throws Exception {
String urlReport = null;
try {
Document document = DocumentHelper.parseText(reportResponse);
Node node = document.selectSingleNode("/report/uuid");
String uuid = node.getText();
node = document.selectSingleNode("/report/totalPages");
Integer totalPages = Integer.parseInt(node.getText());
if (totalPages == 0) {
throw new Exception("Error generando reporte");
}
urlReport = serverUrl + "/report/" + uuid + "?file=report";
} catch (DocumentException e) {
throw e;
}
return urlReport;
}

Make a servlet thread safe in java

I have working code as follows
public class receive_meter_to_store extends HttpServlet {
WSEMAMSTS EMAMService = new WSEMAMSTS();
ItronEMAMStsBinding itronEMAM = EMAMService.getItronEMAMStsBinding();
ItronAuthCredit lItronAuthCredit = new ItronAuthCredit();
EANDeviceID lTerminalID = new EANDeviceID();
EANDeviceID lClientID = new EANDeviceID();
SimpleDateFormat itronDF = new SimpleDateFormat("yyyyMMddHHmmss");
Date current_datetime = new Date();
String s_current_datetime = itronDF.format(current_datetime);
MsgID lMsgID = new MsgID();
reuse_func gc_reuse_func = new reuse_func();
curr_time gs_current_datetime = new curr_time("");
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String retdata = "Failure";
try {
retdata = add_meter_to_store(request, response);
}
finally {
out.println(retdata);
out.close();
}
}
I want to make it thread safe, as in to make it run faster. First I am to remove all the global variables, but when i do so, I get error
"An unhandled program error has occured. Please contact the Support services and report the issue"
I have moved them so they can be local as follows
public class receive_meter_to_store extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String retdata = "Failure";
reuse_func lc_reuse_func = new reuse_func();
try {
WSECMPublic EMAMService = lc_reuse_func.getMeterWebService();
ItronEMAMStsBinding itronEMAM = EMAMService.getItronEMAMStsBinding();
}
catch (Exception ex)
{
String ErrorMsg = ex.getMessage();
out.println("Error" + ErrorMsg);
}
finally {
out.close();
}
try {
retdata = add_meter_to_store(request, response);
}
finally {
out.println(retdata);
out.close();
}
}
Am I doing something wrong here?
the class i am calling add_meter
public String add_meter_to_store(HttpServletRequest request, HttpServletResponse response)
{
reuse_func lc_reuse_func = new reuse_func();
try
{
WSECMPublic EMAMService = lc_reuse_func.getMeterWebService();
ItronEMAMStsBinding itronEMAM = EMAMService.getItronEMAMStsBinding();
ItronAuthCredit lItronAuthCredit = new ItronAuthCredit();
EANDeviceID lTerminalID = new EANDeviceID();
EANDeviceID lClientID = new EANDeviceID();
SimpleDateFormat itronDF = new SimpleDateFormat("yyyyMMddHHmmss");
Date current_datetime = new Date();
String s_current_datetime = itronDF.format(current_datetime);
MsgID lMsgID = new MsgID();
curr_time ls_current_datetime = new curr_time("");
// Declare MeterImportResponse Variable
ItronMeterStsImportResp stsImportResp = new ItronMeterStsImportResp();
// Call meterStsImport WebMethod
stsImportResp = itronEMAM.meterStsImport(stsImportReq);
}
catch (Exception ex) {
// TODO handle custom exceptions here
String ErrorMsg = ex.getMessage();
retdata = "Error : " + ErrorMsg;
}
return retdata;
}
Note: i have removed the global variables in first part and put them in the class
The problem (or one problem, at least) is that in the first finally block, you close out, but then try to use it again later.
This means that your out.println(retdata) statement is always operating on a closed stream.

Redirect servlet async and heart beat

We have tasks in java web-app that take a long time in completing and before the time the task completes the request times out and page cannot be displayed happens. We are think of setting a async redirection servlet that acts as a front-controller redirecting the request to the appropriate action classes and while the request is being served the servlet keeps sending a heartbeat every minute or so, until the request is completed by the corresponding action classes. Has anybody implemented something similar using asynchronous servlet 3.0? Also is this possible? I understand that this is similar to server push. Thanks for guidance.
yes this kind of functionality you can achive by use of
asynchronous servlet 3.0.it basically works like push
notification and also give you respose continously with
out making request here i have one code that i share with
this code may help for you to make async request.
this example check live users
#WebServlet(urlPatterns = { "/checkliveuser" }, asyncSupported = true)
public class CheckLiveUser extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Queue<AsyncContext> queue = new ConcurrentLinkedQueue();
private static final BlockingQueue<String> messageQueue = new LinkedBlockingQueue();
private static final String BEGIN_SCRIPT_TAG = "<script type='text/javascript'>\n";
private static final String END_SCRIPT_TAG = "</script>\n";
private Thread notifierThread = null;
#Override
public void init(ServletConfig config) throws ServletException {
ServletContext context = config.getServletContext();
Set<String> users = new HashSet<String>();
Map<String, String> page = new HashMap<String, String>();
context.setAttribute("page", page);
context.setAttribute("messageQueue", messageQueue);
Runnable notifierRunnable = new Runnable() {
public void run() {
boolean done = false;
while (!done) {
System.out.println("in thread");
String cMessage = null;
try {
cMessage = BEGIN_SCRIPT_TAG + toJsonp("<b>Live User:", messageQueue.take())
+ END_SCRIPT_TAG;
for (AsyncContext ac : queue) {
try {
PrintWriter acWriter = ac.getResponse()
.getWriter();
acWriter.println(cMessage);
acWriter.flush();
} catch (IOException ex) {
System.out.println(ex);
queue.remove(ac);
}
}
} catch (InterruptedException iex) {
done = true;
System.out.println(iex);
}
}
}
};
notifierThread = new Thread(notifierRunnable);
notifierThread.start();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
final AsyncContext ac = request.startAsync();
ac.setTimeout(10 * 60 * 1000 * 1000);
ac.addListener(new AsyncListener() {
public void onComplete(AsyncEvent event) throws IOException {
queue.remove(ac);
System.out.println("on complete");
}
public void onTimeout(AsyncEvent event) throws IOException {
queue.remove(ac);
System.out.println("on timeout");
}
public void onError(AsyncEvent event) throws IOException {
queue.remove(ac);
System.out.println("on error");
}
public void onStartAsync(AsyncEvent event) throws IOException {
System.out.println("on startup");
}
});
queue.add(ac);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
ServletContext context = request.getServletContext();
HttpSession session = request.getSession();
Map<String, String> logins = (Map<String, String>) context
.getAttribute("page");
if (request.getParameter("action") != null
&& !request.getParameter("action").isEmpty()) {
if (request.getParameter("action").equalsIgnoreCase("logout")) {
logins.remove(request.getSession().getId());
request.getSession().invalidate();
}
}
String name = request.getParameter("loginID");
if (name != null) {
session.setAttribute("user", name);
session.setAttribute("jsessionId", session.getId());
logins.put(session.getId(), name);
}
String html = "";
for (Map.Entry<String, String> entry : logins.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
html += entry.getValue() + "<br>";
}
String cMessage = BEGIN_SCRIPT_TAG + toJsonp("<b>Live User:", html)
+ END_SCRIPT_TAG;
notify(cMessage);
response.getWriter().println("success");
if (request.getParameter("action") != null
&& !request.getParameter("action").isEmpty()) {
if (request.getParameter("action").equalsIgnoreCase("logout"))
response.sendRedirect("login.jsp");
} else {
response.sendRedirect("welcome.jsp");
}
}
#Override
public void destroy() {
queue.clear();
notifierThread.interrupt();
}
private void notify(String cMessage) throws IOException {
try {
messageQueue.put(cMessage);
} catch (Exception ex) {
IOException t = new IOException();
t.initCause(ex);
throw t;
}
}
private String escape(String orig) {
StringBuffer buffer = new StringBuffer(orig.length());
for (int i = 0; i < orig.length(); i++) {
char c = orig.charAt(i);
switch (c) {
case '\b':
buffer.append("\\b");
break;
case '\f':
buffer.append("\\f");
break;
case '\n':
buffer.append("<br />");
break;
case '\r':
// ignore
break;
case '\t':
buffer.append("\\t");
break;
case '\'':
buffer.append("\\'");
break;
case '\"':
buffer.append("\\\"");
break;
case '\\':
buffer.append("\\\\");
break;
case '<':
buffer.append("<");
break;
case '>':
buffer.append(">");
break;
case '&':
buffer.append("&");
break;
default:
buffer.append(c);
}
}
return buffer.toString();
}
private String toJsonp(String name, String message) {
return "window.parent.app.update({ name: \"" + escape(name)
+ "\", message: \"" + escape(message) + "\" });\n";
}

How to write to a HttpServletResponse response object?

I have this action class, this class takes care of my response
Update now passing response from DownloadStatus class, but it looks like it is null
public final class DownloadStatus extends ActionSupport implements ServletRequestAware,ServletResponseAware
{
static Logger logger = Logger.getLogger(DownloadStatus.class);
private HttpServletRequest request;
private HttpServletResponse response;
private File cfile;
private String cfileFileName;
#Override
public String execute()
{
logger.debug("Inside DownloadStatus.execute method")
try {
ChainsInvoker invoker = new ChainsInvoker()
def executionResponse = invoker.invoke(request, MYChains.download, cfile, cfileFileName)
if(executionResponse == null || ErrorHandler.checkIfError(executionResponse))
{
return ERROR
}
response.setContentType("APPLICATION/xml")
logger.debug("filename: $cfileFileName")
response.addHeader("Content-Disposition", "attachment; filename=\""+cfileFileName+"\"")
response.getWriter().print(executionResponse)
logger.debug("executionResponse :" + executionResponse)
invoker.invoke(MYChains.clean)
}catch (Exception exp) {
logger.error("Exception while Creating Status ")
logger.error(exp.printStackTrace())
}
return NONE
}
#Override
public void setServletRequest(HttpServletRequest request) { this.request = request; }
#Override
public void setServletResponse(HttpServletResponse response) { this.response = response; }
public File getcfile() { cfile }
public void setcfile(File cfile) { this.cfile = cfile }
public String getcfileFileName() { cfileFileName }
public void setcfileFileName(String cfileFileName){ this.cfileFileName = cfileFileName }
}
and below class to write stream into response
class DownloadStatusResponse implements Command {
static Logger logger = Logger.getLogger(DownloadStatusResponse.class);
#Override
public boolean execute(Context ctx) throws Exception
{
logger.debug("Inside DownloadStatusResponse.execute() method")
OutputStream response = null;
if(ctx.get(ContextParams.absFileName) != null && ctx.get(ContextParams.absFileName).toString().trim().length() != 0 )
{
HttpServletResponse resp = ctx.get(ContextParams.response)
/*I am trying to get Response here*/
response=downloadStatusFile(ctx.get(ContextParams.absFileName).toString(),resp)
}
logger.debug("Response: " + response)
ctx.put(ContextParams.response,response); /*ContextParams is a enum of keywords, having response*/
return false;
}
private OutputStream downloadStatusFile(String filename,HttpServletResponse resp)
{
logger.info("Inside downloadStatusFile() method")
File fname = new File(filename)
if(!fname.exists())
{
logger.info("$filename does not exists")
return null
}
else
{
resp.setContentType("APPLICATION/xml")
/*Exception: cannot setContentType on null object*/
resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\"")
FileInputStream istr = new FileInputStream(fname)
OutputStream ostr = resp.getOutputStream()
/*I need to use resp.getOutputStream() for ostr*/
int curByte=-1;
while( (curByte=istr.read()) !=-1)
ostr.write(curByte)
ostr.flush();
}
return ostr
}
}
My question is how can ostr be returned to the response in DownloadStatus class?
Update (working test servlet)
I have this below servlet which does the job of getting file content into a stream and giving it back to the HttpServletResponse, but i want to use it in above code
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String fileName = req.getParameter("zipFile");
if(fileName == null) return;
File fname = new File(fileName);
System.out.println("filename");
if(!fname.exists()) {System.out.println("Does not exists"); return;}
FileInputStream istr = null;
OutputStream ostr = null;
//resp.setContentType("application/x-download");
resp.setContentType("APPLICATION/ZIP");
resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\"");
System.out.println(fname.getName());
try {
istr = new FileInputStream(fname);
ostr = resp.getOutputStream();
int curByte=-1;
while( (curByte=istr.read()) !=-1)
ostr.write(curByte);
ostr.flush();
} catch(Exception ex){
ex.printStackTrace(System.out);
} finally{
try {
if(istr!=null) istr.close();
if(ostr!=null) ostr.close();
} catch(Exception ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
try {
resp.flushBuffer();
} catch(Exception ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
}
As far as I understand all you require is how to download a file using Struts2.
You need something like this is your struts.xml file
<action name="downloadfile" class="DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/pdf</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="document.pdf"</param>
<param name="bufferSize">1024</param>
</result>
</action>
Code:
public class DownloadAction extends ActionSupport {
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String execute() throws FileNotFoundException {
String filePath = ServletActionContext.getServletContext().getRealPath("/uploads");
File f = new File(filePath + "/nn.pdf");
System.out.println(f.exists());
inputStream = new FileInputStream(f);
return SUCCESS;
}
}

Categories