Enlightensoft's Blog

Helping in your each step

  • Categories

  • Authors

Export to .pdf using Core JAVA

Posted by Pankil Patel on June 22, 2012

Required JAR:

itextpdf-5.3.0.jar

itext-xtra-5.3.0.jar

 

 

File: PDFCreator.java

package co.cc.enlightensoft.pdf;

import java.io.FileOutputStream;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class PDFCreator {
public static void main(String[] args) {
try {

// creation of the document with a certain size and certain margins
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
try {
// creation of the different writers
// HtmlWriter.getInstance(document, System.out);
PdfWriter.getInstance(document,
new FileOutputStream(“text.pdf”));
// we add some meta information to the document
document.addAuthor(“Bruno Lowagie”);
document.addSubject(“This is the result of a Test.”);
// we open the document for writing
document.open();

// ##################### Paragraph : Start #####################
document.add(new Paragraph(“Hello world”));
// ##################### Paragraph : End #####################

// ##################### Chunk : Start #####################
Chunk chunk = new Chunk(“Hello world”, FontFactory.getFont(
FontFactory.COURIER, 20, Font.ITALIC, new BaseColor(
255, 0, 0)));
document.add(chunk);
// ##################### Chunk : End #####################

// ##################### Anchor : Start #####################
Anchor anchor = new Anchor(“\nGoogle\n”);
anchor.setName(“Google”);
anchor.setReference(“http://www.google.com”);

document.add(anchor);
// ##################### Anchor : End #####################

// ##################### Image : Start #####################
Image image = Image.getInstance(“Photo.JPG”);
image.scaleAbsolute(100, 100);
document.add(image);
// ##################### Image : End #####################

// ##################### Table : Start #####################
PdfPTable table = createTable1();
table.setSpacingBefore(5);
table.setSpacingAfter(5);
document.add(table);

// ##################### Table : End #####################

System.out.println(“File Created…”);
} catch (DocumentException de) {
System.err.println(de.getMessage());
}
document.close();
} catch (Throwable t) {
t.printStackTrace();
}
}

/** The resulting PDF file. */
public static final String RESULT = “text.pdf”;

/**
* Creates a table; widths are set with setWidths().
*
* @return a PdfPTable
* @throws DocumentException
*/
public static PdfPTable createTable1() throws DocumentException {
PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(288 / 5.23f);
table.setWidths(new int[] { 2, 1, 1 });
PdfPCell cell;
cell = new PdfPCell(new Phrase(“Table 1”));
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phrase(“Cell with rowspan 2”));
cell.setRowspan(2);
table.addCell(cell);
table.addCell(“row 1; cell 1”);
table.addCell(“row 1; cell 2”);
table.addCell(“row 2; cell 1”);
table.addCell(“row 2; cell 2”);
return table;
}

/**
* Creates a table; widths are set with setWidths().
*
* @return a PdfPTable
* @throws DocumentException
*/
public static PdfPTable createTable2() throws DocumentException {
PdfPTable table = new PdfPTable(3);
table.setTotalWidth(288);
table.setLockedWidth(true);
table.setWidths(new float[] { 2, 1, 1 });
PdfPCell cell;
cell = new PdfPCell(new Phrase(“Table 2”));
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phrase(“Cell with rowspan 2”));
cell.setRowspan(2);
table.addCell(cell);
table.addCell(“row 1; cell 1”);
table.addCell(“row 1; cell 2”);
table.addCell(“row 2; cell 1”);
table.addCell(“row 2; cell 2”);
return table;
}

/**
* Creates a table; widths are set in the constructor.
*
* @return a PdfPTable
* @throws DocumentException
*/
public static PdfPTable createTable3() throws DocumentException {
PdfPTable table = new PdfPTable(new float[] { 2, 1, 1 });
table.setWidthPercentage(55.067f);
PdfPCell cell;
cell = new PdfPCell(new Phrase(“Table 3”));
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phrase(“Cell with rowspan 2”));
cell.setRowspan(2);
table.addCell(cell);
table.addCell(“row 1; cell 1”);
table.addCell(“row 1; cell 2”);
table.addCell(“row 2; cell 1”);
table.addCell(“row 2; cell 2”);
return table;
}

