Pages

Thursday, February 21, 2008

JasperReport Export to Excel Snippet code

Sample code that will export JasperReport(.jasper) to excel, pay attention to the bold code
that's all the tricks. The sample servlet will accept two parameter the date and the name of the report.


/*
* JasperToExcel.java
*/

import bean.report.RowStatistics;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.*;
import javax.servlet.http.*;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;

/**
*
* @author amontejo
* @version
*/
public class JasperToExcel extends HttpServlet {

public static final String REPORT_DIRECTORY = "/reports";

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String reportName = request.getParameter("reportname");
String selectedyear = request.getParameter("SelectedYear");
InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream("/" + REPORT_DIRECTORY + "/" + reportName + ".jasper");

ServletContext context = this.getServletConfig().getServletContext();
JasperPrint jasperPrint = null;
HashMap parameterMap = new HashMap();

parameterMap.put("parayear", new String(selectedyear));

try {
ServletOutputStream servletOutputStream = response.getOutputStream();
JRDataSource dataSource = createReportDataSource(request, selectedyear, reportName);
jasperPrint = JasperFillManager.fillReport(reportStream, new HashMap(), dataSource);
generateXLSOutput(reportName, jasperPrint, response);
} catch (Exception e) {
}
}

private String tagreport(String string) {
java.util.Calendar calendar = java.util.Calendar.getInstance();
return string + calendar.get(calendar.MONTH) + calendar.get(calendar.DAY_OF_MONTH) + calendar.get(calendar.YEAR);
}

private void generateXLSOutput(String reportname,
JasperPrint jasperPrint,
HttpServletResponse resp)
throws IOException, JRException {
String reportfilename = tagreport(reportname) + ".xls";
JExcelApiExporter exporterXLS = new JExcelApiExporter();

exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, resp.getOutputStream());
resp.setHeader("Content-Disposition", "inline;filename=" + reportfilename);
resp.setContentType("application/vnd.ms-excel");

exporterXLS.exportReport();
}


//
/** Handles the HTTP GET method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Handles the HTTP POST method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
//

}

Yahoo gets its best move...

Good Yahoo will denied the offer to save its developer ... its good to know that they valued their engineer. Its good news to us Open-Source ... bravo!!! bravo!!! bravo!!! lets rock the Open-Source world !

Android(aka undroid)

Huh! Ive waited this for so long last year in netbeans plugin, at least it was then release this first week of January , Funny to think that they tweak the name to Undroid, thats why Im so late to find out that this is already out. Okay let me taste the sweet brand new java platform Android... Im excited with this new google new technology with there brand new framework also called Guice... this is excellent...

remodel the Backend ....

What! change specs? wheeeww.. this is a bloody idea. Problem is, the current model made by this son of Einstein outsource people is not that flexible and scalable so I've decided to remodel the backend. And the big plus is were having two database Mysql and oracle using JDBC, This going to a big war ...Anyway Im still standing here... so im going to start digging ...

Tuesday, February 19, 2008

Integrating JasperReports with Hibernate

Please see http://jasperreports.sourceforge.net/ for JasperReports

Please see http://www.hibernate.org for Hibernate

We will make an sample jasperReport that uses the hibernate in populating its data.
we are going to build an sample JRXML template, will name it HibernateQueryDemoReport

-------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jasperReport PUBLIC ���"�//JasperReports//DTD Report Design//EN"
�"�http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="HibernateQueryDemoReport">
<parameter name="countryCode" class="java.lang.String"/>
<queryString language="hql">
<![CDATA[from Aircraft aircraft where country = $P{countryCode}
order by aircraft.id]]>
</queryString>
<field name="id" class="java.lang.String"/>
<field name="aircraftSerial" class="java.lang.String"/>
<field name="yearBuilt" class="java.lang.String"/>
<title>
<band height="30">
<textField>
<reportElement width="555" height="30" x="0" y="0"/>
<textFieldExpression>
<![CDATA[������� "�Aircraft Registered in Country Code: ""+
$P{countryCode}]]>
</textFieldExpression>
</textField>
</band>
</title>
<pageHeader>
<band height="30">
<staticText>
<reportElement width="100" height="30" x="0" y="0"/>
<text>
<![CDATA[Tail Number]]>
</text>
</staticText>
<staticText>
<reportElement width="100" height="30" x="100" y="0" />
<text>
<![CDATA[Serial Number]]>
</text>
</staticText>
<staticText>
<reportElement width="100" height="30" x="200" y="0"/>
<text>
<![CDATA[Year Built]]>
</text>
</staticText>
</band>
</pageHeader>
<detail>
<band height="30">
<textField>
<reportElement width="100" height="30" x="0" y="0"/>
Integrating hibernate with struts sample
<textFieldExpression>
<![CDATA[$F{id}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement width="100" height="30" x="100" y="0"/>
<textFieldExpression>
<![CDATA[$F{aircraftSerial}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement width="100" height="30" x="200" y="0"/>
<textFieldExpression>
<![CDATA[$F{yearBuilt}]]>
</textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>

-------------------------------------------------------
Take a look in the bold portion of the code snippet, the embedded report query was written in Hibernate Query Language(HQL).

The code for this Value Object is as follows:
-------------------------------------------------------
package net.ensode.jasperbook.dbaccess;
import net.ensode.jasperbook.dbaccess.base.BaseAircraft;

/**
*Aircraft.java
* @author amontejo
*/

