STORED PROCEDURE PROGRAMMING IN JAVA USING MYSQL

Some of the benefits of stored procedure programming are faster execution of sql statements and also preventing sql injection. So whenever the application logic of your application is data centric, it is better to use stored procedure.

To access mysql stored procedure in your java application, you first create the stored procedure in mysql. Below is a sample created stored procedure in mysql.

   1: DELIMITER $$

   2: DROP PROCEDURE IF EXISTS `test`.`cdinsert`$$

   3: CREATE DEFINER=`root`@`localhost` PROCEDURE `cdinsert`(cID varchar(15), tdate varchar(15),cdNo int)

   4: BEGIN

   5:  if exists(select ID from cddetail where cdID=cID) then

   6:   update cddetail set transdate=tdate,cdNum=cdNo where cdID=cID;

   7:  else

   8:   insert into cddetail(cdID,transdate,cdNum) values (cID,tdate,cNo);

   9:  end if;

  10: END$$

  11: DELIMITER ;

You then create your java application  to access the stored procedure as shown below

   1: import java.sql.*;

   2: public class storproc {

   3:  

   4:     Connection conn = null;

   5:     Statement stm = null;

   6:     static final String url = "jdbc:mysql://localhost/test";

   7:     static final String user = "root";

   8:     static final String pswd = "password";

   9:  

  10:     //connecting to the mysql database

  11:     public Connection getConnection() {

  12:         try {

  13:             conn = DriverManager.getConnection(url, user, pswd);

  14:         } catch (Exception ex) {

  15:             System.out.println("error occured " + ex.toString());

  16:         }

  17:         return conn;

  18:     }

  19:  

  20:     public void insertNew(String line) {

  21:         try {

  22:             String input[] = line.split(",");

  23:             //calling the created storedprocedure 

  24:             //and passing the required parameters

  25:             CallableStatement cs = this.getConnection().

  26:             prepareCall("{call insertnew(?,?,?)}");

  27:             

  28:             cs.setString(1, input[0]);

  29:             cs.setString(2, input[1]);

  30:             cs.setInt(3, Integer.parseInt(input[2]));

  31:             cs.execute();

  32:         } catch (Exception e) {

  33:             System.out.println("errr  " + e.toString());

  34:         } finally {

  35:             try {

  36:                 conn.close();

  37:             } catch (SQLException ex) {

  38:                 System.out.println("error occured " + ex.toString());

  39:             }

  40:         }

  41:  

  42:     }

  43: }

Advertisements

CREATING SIMPLE HELP FILES IN JAVA

In this post, we are to discuss how to create help for your swing application using swing components. The idea is to create text file for each help file, the content can be formatted with html, then on click of a button you display a particular file in a panel. To make the panel (help page) stay on top of other opened windows of your application we can choose to display it as a dialog.check https://gilbertadjin.wordpress.com/2009/10/21/form-showdialog-in-java/ how to show a panel as dialog.

To start with we create a class that will load a help file from a source(which you have save it in the settings of your application) by passing the file name without the extension….below is the class

   1: import java.io.File;

   2: import java.util.logging.Level;

   3: import java.util.logging.Logger;

   4: import javax.swing.JOptionPane;

   5: import org.apache.commons.io.FileUtils;//download org.apache.commons.io.FileUtils

   6: public class helpFile {

   7:     private String helpContent = null;

   8:     public helpFile(String filename) {

   9:        try {

  10:             //loading the help file from  a location stored in your settings

  11:             File file=new File(Settings.loadProperties().getProperty("xp.helpsource") +"/"+ filename +".txt");

  12:                         if (file.exists()) {

  13:                 helpContent = FileUtils.readFileToString(file);

  14:             } else {  

  15:                 JOptionPane.showMessageDialog(null, "File Does not Exist \n" + file.getPath() + "\n" + file.toString());

  16:             }

  17:         } catch (Exception ex) {

  18:             Logger.getLogger(helpFile.class.getName()).log(Level.SEVERE, null, ex);

  19:         }

  20:     }

  21:     @Override

  22:     public String toString() {

  23:         return helpContent;

  24:     }

  25: }

Then we create a panel and name it “helpdetailPanel”. We then add a JEditorPane to the Panel and then add the constructor below to the panel class

   1: public helpdetailpanel(String text) {

   2:         initComponents();

   3:         this.editor.setContentType("text/html");

   4:         this.editor.setText(text);    

   5:     }

Then in the application,on click of a button we add the code below to show a help based on the name (help file name) we pass to the “helpfile” class. Below shows the code to show the panel with the help content

   1: //helpfile is the class to load the help file from its source

   2:    helpdetailpanel hd = new helpdetailpanel(new helpFile("customers").toString());

   3:    hd.setSize(700, 700);

   4:    popupsjdialog d = new popupsjdialog(null, hd, true);

   5:    d.setVisible(true);