/**
* Creates a table; widths are set with special setWidthPercentage() method.
*
* @return a PdfPTable
* @throws DocumentException
*/
public static PdfPTable createTable4() throws DocumentException {
PdfPTable table = new PdfPTable(3);
Rectangle rect = new Rectangle(523, 770);
table.setWidthPercentage(new float[] { 144, 72, 72 }, rect);
PdfPCell cell;
cell = new PdfPCell(new Phrase(“Table 4”));
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phrase(“Cell with rowspan 2”));
cell.setRowspan(2);
table.addCell(cell);
table.addCell(“row 1; cell 1”);
table.addCell(“row 1; cell 2”);
table.addCell(“row 2; cell 1”);
table.addCell(“row 2; cell 2”);
return table;
}

/**
* Creates a table; widths are set with setTotalWidth().
*
* @return a PdfPTable
* @throws DocumentException
*/
public static PdfPTable createTable5() throws DocumentException {
PdfPTable table = new PdfPTable(3);
table.setTotalWidth(new float[] { 144, 72, 72 });
table.setLockedWidth(true);
PdfPCell cell;
cell = new PdfPCell(new Phrase(“Table 5”));
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phrase(“Cell with rowspan 2”));
cell.setRowspan(2);
table.addCell(cell);
table.addCell(“row 1; cell 1”);
table.addCell(“row 1; cell 2”);
table.addCell(“row 2; cell 1”);
table.addCell(“row 2; cell 2”);
return table;
}

}

Posted in Core Java | Tagged: , , , , , , , | 1 Comment »

Pure JDBC Connection for Oracle Database in Core JAVA using Service name & SID

Posted by Pankil Patel on June 22, 2012

Required JAR: classes12.jar

Pure JDBC Connection for Oracle Database in Core JAVA using :  Service name :

Connection con = null;
Class.forName(“oracle.jdbc.driver.OracleDriver”);
con = DriverManager.getConnection(
“jdbc:oracle:thin:@Hostname:Port/Service name”,
“username”, “password”);

Statement s = con.createStatement();

Pure JDBC Connection for Oracle Database in Core JAVA using :  SID :

Connection con = null;
Class.forName(“oracle.jdbc.driver.OracleDriver”);
con = DriverManager.getConnection(
“jdbc:oracle:thin:@Hostname:Port:SID”,
“username”, “password”);

Statement s = con.createStatement();

Posted in Core Java, Oracle | Tagged: , , , , , | Leave a Comment »

Export to .xls using Core JAVA

Posted by Pankil Patel on June 22, 2012

Required JAR: jxl-2.6.12.jar

File: XlsCreator.java

package co.cc.enlightensoft.xls;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class XlsCreator {
private static WritableSheet s;
private static WritableCellFormat cf;
private static WritableCellFormat cfd;
private static File file;
public static int NUMBER_OF_TIME_QUERY_EXICUTION = 2;

public static WritableWorkbook createFile() throws IOException,
WriteException {
String filename = “QueryResponceTime.xls”;
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale(“en”, “EN”));
XlsCreator.file = new File(filename);
WritableWorkbook workbook = Workbook
.createWorkbook(XlsCreator.file, ws);
XlsCreator.s = workbook.createSheet(“Sheet1”, 0);
// XlsCreator.summary = workbook.createSheet(“Output”, 1);

/* Format the Font */
WritableFont wf = new WritableFont(WritableFont.ARIAL, 12,
WritableFont.BOLD);
WritableFont wfd = new WritableFont(WritableFont.ARIAL, 10,
WritableFont.NO_BOLD);

XlsCreator.cf = new WritableCellFormat(wf);
XlsCreator.cfd = new WritableCellFormat(wfd);

XlsCreator.cf.setWrap(true);
XlsCreator.cfd.setWrap(false);
XlsCreator.cf.setBackground(Colour.AQUA);
XlsCreator.cf.setBorder(Border.ALL, BorderLineStyle.THICK);
XlsCreator.cfd.setBorder(Border.ALL, BorderLineStyle.MEDIUM);

XlsCreator.s.setColumnView(0, 30);
XlsCreator.s.setColumnView(1, 30);
XlsCreator.s.setColumnView(2, 30);

createHeader();
return workbook;
}

