How to retrieve sql table with all its data using java - sql

I am trying to make a Java EE project with SQL as my database and glassfish as my server.
I want to retrieve all the data in my table in to a html page but I have to use servlet and session beans. My output will be shown in a html page.

An example
<%# page language="java"%>
<%# page import = "java.sql.Connection"%>
<%# page import = "java.sql.DriverManager"%>
<%# page import = "java.sql.ResultSet"%>
<%# page import = "java.sql.Statement"%>
<html>
<body>
<h1>Retrieve data</h1>
<%
try
{
Class.forName("org.gjt.mm.mysql.Driver");
Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/db", "user", "pass");
if (!conexion.isClosed())
{
Statement st = conexion.createStatement();
ResultSet rs = st.executeQuery("select * from contact");
out.println("<table border=\"1\"><tr><td>Id</td>< td>Name</td><td>LastName</td><td>Phone</td></tr>");
while (rs.next())
{
out.println("<tr>");
out.println("<td>"+rs.getObject("id")+"</td>");
out.println("<td>"+rs.getObject("Name")+"</td>");
out.println("<td>"+rs.getObject("LastName")+"</td>");
out.println("<td>"+rs.getObject("Phone")+"</td>");
out.println("</tr>");
}
out.println("</table>");
conexion.close();
}
else
out.println("fail");
}
catch (Exception e)
{
out.println("Exception " + e);
e.printStackTrace();
}
%>
</body>
</html>

Related

Handling multiple submit buttons with JSP and Servlets

