Saturday, October 18, 2008

Tricks in Java Emailing

In my earlier post Java Class to Implement Email, I have shown you how you can effectively send mail using Java class, provided you have an SMTP server in your hand. This article will tell you how you can enhance it by setting different property of message and the server you are using. Kindly refer the code (in previous article) in which section you need to add those lines of code to get those affected.




1. How to set the return path of the email?

The return path of the email is by default the email id from which the email is sent. However, different from the sender, it can be easily done by setting the property of the server.

properties.put("mail.smtp.from",your-name@your-domain.com);




2. How to set the importance of the Email Message to high and Sensitivity of Email?


Importance and the sensitivity are the two important property of the message. You can easily set it using setHeader() method of the MimeMessage.

message.setHeader ( "X-Priority", "High" ) ;
message.setHeader ( "Sensitivity", "Company-Confidential" ) ;
message.setHeader ( "Importance", "High" ) ;



3.How to set the reply to option?


If you are familiar with Microsoft Outlook, you probably have used the “Having Replies Sent” mailing option. This enables a sender to identify the intended person to whom the replies should be sent. While experimenting with Java Mail, I found it very simple to do it using setReplyTo() method of the MimeMessage.

message.setReplyTo(new InternetAddress[] { new InternetAddress(your-name@yourdomain.com)});


The figure tells us the major classes and interfaces comprising the Java Mail API, which I missed earlier.




Tuesday, October 14, 2008

Java Specification Request

The Java Specification Request (JSR) is the actual description of proposed and final specifications for the Java platform. JSRs are reviewed by the JCP (Java Community Process) and the public before a final release of a specification is made.
At any one time there are numerous JSRs moving through the review and approval process.

The Java Community Process (JCP) an open organization of international Java developers and licensees who develop and revise Java technology specifications, reference implementations, and technology compatibility kits through a formal process.The JCP involves the use of Java Specification Request (JSR), which are formal documents that describe proposed specifications and technologies to be added to the Java platform. Formal public reviews of JSRs are conducted before the JSR becomes final and is voted on by the JCP Executive Committee. A final JSR provides a reference implementation (RI) which is a free implementation of the technology in source code form and a Technology Compatibility Kit (TCK) to verify the API specification.
Below are the lists of JCP Stages while proceeding with JSRs.

JSR Review

The Java Specification Request (JSR) is the first step in developing or revising a Java technology specification. A specification is initiated by community members and approved for development by the Executive Committee. The Java Specification Request (JSR) is the first step in developing or revising a Java technology specification.

New JSRs

New JSRs are those which have been recently submitted to the JCP.

Early Draft Review
Once a JSR is approved, a group of experts is formed to develop a first draft of the specification that anyone with an Internet connection can review.

Public Review
The JSR draft goes out for review by the public where anyone with an Internet connection can read and comment on the draft. The Expert Group uses the public feedback to further revise the document.

Proposed Final Draft
The version of the draft specification that will be used as the basis for the RI and TCK.

Final Release
The leader of the Expert Group then sees that the reference implementation and its associated Technology Compatibility Kit are completed before sending the specification to the Executive Committee for final approval.

Maintenance Review
The completed specification, reference implementation, and Technology Compatibility Kit are updated in response to ongoing requests for clarification, interpretation, enhancements, and revisions.

Withdrawn JSRs
JSRs that are withdrawn from the JCP by their Spec Leads before going to Final Release.

Rejected JSRs
JSRs that are voted down by the Executive Committee during the JSR Review, Draft Approval, or Final Approval Ballots.


Below is sample of how JSR is created for a particular version:


JSR 207: Process Definition for JavaTM
Definition of an annotated Java syntax and APIs for programming business processes in Java.

Section 1. Identification
Submitting Member: BEA Systems
Name of Contact Person:
E-Mail Address:
Telephone Number:
Fax Number:

Specification Lead:
E-Mail Address:
Telephone Number:
Fax Number:

Initial Expert Group Membership:
BEA SystemsSAP AGSun Microsystems
Supporting this JSR:
Cisco SystemsFujitsu LimitedHewlett-PackardIONANokiaSun Microsystems

Section 2: Request

2.1 Please describe the proposed Specification:

The specification will define metadata, interfaces, and a runtime model that enable business processes to be easily and rapidly implemented using the Java language and deployed in J2EETM containers. Process Definition for Java will provide a functional foundation upon which J2EE programmers can implement business processes. This foundation will support tasks commonly encountered when programming business processes, for example parallel execution and asynchronous messaging, while leveraging the programming constructs of Java. As such, the foundation can also be used to build Java implementations of business process initiatives such as BPEL4WS, WSCI, and W3C Choreography.
Process Definition for Java will build on Java Language Metadata technology (JSR-175) to provide an easy to use syntax for describing a business process at the source code level for the J2EE platform. Metadata will bind data and tasks within the process definition to variables, classes, and tasks in the source code. The metadata will be amenable to manipulation by tools.
The specification is intended to provide a set of programming interfaces for advanced business process programming and access to data manipulated directly by the business process.
The specification will be based on the J2EE 1.4 platform in order to avoid reinventing existing XML and web services standards required in business processes.

2.2 What is the target Java platform? (i.e., desktop, server, personal, embedded, card, etc.)

J2EE 1.4


2.3 What need of the Java community will be addressed by the proposed specification?

