I have downloaded the log4j jar.
But dont know how to use it to save the output to a text file.
My code is:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
public class ShowHeaders extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
String headerName;
String headerValue;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
String method= request.getMethod();
out.println("Request Method: " +method);
out.println("-----------------------");
String uri= request.getRequestURI();
out.println("URI: " +uri);
out.println("-----------------------");
out.println("Request Headers");
Enumeration<?> Enumeration = (java.util.Enumeration<?>) request.getHeaderNames();
while (Enumeration.hasMoreElements()) {
String headerName = (String) Enumeration.nextElement();
String headerValue = request.getHeader(headerName);
out.print(""+headerName + ": ");
out.println(headerValue + "");
}
}
Kindly tell me where to describe the file location & what to use instead of out.println(); to display it that text file
Well, you should take a look at the log4j tutorial. It is really good !
this code should give you a headstart :
public static void main(String[] args) {
Logger X = Logger.getLogger("com.foo");
try {
X.addAppender(new FileAppender(new PatternLayout("%d %-5p [%c{1}] %m%n"),"src/test.log"));
} catch (IOException e) {
e.printStackTrace();
}
X.debug("Hello World debug message");
}
The log4j tutorial explains how to configure logging, and includes example configs that log to a file. (Search for where it says "Here is another configuration file that uses multiple appenders". That "config" includes file appenders.)
Related
I have encountered these errors when trying to implement the docusing embedded signature into my web app (java -eclipse).
java.lang.ClassNotFoundException: org.junit.Assert
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1412)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1220)
com.uniquedeveloper.registration.test2.EmbeddedSigningTest(test2.java:94)
com.uniquedeveloper.registration.test2.doPost(test2.java:79)
javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Here is my code for the test2 class:
package com.uniquedeveloper.registration;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;
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;
import javax.servlet.http.Part;
import javax.servlet.jsp.PageContext;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import static org.junit.Assert.*;
import org.junit.Assert;
import org.junit.Test;
import com.docusign.esign.api.EnvelopesApi;
import com.docusign.esign.client.ApiClient;
import com.docusign.esign.client.ApiException;
import com.docusign.esign.model.Document;
import com.docusign.esign.model.EnvelopeDefinition;
import com.docusign.esign.model.EnvelopeSummary;
import com.docusign.esign.model.RecipientViewRequest;
import com.docusign.esign.model.Recipients;
import com.docusign.esign.model.SignHere;
import com.docusign.esign.model.Signer;
import com.docusign.esign.model.Tabs;
import com.docusign.esign.model.ViewUrl;
/**
* Servlet implementation class test2
*/
#WebServlet("/test2")
public class test2 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String rEmail = request.getParameter("recipientem");
String rName = request.getParameter("recipientname");
/*Part file = request.getPart("file_upload");
*/
/* String filePath = (String)request.getServletContext().getInitParameter("file_upload");*/
/*Part filePart = request.getPart("file_upload");
String fileName=filePart.getSubmittedFileName();
for(Part part : request.getParts()) {
part.write("C:\\Bureau\\"+ fileName);
*/
/*Part filePart = request.getPart("file_upload");
InputStream filecontent = filePart.getInputStream();
if (filePart != null) {
filecontent = filePart.getInputStream();
}
else {
System.out.println("KHAWI");
}*/
String filePath = (String)request.getServletContext().getInitParameter("file_upload");
System.out.println("ZWIN1");
EmbeddedSigningTest(rEmail, rName, filePath);
}
#Test
public void EmbeddedSigningTest(String rEmail, String rName, String filePath ) {
String AccountId = "16501888";
System.out.println("\nEmbeddedSigningTest:\n" + "===========================================");
byte[] fileBytes = null;
try {
String currentDir = System.getProperty("user.dir");
Path path = Paths.get(currentDir + filePath);
fileBytes = Files.readAllBytes(path);
} catch (IOException ioExcp) {
Assert.assertNull(ioExcp);
}
System.out.println("ZWIN2");
// create an envelope to be signed
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.setEmailSubject("Please Sign my Java SDK Envelope (Embedded Signer)");
envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");
// add a document to the envelope
Document doc = new Document();
String base64Doc = Base64.getEncoder().encodeToString(fileBytes);
doc.setDocumentBase64(base64Doc);
doc.setName(filePath);
doc.setDocumentId("1");
List<Document> docs = new ArrayList<>();
docs.add(doc);
envDef.setDocuments(docs);
// Add a recipient to sign the document
Signer signer = new Signer();
signer.setEmail(rEmail);
String name = "Pat Developer";
signer.setName(rName);
signer.setRecipientId("1");
// this value represents the client's unique identifier for the signer
String clientUserId = "2adce842-15eb-4744-9807-5a82020cc313 ";
signer.setClientUserId(clientUserId);
// Create a SignHere tab somewhere on the document for the signer to
// sign
SignHere signHere = new SignHere();
signHere.setDocumentId("1");
signHere.setPageNumber("1");
signHere.setRecipientId("1");
signHere.setXPosition("100");
signHere.setYPosition("100");
signHere.setScaleValue("0.5");
List<SignHere> signHereTabs = new ArrayList<>();
signHereTabs.add(signHere);
Tabs tabs = new Tabs();
tabs.setSignHereTabs(signHereTabs);
signer.setTabs(tabs);
// Above causes issue
envDef.setRecipients(new Recipients());
envDef.getRecipients().setSigners(new ArrayList<>());
envDef.getRecipients().getSigners().add(signer);
// send the envelope (otherwise it will be "created" in the Draft folder
envDef.setStatus("sent");
try {
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(AccountId, envDef);
Assert.assertNotNull(envelopeSummary);
Assert.assertNotNull(envelopeSummary.getEnvelopeId());
System.out.println("EnvelopeSummary: " + envelopeSummary);
String returnUrl = "http://localhost:8080/index/";
RecipientViewRequest recipientView = new RecipientViewRequest();
recipientView.setReturnUrl(returnUrl);
recipientView.setClientUserId(clientUserId);
recipientView.setAuthenticationMethod("email");
recipientView.setUserName(name);
recipientView.setEmail(rEmail);
ViewUrl viewUrl = envelopesApi.createRecipientView(AccountId,
envelopeSummary.getEnvelopeId(), recipientView);
Assert.assertNotNull(viewUrl);
Assert.assertNotNull(viewUrl.getUrl());
// This Url should work in an Iframe or browser to allow signing
System.out.println("ViewUrl is " + viewUrl);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
}
I (pretty sure ) think it has something to do with the file not being uplaoded properly ( null).
Please help !
The error is telling you that the class org.junit.Assert is not on the classpath. Meaning that the JUnit library is missing or it has the wrong scope (if you are using a building tool like Maven or Gradle).
The whole class has several problems, I suspect you are trying to deploy the servlet on Tomcat and there the JUnit dependency is missing. You should redesign it and keep the test separated from the servlet.
This question already has answers here:
how to display image in jasper reports
(2 answers)
JasperReports API. Getting error when using Image in report: net.sf.jasperreports.engine.JRException: Byte data not found at
(1 answer)
How to set the image expression to always store the right image path
(1 answer)
net.sf.jasperreports.engine.JRException: Byte data not found
(3 answers)
Closed 4 years ago.
Is it possible to use jrxml file directly to generate pdf using Java Jasper API when java web application is delpoyed on AWS Elastic Beanstalk. Here I am storing "empprofile.jrxml" file in "WEB-INF/reports" directory. Report successfully generates when I deploy application on localhost. But it does not generate pdf when deployed on AWS Elastic Beanstalk. Please give any sugessions to solve this issue.
Below is the code I have used to generate pdf:
package controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import bean.AppointmentBean;
import bean.EducationBean;
import bean.EmployeeAddressBean;
import bean.EmployeeBankBean;
import bean.EmployeeBean;
import bean.EmployeePersonalBean;
import bean.KnEmployeeBean;
import bean.KrudnyataListBean;
import bean.PayscaleBean;
import bean.RelativeBean;
import bean.ServiceHistoryBean;
import dao.AppointmentDao;
import dao.EducationalDao;
import dao.EmployeeDao;
import dao.PayscaleDao;
import dao.RelativeDao;
import dao.krudnyatanidhi.KrudnyataNidhiDao;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
public class PrintProfile extends HttpServlet {
private static final long serialVersionUID = 1L;
public PrintProfile() {
super();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession(false);
try{
if(session.getAttribute("category")!=null)
{
if(session.getAttribute("category").equals("admin")||session.getAttribute("category").equals("badmin")){
try{
String uid=request.getParameter("uid");
EmployeeDao dao=new EmployeeDao();
EmployeeBean bean=dao.getEmployeeBeanByUID(uid);
request.setAttribute("bean", bean);
session.setAttribute("uid", uid);
request.getRequestDispatcher("printprofile.jsp").forward(request, response);
}catch (Exception e) {
e.printStackTrace();
}
}
else{
session=request.getSession(true);
session.setAttribute("category", null);
response.sendRedirect("../index.jsp?success=0");
}
}
else{
session=request.getSession(true);
session.setAttribute("category", null);
response.sendRedirect("../index.jsp?success=0");
}
}catch(Exception e){
session=request.getSession(true);
session.setAttribute("category", null);
response.sendRedirect("../index.jsp?success=0");
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession(false);
try{
if(session.getAttribute("category")!=null)
{
if(session.getAttribute("category").equals("admin")||session.getAttribute("category").equals("badmin")){
try{
String uid=request.getParameter("uid");
String personal=request.getParameter("personal");
String address=request.getParameter("address");
String bank=request.getParameter("bank");
String appt=request.getParameter("appt");
String educational=request.getParameter("educational");
String serviceh=request.getParameter("serviceh");
String payscale=request.getParameter("payscale");
String krudnyatanidhi=request.getParameter("krudnyatanidhi");
String relative=request.getParameter("relative");
String date=request.getParameter("today");
EmployeePersonalBean pbean=null;
EmployeeBankBean empbank=null;
EmployeeAddressBean empaddress=null;
AppointmentBean empappt=null;
ArrayList<EducationBean> qualsds=null;
ArrayList<PayscaleBean> archives=null;
ArrayList<RelativeBean> relatives=null;
ArrayList<ServiceHistoryBean> sh=null;
KrudnyataListBean knstatus=null;
ArrayList<KnEmployeeBean> knlist=new ArrayList<>();
EmployeeDao dao=new EmployeeDao();
EmployeeBean bean=dao.getEmployeeBeanByUID(uid);
if(personal!=null){
pbean=dao.getEmpPersonal(uid);
}
if(bank!=null){
empbank=dao.getEmpBank(uid);
}
if(address!=null){
empaddress=dao.getEmpAddress(uid);
}
InputStream photo=dao.getEmployeePhoto(uid);
if(photo==null){
String directoryPath=getServletContext().getRealPath("images");
File image=new File(directoryPath+File.separator+"pna.png");
photo=new FileInputStream(image);
}
AppointmentDao adao=new AppointmentDao();
empappt=adao.getAppointmentDetailsForReport(uid);
EducationalDao eDao=new EducationalDao();
if(educational!=null){
qualsds=eDao.getEducationalDetails(uid);
}
JRBeanCollectionDataSource quals=new JRBeanCollectionDataSource(qualsds);
PayscaleDao pdao=new PayscaleDao();
if(payscale!=null){
archives=pdao.getPayscaleArchives(uid);
}
JRBeanCollectionDataSource payscalearchive=new JRBeanCollectionDataSource(archives);
RelativeDao rDao=new RelativeDao();
if(relative!=null){
relatives=rDao.getRelativesDetails(uid);
}
JRBeanCollectionDataSource relativeds=new JRBeanCollectionDataSource(relatives);
if(serviceh!=null){
sh=adao.getBranchHReport(uid);
}
JRBeanCollectionDataSource servicehistoryds=new JRBeanCollectionDataSource(sh);
KrudnyataNidhiDao kdao=new KrudnyataNidhiDao();
Double totalpaid=0.0;
if(krudnyatanidhi!=null){
knlist=kdao.getKNListEmployeewiseForReport(uid);
/*for (KrudnyataPaymentBean b: paymenthistory) {
totalpaid=totalpaid+b.getAmount();
}*/
}
JRBeanCollectionDataSource krpds=new JRBeanCollectionDataSource(knlist);
//Report Generation Code
String imgContext=this.getServletContext().getRealPath("/");
Map<String,Object> parameterMap=new HashMap<String,Object>();
parameterMap.put("uid",uid);
parameterMap.put("context",imgContext);
parameterMap.put("personal",personal);
parameterMap.put("address",address);
parameterMap.put("bank",bank);
parameterMap.put("appt",appt);
parameterMap.put("educational",educational);
parameterMap.put("serviceh",serviceh);
parameterMap.put("payscale",payscale);
parameterMap.put("krudnyatanidhi",krudnyatanidhi);
parameterMap.put("relative",relative);
parameterMap.put("bean",bean);
parameterMap.put("pbean",pbean);
parameterMap.put("empbank",empbank);
parameterMap.put("empaddress",empaddress);
parameterMap.put("photo",photo);
parameterMap.put("empappt",empappt);
parameterMap.put("date",date);
parameterMap.put("quals",quals);
parameterMap.put("payscalearchive",payscalearchive);
parameterMap.put("relativeds",relativeds);
parameterMap.put("knstatus",knstatus);
parameterMap.put("krpds",krpds);
parameterMap.put("totalpaid",totalpaid);
parameterMap.put("servicehistoryds",servicehistoryds);
OutputStream outputStream=response.getOutputStream();
response.setContentType("application/pdf");
/*Connection con=DBConnection.createconnection();*/
ServletContext context = getServletContext();
String report = context.getRealPath("/WEB-INF/reports/empprofile.jrxml");
JasperReport jasperReport = null;
JasperDesign jasperDesign = null;
try {
jasperDesign = JRXmlLoader.load(report);
jasperReport = JasperCompileManager.compileReport(report);
byte[] byteStream = JasperRunManager.runReportToPdf(jasperReport,parameterMap,new JREmptyDataSource());
OutputStream outStream = response.getOutputStream();
response.setContentType("application/pdf");
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",bean.getUid()+"-"+bean.getFname()+" "+bean.getLname()+".pdf");
response.setHeader(headerKey, headerValue);
response.setContentLength(byteStream.length);
outStream.write(byteStream,0,byteStream.length);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}catch (Exception e) {
e.printStackTrace();
}
}
else{
session=request.getSession(true);
session.setAttribute("category", null);
response.sendRedirect("../index.jsp?success=0");
}
}
else{
session=request.getSession(true);
session.setAttribute("category", null);
response.sendRedirect("../index.jsp?success=0");
}
}catch(Exception e){
session=request.getSession(true);
session.setAttribute("category", null);
response.sendRedirect("../index.jsp?success=0");
}
}
}
This is the part of AWS log of catalina.out file :
net.sf.jasperreports.engine.JRException: Byte data not found at : /var/lib/tomcat8/webapps/ROOT/WEB-INF\reports\pdealogo.png
at net.sf.jasperreports.repo.RepositoryUtil.getBytes(RepositoryUtil.java:206)
at net.sf.jasperreports.engine.JRImageRenderer.getInstance(JRImageRenderer.java:141)
at net.sf.jasperreports.engine.fill.JRFillImage.evaluateImage(JRFillImage.java:498)
at net.sf.jasperreports.engine.fill.JRFillImage.evaluate(JRFillImage.java:441)
at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:257)
at net.sf.jasperreports.engine.fill.JRFillFrame.evaluate(JRFillFrame.java:147)
at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:257)
at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:468)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillTitle(JRVerticalFiller.java:327)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:263)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:129)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:903)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:832)
at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:84)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:624)
at net.sf.jasperreports.engine.JasperRunManager.runReportToPdf(JasperRunManager.java:421)
at controller.PrintProfile.doPost(PrintProfile.java:236)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
I have got the solution. I have checked the catalina.out log file from AWS server logs. It contains the exceptions occured as shown below:
net.sf.jasperreports.engine.JRException: Byte data not found at : /var/lib/tomcat8/webapps/ROOT/WEB-INF\reports\pdealogo.png
at net.sf.jasperreports.repo.RepositoryUtil.getBytes(RepositoryUtil.java:206)
at net.sf.jasperreports.engine.JRImageRenderer.getInstance(JRImageRenderer.java:141)
at net.sf.jasperreports.engine.fill.JRFillImage.evaluateImage(JRFillImage.java:498)
at net.sf.jasperreports.engine.fill.JRFillImage.evaluate(JRFillImage.java:441)
at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:257)
at net.sf.jasperreports.engine.fill.JRFillFrame.evaluate(JRFillFrame.java:147)
at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:257)
at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:468)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillTitle(JRVerticalFiller.java:327)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:263)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:129)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:903)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:832)
at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:84)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:624)
at net.sf.jasperreports.engine.JasperRunManager.runReportToPdf(JasperRunManager.java:421)
at controller.PrintProfile.doPost(PrintProfile.java:236)
So the problem was I am developing my web application on Windows and deploying it on Linux server so basically it was the issue of writing path for linux system. I have changed Image Path in jrxml file as shown below:
Old Path:
<imageExpression>
<![CDATA[$P{context}.toString()+"WEB-INF\\reports\\pdealogo.png"]]>
</imageExpression>
New Path:
<imageExpression>
<![CDATA[$P{context}.toString()+"WEB-INF/reports/pdealogo.png"]]>
</imageExpression>
Does anyone know how can I call HttpServlet or VaadinServlet on a button click?
The URL for UI is localhost:8181/OnlineAccounting/
I am able to call servlet by manually entering URL localhost:8181/OnlineAccounting/download but I want to achieve it with clicking a button.
package com.example.Reports;
import java.io.File;
import java.io.FileInputStream;
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 net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.view.JasperViewer;
import com.example.Connection.Connect;
import com.vaadin.server.VaadinServlet;
#WebServlet("download")
public class download extends HttpServlet {
private static final long serialVersionUID = 1L;
public download() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connect c=new Connect("{Call chartofaccounts()}", null);
JRResultSetDataSource DataSet=new JRResultSetDataSource(c.rs);
try{
JasperReport JReport=JasperCompileManager.compileReport("C:\\Users\\mrreh_000\\Desktop\\Jasperreport\\MyReports\\Blank_A4_2.jasper");
JasperPrint jprint;
jprint = JasperFillManager.fillReport(JReport,null,DataSet);
JasperViewer.viewReport(jprint,false);
/// String source="C:\\Users\\mrreh_000\\Desktop\\Jasperreport\\MyReports\\Blank_A4.jrxml";
//String query="{Call chartofaccounts()}";
// JReporting jReporting=new JReporting(source,query);
String serverHomeDir = System.getenv("CATALINA_HOME");
String reportDestination = serverHomeDir +"\\report.pdf";
JasperExportManager.exportReportToPdfFile(jprint, reportDestination);
FileInputStream fis = new FileInputStream(new File(reportDestination));
// Fast way to copy a bytearray from InputStream to OutputStream
org.apache.commons.io.IOUtils.copy(fis, response.getOutputStream());
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=" + reportDestination);
response.flushBuffer();
}catch(Exception e){System.out.println(e);}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Here a similar question on stackexchange.
I suggest that you also add a random part to your report filename (or the report path), otherwise the webbrowser will not redownload the report when it is already cached from a previous download.
I want to get current country name in java . I use this code.
private HttpServletRequest request;
Locale currentCountry = request.getLocale();
System.out.println(currentCountry.getDisplayCountry());
But it through an NullPointerException like Caused by: java.lang.NullPointerException. at 2nd line. Please Help me anyone.
The snippet of code is not enough to tell why you got the Null Pointer. I assume you are use servlet on server side.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HttpServletBean;
public class MyServlet extends HttpServletBean {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
Locale userlocale = request.getLocale();
out.println("Your Country : " + userlocale.getCountry());
out.println();
out.println("");
}
}
UPDATE: I forgot to add my GotApp.java
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GotApp extends HttpServlet {
static DatabaseConn connection = null;
static UserStore dataStore = null;
static TaskCoderWtc coder = null;
ServletContext servletContext = null;
static String coderApp = null;
static String workDir = null;
public void init() {
try {
servletContext = getServletContext();
coderApp = getParameter("tricon.proxy"); //exists in web.xml
workDir = getParameter("data.dir"); //exists in web.xml
dataStore = new UserStore(workDir); //exists in web.xml
}
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
doPost(req, resp);
}
public UserStore getDataStore() {
return dataStore;
}
public DatabaseConn getConnection() { // FIXME This needs a better name.
return connection;
}
String getParameter(String str) throws Exception {
if (servletContext == null) {
throw new Exception("servletContext is null.");
return servletContext.getInitParameter(str);
}
public User getUser(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
// We only really need req.
return dataStore.loadUser(getUsername(req));
}
// Will never return null.
public Task getTask(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
User user = getUser(req, resp);
//if (user == null) {
// return null;
//}
String taskname = req.getParameter("taskname");
Task task = new Task(taskname);
// Make a quick check here.
if (task.isCoding()) {
resp.sendRedirect("task.jsp?" + req.getQueryString());
}
user.addTask(task);
return task;
}
public String getAction(HttpServletRequest req) {
String action = req.getParameter("action");
if (action == null) {
action = "";
}
return action.toLowerCase();
}
I have a web page that asks a user to choose 4 options which will be stored as a string respective to the choice. This is located in my htmltask.java:
import com.nav.wtc.model.coder.TaskRunner;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import helper.DatabaseConn;
import helper.UserStore;
import pages.GotApp;
public class HtmlTask extends GotApp {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
super.doPost(req, resp);
UserStore dataStore = getDataStore();
DatabaseConn connection = getConnection();
TaskRunner runner = getTaskRunner();
Task task = getTask(req, resp);
String action = getAction(req);
resp.getWriter().println(showPage(task));
}
public String showPage(Task task) {
StringBufn sb = new StringBufn();
sb.add("<html>");
sb.add("<body>");
sb.add(showCall(task));
sb.add("</body>
sb.add("</html>
return sb.toString();
}
private String showCall(Task task) {
StringBufn sb = new StringBufn();
sb.add("<div class='area'>");
sb.add("<form method='get' action='task.jsp'>");
sb.add(" <table>");
sb.add(" <tr class='1'>");
sb.add(" <td>");
sb.add(" What level would you like to code to: <br> ");
sb.add(" <input type ='radio' name='call' value='valsel'> Selections<br> ");
sb.add(" <input type ='radio' name='call' value='valselpbd'> Parts<br> ");
sb.add(" <input type ='radio' name='call' value='valselhbd'> Holes<br> ");
sb.add(" <input type ='radio' name='call' value='valselrbd'> C-BOMs<br> ");
sb.add(" <input type ='radio' name='call' value='valselpbdrbd'> BOMs<br> ");
sb.add(" <input type='submit' value='Run Task' />");
sb.add(" </td>");
sb.add(" </tr>");
sb.add(" </table>");
sb.add("</form>");
sb.add("</div>");
return sb.toString();
}
I would like to take one of the values here (which would be submitted by the user) and use that as input in another java class file called TaskCoderImpl.java:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileInputStream; // For debugging.
import java.io.FileOutputStream; // For debugging.
import java.io.OutputStream; // For debugging.
import java.io.InputStream; // For debugging.
void coder(File exe, File ord, File cod, File msg, File rls, String tcc )
throws ProcessException {
String[] cmd = {
exe.getPath(), // Executable
ord.getPath(), // InputOrder (IN)
cod.getPath(), // ResultsCodedOrder (OUT)
msg.getPath(), // Messages (OUT)
rls.getPath(), // Releases (IN)
tcc = ""
};
Order codeOrder(File taskdir, Order order) throws ProcessException {
String ordername = order.getName();
// Create temp 'input' files.
File orderFile = createTriconOrderFile(taskdir, order);
File releaseFile = createTriconReleaseFile(taskdir, order);
// Define temp 'output' files.
File messageFile = new File(taskdir, ordername + msgExt);
File codedFile = new File(taskdir, ordername + codExt);
// Code order.
coder(exe,
orderFile,
codedFile,
messageFile,
releaseFile,
"USER 'value' INPUT");
return codedOrder;
}
Is it even possible for me to use the 'values' from htmltask.java (which contains the servlet ie. req, resp stuff) and use those 'values' as input in my TaskCoderImpl.java as it requires only a string...If so am I missing anything...I really hope I'm not confusing anyone...
UPDATE:
Adding task.jsp:
<%getServletContext().getRequestDispatcher("/Task").forward(request, response);%>
Adding web.xml servlet style
<servlet>
<servlet-name>Task</servlet-name>
<servlet-class>pages.html.HtmlTask</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Task</servlet-name>
<url-pattern>/Task</url-pattern>
</servlet-mapping>
Well the task.jsp is just a java jsp file. The request is an implicit object that the next page will have available.
And as such it will get the html form submission attributes and you can look at those and use them to do whatever.
<%=request.getParameter("call")%>
I think your parameter is 'call'? Print the whole request and pick out the piece you need.
You can do it in EL also.
Hello, ${param.call}
You are making this loads harder by not using EL, jsf and or other more modern things. There are tag libraries for the input box, etc.