I have a table that is generated from the database. This table will be enclosed in a form. Below is the result on a browser:
http://i.imgur.com/NLZzgwP.png (Low rep problems)
Below is the JSP/JSTL code:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Issues</title>
<style type="text/css">
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
td {
padding: 10px;
}
</style>
</head>
<body>
<sql:setDataSource
var="myDS"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/pdfdb"
user="user" password="*******"
/>
<sql:query var="listIssues" dataSource="${myDS}">
SELECT BookId from Book;
</sql:query>
<form method="get" action="fileDownload">
<div align="center">
<table>
<caption>List of Issues</caption>
<tr>
<th>Magazine Issue #</th>
<th>Download</th>
</tr>
<c:forEach var="issue" items="${listIssues.rows}">
<tr>
<td><c:out value="${issue.BookId}" /></td>
<td><input name='<c:out value="${issue.BookId}" />' type="submit" value="Download"></td>
</tr>
</c:forEach>
</table>
</div>
</form>
</body>
</html>
Now, what I want is for the download button to be kind of linked with the id/Issue number that is placed on the same row as the button such that, when the user clicks the download button, it passes the id/magazine issue number to the url telling the browser that the user wants to download the corresponding magazine issue number of that button clicked. Below is the servlet I use to implement this:
package com.mypackage.fileDownload;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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;
/**
* Servlet implementation class FileDownloadServlet
*/
#WebServlet("/fileDownload")
public class FileDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//size of byte buffer to send file
private static final int BUFFER_SIZE = 4096;
//database connection settings
private String dbUrl = "jdbc:mysql://localhost:3306/pdfdb";
private String dbUser = "user";
private String dbPass = "******";
/**
* #see HttpServlet#doGet(HttpServletRequesrequest,HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get upload id from URL's parameters
String uploadId = request.getParameter("name");
Connection con = null; //connects to the database
try {
//connects to the database
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbUrl, dbUser, dbPass);
//queries the database
String sql = "SELECT * FROM Book WHERE BookId = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, uploadId);
ResultSet result = pstmt.executeQuery();
if(result.next()) {
//gets file name and file blob data
String fileId = result.getString("BookId");
Blob blob = result.getBlob("BookContent");
InputStream inputStream = blob.getBinaryStream();
int fileLength = inputStream.available();
System.out.println("File length = " + fileLength);
ServletContext context = getServletContext();
//Sets MIME type for the file download
String mimeType = context.getMimeType(fileId);
if(mimeType == null) {
mimeType = "application/octet-stream";
}
//set content properties and header attributes for the response
response.setContentType(mimeType);
response.setContentLength(fileLength);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileId);
response.setHeader(headerKey, headerValue);
//writes the file to the client
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
} else {
//no file found
response.getWriter().print("File not found for the id: " + uploadId);
}
} catch(SQLException ex) {
ex.printStackTrace();
response.getWriter().print("SQL Error: " + ex.getMessage());
} catch(IOException ex) {
ex.printStackTrace();
response.getWriter().print("IO Error: " + ex.getMessage());
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
response.getWriter().print("Class Missing Error: " + ex.getMessage());
}
finally {
if(con != null) {
//closes the database connection
try {
con.close();
} catch(SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
Well, from the way I have done this, it is not working the way I wanted it to. For example, if you run this code on the server and click any of the download buttons, the url will be something like
issue.jsp?1=Download
which is weird.It will also display on the browser
File not found for the id: null
I expect something like(on the url)
issue.jsp?Download=1
where 1 is the issue being downloaded. My database has two columns: the IssueId and fileContent(content of file stored in BLOB).
I think I have explained enough and the concept is clear. Any help will be appreciated and this is as far as I could go with my code & research. Thanks!
The simplest way is to just move the form inside the table and do multiple forms:
<div align="center">
<table>
<caption>List of Issues</caption>
<tr>
<th>Magazine Issue #</th>
<th>Download</th>
</tr>
<c:forEach var="issue" items="${listIssues.rows}">
<tr>
<td><c:out value="${issue.BookId}" /></td>
<td>
<form method="get" action="fileDownload">
<input type='hidden' name='bookid' value='<c:out value="${issue.BookId}" />' />
<input type="submit" value="Download">
</form>
</td>
</tr>
</c:forEach>
</table>
</div>
You also need to move the value out of the name attribute of the button and into the value attribute of a hidden input. That hidden input needs a name you will use to get the value in the servlet: request.getParameter("bookid");

Silverlight bingMapContril using LocalproxyPage to downLoad MapTiles Extremely Slow

as we know silverlight5 has ability to get pageElement's visual so we can print or save them as pictrue.but if your MapTilesSource uri is in a differentDomain to your silverlight Application host site,you can not get BingMapControl's visual,because of "cross-domain problem",clr would throw a System.Security.SecurityException.
To avoid this problem I add a Proxy aspx page in the silverlight host site,which can send bingMap TileImage request to the remote MapTilesService.
here is my customer Class inherit from TileSource:
public class GoogleTileSource : TileSource
{
public GoogleTileSource()
: base("http://mt{0}.google.cn/vt/lyrs={1}#180000000&hl=zh-CN&gl=cn&z={2}&x={3}&y={4}")
{
this.Type = GoogleTileType.Hybrid;
}
public override Uri GetUri(int x, int y, int zoomLevel)
{
string TargetUrl = string.Format(this.UriFormat, this.Server, (char)this.Type, zoomLevel, x, y);
return new Uri(string.Format(http://localhost:52879/MapTilesServerProxy.aspx + "?sourceUrl={0}", TargetUrl));
//return new Uri(string.Format(this.UriFormat, this.Server, (char)this.Type, zoomLevel, x, y));
}
public int Server
{
get;
set;
}
public GoogleTileType Type
{
get;
set;
}
}
here is my proxy page code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="MapTilesServerProxy.aspx.cs" Inherits="AeroZH.Web.MapTilesServerProxy" %>
<%# Import Namespace=System.Net %>
<%# Import Namespace=System.IO %>
<%# Import Namespace=System.Diagnostics %>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
ProxyRequest();
}
private void ProxyRequest()
{
try
{
string url = "";
url = this.Page.Request.Url.AbsoluteUri.Split(new string[] { "?sourceUrl=" }, StringSplitOptions.RemoveEmptyEntries)[1];
Debug.WriteLine("url:" + url);
Debug.WriteLine(url + "——requestTime:" + System.DateTime.Now);
HttpWebRequest loHttp = (HttpWebRequest)WebRequest.Create(url);
loHttp.Timeout = 10000; // 10 secs
loHttp.UserAgent = "Web Client";
HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse();
Debug.WriteLine(url + "——responseTime:" + System.DateTime.Now);
using (Stream inputStream = loWebResponse.GetResponseStream())
{
byte[] buffer = new byte[4096 * 100];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
} while (bytesRead != 0);
Response.BinaryWrite(buffer);
Response.End();
}
loWebResponse.Close();
if (loHttp != null)
loHttp.Abort();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
after this work,bingMapcontrol successfully make its image request thought the proxy page ,and the ProxyPage's request get response form remote server is also success.but only a few mapTiles show in the map.
I using debug.write to trace response status,almost everyRequest has correct response,i don't know why only few mapTiles show in map.
First off, using Google map tiles in Bing Maps is against the terms of use of both the Bing Maps and Google Maps terms of use.
Secondly, The Bing Maps Silverlight control is nearing end of life. The documentation is already offline and it won't be long before the control is disabled. No new development should be one with it. Also, the end of life for Silverlight in general was announced a few years ago.

How to implement Generate Jasper Report PDF on button click in Liferay Portal 6.1

I have a requirement to provide report generation functionality on a button click. I am using Liferay Portal 6.1 with Tomcat 7 as web portal, Liferay Developer Studio (Eclipse Indigo) IDE, iReport (to create report template), and JasperReports library to produce the PDF. The portal is a ticket management system with two entities (Tickets and Documents) which are entered via their respective custom portlets. Both entities, when in edit mode, need the 'View Report' function. I have searched for answers to this problem extensively, picking up a snippet here and there, but nothing I have found is exactly my situation. Upon clicking the 'View Report' button, the user needs to be presented with a formatted PDF where the user can then decide to 'Save', 'Print', or 'Close' from. I also need to pass data to the report so information can be retrieved for the entity that is open (i.e., documentId, ticketId, docType, etc.), but this piece can be added later; once I just get a PDF to open.
Not knowing how to go about implementing this, I decided to use a jQuery Modal to open 'viewReport.jsp' page and process the report there. However, this approach yields a JRException IllegalState: cannot obtain OutputStream because writer is already in use. I have read in my searches that Liferay layout uses OutputStream and that's probably why the writer is already in use. Here's the code I am using:
edit_document.jsp (button and jQuery Modal)
<!-- View Report Button at bottom of form -->
<aui:button type="button" id="viewReportBtn" value="View Report" />
<!-- URL declaration for PDF popup window -->
<portlet:renderURL var="viewReportURL" windowState="<%= LiferayWindowState.EXCLUSIVE.toString() %>" >
<portlet:param name="mvcPath" value="/html/document/viewReport.jsp" />
<portlet:param name="documentId" value="<%= Long.toString(documentID) %>" />
<portlet:param name="ticketId" value="<%= Long.toString(ticketID) %>: />
<portlet:param name="docType" value="<%= docType %>" /> <!-- This is already a String value -->
</portlet:renderURL>
<!-- jQuery to open popup window for PDF -->
<aui:script use="aui-dialog, aui-overlay-manager, dd-constrain" >
var reportDialogOptions = {
title : 'Dialog',
bodyContent : '',
centered : true,
group : default,
height : 800,
width : 1000,
modal : true,
};
$('#viewReportBtn').on('click', finction(event) {
var editFeelingDialog = new A.Dialog(
A.merge(reportDialogOptions, {
title : 'Document View Report'
})
).plugin(A.Plugin.IO,{uri : '<%= viewReportURL %>'}).render();
});
</aui:script>
viewReport.jsp (page to process jrxml template and open PDF)
<!-- viewReport.jsp page to render PDF -->
<%# page contentType = "application/pdf" %>
<%# page trimDirectiveWhitespaces = "true" %>
<%# page import = "net.sf.jasperreports.engine.*" %>
<%# page import = "java.io.File" %>
<%# page import = "java.io.FileInputStream" %>
<%# page import = "java.io.FileNotFoundException" %>
<%# page import = "java.io.InputStream" %>
<%# page import = "java.sql.Connection" %>
<%# page import = "java.sql.SQLException" %>
<%
Connection conn = null;
try
{
String url = "jdbc:oracle:thin:#myDBSRV:1521:myDatabase";
String userName = "myUsername";
String password = "myPassword";
// Connecting to the Oracle database
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
// Loading the Jasper Report file from local file system\
String jrxmlFile = session.getServletContext().getRealPath(request.getContextPath())+"\\report5.jrxml";
InputStream input = new FileInputStream(new File(jrxmlFile));
// Generate the report
JasperReport jasperReport = JasperCompileManager.compileReport(input);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPrint, null, conn);
// Export the report as a PDF
JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
}
catch (FileNotFoundExcecption ex)
{
System.out.println(ex.getMessage());
ex.printStakeTrace();
}
catch (JRException ex)
{
System.out.println(ex.getMessage());
ex.printStakeTrace();
}
catch (ClassNotFoundException ex)
{
System.out.println(ex.getMessage());
ex.printStakeTrace();
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
ex.printStakeTrace();
}
finally
{
if (conn != null)
{
conn.close();
}
}
%>
I also tried to add java methods to my DocumentPortlet.java class and call the method(s) when the button is clicked, but I am not that familiar enough with ajax to get it right:
DocumentPortlet.java
public class DocumentPortlet extends MVCPortlet{
Connection conn = null;
// More methods for saving, editing, and deleting documents are here...
public void generateReport()
{
initConnection();
showReport();
}
public void initConnection()
{
String host = "jdbc:oracle:thin:#ncimsdbsrv:1521:ncimsdev";
String userName = "lportal";
String password = "NSS4207itnp";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
try
{
conn = DriverManager.getConnection(host, userName, password);
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
public void showReport()
{
//Path to your .jrxml file
String reportName = "[path to file]";
//Get a stream to read the file
InputStream is = this.getClass().getClassLoader().getResourceAsStream(reportName);
try
{
//Fill the report with parameter, connection, and stream reader
JasperPrint jp = JasperFillManager.fillReport(is, null, session);
//Viewer for Jasper report
JRViewer jv = new JRViewer(jp);
//Insert viewer to a JFrame to make it showable
JFrame jf = new JFrame();
jf.getContentPane().add(jv);
jf.validate();
jf.setVisible(true);
jf.setSize(new Dimension(800, 600));
jf.setLocation(300, 100);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
catch (JRException ex)
{
ex.printStakeTrace();
}
finally
{
closeSession(session);
}
}
}
How can I provide this functionality in a way that my users can click the button and a PDF be generated on their screen? I need a clear and concise solution to this problem. Thank you!
Lee
In case anyone is interested, I found an answer on a Liferay forum. My implementation was not correct. So now I have this in my
viewDocument.jsp:
<!-- View Report button at bottom of form -->
<aui:button id="viewReportBtn" value="View Report" />
<!-- URL declaration for PDF generation -->
<portlet:resourceURL id="generatePDF" var="generateReportURL" >
<portlet:param name="jspPage" value="/html/document/viewReport.jsp" />
<portlet:param name="docType" value="<%= docType %>" />
</portlet:resourceURL>
<!-- AJAX call to resource request handler in DocumentPortlet.java file -->
<aui:script use="aui-dialog, aui-overlay-manager, dd-constrain" >
$(document).ready(function()
{
$('#viewReportBtn').click(function(event)
{
$.ajax('<%= generateReportURL %>');
}
});
I also created the ResourceRequestHandler in my Portlet java file like so:
DocumentPortlet.java:
public class DocumentPortlet extends MVCPortlet{
Connection conn = null;
// More methods to add, update, and delete here
#Override
public void serveResource(ResourceRequest request, ResourceResponse response)
throws IOException, PortletException
{
String url = "jdbc:oracle:thin:#myDatabaseSrv:1521:myDatabaseSid";
String user = "myUserName";
String pass = "myPassword";
String docType = ParamUtil.getString(request, "docType");
try
{
// Connect to database
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, pass);
// Load JRXml file from local file system
String jrxmlFile = "C:\\Reports\\report5.jrxml";
InputStream input = new FileInputStream(new File(jrxmlFile));
// Generate report
JasperReport jasperReport = JasperCompileManager.compileReport(input);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPrint, null, conn);
/***** Display PDF in Adobe Reader *****/
// Create new OutputStream where data is written to byte array[]
ByteArrayOutputStream output = new ByteArrayOutputStream();
// Export the report to PDF format
JasperExportManager.exportReportToPdfStream(jasperPrint, output);
// Create a String for thr report title
final String fileName = docType + ".pdf";
//Create a new stream and call the report
OutputStream pdfFile = new FileOutputStream(new File(fileName));
//Write the PDF
pdfFile.write(output.toByteArray());
//Clean the PDF
pdfFile.flush();
//Close it
pdfFile.close();
//Run the brand new PDF report
final String PDF_RUN = "rundll32 url.dll, FileProtocolHandaler " + fileName;
//Execute the command
Runtime.getRuntime().exec(PDF_RUN);
}
catch(FileNotFoundException ex)
{
System.out.println("File not found on file system, check file path!!" + ex.getMessage());
ex.printStackTrace();
}
catch(JRException ex)
{
System.out.println("Error in Jasper Report!!" + ex.getMessage());
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
System.out.println("Oracle Class for driver not found!!" + ex.getMessage());
ex.printStackTrace();
}
catch(SQLException ex)
{
System.out.println("Error getting connection to database!!" + ex.getMessage());
ex.printStackTrace();
}
}
}
This eliminated the IllegalStateException I was getting and will open the pdf in Adobe Reader just fine, however, it opens it up on the server. Therefore, a problem still remains. Anybody know how I can get this pdf to open on the client machine?