Although Java developers can author business processes using existing J2EE APIs, the process is slow, tedious and yields code that is hard to revise and maintain over time. A new standard is required to enable Java developers to rapidly and easily build and deploy complex business processes.
Java needs to maintain its lead as the most competitive platform for corporate application development. As business process-style programming becomes more commonplace, it is very important to the Java community that Java applications programmers have a common model for writing and running business processes under J2EE.
The goal of the specification is to provide a mechanism built on top of the existing J2EE APIs, including the core J2EE web services APIs and the Java Language Metadata technology (JSR-175), that supports the requirements of business process programming in an easy to use, simple syntax.
The JSR aims to address the common needs of business process programming: asynchronous and synchronous messaging using XML and web services, message routing with correlation, parallel execution of tasks, exception processing, and compensation.


2.4 Why isn't this need met by existing specifications?

J2EE provides APIs that can be used to develop business processes. But due to lack of specific support for asynchronous conversations, request/response sequences, and message correlation, workflows written using the current J2EE APIs are tedious and time consuming to develop, difficult to modify and maintain, and hard to deploy.


2.5 Please give a short description of the underlying technology or technologies:

Java Language Metadata (JSR 175) provides a standard model for annotating Java code, of which Process Definition for Java will be one application.
Javadoc is a standard syntax for structured comments introduced in the first version of the Java Language Specification.
J2EE provides existing technologies for messaging, state management, and communication; the Process Definition for Java specification will rely on these technologies.




2.6 Is there a proposed package name for the API Specification? (i.e., javapi.something, org.something, etc.)

javax.process.*




2.7 Does the proposed specification have any dependencies on specific operating systems, CPUs, or I/O devices that you know of?

No.




2.8 Are there any security issues that cannot be addressed by the current security model?

No.




2.9 Are there any internationalization or localization issues?

No.



2.10 Are there any existing specifications that might be rendered obsolete, deprecated, or in need of revision as a result of this work?

No.




2.11 Please describe the anticipated schedule for the development of this specification.

March 31, 2003: Expert Group FormedSeptember 30, 2003: Release Community DraftNovember 30, 2003: Release Public Review DraftMarch 31, 2004: Final Release
The schedule above is dependent upon the timely completion of JSR-175.




2.12 Please describe the anticipated working model for the Expert Group working on developing this specification.

Once this JSR is approved, invitations to participate in the Expert Group will be sent to known parties in the business process industry in addition to the standard notification sent to Java Community members. A baseline specification will be created by a process of analyzing and comparing existing proprietary APIs, and this will be developed iteratively by the Expert Group using email and telephone conferencing as the primary mechanisms.
Occasional face-to-face meetings will also be held, roughly quarterly after the initial face-to-face.



2.13 Please describe how the RI and TCK will de delivered, i.e. as part of a profile or platform edition, or stand-alone, or both. Include version information for the profile or platform in your answer.

BEA will deliver a standalone reference implementation (RI) and Technology Compatibility Kit (TCK) for Java Process Definition.



2.14 Please state the rationale if previous versions are available stand-alone and you are now proposing in 2.13 to only deliver RI and TCK as part of a profile or platform edition (See sections 1.1.5 and 1.1.6 of the JCP 2 document).

N/A



2.15 Please provide a description of the business terms for the Specification, RI and TCK that will apply when this JSR is final.

BEA will license the specification, RI and TCK to all interested parties on a royalty free basis.

Section 3: Contributions
3.1 Please list any existing documents, specifications, or implementations that describe the technology. Please include links to the documents if they are publicly available.

Existing J2EE specifications, e.g. JAX J2EE 1.4 http://jcp.org/en/jsr/detail?id=151

BEA WebLogic Integration(reference material will be provided to Expert Group, once it is formed) BPEL4WS http://dev2dev.bea.com/techtrack/BPEL4WS.jsp

Sun's Java Business Integration JSR http://jcp.org/en/jsr/detail?id=208




3.2 Explanation of how these items might be used as a starting point for the work.

The purpose of this specification is to leverage the first standard above, Java Language Metadata (JSR 175), to provide a standard that simplifies development of the commonly required functionality for implementing business processes. Process Definition for Java will utilize the metadata syntax of JSR 175. Since JSR 175 is scheduled for completion with J2SE 1.5, Process Definition for Java may use a pre-processor on the JSR-175 syntax for J2EE 1.4 implementations.




In investigating deployment models for Process Definition for Java, the expert group will determine the extent to which this specification should refer and relate to JSR-088.
The existing XML Schema standard is referenced because it will describe the structure of messages passed between participants in a business process.
Existing implementations such as item 5 above achieve several goals of this JSR and will provide a starting point for the specification.




Items 6-10 above reference cross-platform business process initiatives. This specification anticipates that these initiatives would be implemented on the Java platform using Process Definition for Java. Sun's Java Business Integration JSR will define SPIs that provide a business integration environment. An implementation of Process Definition for Java could use the JBI SPIs.


http://jcp.org/en/jsr/all -- This is the link where you can find all the JSRs.




Tuesday, September 23, 2008

Third Option

Every day, thousands of companies generate digital landfills of data as they cater to new customers and generate sales through the internet. All this requires vast data centres to adroitly — and safely — manage and store digital information. India, an IT hotspot, is destined to bite off a large chunk of this rapidly growing business. The business world says it all: ---------





The data centre market in India is about $120 million — a meagre 1 per cent of the global market. However, India is “the fastest growing market in the APAC region, with growth rates in the next five years expected to be 22.30 per cent”, says Naresh Singh, principal analyst for enterprise network infrastructure & services at Gartner. According to Anu David, senior research analyst for the ICT practice of Frost & Sullivan, South Asia & Middle East, Indian data centres will soon become globally competitive.





