Showing your own custom dialog box in java

While developing our ERP application we need to show a list of
all accounts in a dialog box and upon selecting an account the
base form will be updated. For this we need our custom dialog
box to show the list of accounts. Here i give an example of how
can you show your own custom dialog box and get desired value on
closing the dialog.

At first i like to describe the custom dialog class.



import javax.swing.JDialog;
import javax.swing.JFrame;

/**
* @author ratul
*/
public class CustomDialog extends JDialog {

private javax.swing.JLabel jLabel1;
private javax.swing.JButton jbtOK;
private javax.swing.JTextField jtfInput;
private String inputString = "";

public CustomDialog(JFrame frame, boolean modal) {
super(frame, modal);
initComponents();
pack();
setLocationRelativeTo(frame);
setVisible(true);
}

private void initComponents() {

jbtOK = new javax.swing.JButton();
jtfInput = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();

setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

jbtOK.setText("OK");
jbtOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtOKActionPerformed(evt);
}
});
add(jbtOK, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 190,
-1,-1));

jtfInput.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jtfInputKeyReleased(evt);
}
});
add(jtfInput, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 120,
160, 20));

jLabel1.setText("Input some text here:");
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 120,
-1, -1));
}

private void jbtOKActionPerformed(java.awt.event.ActionEvent evt)
{
this.dispose();
}

private void jtfInputKeyReleased(java.awt.event.KeyEvent evt)
{
inputString += evt.getKeyChar();
}

public String getInputText()
{
return inputString;
}

}



The CustomDialog class extends the JDialog class. The first
parameter of the constructor is the parent frame, second parameter
determines whether the parent frame is disabled or enabled when
the dialog box will be shown.

In the key released action of the text field i populate the inputString.
The dialog box can be closed either by clicking the 'OK' button or close
button of the top right corner. You can get the value of the input
field from the parent from by calling the public String getInputText() method.

Now i describe how to open your custom dialog box:
In the action handler of a button in the parent frame write the following code



CustomDialog cDialog = new CustomDialog(this, true);
this.jtfShowText.setText(cDialog.getInputText());



This will show the dialog box. Now Input some text on the text field
and close the dialog box. The input text will be shown in the text
field of the parent frame.

NB: use null or absolute layout to design the custom dialog box.

Introduction to Java Persistence Query Language (JPQL)

The Java Persistence Query Language(JPQL) is one of the basic area of Java Persistence which allows you to write portable queries that work regardless of the underlying data store. It uses a SQL-like syntax to select objects or values based on entity abstract schema types and relationships among them. An entity is a lightweight persistence domain object. Typically an entity represents a table in a relational database, and each entity instance corresponds to a row in that table.

Here i describes some syntax of the language so that you can build
your own query in JPQL easily.

Lets start from a basic select query
SELECT p FROM Player p
This statement retrieves all players from Player entity.

Now write a query with WHERE clause and input parameter
SELECT DISTINCT p FROM Player p WHERE p.position = ?1
Retrieves players with the position specified. The DISTINCT keyword eliminates duplicate values. ?1 element denotes the input parameter of the query. Here position a persistent field of the Player Entity.

Select statement with named parameters
SELECT DISTINCT p FROM Player p WHERE p.position = :position AND p.name = :name
The WHERE clause compares the values of these fields with the
named parameters of the query, set using the Query.setNamedParameter
method. The query language denotes a named input parameter using
colon (:) followed by an identifier. The first input parameter is
:position, the second is :name.

At the time of writing Entity we relates one entity with another. Lets
talk about queries that navigate to related entities. One thing to
remember"Expressions can navigate to relationship fields (related
entities), but not to persistent fields"

SELECT DISTINCT p FROM Player p, IN(p.teams) t
Retrieves All players who belong to a team. The IN keyword signifies
that teams is a collection of the Player entity. The p.teams
expression navigates from a Player to its related Team. The period
in the p.teams expression is the navigation operator.

JOIN statement for the same query
SELECT DISTINCT p FROM Player p JOIN p.teams t

Another statement that serves the same purpose
SELECT DISTINCT p FROM Player p WHERE p.team IS NOT EMPTY

Navigating to single valued relationship field
SELECT t FROM Team t JOIN t.league l WHERE l.sport = 'soccer' OR l.sport ='football'