jasper pdf report does not show up

my JSF 2.0 web application is intended to produce PDF reports.
the problem is that no PDF report is shown up in the explorer window.
I am using eclipse kepler, with apache-tomcat-7.0.52 and the version of jasper Ireport is 4.8
any help would be appreciated.
I will provide the whole java class :
package khldqr.beans;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
#ManagedBean
#SessionScoped
public class TestReport {
private List<Refugee> refugee;
public List<Refugee> connectRefugeeData() {
ResultSet rs = null;
PreparedStatement pst = null;
Connection con = Database.getConnection();
String stm = "Select R_NO, F_P_Name from M_MAIN_INFO where R_NO < 10";
refugee = new ArrayList<Refugee>();
try {
pst = con.prepareStatement(stm);
pst.execute();
rs = pst.getResultSet();
while (rs.next()) {
Refugee refugeelist = new Refugee();
refugeelist.setR_NO(rs.getInt(1));
refugeelist.setF_P_Name(rs.getString(2));
refugee.add(refugeelist);
}
} catch (SQLException e) {
e.printStackTrace();
}
return refugee;
}
public void PDF(ActionEvent actionEvent) throws IOException, JRException {
System.out.println("this is not my lucky day!!!!!");
File jasper = new File(FacesContext.getCurrentInstance().getExternalContext().getRealPath("report/Majd.jasper"));
byte[] bytes = JasperRunManager.runReportToPdf(jasper.getPath(),null,new JRBeanCollectionDataSource(refugee));
HttpServletResponse response =(HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setContentType("application/pdf");
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(bytes, 0 , bytes.length);
outputStream.flush();
outputStream.close();
FacesContext.getCurrentInstance().responseComplete();
}
public TestReport() {
connectRefugeeData();
}
public List<Refugee> getRefugee() {
return refugee;
}
public void setRefugee(List<Refugee> refugee) {
this.refugee = refugee;
}
}
and here is xhtml file:
<?xml version='1.0' encoding='UTF-8' ?>
<!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"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Hello To GOPA World!!</title>
</h:head>
<h:body dir="rtl">
<h:form>
<p:commandButton value = "PDF" actionListener="#{testReport.PDF}"></p:commandButton>
</h:form>
<h:dataTable value="#{testReport.refugee}" var="var">
<h:column>
<h:outputText value="#{var.r_NO}"></h:outputText>
</h:column>
<h:column >
<h:outputText value="#{var.f_P_Name}"></h:outputText>
</h:column>
</h:dataTable>
</h:body>
</html>
I can see the message on the console and the page gets refreshed but no PDF report is come up the explorer screen
I have replaced the above PDF method with the code below, but in vain, the same result: no PDF report is coming up the explorer screen.
JasperPrint jasperPrint;
public void init() throws JRException{
JRBeanCollectionDataSource beanCollectionDataSource=new JRBeanCollectionDataSource(refugee);
String reportPath= "e:\\Rita.jasper";
jasperPrint=JasperFillManager.fillReport(reportPath, new HashMap(),beanCollectionDataSource);
}
public void PDF(ActionEvent actionEvent) throws JRException, IOException{
init();
HttpServletResponse httpServletResponse=(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
// httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");
FacesContext.getCurrentInstance().getExternalContext().setResponseContentType("‌​application/pdf");
ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
System.out.println("All done the report is done");
servletOutputStream.flush();
servletOutputStream.close();
FacesContext.getCurrentInstance().responseComplete();
}
the code is correct, and there is nothing wrong with it.
the problem was some kind of security issue.
I faced the above problem when the report was in a full access folder to all users.
put when I put both of the requested xhtml and the report in a secured folder, everything went OK.
I don't know why!! but that was the case with me.
hoping others will make use of this.
thx.
<p:commandButton value = "PDF" actionListener="#{testReport.PDF}" ajax="false" type="submit"></p:commandButton>
you cant use ajax when calling jasperReports

AnnotationChart dateformat from sqlserver

Hi Im trying to implement an Annotation chart that get its data from Sql Server. The code is working as the data is coming back . My problem is the format of the date / datetime when doing google.visualization.DataTable().addRow()
The date format returned from sqlserver is 2014-03-19 12:00:00 AM
How to change this date format to insert into the datatable.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script type='text/javascript' src='http://www.google.com/jsapi'></script>
<script type="text/javascript">
google.load('visualization', '1.1', { packages: ['annotationchart'] });
</script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'Default.aspx/GetData',
data: '{}',
success:
function (response) {
drawVisualization(response.d);
}
});
})
function drawVisualization(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Column Name');
data.addColumn('number', 'Column Value');
data.addColumn('number', 'Column Value2');
console.log(dataValues[0].ColumnName);
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].ColumnName, dataValues[i].Value, dataValues[i].Value2]);
}
var formatter = new google.visualization.DateFormat({pattern: 'yyyy-MM-dd'});
var chart = new google.visualization.AnnotationChart(document.getElementById('visualization'));
var options = {
displayAnnotations: false,
};
chart.draw(data, options);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="visualization" style="width: 1000px; height: 500px;">
</div>
</form>
</body>
</html>
This is the C# code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<Data> GetData()
{
SqlConnection conn = new SqlConnection(****);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
conn.Open();
string cmdstr = "select LogDate, val1, val2from [vwTest]";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
dt = ds.Tables[0];
List<Data> dataList = new List<Data>();
string cat = "";
int val = 0;
int val2 = 0;
foreach (DataRow dr in dt.Rows)
{
cat = dr[0].ToString();
val = Convert.ToInt32(dr[1]);
val2 = Convert.ToInt32(dr[2]);
DateTime dte = DateTime.Parse(DateTime.Parse(cat).ToString("yyyy-MM-dd"));
dataList.Add(new Data(dte, val, val2));//Dont know what to do here
}
return dataList;
}
public class Data
{
public DateTime ColumnName;
public int Value = 0;
public int Value2 = 0;
public Data(DateTime columnName, int value, int value2)
{
ColumnName = columnName;
Value = value;
Value2 = value2;
}
}
}
I see examples where people use new Date(2013,23,3,4,5) say but im not hard coding my data.
Please assist. This is my first Attempt at Google Visualization API
Dates are tricky to work with when you are sending data via JSON (since JSON does not have a date standard). The only way to get them input as proper Date objects is to use the full JSON DataTable syntax for specifying rows, columns, and cells of data. Since I'm not quite sure how this would be done in C#, I have an alternative approach I can demonstrate for you. Since you need Date objects for your DataTable, and your output is giving you date strings, it is a relatively simple task to parse the strings into year, month, and day, and then build a Date object from those:
for (var i = 0; i < dataValues.length; i++) {
// assumes the date string is in the format "yyyy-MM-dd"
var dateArr = dataValues[i].ColumnName.split('-');
var year = dateArr[0];
var month = dateArr[1] - 1; // adjust for javascript's 0-indexed months
var day = dateArr[2];
data.addRow([new Date(year, month, day), dataValues[i].Value, dataValues[i].Value2]);
}