Notably, companies are rapidly moving from managing their content through in-house or ‘captive’ data centres, to ‘third party’ ones run by Indian companies. Today, India has twice as many captive data centres as it does third-party ones. Estimates by Datamonitor, a London-based market research company, suggest that of the 7 million sq. ft of data centre space to be added in the next four years, more than 90 per cent will be for third-party data centres.





In the past, companies were concerned about outsourcing their data handling to others because of security, accountability and intellectual property rights issues. For instance, firms such as ICICI Bank and Indian Oil Corporation (IOCL) have traditionally banked on in-house data centres. ICICI Bank has its main data centre in Mumbai and a disaster recovery site in Hyderabad, while IOCL has data centres in Jaipur and Gurgaon. “The biggest advantage is that we are not dependent on uncertainties faced by a vendor,” says S.S. Soni, executive director for information systems at IOCL. “We are also able to maintain secrecy of information.”





Today, Indian companies who had been using data centres located in the US are shifting their data to local, Indian ones who offer them six times the access speed. For instance, clients of Tata Communications have expressed an intention to move their data centres from the US and EMEA region (Europe, Middle East and Africa) to India. Moreover, Indian businesses are also adopting data centres to host their mission-critical applications such as enterprise resource planning and customer relationship management software. Indian data centre companies have also begun to rapidly embrace data centres as places where long-term, sustainable business solutions are offered for data storage and management. Companies in banking, financial services and insurance, telecom and manufacturing are also investing in data centres.





“A few years ago, if you had to set up a data centre, it had to be in Manhattan or California,” says K.P. Unnikrishnan, director of marketing (alliances and teleweb sales) of Sun Microsystems India. “But in the coming years, most data centres will be in the Asia-Pacific region with preference for India.” Says Sunil Gupta, head of business operations of data centre services at Reliance Infocomm, “The past three years have seen an explosive growth in the data centre business.” His outfit plans to pump in between Rs 1,000 crore and Rs 1,500 crore for seven more data centres in addition to the six the company has in Bangalore and Mumbai. Tata Communications has 34 data centres across three continents and plans to expand to 500,000 sq. ft across 20 new centres in India, UK, US and Singapore. “Close to 400,000 sq. ft is going to be in India,” says Vinay Nagpal, group manager for hosting and data centre services of global managed services at Tata Communications. “Given that demand is way above supply, most of the facilities we are building are already sold out. In fact, we are not able to build up fast enough.”





Ctrl S Data in Hyderabad is also expanding at a rapid clip. Having already set up the country’s first tier-IV data centre in Hyderabad, it intends to spend Rs 750 crore on data centres in six cities across the country. Says P. Sridhar Reddy, chairman and managing director of the company, “The Indian data centre market grew very slowly till 2004 due to the high cost of hosting, which can be attributed to the expensive bandwidth. But with the bandwidth costs going down drastically, data centres in India are set for a giant leap.”





The shift from captive to third party is making increasingly more sense to companies who are interested in focusing on their core competencies. Companies require huge investments in order to maintain support infrastructure, whereas third-party outsourcing assumes the burden for doing so. Nagging daily concerns over power supply, reliability, sufficient bandwidth and ample disk space are now somebody else’s problems, while stringent service level agreements will ensure that a high quality of service offered by outside-companies is a contractual obligation.
“We invested in data centres back in 1999 when we didn’t have any other option,” says Pravir Vohra, chief technology officer of the ICICI Group. “But in principle, we are not against outsourcing applications to third party vendors, especially those that are not mission-critical.” The physical structure and equipment within the data centres belongs to the ICICI group, but it has outsourced certain applications and management to third-party providers such as HP, Sun Microsystems and IBM.





So, what could trip up growth of data centres in India? Power is the biggest concern, considering the shoddy state of the power sector in India. Gartner estimates that power will become a critical decision factor for India in about two years. Considering traditional data centres typically waste more than 60 per cent of the energy that they use to cool equipment, this is bad news for Indian companies. This means that backup generators or indigenous ‘clean’ technologies will become a necessity. Says Unnikrishnan, “New greening technologies can lead to dramatic improvements in energy efficiency and cost as the data centre is fast becoming critical for today’s business.”





David says that India will “become a major player in terms of both revenue and capacity, second only to Japan”, despite the many sizeable potholes facing the data centre industry. For this to come true, however, the government needs to fix the basic infrastructure so that companies are not hindered in their goals of becoming global leaders.


Hope you all will find it useful.

Monday, August 18, 2008

Making Charts using JFreeChart JAVA

Hi All,
The previous articles have guided you how to deal with excel files using JAVA and how to read/write and create charts within excel file. Now I take you through how you can create chart panels in the JAVA frame (AWT/Swing).

The JFree.org provides a way to create chart panels in the JAVA platform. JFreeChart is a Java free chart library which supports pie charts (2D and 3D), bar charts (horizontal and vertical, regular and stacked), line charts, scatter plots, time series charts, high-low-open-close charts, candlestick plots, Gantt charts, combined plots, thermometers, dials and more. JFreeChart can be used in applications, applets, servlets and JSP. You can download the latest version of JFreeChart using the following link: http://www.jfree.org/jfreechart/download.html. JFreeChart requires the JCommon class library. The JCommon runtime jar file is included in the JFreeChart download. You can also download the class library of the JCommon class from here.

The API for JFreeChart is available in the following link:
http://www.jfree.org/jfreechart/api/javadoc/index.html