public static void closeFile(WritableWorkbook workbook) throws IOException,
WriteException {
workbook.write();
workbook.close();
}

public static void createHeader() throws RowsExceededException,
WriteException {
/* Creates Label and writes date to one cell of sheet */
Label oid = new Label(0, 0, “OID”, XlsCreator.cf);
Label totalTime = new Label(1, 0, “Total Time (Milli Second)”,
XlsCreator.cf);
Label queryTime = new Label(2, 0, “Query Time (Milli Second)”,
XlsCreator.cf);
XlsCreator.s.addCell(oid);
XlsCreator.s.addCell(totalTime);
XlsCreator.s.addCell(queryTime);
}

public static void addRow(long oid, long totalTime, long queryTime,
int index) throws RowsExceededException, WriteException {
Number c1_data = new Number(0, index, oid, cfd);
Number c2_data = new Number(1, index, totalTime, cfd);
Number c3_data = new Number(2, index, queryTime, cfd);
XlsCreator.s.addCell(c1_data);
XlsCreator.s.addCell(c2_data);
XlsCreator.s.addCell(c3_data);
}

public static void main(String[] args) throws WriteException, IOException {
WritableWorkbook wb = XlsCreator.createFile();
addRow(123, 456, 001, 1);
addRow(52468, 123, 010, 2);
addSummary(3);
XlsCreator.closeFile(wb);
System.out.println(“.xls file is created… \n Location: ”
+ XlsCreator.file.getAbsoluteFile());
}

public static void addSummary(int index) throws RowsExceededException,
WriteException {
String avg = “AVERAGE”;
String avgTotalTime = “AVERAGE(B2:B”
+ (NUMBER_OF_TIME_QUERY_EXICUTION + 1) + “)”;
String avgQueryTime = “AVERAGE(C2:C”
+ (NUMBER_OF_TIME_QUERY_EXICUTION + 1) + “)”;

// Create label for average
Label formulaLabel = new Label(0, index, avg, cf);
XlsCreator.s.addCell(formulaLabel);

// Create a formula for average
Formula formulaAvgTotalTime = new Formula(1, index, avgTotalTime, cf);
XlsCreator.s.addCell(formulaAvgTotalTime);

// Create a formula for average
Formula formulaAvgQueryTime = new Formula(2, index, avgQueryTime, cf);
XlsCreator.s.addCell(formulaAvgQueryTime);

String min = “MIN”;
String minTotalTime = “MIN(B2:B” + (NUMBER_OF_TIME_QUERY_EXICUTION + 1)
+ “)”;
String minQueryTime = “MIN(C2:C” + (NUMBER_OF_TIME_QUERY_EXICUTION + 1)
+ “)”;

// Create label for average
Label minLabel = new Label(0, index + 1, min, cf);
XlsCreator.s.addCell(minLabel);

// Create a formula for average
Formula formulaMinTotalTime = new Formula(1, index + 1, minTotalTime,
cf);
XlsCreator.s.addCell(formulaMinTotalTime);

// Create a formula for average
Formula formulaMinQueryTime = new Formula(2, index + 1, minQueryTime,
cf);
XlsCreator.s.addCell(formulaMinQueryTime);

String max = “MAX”;
String maxTotalTime = “MAX(B2:B” + (NUMBER_OF_TIME_QUERY_EXICUTION + 1)
+ “)”;
String maxQueryTime = “MAX(C2:C” + (NUMBER_OF_TIME_QUERY_EXICUTION + 1)
+ “)”;

// Create label for average
Label maxLabel = new Label(0, index + 2, max, cf);
XlsCreator.s.addCell(maxLabel);

// Create a formula for average
Formula formulaMaxTotalTime = new Formula(1, index + 2, maxTotalTime,
cf);
XlsCreator.s.addCell(formulaMaxTotalTime);

// Create a formula for average
Formula formulaMaxQueryTime = new Formula(2, index + 2, maxQueryTime,
cf);
XlsCreator.s.addCell(formulaMaxQueryTime);

}
}

