I have a service class that creates reports in xls using dynamicjasper, I wonder how I can include a button in my flex app to execute this method.
#Service("downloadService")
#Transactional
public class DownServiceRelTemp {
private static Logger logger = Logger.getLogger("service");
#Resource(name="sessionFactory")
private SessionFactory sessionFactory;
public void downloadXLS(HttpServletResponse response) throws ColumnBuilderException,
ClassNotFoundException, JRException {
logger.debug("Downloading Excel report");
DynamicReport dr = LayouteRelTemp.buildReportLayout();
JRDataSource ds = getDataSource();
JasperReport jr = DynamicJasperHelper.generateJasperReport(dr, new ClassicLayoutManager(), null);
JasperPrint jp = JasperFillManager.fillReport(jr, null, ds);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Exporter.exportToXLS(jp, baos);
String fileName = "MyReport.xls";
response.setHeader("Content-Disposition", "inline; filename=" + fileName);
response.setContentType("application/vnd.ms-excel");
response.setContentLength(baos.size());
Writer.write(response, baos);
}
Any suggestions, do not have much experience with adobe flex and would like a simple help.
There's some ways to interactive flex with java
Using Web Services
Using servlets
By Remoting objects. By AMF thecnology.
I recommend this tutorial of the evangelist James Ward, in this tutorial him explains the differents ways to connect flex and java with code example. That's how I learned to comunicate flex and Java
Notes that you need to check blazeDs Library
Related
I am exports PDF usgin jasper reports. In develop, it works fine. But when compile the jar, system throws and FileNotFound Exception for "src/main/resources/reports/myJasperReport.jxml"
When I explore the JAR,I came across that the URL for the report is "/BOOT-INF/classes/resports/myJasperReport.jxml"
I found this link to File inside jar is not visible but didn't solve my problem.
Could you help me please?
#Slf4j
#Service
public class ReportService {
private static final String REPORTS_BASE_PATH = "src/main/resources/reports/";
public ByteArrayInputStream exportReport(
String reportFileName,
Integer idCC,
Map<String,Object> parameters
) throws Exception {
Connection connection = CustomEntityManagerFactoryPostgresImpl
.getInstance()
.getConnection(idCC);
File file = ResourceUtils.getFile(REPORTS_BASE_PATH + reportFileName);
JasperReport jasperReport = JasperCompileManager.compileReport(file.getAbsolutePath());
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, connection);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
return new ByteArrayInputStream(outputStream.toByteArray());
}
}
Add classpath: prefix to your path. And consider the resources folder to be a root.
ResourceUtils.getFile("classpath:reports/" + reportFileName);
UPD:
Actually, you don't need to get a file at all. Try to get resource as stream:
InputStream report = ReportService.class.getClassLoader().getResourceAsStream("reports/" + reportFileName);
JasperReport jasperReport = JasperCompileManager.compileReport(report);
I am creating HTTP server with Tomee, i am placed jasper report file (.jasper) in webapp directory. if i access http://localhost:8080/test.jasper in browser, the browser will prompt to download the file.
In my java project i'm creating simple code to access that link and then preview the report. I use async-http-client library for request.
DefaultAsyncHttpClient client = new DefaultAsyncHttpClient();
BoundRequestBuilder brb = client.prepareGet("http://localhost:8765/qa/test.jasper");
Future<InputStream> f = brb.execute(new AsyncCompletionHandler<InputStream>() {
#Override
public InputStream onCompleted(Response resp) {
try {
String[][] data = {{"Jakarta"},{"Surabaya"},{"Solo"},{"Denpasar"}};
String[] columnNames = {"City"};
DefaultTableModel dtm = new DefaultTableModel(data, columnNames);
Map<String,Object> params = new HashMap<>();
JasperPrint jPrint = JasperFillManager.fillReport(
resp.getResponseBodyAsStream(),
params,
new JRTableModelDataSource(dtm)
);
JasperViewer jpView = new JasperViewer(jPrint,false);
jpView.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jpView.setSize(800, 600);
jpView.setLocationRelativeTo(null);
jpView.setVisible(true);
} catch (JRException ex) {
System.out.println(ex.getMessage());
}
return resp.getResponseBodyAsStream();
}
});
From my code above, i got an error Error loading object from InputStream
normally i can use
InputStream input = MainContext.class.getResourceAsStream(filename);
But i want to replace file input stream with http request (stream too).
How exactly i can serve .jasper file with http server...?
Error loading object from InputStream error came from corrupt InputStream, if i download .jasper file normally via browser and execute the report with JRLoader.loadObjectFromFile(path to file) it doesn't works too, because tomee give corrupt file (the source file not corrupt).
My own solution is read source file as stream, convert it to base64 encode, and serve it via HTTP API protocol.
finput = new FileInputStream(sPath);
byte[] bFile = Base64.getEncoder().encode(IOUtils.toByteArray(finput));
String sFile = new String(bFile);
inside client side, i received it as body string, decode the base64 string, convert it to InputStream and Finally execute the report with InputStream.
byte[] bBody = Base64.getDecoder().decode(sBody);
InputStream mainReport = new ByteArrayInputStream(bBody);
return JasperFillManager.fillReport(mainReport, params);
I need to send a pdf jasper directly to the printer, the current code PDF is delegated to the browser and therefore the user can print as many copies as desired. Must allow only print one copy, so I thought I'd send directly to printing.
I searched the forum but did not understand what would be the best solution to the issue.
Take a look at my code:
public class UtilRelatorios {
public static void imprimeRelatorio(String relatorioNome,
HashMap parametros) throws IOException, JRException {
FacesContext fc = FacesContext.getCurrentInstance();
ServletContext context = (ServletContext) fc.getExternalContext().getContext();
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
JasperPrint jasperPrint =
JasperFillManager.fillReport(
context.getRealPath("/relatorios")+ File.separator+relatorioNome+".jasper",
parametros);
//int finalPag = jasperPrint.getPages().size();
//System.out.println("page: "+finalPag);
//JasperPrintManager.printPage(jasperPrint,finalPag,false);
byte[] b = null;
//JasperPrintManager.printPage(jasperPrint, 0, false);
try {
b = JasperExportManager.exportReportToPdf(jasperPrint);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
if (b != null && b.length > 0) {
// Envia o relatório em formato PDF para o browser
response.setContentType("application/pdf");
int codigo = (int) (Math.random()*1000);
response.setHeader("Content-disposition","inline);filename=relatorio_"+codigo+".pdf");
response.setContentLength(b.length);
ServletOutputStream ouputStream = response.getOutputStream();
ouputStream.write(b, 0, b.length);
ouputStream.flush();
ouputStream.close();
}
}
}
If as seems in question you like to send the report directly to user's printer via web application, browser.
This can not be done!, you can not control the web users printer directly from the browser (excluding the use of activeX or other home made plugins)
Probably this is luck since otherwise while navigating on internet you would have people printing alot of advertising on your printer....
If instead you like to send it to a printer attached to server, this can be done!
If its the server printer please let me know and I can pass you some code.
If the client & server PC are on the same network ie LAN, you can share the client's printer on the server, then send report to it just like you'd send to a locally installed printer.
I have a java web application based on Spring MVC.
The task is to generate a pdf file. As all knows the spring engine has its own built-in iText library so the generating of pdf file is really simple. First of all we need to do is to overload AbstractView and create some PdfView. And the seconf thing is to use that view in controller. But in my application I am also have to be able to store generated pdf files on local drive or give my users some link to download that file. So the view in that case is not suitable for me.
I want to create some universal pdf generator that creates a pdf file and returns the bytes array. So I can use that array for file storing (on hard drive) or printing it directly in browser. And the question is - are there any way to use such engine (that returns only the bytes array) in PdfVIew solution? I am asking because overloaded buildPdfDocument method (in PdfView) already have PdfWriter and Document parameters.
Thank you
tldr; you should be able to use a view and save it to a file.
Try using Flying Saucer and its iTextRenderer when you overload AbstractPdfView.
import org.xhtmlrenderer.pdf.ITextRenderer;
public class MyAbstractView extends AbstractView {
OutputStream os;
public void buildPdfDocument(Map<String,Object> model, com.lowagie.text.Document document, com.lowagie.text.pdf.PdfWriter writer, HttpServletRequest request, HttpServletResponse response){
//process model params
os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
String url = "http://www.mysite.com"; //set your sample url namespace here
renderer.setDocument(document, url); //use the passed in document
renderer.layout();
renderer.createPDF(os);
os.close();
}
}
protected final void renderMergedOutputModel(Map<String,Object> model,
HttpServletRequest request,
HttpServletResponse response)
throws Exception{
if(os != null){
response.outputStream = os;
}
public byte[] getPDFAsBytes(){
if(os != null){
byte[] stuff;
os.write(stuff);
return stuff;
}
}
}
You'll probably have to tweak the sample implementation shown here, but that should provide a basic gist.
I have a simple question about sending a file (XML file) from my webapp server to another server with Java (struts2 framework).
I hope someone can give a look to my code, because it is impossible for me to check if the code will work - the other server (the one that have to receive the file) is still not implemented. And I have to prepare my webapp server the most correct possible to send the file.
I have an XML file path, and the server address and the port its filled by the spring framework.
Looking at some examples in internet and also in some other questions in this awesome site, I have tried to write a simple code to send my file to the given address. This is the code:
private String server;
private Integer port;
// getters and settlers methods for server and port properties
public void sendXML(String fileName) throws Exception{
try{
Socket socket = new Socket(server, port);
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
OutputStream os = socket.getOutputStream();
byte [] bytearray = new byte [(int)file.length()];
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(bytearray,0,bytearray.length);
os.write(bytearray,0,bytearray.length);
os.flush();
socket.close();
}
catch(IOException e){
e.printStackTrace();
}
}
So, I will be very grateful if someone can give a look to my code and tell me if you think that it will not work. If you think that there is another better way to do it I also would be grateful to know it.
Thank you people, you are always really really helpful ;)
Regards,
Aleix
I suggest you use HTTP rather than raw sockets. It will deal with timeouts, chunking, encoding, etc.
Have a look at the commons http library (formerly known as http-client), it will save you writing your own code.
I have look how to do it trough HTTP with the Apache HttpClient4 and HttpCore4 libraries and I have wrote this code, you think it would work properly? Thank you very much!
private String server;
//private Integer port;
// getter and settler methods for server property
public void sendXML(String fileName) throws Exception{
try{
File file = new File(fileName);
FileEntity entity = new FileEntity(file, "text/xml; charset=\"UTF-8\"");
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost method = new HttpPost(server);
method.setEntity(entity);
HttpResponse response = httpclient.execute(method);
}
catch(IOException e){
e.printStackTrace();
}
}