The below is source code for creating charts using JFreeChart.



import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;

public class ChartDrawDemo extends JFrame{
private static final long serialVersionUID = 1L;
private DefaultPieDataset datasetcls;
private JFreeChart jfccls;
PiePlot ppcls;
public ChartDrawDemo() {
datasetcls = new DefaultPieDataset();
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}

this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
setVisible(false);
}
});

this.setTitle("Demo Charts");
//this.setSize(700,450);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setValueClassification("A",new Double(10));
this.setValueClassification("B",new Double(20));

this.setCharClassification("Demo Chart");
this.Show();
}

public void setValueClassification(String title, Double numDouble) {
datasetcls.setValue(title, numDouble);
}
public void setCharClassification(String title) {
jfccls = ChartFactory.createPieChart(title, datasetcls, true, true, false);
ppcls = (PiePlot) jfccls.getPlot();
ppcls.setSectionOutlinesVisible(false);
ppcls.setCircular(true);
ppcls.setLabelFont(new Font("SansSerif", Font.PLAIN, 8));
ppcls.setNoDataMessage("No Data Available");
ppcls.setLabelGenerator(null);
ppcls.setLabelGap(0.02);
}

private JPanel createPanelClassification() {
return new ChartPanel(jfccls,400,400,400,400,400,400,true,true,true,true,true,true);
}

public void Show() {
setLayout(new GridBagLayout());
add(createPanelClassification());
pack();
setLocationRelativeTo(null);
setVisible(true);
}

public static void main(String[] args) {
ChartDrawDemo ce = new ChartDrawDemo();
}
}






Hope you all will find it useful.

Thursday, August 14, 2008

Making Charts in MS Excel using JAVA

Probably the best part of using MS Excel would be the chart as it only allows you to track the record which you’ve entered efficiently, but also it helps you to project the data in a presentable way.

Jxcell provides a way to create charts in MS Excel using JAVA which takes the data from the MS Excel file and create the excel chart in a specific location.

Below is the code for creating charts in Excel using Jxcell.


import com.jxcell.GRChart;
import com.jxcell.RangeRef;
import com.jxcell.View;
import com.jxcell.chart.ChartFormat;

import java.awt.*;

public class ChartFormatTest {

private void createChart(){
View m_view = new View();
RangeRef newRange = null;
try {
m_view.getLock();
m_view.setEntry(1,2,"Jan");
m_view.setEntry(1,3,"Feb");
m_view.setEntry(1,4,"Mar");
m_view.setEntry(1,5,"Apr");
m_view.setEntry(2,1,"Bananas");
m_view.setEntry(3,1,"Papaya");
m_view.setEntry(4,1,"Mango");
m_view.setEntry(5,1,"Lilikoi");
m_view.setEntry(6,1,"Comfrey");
m_view.setEntry(7,1,"Total");
m_view.setEntry(1,6,"time");
m_view.setNumber(2,6,1);
m_view.setNumber(3,6,2);
m_view.setNumber(4,6,3);
m_view.setNumber(5,6,4);
m_view.setNumber(6,6,5);
m_view.setNumber(7,6,6);

for(int col = 2; col <= 5; col++)
for(int row = 2; row <= 7; row++)
m_view.setFormula(row, col, "rand()");
m_view.setFormula(7, 2, "SUM(C3:C7)");
m_view.setSelection("C8:F8");
m_view.editCopyRight();
com.jxcell.GRChart chart = (GRChart)m_view.addObject(com.jxcell.GRObject.eChart, 0, 9.1, 7, 20.4);
chart.setChartType(GRChart.eChartLine);
// chart.setLinkRange("Sheet1!$C$2", false);
chart.addSeries();
chart.setSeriesName(0, "Sheet1!$C$2");
chart.setSeriesYValueFormula(0, "Sheet1!$C$3:$C$7");
chart.setCategoryFormula("Sheet1!$B$3:$B$7");
chart.addSeries();
chart.setSeriesName(1, "Sheet1!$D$2");
chart.setSeriesYValueFormula(1, "Sheet1!$D$3:$D$7");
chart.addSeries();
chart.setSeriesName(2, "Sheet1!$E$2");
chart.setSeriesYValueFormula(2, "Sheet1!$E$3:$E$7");
chart.addSeries();
chart.setSeriesName(3, "Sheet1!$F$2");
chart.setSeriesYValueFormula(3, "Sheet1!$F$3:$F$7");
chart.getChart().validateData();
chart.setAxisTitle(GRChart.eXAxis, 0, "Category");
chart.setAxisTitle(GRChart.eYAxis, 0, "Amount");
// set fill color
ChartFormat cf = chart.getChartFormat();
cf.setPattern((short)1);
cf.setPatternFG(Color.LIGHT_GRAY);
chart.setChartFormat(cf);
cf = chart.getPlotFormat();
cf.setPattern((short)1);
cf.setPatternFG(new Color(204, 255, 255));
chart.setPlotFormat(cf);
cf = chart.getAxisFormat(GRChart.eXAxis, 0);
cf.setFontSizeInPoints(8.5);
chart.setAxisFormat(GRChart.eXAxis, 0, cf);
cf = chart.getAxisFormat(GRChart.eYAxis, 0);
cf.setFontSizeInPoints(8.5);
chart.setAxisFormat(GRChart.eYAxis, 0, cf);
cf = chart.getSeriesFormat(0);
cf.setLineStyle(1);
cf.setLineWeight(3*20);
cf.setLineColor((new Color(0, 0, 128)).getRGB());
cf.setMarkerAuto(false);
cf.setMarkerStyle((short)0);
chart.setSeriesFormat(0, cf);
cf = chart.getSeriesFormat(1);
cf.setLineStyle(1);
cf.setLineWeight(3*20);
cf.setLineColor((new Color(255, 0, 255)).getRGB());
cf.setMarkerAuto(false);
cf.setMarkerStyle((short)0);
chart.setSeriesFormat(1, cf);
cf = chart.getSeriesFormat(2);
cf.setLineStyle(1);
cf.setLineWeight(3*20);
cf.setLineColor((new Color(255, 255, 0)).getRGB());
cf.setMarkerAuto(false);
cf.setMarkerStyle((short)0);
chart.setSeriesFormat(2, cf);
cf = chart.getSeriesFormat(3);
cf.setLineStyle(1);
cf.setLineWeight(3*20);
cf.setLineColor((new Color(0, 255, 255)).getRGB());
cf.setMarkerAuto(false);
cf.setMarkerStyle((short)0);
chart.setSeriesFormat(3, cf);
cf = chart.getMajorGridFormat(GRChart.eYAxis, 0);
cf.setLineStyle(2);
cf.setLineColor((new Color(255, 0, 0)).getRGB());
cf.setLineAuto(false);
chart.setMajorGridFormat(GRChart.eYAxis, 0, cf);
chart.setLegendPos(ChartFormat.eLegendPlacementTop);
cf = chart.getLegendFormat();
cf.setFontBold(true);
cf.setFontSizeInPoints(8);
chart.setLegendFormat(cf);
m_view.write("C:\\out.xls", View.eFileExcel);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
m_view.releaseLock();
}
}
public static void main(String args[]) {
ChartFormatTest cft = new ChartFormatTest(); cft.createChart();
}
}