public class Aircraft extends BaseAircraft
{
private static final long serialVersionUID = 1L;

public Aircraft()
{
super();
}
/**
* Constructor for primary key
*/
public Aircraft(java.lang.String id)
{
super(id);
}
/**
* Constructor for required fields
*/
public Aircraft(java.lang.String id, java.lang.String
aircraftSerial, java.lang.String aircraftModelCode,
java.lang.String aircraftEngineCode, java.lang.String
yearBuilt, java.lang.String aircraftTypeId, java.lang.String
aircraftEngineTypeId, java.lang.String registrantTypeId,
java.lang.String name, java.lang.String address1,
java.lang.String address2, java.lang.String city, java.lang
String state, java.lang.String zip, java.lang.String region,
java.lang.String county, java.lang.String country, java.lang
String certification, java.lang.String statusCode, java.lang
String modeSCode, java.lang.String fractOwner, java.util.Date
lastActionDate, java.util.Date certIssueDate, java.util.Date
airWorthDate)
{
super(id, aircraftSerial, aircraftModelCode, aircraftEngineCode,
yearBuilt, aircraftTypeId, aircraftEngineTypeId, registrantTypeId,
name, address1, address2, city, state, zip, region, county,
country, certification, statusCode, modeSCode, fractOwner,
lastActionDate, certIssueDate, airWorthDate);
}

}

-------------------------------------------------------
The class Aircraft extends a class called BaseAircraft, and its source code is as follows:
-------------------------------------------------------

package net.ensode.jasperbook.dbaccess.base;
import java.lang.Comparable;

/**
*BaseAircraft.java
* @author amontejo
*/