Posted in Core Java | Tagged: , , , , , , , , , | Leave a Comment »

How to Use Hibernate Annotation & .hbm.xml files at single time on a Same project?

Posted by Pankil Patel on June 11, 2012

Use sessionFactory as org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean in its configuration file instead of org.springframework.orm.hibernate3.LocalSessionFactoryBean

Sample configuration is as below:

<bean id=”sessionFactory”
class=”org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean”>
<property name=”annotatedClasses“>
<list>
<value>co.cc.enlightensoft.model.businessobject.Product</value>
</list>
</property>
<property name=”mappingResources“>
<list>
<value>co/cc/enlightensoft/model/businessobject/Category.hbm.xml</value>
<value>co/cc/enlightensoft/model/businessobject/User.hbm.xml</value>
</list>
</property>

<property name=”hibernateProperties”>
<props>
<prop key=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</prop>
<prop key=”hibernate.show_sql”>true</prop>
<prop key=”hibernate.cglib.use_reflection_optimizer”>true</prop>
<prop key=”hibernate.cache.provider_class”>org.hibernate.cache.HashtableCacheProvider</prop>
</props>
</property>

<property name=”dataSource”>
<ref bean=”dataSource” />
</property>

</bean>

Posted in Hibernate, Spring | Tagged: , , , , , , , , , | Leave a Comment »

How to use/connect database from mysql command prompt

Posted by Pankil Patel on May 17, 2012

Note: Please make sure that you have checked the command prompt feature during mysql installation.

Step 1: type “cmd” into your run window of your OS

Step 2: type below command into your cmd terminal

>mysql -h localhost -u root -p

it will ask for passwod like below

Enter password: ****

you need to give password and after that press enter key.

Step 3: now it will give mysql> terminal initial, When you see mysql> it means from a MySQL prompt after successful logging into MySQL using “localhost” as a host and “root” as a user.

Step 4: Now perform any database commands into your database by creating / selecting your database.

Ex:

mysql> create database mytest;
Query OK, 1 row affected (0.00 sec)

mysql> use mytest;
Database changed
mysql>

Posted in Database, MySQL | Leave a Comment »

How to Configure MAVEN

Posted by Pankil Patel on May 16, 2012

Step 1: Download Maven zip from http://maven.apache.org/download.html (Ex: apache-maven-3.0.4-bin.zip)

Step 2: Unzip it into your drive (Ex: C:\java\apache-maven-3.0.4)

Step 3: Add system environment variables M2_HOME & M2 (Ex: M2_HOME=C:\java\apache-maven-3.0.4 & M2=C:\java\apache-maven-3.0.4\bin)

Step 4: Add M2 into your PATH system environment variable  (Ex: PATH=%M2%;%JAVA_HOME%\bin;%ANT_HOME%\bin)

Step 5: Set your MAVEN repository location :

  • Open file C:\java\apache-maven-3.0.4\conf\settings.xml for edit
  • uncomment <localRepository> tag in settings.xml file and set the repository location like below:<localRepository>C:\java\apache-maven-3.0.4\.m2\repository</localRepository>

Step 6: Verify your set up by typing command: mvn –version into your command prompt window.

It should give detail of your mvn like below:

C:\Documents and Settings\pankil.patel>mvn –version
Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)
Java version: 1.6.0_23
Java home: C:\java\jdk1.6.0_23\jre
Default locale: en_US, platform encoding: Cp1252
OS name: “windows xp” version: “5.1” arch: “x86” Family: “windows”
C:\Documents and Settings\pankil.patel>

You are now ready to use your MAVEN for your project…….

 

Posted in Maven | Leave a Comment »

Eclipse PlugIn For SVN, FIND BUG, MAVEN, PMD & CheckStyle

Posted by Pankil Patel on May 15, 2012

Eclipse & Oracle Workshop for WebLogic Plug-In For SVN, FIND BUG, MAVEN, PMD & CheckStyle