Hope you all will find it useful.

Writing in MS Excel through Jxcell

In my previous articles of “Writing in MS Excel”, I gave you the overview of how you can write into it through POI package. There is another API available Jxcell, which will guide you the same thing, but in different way. You can download the latest version of Jxcell using following link:
http://www.jxcell.net/
The following code will guide you how to deal with MS Excel using Jxcell.

import com.jxcell.CellFormat;
import com.jxcell.TextWithFormat;
import com.jxcell.View;
import com.jxcell.designer.Designer;

import java.awt.*;

public class TextFormattingTest {

private void doTextFormatting(){
View m_view = new View();
try {
m_view.setText(0,0,"Hello, you are welcome!");
m_view.setColWidth(0, 36*256);
m_view.setRowHeight(0, 120*20);
CellFormat rangeStyle = m_view.getCellFormat();
rangeStyle.setOrientation((short)45);
m_view.setCellFormat(rangeStyle);
TextWithFormat[] tf = new TextWithFormat[4];
tf[0] = new TextWithFormat(m_view);
tf[1] = new TextWithFormat(m_view);
tf[2] = new TextWithFormat(m_view);
tf[3] = new TextWithFormat(m_view);
tf[0].setFontItalic(true);
tf[0].setStartPos(0);
tf[0].setFontColor(Color.BLUE.getRGB());
tf[1].setFontBold(true);
tf[1].setFontSize(16*20);
tf[1].setStartPos(7);
tf[2].setFontUnderline(true);
tf[2].setStartPos(11);
tf[2].setFontColor(Color.GREEN.getRGB());
tf[3].setFontSize(14*20);
tf[3].setStartPos(14);
m_view.setTextFormat(tf);
m_view.write("C:/TextFormatting.xls", View.eFileExcel);
Designer.newDesigner(m_view);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
TextFormattingTest tft = new TextFormattingTest();
tft.doTextFormatting();
}
}






The next section will guide you how to create charts using Jxcell.

Reading From MS Excel using JAVA

The previous article has shown us how to write or populate the excel files. In this article, I walk through the steps of code of how to read from MS Excel file all using JAVA.


The steps for reading from MS Excel files are:
1. Opening the file with fileinputstream and opening the workbook of that excel file with the help of POI package.
2. Opening the HSSF sheet and HSSFcell to that row and column.
3. Get the value of that cell.



import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class JavaExcelRead{
HSSFWorkbook workBook;
HSSFSheet sheet;
HSSFRow row;
HSSFCell cell;
FileInputStream fileInputStream;
HSSFWorkbook workbook;

JavaExcelRead(){
}

public void readFromExcelFile(){
double cellVal = 0.0;
// getting all the data from sheet
try{
FileInputStream fileInputStream = new FileInputStream("C:\\Demo.xls");
HSSFWorkbook workBook = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = workBook.getSheet("Demo");
HSSFRow row = sheet.getRow(0);
HSSFCell cell = null;
for(int i=0;i"lessthanequal"1;i++){
row = sheet.getRow(i);
for(int j=0;j"lessthanequal"1;j++){
cell = row.getCell((short)j);
System.out.println("Data is: "+cell.getStringCellValue());
}
}
fileInputStream.close();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}

public static void main(String args[]) {
JavaExcelRead jer = new JavaExcelRead();
jer.readFromExcelFile();
}
}

Hope you will find it useful.

Writing in MS Excel through JAVA using POI

Whether you have account information, data for employees, students, salary slips, calculations sheets for tax, Microsoft Excel is the best editor to compile such kind of things. The person whether he is from IT background or non-IT background, he feels comfortable working with MS Excel. The Jakarta POI (Poor Obfuscation Implementation) API is a fantastic way for Java programmers to access Microsoft document formats. The most mature API from Jakarta POI is the HSSF (Horrible Spreadsheet Format) API, which accesses Microsoft Excel documents.
POI terminology:

The key terms associated with Jakarta POI are as follows:
POIFS (Poor Obfuscation Implementation File System): Java APIs for reading and writing OLE (Object Linking and Embedding) 2 compound document formats
HSSF (Horrible Spreadsheet Format): Java API to read Microsoft Excel
HDF (Horrible Document Format): Java API to read and write Microsoft Word 97
HPSF (Horrible Property Set Format): Java API for reading property sets using (only) Java
Here is the code which can really guide you to use the POI package to write into the Excel file.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class JavaExcelPOI{
BufferedWriter out;
File file = null;
FileOutputStream fileoutputstream;
HSSFWorkbook workbook;
HSSFCell cell;
HSSFRow row;
HSSFSheet sheet;
HSSFFont font;
HSSFCellStyle cellStyle;
int i = 0;
int j = 1;
JavaExcelPOI() {
}
private void doWriteIntoExcelFile(){
try {
fileoutputstream = new FileOutputStream(new File("C:\\Demo"+".xls"));
workbook = new HSSFWorkbook();
sheet = workbook.createSheet("Demo");
String header[] = {"Header1","Header2"};
row = sheet.createRow((short)0);
cellStyle = workbook.createCellStyle();
font = workbook.createFont();
font.setColor(HSSFFont.COLOR_RED);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
cellStyle.setFont(font);
for(i = 0;i"lessthan"header.length;i++){
cell = row.createCell((short)i);
cell.setCellValue(header[i]);
cell.setCellStyle(cellStyle);
}
String celldetails = "";
row = sheet.createRow((short)j);
for(i =0;i"lessthan"header.length;i++){
cell = row.createCell((short)i);
celldetails = "Cell Value";
cell.setCellValue(celldetails+i);
}
j = j+1;
workbook.write(fileoutputstream);
} catch(Exception se){
se.printStackTrace();
}

}

public static void main(String args[]) {
JavaExcelPOI jePOI= new JavaExcelPOI();
jePOI.doWriteIntoExcelFile();
}
}
You can download the latest version of the POI package from the following link:
http://poi.apache.org/index.html.
You can also view the API documentation of the POI package:
http://poi.apache.org/apidocs/

The code is also using the functionality of the POI packages that cause the cell to define with definite style and font.

The next sections will guide you through more details about it.

Monday, August 11, 2008

Java Class to Implement Email

Hi, The java developers can use the following code to send email through code. The developers should have smtp (Simple Mail Transfer Protocol) server, where she/he can authenticate her/him self with the help of her/his credentials. The default port the smtp server normally uses is 25. The developers can check it whether it works or not. Here we are going to use the default mail package of sun. You can download the javax.mail package from the following link: http://java.sun.com/products/javamail/.
The API is also available through the following link:
http://java.sun.com/products/javamail/javadocs/index.html?javax/mail/package-summary.html

The following code is useful for different scenarios. For example there are four constructors where you can define the possible situations of having cc, attachment. The possible combinations are:
SUBJECT, FROM, TO, CC, ATTACHMENT, BODY.
SUBJECT, FROM, TO, ATTACHMENT, BODY.
SUBJECT, FROM, TO, CC, BODY.
SUBJECT, FROM, TO, BODY.

The code does not authenticate the email id. So you can easily mention any non existing email id also.
package mailpackage;


import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Flags;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;


public class ErrorMail {

String subject;
String from;
String[] to;
String[] cc;
String attachmentpath;
String body;

/**
* @param subject SUBJECT
* @param from FROM
* @param to TO
* @param cc CC
* @param attachmentpath ATTACHMENTPATH
* @param body BODY
*/

public ErrorMail(String subject,String from,String[] to,String[] cc,String attachmentpath,String body){
this.subject = subject;
this.from = from;
this.to = to;
this.cc = cc;
this.attachmentpath = attachmentpath;
this.body = body;
}

/ *
* @param subject SUBJECT
* @param from FROM
* @param to TO
* @param attachmentpath ATTACHMENTPATH
* @param body BODY
*/



public ErrorMail(String subject,String from,String[] to,String attachmentpath,String body){
this.subject = subject;
this.to = to;
this.attachmentpath = attachmentpath;
this.body = body;
this.from = from;
}


/**
* @param subject SUBJECT
* @param from FROM
* @param to TO
* @param cc CC
* @param body BODY
*/

public ErrorMail(String subject,String from,String[] to,String cc[],String body){
this.subject = subject;
this.to = to;
this.cc = cc;
this.body = body;
this.from = from;
}




/**
* @param subject SUBJECT
* @param from FROM
* @param to TO
* @param body BODY
*/


public ErrorMail(String subject,String from,String[] to,String body){
this.subject = subject;
this.to = to;
this.body = body;
this.from = from;
}




public void run() {
try{
Session session = getSession();
MimeMessage message = new MimeMessage(session);
session.setDebug(true);
InternetAddress[] addressTO = new InternetAddress[to.length];
for(int i=0;i < to.length;i++){
System.out.println("to is "+to[i]);
addressTO[i] = new InternetAddress(to[i]);
}
message.setRecipients(RecipientType.TO,addressTO);
System.out.println("cc "+cc);
if(cc!=null){
InternetAddress[] addressCC = new InternetAddress[cc.length];
for(int i=0;i < cc.length;i++){
System.out.println("cc is "+cc[i]);
addressCC[i] = new InternetAddress(cc[i]);
}
message.setRecipients(RecipientType.CC,addressCC);
}
System.out.println("from : "+from);
message.addFrom(new InternetAddress[] { new InternetAddress(from) });
message.setSubject(subject);
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(body);

Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
System.out.println("attachmentpath "+attachmentpath);
if(attachmentpath!=null){
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(attachmentpath);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
mp.addBodyPart(mbp2);
}

message.setContent(mp);

Transport.send(message);
}catch(MessagingException me){
me.printStackTrace();
}
}

private Session getSession() {
Authenticator authenticator = new Authenticator();

Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");

properties.setProperty("mail.smtp.host",”myhost.smtpserver”);
properties.setProperty("mail.smtp.port",”myhostport”);

return Session.getInstance(properties, authenticator);
}

private class Authenticator extends javax.mail.Authenticator {
private PasswordAuthentication authentication;

public Authenticator() {
String username =”validuserofthesmtpserver”;
String password =”password”;
authentication = new PasswordAuthentication(username, password);
}

protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}

public static void main(String[] args) throws MessagingException {
ErrorMail mwpa1 = new ErrorMail("SUBJECT","abc@domain.com",new String[] {"xyz @domain.com","efg @domain.com"},"BODY");
mwpa1.run();

ErrorMail mwpa2 = new ErrorMail("SUBJECT","abc@domain.com",new String[] {"pqr@domain.com","efg@domain.com","xyz@domain.com"},"C:\\attachment.txt ","Body");
mwpa2.run();
ErrorMail mwpa3 = new ErrorMail("SUBJECT","abc@domain.com",new String[] {"abc@domain.com","efg@domain.com","pqr@domain.com"},new String[] {"abc@domain.com","pqr@domain.com"}," Body");
mwpa3.run();
ErrorMail mwpa4 = new ErrorMail("SUBJECT","abc@domain.com",new String[] {"abc@domain.com","efg@domain.com","pqr@domain.com","xyz @dsomain.com"},"Body");
mwpa4.run();

}
}

Hope you all will find it useful.

JUnit Test Case

One of the tenets of agile development is continuous testing. Agile development states that code should be tested as often as possible, during development. Not only should the new module be tested, the whole application should be tested each time a new module or new feature is added to it, to ensure that the application is not broken. In case of manual testing, if testing frequency is increased, tester moral will become very low. As the number of tests to be executed increases, testers may miss executing a few tests, resulting in problems at later stages. To overcome some of these problems, usage of automated testing in the development cycle is crucial. Though automated testing will not identify all code bugs, it will overcome the problem of low morale due to frequent execution of the tests. Usually when automated tests are executed a test log is generated. This test log is analyzed for success or failure of the tests. Such test logs can be circulated to the customer, to assure the customer that the developed code does work as expected under test conditions. Such an exchange of information will build customer’s confidence in the development team and the development process.
JUnit

JUnit, as the name suggests is an API for developing unit test cases using Java. Unit tests are used to test the business logic of the application.

Each test case is derived from the TestCase class. Each unit test starts with the prefix “test”. The success or failure of each test is determined by “assert”ing the result. If the result matches expectation, the test is a success. Else the test is a failure.

Key Points:

JUnit is open source project and hence it is free !!
Fast development while increasing quality of code.
Easy to understand.
Integrated with IDE’s like Eclipse and Ant, makes it easy to use and inexpensive to write.
Provides immediate feedback about code changes.
Regression testing can be automated using Junit test suites.
Increases stability of software.
Without going into the much details, lets have a look how the junit test cases are prepared in real case:

Writing Sample TestCase:

Test Class:
public class Demo {
static public int add(int a, int b) {
return a + b;
}
}

JUNIT TestCase

import junit.framework.*;
public class DemoTest extends TestCase {
setUp() { }
tearDown() { }
public void testAdd() {
int no1 = 5;
int no2 = 5;
int total = 10;
int addResult = 0;
addResult = Math.add(no1, no2);
assertEquals(total,addResult);
}
}


JUnit TestSuite:

JUnit TestSuite includes several test cases. It allows multiple test cases to run in one go. It also automates regression testing process.

To write a test suite, follow these steps:
ü Write a Java class that defines a static suite() factory method that creates a TestSuite containing all the tests.
ü Optionally define a main() method that runs the TestSuite in batch mode.


public class JUnitPracSuite {
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new TestSuite("Test for Demo");
suite.addTestSuite(Demo.class);
//More TestCase classes to be added.
return suite;
}
}


Running a TestSuite will automatically run all of its subordinate TestCase instances and TestSuite instances. Running a TestCase will automatically invoke all of its public testXXX() methods. JUnit provides both a textual and a graphical user interface. The interface provided are No. of Test cases Run, Simple sompletion status, Error if any.

To run textual user interface----java junit.textui.TestRunner MathsClassTest
To run graphical user interface----java junit.swingui.TestRunner MathsClassTest
To run TestSuite----java junit.swingui.TestRunner JUnitPractSuite

TestCase object extends Assert which provides way to judge if a test has succeeded or failed:

Types of Assert statements:
assertEquals: Provides a series of overloads that allows to test if an actual value matches the expected one.
assertFalse: Use this if the function will always return false (fails if it receives true)
assertNotNull: If method returns null in the event of failure use this to check to see if it succeeds.
assertNotSame: If method is supposed to return an element from a list, use this to check if the element returned is the one from the actual list
assertNull: If method returns null in the event of failure, use this to check to see if it fails
fail: Will fail the test, use this in conjunction with conditionals
failNotEquals: Essentially the same as assertEquals but will fail the test if they aren’t equal instead of causing an error
failNotSame: Essentially the same as assertNotSame except instead of causing an error it will cause a failure

Suggestions for arranging tests in development environment:

Create test cases in the same package as the code under test.
To avoid combining application and testing code in your source directories, create a mirrored directory structure aligned with the package structure that contains the test code.
For each Java package in your application, define a TestSuite class that contains all the tests for validating the code in the package.
Define similar TestSuite classes that create higher-level and lower-level test suites in the other packages (and sub-packages) of the application.
Make sure your build process includes the compilation of all tests.


To Watch:

The software does well those things that the tests check.
Test a little, code a little, test a little, code a little...
Make sure all tests always run at 100%.
Write tests for the areas of code with the highest probability of breakage.
Write tests that have the highest possible return on your testing investment.
If you find yourself debugging using System.out.println(), write a test to automatically check the result instead.
Write unit tests before writing the code and only write new code when a test is failing.

Download JUnit latest version from http://www.junit.org/home
Hope you all will find it useful.

Friday, August 8, 2008

Java class to capture frame in JPG format

Here is the thing that enables java developers to capture the frame into a picture. To capture a frame, you need to use BufferedImage class of the java.awt.image package.

The BufferedImage subclass describes an Image with an accessible buffer of image data. A BufferedImage is comprised of a ColorModel and a Raster of image data. The number and types of bands in the SampleModel of the Raster must match the number and types required by the ColorModel to represent its color and alpha components. All BufferedImage objects have an upper left corner coordinate of (0, 0). Any Raster used to construct a BufferedImage must therefore have minX=0 and minY=0.

You can go to the following link to see the API of BufferedImage class.
http://java.sun.com/j2se/1.5.0/docs/api/java/awt/image/BufferedImage.html

A demo code for capturing the frame into picture is given below.

Source code:

import java.awt.AWTException;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;


public class Fig extends javax.swing.JFrame implements ActionListener{

private JButton jButton1 = null;
private JLabel jLabel1 = null;
public Fig(){
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
setLayout(new FlowLayout());
jLabel1 = new JLabel("Demo");
jButton1 = new JButton("Demo");

this.add(jLabel1);
this.add(jButton1);
jButton1.setActionCommand("Demo");
jButton1.addActionListener(this);
this.setTitle("Figure");
this.setSize(200,100);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setVisible(true);
}

public void actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("Demo")){
try {
this.createImage(this,"C:\\Demo.jpg");
} catch (AWTException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
// Methods to create Image correspoding to the frame.
public static BufferedImage createImage(Component component, String fileName)
throws AWTException, IOException {
Point p = new Point(0, 0);
SwingUtilities.convertPointToScreen(p, component);
Rectangle region = component.getBounds();
region.x = p.x;
region.y = p.y;
return Fig.createImage(region, fileName);
}

public static BufferedImage createImage(Rectangle region, String fileName)
throws AWTException, IOException {
BufferedImage image = new Robot().createScreenCapture( region );
Fig.writeImage(image, fileName);
return image;
}

public static void writeImage(BufferedImage image, String fileName)
throws IOException {
if (fileName == null) return;
int offset = fileName.lastIndexOf( "." );
String type = offset == -1 ? "jpg" : fileName.substring(offset + 1);

ImageIO.write(image, type, new File( fileName ));
}
// Methods to create Images
//End
public static void main(String args[]){
Fig fig = new Fig();
}
}


The highlighted portion of the code is responsible for capturing the frame into picture. There are two createImage methods in the code.

The first one converts a point from the component’s coordinate system to screen coordinates. Then it gets the bound of the component in the form of rectangle object. The bound specify the width, height and location relative to its parents.

It passes the location/region and size details to the second createImage method. The second one creates the image containing the pixels read from the screen corresponding to the region.

The writeImage method writes it to the specific file in jpg format with the help of write method of ImageIO class.




Practical Use:

It is quite useful in standalone applications.

The application is also useful, whenever you want some frame to be shown to a particular group of people. If you want some chart frame or any status frame which indicates some record over the past few months, you can easily capture it in jpg format and send it to concerned persons.



Hope you all will find it useful.

Saturday, June 28, 2008

AutoComplete in Java

While using Internet Explorer, we use autocomplete facility in browsers, google search for e.g. if you type 'g' in the browser, all the urls starting with 'g' will appear below.

If you are using java and you want the same thing in a textfield, for e.g. you want that whenever you write anything in the textfield, it should show every value those are starting with the letter you type, meaning, you want autocomplete in textfield, here is the trick.

In java, there are APIs available to do that effectively.

Suppose jTextField1 is the textfield in which you want to have that autocomplete facility. Here is the code to do it.

Demo Code

AutoComplete au = new AutoComplete(jTextField1);

au.add("One");

au.add("Two");

au.add("Three");

au.add("Four");


au.add("Five");

au.add("Six");

au.add("Seven");

au.add("Eight");

au.add("Nine");

au.add("Ten");

You can find the API in below mentioned links:

http://femur.biostr.washington.edu/~mindseer/doc/edu/washington/biostr/sig/brainj3d/shwing/swing/AutoComplete.html



It needs a specific jar file. You can find it in below link:

http://sig.biostr.washington.edu/projects/MindSeer/download.html

Practical Use

Suppose, you are using database. And you need the details based on a particular field or column which may be your primary key. You can add these primary keys to the autocomplete and use it.





Total Pageviews