Java, Struts 1 & 2, Spring, Hibernate, iBatis, Jasper Reports, RDBMS, JDBC, JSP, Servlet, HTML, JS, AJAX, JQuery
Tuesday, June 29, 2010
Glassfish v2( JDBC Connection Pool, JNDI)
Place database driver in glassfish lib dir. (e.g. lib/mysql-jdbc-5.1.11.jar) and restart server.
Step 2:
Login to Admin Console: http:\\localhost:4848\
Goto Resource > JDBC > Connection Pool
Provide Name, Select Database vendor and Select Resource Type
Step 3:
Enter DataSource class name (Database driver)
Change other settings as you want
Save and Ping
:) "Ping Succeed"
Connection Pool is ready
Thursday, May 27, 2010
Converter - Convert MS Word/Excel to PDF
Converts MS Excel Spreadsheet to PDF, image etc
Supported formats, MS Word, Excel, Powerpoint, Txt, Csv, Flash, ODT, RTF, PDF.. etc.
Here is the code:
long startTime1 = System.currentTimeMillis();
// connect to an OpenOffice.org instance running on port 8100
OpenOfficeConnection connection = new SocketOpenOfficeConnection(SocketOpenOfficeConnection.DEFAULT_PORT);
connection.connect();
DocumentConverter converter1 = new OpenOfficeDocumentConverter(connection);
File inputFile = new File("C:\\Miral\\temp\\myDocument.doc"));
File outputFile = new File("C:\\Miral\\temp\\myPortDocument.pdf");
totalFileSize+=(inputFile.length()/1024*100000)/100000;
converter1.convert(inputFile, outputFile);
System.out.println("Total File Size(kb): "+totalFileSize);
long endTime1 = System.currentTimeMillis();
System.out.println("Conversion Time: "+(endTime1-startTime1));
// close the connection
connection.disconnect();
Tuesday, April 27, 2010
iBatis (MyBatis)
You can execute stored procedure via SqlMap xml file.
See the folloing example:
<!-- To call stored procedure. -->
<procedure id="getItemInfo" resultClass="Items" parameterMap="getItemInfoCall">
{ call getEmp( #invoiceNo# ) }
</procedure>
<parameterMap id="getItemInfoCall" class="map">
<parameter property="invoiceNo" jdbcType="INT" javaType="java.lang.Integer" mode="IN"/>
</parameterMap>
<!-- Now call this method -->
Reader rd = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient smclient = SqlMapClientBuilder.buildSqlMapClient(rd);
int invoiceNo = 1;
System.out.println("Getting item information from db");
Items itm = (Items)smclient .queryForObject ("Items.getItemInfo", invoiceNo);
- Steps to generate doa, mapping files and pojos using iBator
- iBatis and Oracle selectByExamplePaginatedList
Monday, August 3, 2009
Struts 2 Validation Annotation
Follow these steps to implement the example ... There's more
1. Create a dynamic web project in Eclipse.
2. Copy the following jar files into the WEB-INF/lib directory, all these files are available with sturts download.
* struts2-core-2.0.11.1.jar
* xwork-2.0.4.jar
* freemarker-2.3.8.jar
* commons-logging-1.1.1.jar
* ognl-2.6.11.jar
3. Update your web deployment desciptor to include the sturts filter dispatcher.
WEB-INF/web.xml
4. Create the input JSP : transactions.jsp
Note: The method="noValidation" indicates to struts that on submission, the noValidation() method will be invoked on the AddTransactionAction class.
5. Create the output JSP : done.jsp
6. Create the Action class :AddTransactionAction.java
package actions;
import org.apache.struts2.interceptor.validation.SkipValidation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;
import com.opensymphony.xwork2.validator.annotations.Validation;
@Validation
public class AddTransactionAction extends ActionSupport {
private String symbol;
private String type;
private String date;
private String numberOfShares;
private String price;
private String comission;
private String notes;
public String execute() throws Exception {
System.out.println("In Execute");
return SUCCESS;
}
@SkipValidation
public String noValidation() throws Exception {
System.out.println("In Novalidation");
return SUCCESS;
}
public String getSymbol() {
return symbol;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = "Symbol Required")
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getType() {
return type;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = "Type Required")
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = "Date Required")
@RegexFieldValidator(type=ValidatorType.FIELD, message="",key="date.error.message", expression = "[0-9][0-9]/[0-9][0-9]/[1-9][0-9][0-9][0-9]")
public void setDate(String date) {
this.date = date;
}
public String getNumberOfShares() {
return numberOfShares;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = " Number of Shares Required")
public void setNumberOfShares(String numberOfShares) {
this.numberOfShares = numberOfShares;
}
public String getPrice() {
return price;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = "Price Required")
public void setPrice(String price) {
this.price = price;
}
public String getComission() {
return comission;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = "Comission Required")
public void setComission(String comission) {
this.comission = comission;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
Note:
* The annotation @Validation is used to indicate that the current action might need validation. The validations on a method level can be skipped using the @SkipValidation annotation on the method.
* The method noValidations() uses the @SkipValidation annotation, you can see this when you click on "Submit without validation" in the JSP
* The @RequiredStringValidator annotation is used to indicate a Required Strint similar to the following xml rule
* On the date field, I used a @RegexFieldValidator annotation, so that the date field will be mandated to have a given format.
* Parameterized messages: You will notice that the message attribute of the @RegexFieldValidator is set to an empty string, while the key is set to a value. This is due to the fact that the message attribute is mandatory, and the key attribute is used to denote the message key from the properties files. The parameters can be retrieved in the properties files using the ${date} notation where the "date" variable is expected to available in the value stack.
7. Create a definition for the action in struts.xml
Note: The result with name "input" is because the validator returns the result to input when validation fails.
8. Create the properties file for messages
date.error.message=Date ${date} is not properly formatted.
package.properties
Note: In the properties file, ${date} is used to retrieve the "date" value from the value stack, this is the way Struts 2 supports parameterization.
9. Create the struts.properties file to set the theme to simple theme, so that you have more control how the UI components are laid out.
struts.ui.theme=simple
struts.properties
Thursday, July 23, 2009
Glassfish: Add Cluster Support
Command: asadmin start-domain domain1
You will see message:
Domain does not support application server clusters and other standalone instances.
Goto: http://localhost:4848/
Go to the Application Server tree node, on the right hand side, you will see the 'Add Cluster Support' button. Click on this button
The next page will show you the implication about this action. Click OK
You will see that the profile has been successfully upgraded and server restart is required
Now restart your server.
You will see message:
Domain supports application server clusters and other standalone instances.
Friday, July 10, 2009
JQuery
jQuery is easy to learn.
Fast, Easy to use, Easy-to-use AJAX (I love the $.ajaxSetup() function)
Nice Event handlers
CSS selectors
features:
* HTML element selections
* HTML element manipulation
* CSS manipulation
* HTML event functions
* JavaScript Effects and animations
* HTML DOM traversal and modification
* AJAX
* Utilities
Tuesday, May 5, 2009
Integrate Birt Report Engine To Your Application
1. Download Birt Runtime
2. Copy all the jars in the birt-runtime/ReportEngine/lib directory from the Report Engine download into your ApplicationRoot/WEB-INF/lib directory.
3. Create a directory named platform in your WEB-INF folder.
4. Copy the birt-runtime/Report Engine/plugins and birt-runtime/ReportEngine/configuration directories to the platform directory you just created.
5. Copy iText.jar to the platform/plugins/com.lowagie.itext/lib directory. If the directory does not exist, create it.
6. Copy servlet.jar into WEB-INF/lib
* BirtConfig.properties - Configuration properties for the Engine.Place it to /WEB-INF/classes folder
* BirtEngine.java - Class used to initialize the Report Engine.
* WebReport.java - The servlet that handles report generation on a GET command.
* Copy Database driver class to
BirtConfig.properties
logDirectory=c:/temp
logLevel=FINEST
BirtEngine.java
import java.io.InputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import javax.servlet.*;
import org.eclipse.birt.core.framework.PlatformServletContext;
import org.eclipse.birt.core.framework.IPlatformContext;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
public class BirtEngine {
private static IReportEngine birtEngine = null;
private static Properties configProps = new Properties();
private final static String configFile = "BirtConfig.properties";
public static synchronized void initBirtConfig() {
loadEngineProps();
}
public static synchronized IReportEngine getBirtEngine(ServletContext sc) {
if (birtEngine == null)
{
EngineConfig config = new EngineConfig();
if( configProps != null){
String logLevel = configProps.getProperty("logLevel");
Level level = Level.OFF;
if ("SEVERE".equalsIgnoreCase(logLevel))
{
level = Level.SEVERE;
} else if ("WARNING".equalsIgnoreCase(logLevel))
{
level = Level.WARNING;
} else if ("INFO".equalsIgnoreCase(logLevel))
{
level = Level.INFO;
} else if ("CONFIG".equalsIgnoreCase(logLevel))
{
level = Level.CONFIG;
} else if ("FINE".equalsIgnoreCase(logLevel))
{
level = Level.FINE;
} else if ("FINER".equalsIgnoreCase(logLevel))
{
level = Level.FINER;
} else if ("FINEST".equalsIgnoreCase(logLevel))
{
level = Level.FINEST;
} else if ("OFF".equalsIgnoreCase(logLevel))
{
level = Level.OFF;
}
config.setLogConfig(configProps.getProperty("logDirectory"), level);
}
config.setEngineHome("");
IPlatformContext context = new PlatformServletContext( sc );
config.setPlatformContext( context );
try
{
Platform.startup( config );
}
catch ( BirtException e )
{
e.printStackTrace( );
}
IReportEngineFactory factory = (IReportEngineFactory) Platform
.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
birtEngine = factory.createReportEngine( config );
}
return birtEngine;
}
public static synchronized void destroyBirtEngine() {
if (birtEngine == null) {
return;
}
birtEngine.shutdown();
Platform.shutdown();
birtEngine = null;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
private static void loadEngineProps() {
try {
//Config File must be in classpath
ClassLoader cl = Thread.currentThread ().getContextClassLoader();
InputStream in = null;
in = cl.getResourceAsStream (configFile);
configProps.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
WebReport.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLRenderContext;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.IReportEngine;
public class WebReport extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Constructor of the object.
*/
private IReportEngine birtReportEngine = null;
protected static Logger logger = Logger.getLogger( "org.eclipse.birt" );
public WebReport() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy();
BirtEngine.destroyBirtEngine();
}
/**
* The doGet method of the servlet.
*
*/
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//get report name and launch the engine
resp.setContentType("text/html");
//resp.setContentType( "application/pdf" );
//resp.setHeader ("Content-Disposition","inline; filename=test.pdf");
String reportName = req.getParameter("ReportName");
ServletContext sc = req.getSession().getServletContext();
this.birtReportEngine = BirtEngine.getBirtEngine(sc);
//setup image directory
HTMLRenderContext renderContext = new HTMLRenderContext();
renderContext.setBaseImageURL(req.getContextPath()+"/images");
renderContext.setImageDirectory(sc.getRealPath("/images"));
logger.log( Level.FINE, "image directory " + sc.getRealPath("/images"));
System.out.println("stdout image directory " + sc.getRealPath("/images"));
HashMap contextMap = new HashMap();
contextMap.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext );
IReportRunnable design;
try
{
//Open report design
design = birtReportEngine.openReportDesign( sc.getRealPath("/Reports")+"/"+reportName );
//create task to run and render report
IRunAndRenderTask task = birtReportEngine.createRunAndRenderTask( design );
task.setAppContext( contextMap );
//set output options
HTMLRenderOption options = new HTMLRenderOption();
options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);
//options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);
options.setOutputStream(resp.getOutputStream());
task.setRenderOption(options);
//run report
task.run();
task.close();
}catch (Exception e){
e.printStackTrace();
throw new ServletException( e );
}
}
/**
* The doPost method of the servlet.
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println(" ");
out.println(" ");
out.println(" Post does nothing");
out.println(" ");
out.println("");
out.flush();
out.close();
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
BirtEngine.initBirtConfig();
}
}