CheckStyle: http://eclipse-cs.sf.net/update/

SVN: http://subclipse.tigris.org/update_1.0.x or http://subclipse.tigris.org/update_1.6.x or http://subclipse.tigris.org/update_1.8.x or http://subclipse.tigris.org/update_1.10.x

FIND BUG: http://findbugs.cs.umd.edu/eclipse

PMD: http://pmd.sourceforge.net/eclipse

MAVEN: http://m2eclipse.sonatype.org/sites/archives/m2e-0.10.0-20100209-0800/

Mule ESB: http://studio.mulesoft.org/3.4/plugin

Ref. URL: http://blogs.mulesoft.org/installing-mule-studio-3-4-via-update-site-or-eclipse-marketplace/comment-page-1/

Posted in IDE, Other | Leave a Comment »

Nth Highest record in Oracle

Posted by Pankil Patel on April 18, 2012

First solution:

nth highest record from Bv_Category table based on Indvl_Rank_Id

select * From
(
Select C.*, Dense_Rank() Over (Order By C.Indvl_Rank_Id Desc) Ranking From Bv_Category C
)
where Ranking = (nth index)

Example: Record with Second Highest Indvl_Rank_Id

select * From
(
Select C.*, Dense_Rank() Over (Order By C.Indvl_Rank_Id Desc) Ranking From Bv_Category C
)
where Ranking = 2

For more detail visit:

http://www.oratable.com/nth-highest-salary-in-oracle/

Second solution:

Example: Second Highest Indvl_Rank_Id

Select Min(Indvl_Rank_Id) From (
select * from (
Select Unique Indvl_Rank_Id From
Bv_Category
ORDER BY Indvl_Rank_Id DESC) where ROWNUM <= 2)

Posted in Database, Oracle | Tagged: , , , | Leave a Comment »

Hibernate Automatic Dirty Check for Detached Objects

Posted by Pankil Patel on April 18, 2012

To deal with Dirty check for detached objects in Hibernate there are two ways:

1)

.hbm.xml file:

Using <version> tag in .hbm.xml file like below:

In .hbm.xml file: <version name=”version” access=”field” column=”version” type=”long”/>

In respected VO / POJO: private Long version; /* used for optimistic locking */

Annotation:

import javax.persistence.Version;

@Version
private Long version;

 

2) 

.hbm.xml file:

Using <timestamp> tag in .hbm.xml file like below:

In .hbm.xml file: <timestamp name="lastModifyDataTime" column="LAST_MODIFIY_DATE_TIME" access="field">

In respected VO / POJO: private Long lastModifyDataTime;

Annotation:

import javax.persistence.Version;

@Version
private Long lastModifyDataTime;

 

Note: Hibernate ignores the version when getting object and updating fields and then version are in the same session.

 

For more detail on Optimistic lock in Hibernate visit:

http://turgaykivrak.wordpress.com/2009/05/16/72/

AND

http://www.intertech.com/Blog/Post/Versioning-Optimistic-Locking-in-Hibernate.aspx

 

3) Use select-before-update=”true” mapping into your .hbm.xml file:

<class name=”com…….AbcVO”
table=”ABC” select-before-update=”true”>

4) By extending some of its public API:

http://www.brimllc.com/2010/08/hibernate-automatic-dirty-check-for-detached-objects/

Posted in Hibernate | Tagged: , , , | Leave a Comment »

SubSelect in hbm.xml file

Posted by Pankil Patel on April 16, 2012

<class name=”com……StaffView”
entity-name=”staff_phase2_with_Inactive”>
<subselect>
<![CDATA[
SELECT DISTINCT u.ID,
u.FIRST_NM,
u.LAST_NM,
u.MIDDLE_INIT_NM,
u.FULL_NM,
u.PRFRRD_FRST_NM,
u.STTS_CD,
u.STTS_NM
FROM USER_TABLE u
]]>
</subselect>
<id name=”staffSID” type=”string” length=”28″>
<column name=”ID” />
<generator />
</id>
<property …

.

.

.

.

.

.
</property>
</class>

Posted in Hibernate | Leave a Comment »