public abstract class BaseAircraft implements Comparable, Serializable
{
public static String REF = �"�Aircraft";
public static String PROP_AIRCRAFT_SERIAL = �"�AircraftSerial";
public static String PROP_AIRCRAFT_TYPE_ID = �"�AircraftTypeId";
public static String PROP_STATE = �"�State";
public static String PROP_REGISTRANT_TYPE_ID = �"�RegistrantTypeId";
public static String PROP_ADDRESS1 = �"�Address1";
//remaining property constants removed for brevity
//constructors
public BaseAircraft()
{
initialize();
}
/**
* Constructor for primary key
*/
public BaseAircraft(java.lang.String id)
{
this.setId(id);
initialize();
}
/**
* Constructor for required fields
*/
public BaseAircraft(java.lang.String id, java.lang.String
aircraftSerial, java.lang.String aircraftModelCode,
java.lang.String aircraftEngineCode, java.lang.String
yearBuilt, java.lang.String aircraftTypeId, java.lang.String
aircraftEngineTypeId, java.lang.String registrantTypeId,
java.lang.String name, java.lang.String address1, java.lang.
String address2, java.lang.String city, java.lang.String
state, java.lang.String zip, java.lang.String region, java.
lang.String county, java.lang.String country, java.lang.
String certification, java.lang.String statusCode, java.lang.
String modeSCode, java.lang.String fractOwner, java.util.Date
lastActionDate, java.util.Date certIssueDate, java.util.Date
airWorthDate)
{
this.setId(id);
this.setAircraftSerial(aircraftSerial);
this.setAircraftModelCode(aircraftModelCode);
this.setAircraftEngineCode(aircraftEngineCode);
this.setYearBuilt(yearBuilt);
this.setAircraftTypeId(aircraftTypeId);
this.setAircraftEngineTypeId(aircraftEngineTypeId);
this.setRegistrantTypeId(registrantTypeId);
this.setName(name);
this.setAddress1(address1);
this.setAddress2(address2);
this.setCity(city);
this.setState(state);
this.setZip(zip);
this.setRegion(region);
this.setCounty(county);
this.setCountry(country);
this.setCertification(certification);
this.setStatusCode(statusCode);
this.setModeSCode(modeSCode);
this.setFractOwner(fractOwner);
this.setLastActionDate(lastActionDate);
this.setCertIssueDate(certIssueDate);
this.setAirWorthDate(airWorthDate);
initialize();
}
protected void initialize()
{
}

private int hashCode = Integer.MIN_VALUE;
// primary key
private java.lang.String id;
// fields
private java.lang.String aircraftSerial;
private java.lang.String aircraftModelCode;
private java.lang.String aircraftEngineCode;
private java.lang.String yearBuilt;
private java.lang.String aircraftTypeId;
private java.lang.String aircraftEngineTypeId;
private java.lang.String registrantTypeId;
private java.lang.String name;
private java.lang.String address1;
private java.lang.String address2;
private java.lang.String city;
private java.lang.String state;
private java.lang.String zip;
private java.lang.String region;
private java.lang.String county;
private java.lang.String country;
private java.lang.String certification;
private java.lang.String statusCode;
private java.lang.String modeSCode;
private java.lang.String fractOwner;
private java.util.Date lastActionDate;
private java.util.Date certIssueDate;
private java.util.Date airWorthDate;
//Setters and getters omitted for brevity
public boolean equals(Object obj)
{
if (null == obj)
return false;
if (!(obj instanceof net.ensode.jasperbook.dbaccess.Aircraft))
return false;
else
{
net.ensode.jasperbook.dbaccess.Aircraft aircraft =
(net.ensode.jasperbook.dbaccess.Aircraft) obj;
if (null == this.getId() || null == aircraft.getId())
return false;
else
return (this.getId().equals(aircraft.getId()));
}
}
public int hashCode()
{
if (Integer.MIN_VALUE == this.hashCode)
{
if (null == this.getId())
return super.hashCode();
{
String hashStr = this.getClass().getName() + �"�:"
+ this.getId().hashCode();
this.hashCode = hashStr.hashCode();
}
}
return this.hashCode;
}
public int compareTo(Object obj)
{
if (obj.hashCode() > hashCode())
return 1;
else if (obj.hashCode()

< package="net.ensode.jasperbook.dbaccess">

-------------------------------------------------------
This XML file lets Hibernate know that the Aircraft class maps to the aircraft table, and also defines the mapping between the table's columns and the class fields.
Hibernate needs another XML configuration file, which allows it to know the database connection information and what XML files to use to map database tables to Java classes. This XML configuration file is called hibernate.cfg.xml.
-------------------------------------------------------

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"����-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"�http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>

<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/flightstats
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">password


<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.show_sql">false

<property name="hibernate.transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory
</property>
<mapping resource="Aircraft.hbm.xml" />
<mapping resource="AircraftEngines.hbm.xml"/>
<mapping resource="AircraftEngineTypes.hbm.xml"/>
<mapping resource="AircraftModels.hbm.xml"/>
<mapping resource="AircraftTypes.hbm.xml"/>
</session-factory>
</hibernate-configuration>

-------------------------------------------------------
Below the code fragment to illustrates how to fill a report using HQL as its
query language:
-------------------------------------------------------

package net.ensode.jasperbook;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.query.JRHibernateQueryExecuterFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
*HibernateQueryDemo.java
* @author amontejo
*/

public class HibernateQueryDemo
{
Session session;
SessionFactory sessionFactory;
public static void main(String[] args)
{

-------------------------------------------------------
Done, Pretty Straight forward right! ... enjoy.

Tuesday, February 12, 2008

10 years ago (Fun stuff)

An application was for employment

A program was a television show

Windows were something
you hated to clean,

A keyboard was a piano

A cursor used profanity

Memory was something you lost with age

A CD was a bank account

And if you had a 3 1/2 floppy
you hoped no one found out

Compress was something you did to garbage

If you unzipped in public you went to jail

Log on was adding wood to a fire

A hard drive was a long trip on the road

A mouse pad was where a mouse lived


And a backup happened to your toilet

Cut you did with scissors

Paste you did with glue

A web was a spider's home

And a virus was the flu!!!

WOW HOW TIMES HAVE CHANGED!

A man with a sharp wit ...(Fun stuff)

On this day in 1957, Felix Wankel's first working prototype DKM 54 of the Wankel engine was running at the NSU research and development department Versuchsabteilung TX in Germany. In 1913, New York City's Grand Central Terminal opened as the world's largest train station. In 1893, Thomas A. Edison finished construction of the first motion picture studio, the BPublish Postlack Maria in West Orange, New Jersey. And in 1884, edition one of the Oxford English Dictionary was published. Happy Birthday Pauly Shore and Lisa Marie Presley (1968), Brandon Lee (1965-1993), Bill Mumy (1954), Rick James (1948-2004), Jessica Savitch (1947), Terry Jones (1942), Sherman Hemsley (1938), Garrett Morris (1937), President Boris Yeltsin (1931-2007), S. J. Perelman (1904-1979), Langston Hughes (1902-1967) and Clark Gable (1901). RIP Buster Keaton (d. 1966).

"Ahhh. A man with a sharp wit. Someone ought to take it away from him before he cuts himself."
- Peter da Silva

Monday, February 11, 2008

Dilbert

Try This lots of fun, this can make you refresh your burn mind. huh! lots of work today...

Saturday, February 9, 2008

Your theory is crazy ... (Fun stuff)

On this day in 1996, the massive Internet collaboration "24 Hours in Cyberspace" took place. In 1978, the proceedings of the United States Senate were first broadcast on radio. In 1974, after 84 days in space, the crew of the first American space station Skylab returned to Earth. In 1971, the Nasdaq stock market index debuted. In 1922, President Warren G. Harding introduced the first radio in the White House. And in 1879, Sandford Fleming first proposed adoption of Universal Standard Time at a meeting of the Royal Canadian Institute. Happy Birthday Seth Green (1974), Alonzo Mourning (1970), Gary Coleman (1968), Vince Neil (1961), John Grisham (1955), Mary Steenburgen (1953), Nick Nolte (1941), Ted Koppel (1940), James Dean (1931-1955), Jack Lemmon (1925-2001), Audrey Meadows (1922-1996), Lana Turner (1921-1995), Jules Verne (1828-1905) and Daniel Bernoulli (1700-1782). RIP Anna Nicole Smith (d. 2007).

"Your theory is crazy, but it's not crazy enough to be true."
- Niels Bohr, to a young physicist

Friday, February 8, 2008

Yahoo Widgets

Now that Microsoft and Yahoo were going to merge. What will happen to us developer that uses some of yahoo widgets? I have been using yahoo widgets for quite some time and it really helps a lots, im using Jmaki framework an lightweight View framework. So by now that they are going to merge and Microsoft has its SilverLight, so I guess its the end of their cool widgets...

I hope so not. Please keep it evolving and OPen...

Thursday, February 7, 2008

Web Developement Standard ?


We had our monthly meeting yesterday Feb. 02, 2008. We've discuss about System Development Life Cycle(SDLC) since we are going to adapt and implement that methodology in our new project. So one of our developer come up with the proposal to our Business Process Engineer(BPE) that they were going to use UML in their requirement phase so that that well become our standard means of communication to them. But I guess only selected UML diagram that they are going to use because I believe that building an blueprint of the system must have a deep understanding about Object-Oriented Architecture and you cannot fully understand its concept and approach if your not gone through with an Object-Oriented Language. Anyway which UML Diagram that will fit to them?

After our discussion about those BPE's side we then proceed to my domain Java, Now our boss wanted me to come up with the Java web application standard, and she wanted to utilize all the oracle tools since were using Oracle 10G database. so I guess I must come up with....

IDE = JDeveloper
Model = ADF/TopLink
Controller = Struts
View = JSF/ADFUI

So am my right ?

But at the back of my mind I want to use Suns tools since when developing the frontend you dont have to deal with the oracle. So this is what I think.

IDE = Netbeans 6.* "not just IDE its Community"
Model = JPA/EJB 3.0
Controller = Spring 2.*
View = JSF 2.*/Jmaki 1.*

its really confusing and I must deliver this web standard this March 10, 2008. Can anyone suggest which ones good?

question is there such thing called as "Java Web Standard"? ...


Wednesday, February 6, 2008

A computer geek loved a girl!

He sent a letter, saying:



I LOVE YOU MORE THAN MY COMPUTER

Believe me it is true …

You installed the best in me.

Your picture is always in my background.

You clicked my heart gently.

You drive me crazy when I see you.

Your love reset my life and deleted all the sadness in me.

You restored my kindness after I thought it was corrupted.

I’m always connected to you with more than 56 heart beat per second.

You hacked my brain and registered your name in it.

You are the only one that could navigate my feelings and explore my
emotions at the same time.

I feel lost when I try to call you and you are not responding.

I always feel you close to me when I shut down my eyes, or when I open
my windows waiting for you to pass.

You are the only one that can log into my heart and never log out.

I dream of being your only server as long as I live.

You don’t have to search for me, cause we are always linked to each
others.

I see your name everywhere, my front page, my homepage and all my
software.

I scanned my life and found that I’m only infected by you.

You are the virus I’d never remove, and why should I do?
Believe me it is true…

I love you more than my CPU!!!!

DI annotations supported by Spring

org.springframework.beans.factory.annotation.Required
  • Identifies bean property setters that must be called (as opposed to optional setters). Supported since Spring 2.0.
org.springframework.beans.factory.annotation.Autowired
  • Spring 2.5's central injection annotation, applying to constructors, config methods and fields. Performs injection of components by type, with supporting for qualifier annotations that narrow the potential set of candidates in case of multiple matches.
javax.annotation.PostConstruct
  • JSR-250's common annotation for what Spring calls init methods.
javax.annotation.PreDestroy
  • JSR-250's common annotation for what Spring calls destroy methods.
javax.annotation.Resource
  • JSR-250's common annotation for injecting an external component by name. A resource in JSR-250 terminology really refers to a middleware component such as a DataSource.
javax.xml.ws.WebServiceRef
  • @Resource-like, for JAX-WS service lookups, injecting a JAX-WS port proxy.
javax.ejb.EJB
  • @Resource-like, for EJB Session Bean lookups, injecting an EJB component reference.
javax.persistence.PersistenceUnit
  • injecting a JPA EntityManagerFactory by persistence unit name(supported since Spring 2.0).
javax.persistence.PersistenceContext
  • injecting a JPA EntityManager by persistence unit name(supported since Spring 2.0).