In the code above, “customers” is the name of a help file with a content below.

   1: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

   2: <html>

   3: <head>

   4: " "

   5: </head>

   6: <body>

   7: <span style="" bold=""

   8:  text-decoration="" underline="">&nbsp;<span

   9:  style="font-weight: bold; text-decoration: underline;">CUSTOMER

  10: INFORMATION</span> </span>

  11: <br>

  12: <br>

  13: 1. To &nbsp;add a new Customer click on the add new button. Enter <br>

  14: &nbsp; &nbsp; &nbsp;the required information and click on

  15: Save<br>

  16: <br>

  17: 2. To Edit a Customer select it from the table view, make the changes

  18: required and click on Save<br>

  19: <br>

  20: 3. To delete a Customer, select it from the table view, and click on

  21: the delete button<br>

  22: </body>

  23: </html>

The picture below shows how the help content that is displayed at runtime on click of a help button in the Customers Panel.

image

Cheers  !!!!!!!!!!!

STRINGS IN JAVA

“Wow !!!! Now Thus Intereeessssting” That was how i exclaimed when i saw these interesting features of the STRING class in java. All this while when i wanted to convert a character array to a string , i had to go through a loop. For example

String password = “” ;
char[] pass = this.txtPassword.getPassword();
for (int i = 0; i < pass.length; i++) {
password = password + pass[i];
}

But this char[] pass can easily be converted to string by just a line of code:

char[] pass = this.txtPassword.getPassword();
String password=new String(pass);

Also another interesting feature of the string class is that you can easily get the string value out of a byte array and vice versa with so much ease. check this.

byte[] array=”sdfdfd”.getBytes();
String string=new String(array);

These are not all, there are more interesting features, exploree!!!!

Fellows, enjoy the weekend

FORM.SHOWDIALOG() IN JAVA

Have you wondered how to show a panel(form) as a dialog in java applications as done in .NET applications by using the form.showDialog() method?  For example, when a user selects “Add New” from a Customer combobox, the customer panel shows as a dialog for a new entry before the user can continue. If you have been searching for this, here is your stop.

We will be making use of one JDialog, and your FORMS(JPanels in this sense).

To implement this add a JDialog to your application. Declare a variable contentPane and add the constructor like the one specified below.

private Container contentPane = null;

public popupsjdialog(java.awt.Frame parent, JPanel panel, boolean modal) {
//super(parent, modal);
contentPane = this.getContentPane();
initComponents();
this.setSize(panel.getSize().width + 30, panel.getSize().width + 50);
panel.setLocation(10, 30);
contentPane.add(panel);
repaint();
this.setLocationRelativeTo(null);

}

Your are now done. Now to show any JPanel as a dialog add the following code to your event.

helpdetailpanel hd = new helpdetailpanel(helpContent);
hd.setSize(700, 700);
popupsjdialog d = new popupsjdialog(null, hd, true);
d.setVisible(true);

Helpdetailpanel is a Jpanel (form) you want to show as a dialog and the popupsjdialog is an instance of the Jdialog we created its constructot above.

Cheers !!!!!!!!!!!!!!!!!

CREATING A JASPER REPORT WITHOUT A DATASOURCE

If you want to generate jasper reports in your JAVA applications without using a data source, then here is your stop. For example printing receipts directly from user inputs, where all you need are parameters. Also this piece talks about how to insert images from the file system ( hard drives pen dirves) into jasper reports at runtime.It assumed you know how to generate reports with jasper reports. This help was created using Netbeans 6.7 and iReport 3.5.2

Relax and Enjoy!!!!!!!!!!!!!!!

In this our example, we are creating a report that requires a name, hometown and a picture from the user at runtime to be displayed on our report. Design your report by creating the parameters; name as string, hometown as string and picture as object. With the name and hometown parameters, you can drag them onto the report interface, but for the image, drag  the image item from the tool bar and bind it to the picture parameter. Below is a picture of the report

the report designed in iReport

After this, go to Netbeans and do some simple coding. Below are the methods needed to run your application. Make sure to add the Jasper jar files to your application

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

// a method to generate the report, by assigning the prameter to their value, and calling te generate report method

Map<String, Object> param = new HashMap<String, Object>();

param.put("name", this.tfName.getText());

param.put("hometown", this.tfHometown.getText());

param.put("photo", photo);

generateReports("report1", ls, param);

}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// a mehod t browse for an image to be inserted into te report

//photo is a variable of type image