Navigating relationship field with input parameter
SELECT DISTINCT p FROM Player p, IN (p.teams) t WHERE t.city = :city

Some times you need to traverse multiple relationships. Following query navigate over two relationships.
SELECT DISTINCT p FROM Player p, IN (p.teams) t WHERE t.league = :league

To reach to a persistent field of league you can navigate by following way
SELECT DISTINCT p FROM Player p, IN (p.teams) t WHERE t.league.sport = :sport
Here sport is a persistent field of League. And you have to navigate from Player to League via Team.

After WHERE clause you have to use some conditional expression.
Lets talk about conditional expressions of JPQL
LIKE:
SELECT p FROM Player p WHERE p.name LIKE 'Mich%'

IS NULL:
SELECT t FROM Team t WHERE t.league IS NULL
Retrieves All teams not associated with a league.

IS EMPTY:
SELECT p FROM Player p WHERE p.teams IS EMPTY
Retrieves all players not belong to a team

BETWEEN:
SELECT DISTINCT p FROM Player p WHERE p.salary BETWEEN :lowerSalary AND :higherSalary

[NOT] MEMBER [OF]:(Determines whether a value is a member of a collection. The value and the collection members must have the same type):
SELECT o FROM Order o WHERE :lineItem MEMBER OF o.lineItems


[NOT] EXISTS:(Return true only if the result of the subquery consists of one or more values and is false otherwise):
SELECT DISTINCT emp FROM Employee emp WHERE EXISTS (SELECT spouseEmp FROM Employee spouseEmp WHERE spouseEmp = emp.spouse)

ALL and ANY:
The ALL expression is used with a sub-query, and is true if all the
values returned by the sub-query are true, or if the sub-query is empty.

The ANY expression is used with a sub-query, and is true if some of
the values returned by the sub-query are true. An ANY expression
is false if the sub-query result is empty, or if all the values returned
are false. The SOME keyword is synonymous with ANY.
The ALL and ANY expressions are used with the =, <, <=, >, >=, <>
comparison operators.
SELECT emp FROM Employee emp WHERE emp.salary > ALL (
SELECT m.salary FROM Manager m WHERE m.department = emp.department)


The following two queries tell you how to write UPDATE and DELETE
statement in JPQL
UPDATE Player p SET p.status = 'inactive' WHERE p.lastPlayed < :inactiveThr
DELETE FROM Player p WHERE p.status = 'inactive' AND p.teams IS EMPTY

Lets talk about aggregate functions of JPQL, Some frequently used aggregate functions are AVG, COUNT, MAX, MIN, SUM.
SELECT AVG(o.quantity) FROM Order o

SELECT SUM(l.price) FROM Order o JOIN o.lineItems l JOIN o.customer c WHERE c.lastname = 'Coss' AND c.firstname = 'Roxane'

In most cases after aggregate functions you have to use GROUP_BY or HAVING clause. but how to use them in JPQL? Here is the answer
SELECT c.country, COUNT(c) FROM Customer c GROUP BY c.country

SELECT c.status, AVG(o.totalPrice) FROM Order o JOIN o.customer c GROUP BY c.status HAVING c.status IN (1, 2, 3)

If you want to fetch data by your defined order then use ORDER_BY in the query
SELECT o FROM Customer c JOIN c.orders o JOIN c.address a WHERE a.state = 'CA' ORDER BY o.quantity, o.totalcost


Constructor expressions: It is an advance feature of JPQL. It allows you to return Java instances that store a query result element instead of an Object[]. The following query creates a CustomerDetail instance per Customer matching the WHERE clause. A CustomerDetail stores the customer name and customer’s country name. So the query returns a List of CustomerDetail instances.
SELECT NEW com.xyz.CustomerDetail(c.name, c.country.name) FROM customer c WHERE c.lastname = 'Coss' AND c.firstname = 'Roxane'

For more information about JPQL click here

How to create a Open flash chart in Rails Application

Open flash chart is a free service, by using it you can create different types of charts easily.

To create a open flash chart in Rails application at first you need
the open flash chart plugin. To get this plugin go to your project folder and run:
ruby script/plugin install http://svn.pullmonkey.com/plugins/trunk/open_flash_chart/

After this Move the open_flash_chart.swf file into your RAILS_ROOT/public directory

Now create a controller and add the following code


