RSS

Category Archives: Java

How to access Session Bean from JSP in GlassFish

Using Session Bean in JSP differs from the usage in servlets. We can inject session bean in servlets or in another session bean. But in JSP we can not use EJB in the same way. Most common approach would be a JNDI lookup to  find the required bean.

First add a reference in deployment descriptor to the session bean.

<ejb-local-ref>
<ejb-ref-name>AccountTypeFacadeRef</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>com.my.ejb.AccountTypeFacade</local>
<ejb-link>BankApp-ejb.jar#AccountTypeFacade</ejb-link>
</ejb-local-ref>

is optional.

In JSP use JNDI lookup to find the resource.

<%
String prefix = "java:comp/env/";
String ejbRefName = "AccountTypeFacadeRef";
String jndiUrl = prefix + ejbRefName;

javax.naming.Context ctx = new javax.naming.InitialContext();
AccountTypeFacade atf = ( AccountTypeFacade ) ctx.lookup( jndiUrl );
List<AccountType> accountTypeList = atf.findAll();
%>

 

 
Leave a comment

Posted by on November 9, 2013 in J2EE

 

Tags: ,

Swing File Chooser Demo

Swing File Chooser

Swing File Chooser

package main;

import java.awt.BorderLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class SwingFileChooser extends JPanel implements ActionListener{
private static final String newLine = "\n";
private JButton openButton,saveButton;
private JTextArea log;
private JFileChooser fc;

public SwingFileChooser(){
super(new BorderLayout());
initComponents();

}

private void initComponents(){
log = new JTextArea();
log.setMargin(new Insets(5, 5, 5, 5));
log.setEditable(false);
JScrollPane jsp = new JScrollPane(log);
fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
openButton = new JButton("Open File");
openButton.addActionListener(this);
saveButton = new JButton("Save File");
saveButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);
buttonPanel.add(saveButton);
add(buttonPanel,BorderLayout.NORTH);
add(jsp,BorderLayout.CENTER);
}

@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == openButton){
int returnVal = fc.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
log.append("Opening " + file.getName() + newLine);
}else{
log.append("cancelled file opening" + newLine);
}
log.setCaretPosition(log.getDocument().getLength());

}else if(e.getSource() == saveButton){
int returnVal = fc.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
log.append("Saving " + file.getName() + newLine);
}else{
log.append("cancelled file saving" + newLine);
}
log.setCaretPosition(log.getDocument().getLength());
}
}

private static void createGUI(){
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SwingFileChooser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JComponent newContentPane = new SwingFileChooser();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
createGUI();
}
});

}
}

 
1 Comment

Posted by on October 30, 2013 in Java

 

Tags:

Create Charts with jFreeChart

 jFreeChart Demo

jFreeChart Demo

This tutorial is all about creating graphs. There are several tools for generating graphs without any hassle. Programming a graph from scratch might little be  tricky as it also deals with some graphics. Using a tool or library reduces the development time a lot. So we gonna use an OpenSource chart tool named jFreeChart for Java development.

Creating a graph with jFreeChart is just a matter of entering the required graph data and a little piece of code. Therefore, as the CodeZone4 norm I just go ahead with a 3D bar graph implementation using jFreeChart.

You can find source code for other types of graph on the internet.

First download required JARs from jFreeChart and add them in your project’s classpath.

import org.jfree.chart.*;
import org.jfree.data.category.*;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.*;
import org.jfree.data.*;
import org.jfree.chart.renderer.category.*;
import org.jfree.chart.plot.*;
import java.awt.*;

public class Main {

public static void main(String[] args) {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.setValue(3780, "A", "2008");
dataset.setValue(5000, "B", "2008");
dataset.setValue(6500, "A", "2009");
dataset.setValue(6000, "B", "2009");
dataset.setValue(9000, "A", "2010");
dataset.setValue(10000, "B", "2010");
JFreeChart chart = ChartFactory.createBarChart3D("Annual Income Analysis", "Year", "Income",
dataset, PlotOrientation.VERTICAL, true, true, false);
chart.setBackgroundPaint(Color.yellow);
chart.getTitle().setPaint(Color.blue);
CategoryPlot p = chart.getCategoryPlot();
p.setRangeGridlinePaint(Color.red);
ChartFrame frame1 = new ChartFrame("Income Data", chart);
frame1.setVisible(true);
frame1.setSize(300, 300);
}
}

 
Leave a comment

Posted by on September 29, 2013 in Java

 

Tags:

REST clients for Java, MySQL and JSON Restful Web Services

This is the second part of the tutorial which demonstrates Restful web service using Java, MySQL and JSON. In this tutorial we are going to create several REST clients for our web service. You can download each REST client project. Each REST client is going to parse the JSON response and display output.

Java REST client
Download
We use Java SE application as our client. To parse JSON, gson library is added to project /lib folder Also it is included in project build path as an external JAR.

Course.java – data bound model class

public class Course
{
private int id;
private String name;
private String duration;
private double fee;

public Course()
{

}

public Course(int id, String name, String duration, double fee)
{
super();
this.id = id;
this.name = name;
this.duration = duration;
this.fee = fee;
}

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public String getDuration()
{
return duration;
}

public void setDuration(String duration)
{
this.duration = duration;
}

public double getFee()
{
return fee;
}

public void setFee(double fee)
{
this.fee = fee;
}

@Override
public String toString()
{
return "Course [id=" + id + ", name=" + name + ", duration=" + duration
+ ", fee=" + fee + "]";
}

}

Main.java

package com;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class Main
{

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
String json = readUrl("http://localhost:8080/RestProject/Rest/courseService/courses");
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
JsonArray courseArray = jsonParser.parse(json).getAsJsonArray();
List<Course> coursesList = new ArrayList<Course>();
for (JsonElement course : courseArray)
{
Course courseObj = gson.fromJson(course, Course.class);
coursesList.add(courseObj);
}

for (Course courseObj : coursesList)
{
System.out.println("ID : " + courseObj.getId());
System.out.println("Course Name : " + courseObj.getName());
System.out.println("Duration : " + courseObj.getDuration());
System.out.println("Course fee : " + courseObj.getFee());
}

}

private static String readUrl(String urlString) throws Exception
{
BufferedReader reader = null;
try
{
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);

return buffer.toString();
} finally
{
if (reader != null)
reader.close();
}

}
}

PHP REST client
CURL or file_get_contents() can be used to get JSON  from the web service URL.

$json = file_get_contents("http://localhost:8080/RestProject/Rest/courseService/courses");
$json_o = json_decode($json);

$msg .= "";
foreach($json_o as $item)
{
$msg .= "Course ID : ". $item->id. "<br>";
$msg .= "Course Name : ". $item->name. "<br>";
$msg .= "Duration  : ". $item->duration. "<br>";
$msg .= "Course fee : ". $item->fee. "<br><br>";
}
echo $msg;

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, "http://localhost:8080/RestProject/Rest/courseService/courses");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$json = curl_exec($ch);
$json_o = json_decode($json);

$msg .= "";
foreach($json_o as $item)
{
$msg .= "Course ID : ". $item->id. "<br>";
$msg .= "Course Name : ". $item->name. "<br>";
$msg .= "Duration  : ". $item->duration. "<br>";
$msg .= "Course fee : ". $item->fee. "<br><br>";
}
echo $msg;

Android REST client

Download


 
3 Comments

Posted by on November 28, 2012 in C#.Net, Java, PHP

 

Tags: ,