fc.setFileFilter(new FileNameExtensionFilter("Images", "jpg", "gif", "bmp"));

if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {

fc.setCurrentDirectory(fc.getCurrentDirectory());

ImageIcon icon = new ImageIcon(fc.getSelectedFile().getAbsolutePath());

icon = new ImageIcon(icon.getImage().getScaledInstance(350, 350, Image.SCALE_DEFAULT));

photo = icon.getImage();

}

}

private void generateReports(String name, Collection data, Map param) {

//a method to generate th report

try {

String source = "C:/sabonay/jasperreports/" + name + ".jrxml";

if (new File(source).exists() == false) {

xputils.showMessage("Please go report file does not exst");

return;

}

JasperReport jasperReport = JasperCompileManager.compileReport(source);

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, param, new    JREmptyDataSource());

JasperViewer.viewReport(jasperPrint, false);

} catch (Exception e) {

e.printStackTrace();

System.out.println("reports Error  " + e.toString());

}

}

Below are pictures after running theappliation

using entering parameter values
Sample report generated

Creating MDI Applications in Java Using Netbeans

This is a simple process for Java users who want to create Multiple Document Interface Applications in Java. The application makes use of JPanels , a JFrame and a JDesktopPane.

To start with, all your child forms should be created using panels (JPanels) as the container. A frame is then created as the parent form. A desktop pane is then added to the frame to be container for the panels on the JFrame.

Below is how the application Works

1.   Create your child forms on a panel

2.   Create a frame and add a desktoppane to it as shown below

main

The black color is showing the JDesktopPane. You can set the “Anchor” and “Auto Resizing” properties of the DesktopPane so that it fits the desired size of your choice.

Add the method below to your Frame Class

public void addFrame(JPanel panel, String title) {

try {

JInternalFrame[] children = jDesktopPane1.getAllFrames();

//creating a new internal frame from the Panel passes as parameter

internalframe j = new internalframe(panel, title);

//checking to see if the child form already exist

for (JInternalFrame f : children) {

if (f.getTitle().equals(j.getTitle())) {

f.setSelected(true);

return;

}

}

//adding a new child

jDesktopPane1.add(j);

j.setVisible(true);

j.setSelected(true);

} catch (PropertyVetoException ex) {

Logger.getLogger(mainxpframe.class.getName()).log(Level.SEVERE, null, ex);

}

}

To show the child forms add the code below to the button click event

customersdetailpanel sd=new customersdetailpanel();

sd.setSize(750, 600);

addFrame(sd, "Customers Information");

the “customersdetailpanel” is one of the child forms.

Below is an interface showing showing the MDI Application

sub

Hope this will be helpful

SAVING IMAGES IN A DATABASE USING EJBS

It is sometimes troublesome to save and retrieve images in  a database using java. Below are methods that are useful in saving and retrieving images from a database

To save an image in a database the datatype of the column should be “blob”. One thing to note is that in the EJBs the blob datatype is change to an array of bytes (“byte[]”)

A function to change an image file into its bytes

public Function byte[] setImagebytes(File imageFile) {

byte[] imagebytes = null;

try {

FileInputStream fis = new FileInputStream(imageFile);

imagebytes = new byte[(int) imageFile.length()];

fis.read(imagebytes);

} catch (FileNotFoundException ex) {

ex.printStackTrace();

} catch (IOException ex) {

ex.printStackTrace();

}

Return imagebytes;

}

A method to browse for an image file from its location and show it in a label

private void btBrowseActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

// a method to browse for a picture and pass the image file to the setImagebytes method

fc.setFileFilter(new FileNameExtensionFilter("Images", "jpg", "gif", "bmp"));

if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {

fc.setCurrentDirectory(fc.getCurrentDirectory());

ImageIcon icon = new ImageIcon(fc.getSelectedFile().getAbsolutePath());

icon = new ImageIcon(icon.getImage().getScaledInstance(150, 150, Image.SCALE_DEFAULT));

this.lbPicture.setIcon(icon);

//passing the image file to the setImagebytes to create the image bytes

this.setImagebytes(fc.getSelectedFile());

//icon.getImage()

repaint();

}

}

A method to convert the bytes array (byte[]) into a pictures to display in a label

Private void getRealImage(byte[] imagebytes){

if (imagebytes != null) {

ImageIcon icon = new ImageIcon(imagebytes);

icon = new ImageIcon(icon.getImage().getScaledInstance(150, 150, Image.SCALE_DEFAULT));

this.lbPicture.setIcon(icon);

} else {

ImageIcon icon = new ImageIcon();

//showing the image in a label

this.lbPicture.setIcon(icon);

}

}