def index
@graph_data = open_flash_chart_object(450,220,
'/flash_chart/show_flash_chart',false,'/',true)
end



def show_flash_chart
begin
chart = draw_chart
render :text => chart
rescue Exception => error
logger.debug "error>>" + error.inspect
end
end



def draw_chart

chart_data = get_chart_data

#get data to display in chart
x_lebels = chart_data[:x_level]

# get x labels in a array
data = chart_data[:value]

# get y axis value
line_data_hashes = [{:color => "#e11456",
:legend => "Cost", :values => data}]
g = Graph.new

#draw line
if line_data_hashes
line_data_hashes.each do |line|
g.line(2, line[:color], line[:legend], 10)
g.set_data(line[:values])
end
end

g.set_tool_tip('Year: #x_label#
Cost: #val#')
g.set_title("Sample Flash Chart",
'{font-size: 14px; color: #784016}')

#set minimum y axis value
g.set_y_min(0)

#set maximum y axis value
g.set_y_max(100)

#set number of steps in y axis
g.set_y_label_steps(5)

# set y axis legend
g.set_y_legend("Cost", 12, "#b9d800")

# set x axix value
g.set_x_labels(x_lebels)

#set x axis label's style
g.set_x_label_style(10, '#000000', 2)

#set x axis legend
g.set_x_legend("Year", 12, "#b9d800")

return g.render

end


In index.rhtml put the following code

<%= @graph_data %>


Now run it and you will see the magic


How to run cruisecontrol.rb for continuous integration of Ruby on Rails application

CruiseControl.rb is a continuous integration tool for Ruby on Rails application. Its basic purpose is to alert members of a software project when one of them checks something into source control that breaks the build.

To run cruisecontrol.rb first download it from http://cruisecontrolrb.thoughtworks.com/
Unpack the downloaded file.
Then go to the folder from command prompt where it is unpacked
and run:
cruise add project_name --url (url of your subversion trunk)

This will create a directory under [cruise_data]/project/project_name and then checks out your project from the subversion URL you provided to [cruise_data]/projects/project_name/work/

Now run: cruise start
This will start your web browser on port 3333
Browse http://localhost:3333 and press the “Build Now” button on the Dashboard to build your project.

After this every time any one checks something into source control cruise control automatically
builds your project and report about the Build Changeset , Test failures and errors, etc.



Sending mail asynchronously by using Amazon SQS and ActiveMessaging

From our application we send mail to our users in many cases. Sending mail synchronously slows down the whole process. So to improve our application’s performance we feel the need of sending mail asynchronously. And I have done it using the Amazon SQS and ActiveMessaging.

What is Amazon SQS:

Amazon Simple Queue Service (Amazon SQS) offers a reliable, highly scalable, hosted queue for storing messages as they travel between computers.
Developers can push message to the queue any time and get the message when required. They can create an unlimited number of Amazon SQS queues, each of which can send and receive an unlimited number of messages. The message body can contain up to 8 KB of text in any format. A message is "locked" while a computer is processing it Messages can be retained in queues for up to 4 days

What is ActiveMessaging:

ActiveMessaging is a Rails plug-in framework, which simplifies messaging integration. It is a generic framework to ease using messaging, but is not tied to any particular messaging system - in fact, it now has support for Stomp, JMS (using Stomp Connect or direct on JRuby), WebSphere MQ, Amazon Simple Queue Service (SQS), and the all Ruby ReliableMessaging. With ActiveMessaging and Rails now you can loosely integrate with systems as disparate as mainframes sending MQ messages or J2EE webapps, offload processing long-running tasks, or create applications with event or message-driven architectures.

To integrate ActiveMessagin with your apllication
you have to install the following gem and pugin

gem install daemons
ruby script/plugin installhttp://activemessaging.googlecode.com/svn/trunk/plugins/activemessaging

First create a process using the following command
script/generate processor message
Running this generate for the first time outputs the following:

create app/processors
create app/processors/message_processor.rb
create config/messaging.rb
create config/broker.yml
create app/processors/application.rb
create script/poller

Now configure the broker.yml as which broker you are using.
I have used Amazon SQS as a broker. Here is my configure file

development:
adapter: asqs
access_key_id: xxxxxxxxxxxxxxxxxxxxxxxx
secret_access_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

test:
adapter: asqs
access_key_id: xxxxxxxxxxxxxxxxxxxxxxxx
secret_access_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

production:
adapter: asqs
access_key_id: xxxxxxxxxxxxxxxxxxxxxxxx
secret_access_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Define your own queue by changing the config/messaging.rb file

s.destination :queue_name, ' queue_name

Add the following to the controller from where you push message to the queue


require 'activemessaging/processor'
include ActiveMessaging::MessageSender
publishes_to : queue_name

def method_from_where_push_message_to_queue
publish : scrumpadmailer, “put the required value to process the message"
end

Add the following to the app/processors/message_processor.rb


subscribes_to : queue_name
def on_message(message)
begin
send mail by processing the message
rescue
publish : scrumpadmailer, “put the received message"
end
end

Now run the poller which monitors the queue continuously and upon receiving a message it calls the on_message method of app/processors/message_processor.rb

Go to your application directory and run the following command
ruby script/poller run

To run the poller as a background process in linux run the following command
nohup ruby script/poller run >> mail_logger.txt &


Everything is done. Now when a message is pushed in the queue the on_message method
Is triggered and mail will be sent

Automatic Deployment of Rails Application by Capistrano

Previously we deployed our application manually in our Linux box. This was taking a lot of time and after every deploy we were facing some serious issues. Automatic deployment by Capistrano has made deployment life easy. Here i have shared my experience about deployment by Capistrano.

Requirements:
Install Capistrano in local machine by : gem install capistrano
Install subversion command line client in local machine
Install subversion in Linux box. I have done it by a rpm

Assumptions:

  • You are deploying to a single server, at least initially.
  • Your username is the same for both your subversion repository and your deployment machine.
  • Your subversion repository is accessible from both your local host, and the host that you will be deploying to
  • You have configured a public key to use for SSH access to your target host


Run Capistrano:

From command prompt go to your application directory then run .capify.This will create a capfile in the application root directory and deploy.rb in config folder.


Configure deploy.rb:

Now modify the deploy.rb file to deploy your application. Here is my deploy.rb

require 'mongrel_cluster/recipes‘

set :application, “your application name"
set :repository, “url of your repository"
set :scm_username, “name"
set :scm_password, “password"
set :rails_env, "production --trace"
set :deploy_to, "/var/www/rails/#{application}"

#ssh configuration
set :user, ‘user_name'
ssh_options[:port] = 22
ssh_options[:username] = ‘user_name‘
ssh_options[:host_key] = 'ssh-dss'

#set app, web, db role
role :app, "www.scrumpad.com"
role :web, "www.scrumpad.com"
role :db, "www.scrumpad.com", :primary => true

#configure for mongrel cluster
set :mongrel_servers, 3
set :mongrel_port, 6010
set :mongrel_environment, 'production'
set :mongrel_conf,"#{deploy_to}/current/config/mongrel_cluster.yml"

Now the time for deploying your application:

Go to your project directory and run cap deploy:setup Capistrano will now log into your server and try to set up a simple directory hierarchy. The basic layout is:
#{deploy_to}/
#{deploy_to}/releases
#{deploy_to}/shared
#{deploy_to}/shared/log
#{deploy_to}/shared/system
#{deploy_to}/shared/pids

Every time you deploy your application, a new directory is created under the releases directory, and then a symlink is created at “#{deploy_to}/current that points at the newr elease. This current symlink should be considered the root directory of the currently active release.

run cap -q deploy:check to check dependencies.

Cold deploy: The first time your application is not running. Things are “cold”. For this case, run cap deploy:cold

Subsequent Deploys: After the first deploy every time you want to deploy just
run cap deploy

Roll back your application to the previous release cap deploy:rollback

Problem I faced:
After deploying my application on a Linux box, I faced some permission related problem to run the application. To solve this I had to put the required file in a directory and modify my deploy.rb in the following way:


after "deploy:symlink", :copy_permitted_files
task :copy_permitted_files, :roles => :app do
run "cp -rpf /var/www/rails/Permitted/public/* /var/www/rails/# application}/current/public/"
run "cp -pf /var/www/rails/Permitted/database.yml /var/www/rails/#{application}/current/config/"
run "cp -rpf /var/www/rails/Permitted/log/* /var/www/rails/#{application}/current/log/"
end

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers