Thursday, December 27, 2012

How to create a Java web service

How To:

Web service is a XML-based standard that allows interoperability between different applications on different platforms, for example, a .NET based application on Windows can communicate with a Java based one on Linux. The communication can be done through a set of XML messages over HTTP protocol.

Throughout this article, you will learn how to create and publish a web service, and consume the web service by a command line client. This article supposes you are familiar with basic Java programming using Eclipse IDE, as well as Ant build script at fundamental level.


Java web service API

Java API for XML Web Services (JAX-WS) has been included in the Java SE platform since version 6. That means, prior to Java SE 6, JAX-WS is only available for the Java EE platform, so developers could not write web services aware applications without Java EE runtime. However, JAX-WS is now a part of the Java SE platform.
The API comprises two main packages:


  • javax.xml.ws: contains the core JAX-WS APIs.
  • javax.jws: contains annotation classes that describe web service metadata. Annotations help writing web services based applications easily.



In addition, the Java SE platform provides some useful tools for generating web services artifacts: wgen, wsimport, schemagen and xjc. In this article, you will use the wsimport tool for generating Java classes for web services client.


Create a web service class

  • Create a new Java project in Eclipse by selecting File -> New Project, name the project as MyWebService.
  • Create a source package called com.mycompany.service.
  • Create a new, empty Java class in the above package, name it as HelloWeb.java. You should end up with a screen like this:


Name:  create project.png
Views: 7793
Size:  43.9 KB
Figure: Create a web service class

The class is empty now. We will mark it as a web service by adding @WebService annotation to the class and implement a web service method by using @WebMethod annotation. Update source code of the class like the following:

Java Code: Web service class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.mycompany.service;
 
import javax.jws.WebMethod;
 
import javax.jws.WebService;
 
@WebService
 
public class HelloWeb {
 
    
 
    @WebMethod
 
    public String sayGreeting(String name) {
 
        return "Greeting " + name + "!";
 
    }
 
}
Both the annotation types are from package javax.jws. The @WebService annotation marks a class as implementing a web service, and the @WebMethod annotation is used to expose a method as web service method.

And we are done creating a web service class, pretty simple!


Create a server class

Instead of deploying the web service on a heavy weight Java EE application server such as Tomcat or Glassfish, we can deploy it on a built-in, lightweight server with the help of javax.xml.ws.Endpoint class.

In Eclipse, create a new class called Server.java under the package com.mycompany.service with a main() method, and just add two lines of code to the main() method:

Java Code: Server class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.mycompany.service;
 
import javax.xml.ws.Endpoint;
 
public class Server {
 
    public static void main(String[] args) {
 
        Endpoint.publish("http://localhost:9898/HelloWeb", new HelloWeb());
 
        System.out.println("HelloWeb service is ready");
 
    }
 
}

The static method publish(String address, Object implementor) creates and publishes a web service at a specified URL. In the code above:

  • A local server is created to listen at the port 9898.
  • A new instance of HelloWeb is created and bind to the URL /HelloWeb



The server code is done, and we are ready to test the web service now.


Publish the web service

Run the Server class as a standalone Java application by selecting Run -> Run As -> Java Application from Eclipse’s main menu. Once the server is started, you should see the following message in Console view:

Name:  server started.png
Views: 7722
Size:  12.0 KB
Figure: the web service is published on a built in server
  • We now try to access the server. Select Window -> Show View -> Other, select General – Internal Web Browser, to open an internal browser in Eclipse.
  • Type the following line into address bar of the internal browser:

  • The server should return an XML document as in the following screen-shot:


blogs/web-service/attachments/3404-how-create-java-web-service-wsdl-xml.png
Figure: The WSDL document returned from the server

The WSDL document describes a web service in XML format, allows other applications to discover and consume web service methods as per described by the WSDL.


Invoke the web service method

Now we are trying to invoke the sayGreeting() method from web interface in Eclipse.

Make sure you have the Java EE perspective is active in Eclipse. Select Run -> Run the Web Services Explorer. The Web Services Explorer view is opened:

Name:  web services epxplorer.png
Views: 7758
Size:  27.1 KB
Figure: Open Web Services Explorer View

In this view, click on the icon “WSDL Page” at the top right corner:

Name:  click wsdl page icon.png
Views: 7732
Size:  3.5 KB
Figure: Add a WSDL page

Select WSDL Main in the Navigator left pane. In the Actions pane on the right, type the URL: http://localhost:9898/HelloWeb?wsdl into the field WSDL URL, click Go.

The WSDL Binding Details page is displayed, which shows the sayGreeting() method as a web service method:

Name:  wsdl binding details.png
Views: 7742
Size:  36.4 KB
Figure: WSDL Binding Details

Click on the sayGreeting name, the page Invoke a WSDL Operation is displayed, which shows details of the method sayGreeting:

Name:  say greeting method details.png
Views: 7754
Size:  35.2 KB
Figure: Invoke a WSDL Operation

The sayGreeting() method has one String argument, click on Add link to add value for the argument. Type “The President” into the text box:

Name:  type argument.png
Views: 7707
Size:  4.1 KB
Figure: Set argument for web service method

Click Go, the web service method is invoked and return a response is returned in the Status bottom pane:

Name:  method return.png
Views: 7735
Size:  38.5 KB
Figure: Invoke the web service method

That means the web service method is invoked successfully.


Create a web service client

So far we have been able to access the web service via a web interface inside Eclipse. It would be more interesting if the web service can be accessed via a standalone program. Such program is called a web service client, which we will write now. The steps to create a web service client are as follows:
  • First, we need to generate web service client Java sources file based on the WSDL page returned by the server. To do so, we should use the wsimport tool which comes with JDK. Syntax of the wsimport command line tool is:

    wsimport [options] <WSDL_URI>

    • <WSDL_URI>: specifies URI of the web service’s WSDL page, it should be http://localhost:9898/HelloWeb?wsdl for our sample program.
    • [options]: specifies some options such as where to read web service source files and where to put generated source files. We will use these three options:

    • -s: specifies the directory where to place generated source files.
    • -p: specifies a package to place generated source files.
    • -keep: keep the generated files.

    So the command would be:

    wsimport -keep -s ./src -p com.mycompany.service.client http://localhost:9898/HelloWeb?wsdl

    We put the generated files into package com.mycompany.service.client
  • Next, we create an Ant build file to execute the wsimport command within Eclipse IDE.

    • Create a new XML file, say wsbuild.xml, save it into project directory.
    • Write content for the wsbuild.xml as follow:


    XML Code: Ant build script to generate web service client classes
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <project name="My Web Service Build" default="wsimport">
     
        <target name="wsimport">
     
            <exec executable="wsimport">
     
                <arg line="-keep -s ./src -p com.mycompany.service.client http://localhost:9898/HelloWeb?wsdl"/>
     
            </exec>          
     
        </target>
     
        
     
    </project>
  • Open Ant View by selecting Window -> Show View -> Ant.

    • Click on Add Buildfiles icon to add wsbuild.xml to the view.
    • Make sure the server program is still running, if not, start it. Click on Run icon to execute the default target of the Ant script.

    Name:  ant view.png
Views: 7703
Size:  7.8 KB
    Figure: Ant View

    The wsimport command will connect to the server and parse the WSDL page from the given URL to generate Java source files for web service client. And you should see a BUILD SUCCESSFUL message in the Console view.
  • Refresh the project in Project Explorer view, you will see there are 6 Java source files are generated under the package com.mycompany.service.client:

    Name:  generated source files.png
Views: 7704
Size:  12.2 KB
    Figure: Generated Java source files
  • The generated Java files are necessary for writing a web service client. We are interested in the class HelloWebService.java because it wraps all the details and exposes some methods ready for implementing a client.
  • Create a new Java class, say Client.java under the package com.mycompany.service, with a main() method. Update the source code of the class looks like this:


Java Code: The web service client code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.mycompany.service;
 
import com.mycompany.service.client.HelloWebService;
 
public class Client {
 
    public static void main(String[] args) {
 
        HelloWebService service = new HelloWebService();
 
        com.mycompany.service.client.HelloWeb helloWeb = service.getHelloWebPort();
 
        String response = helloWeb.sayGreeting("The President");
 
        System.out.println("Web service response: " + response);
 
    }
 
}
And we are done writing a web service client. Be ready to test it now!


Test the web service

So far we have done both the server and the client for a sample web service. Both are standalone command line java programs and can be launched by selecting Run -> Run As -> Java Application from Eclipse’s main menu.

  • Start the server, and make sure you got the message “HelloWeb service is ready” in the console. The server is now waiting for request.
  • Start the client, it will connect to the server, invoke the web service method and receive a response back. And finally you should see the message “Web service response: Greeting The President!”



In this article we only run the server and the client on a same computer. It is also possible to deploy the client and the server on two different machines.

  • The server part contains only two Java files: HelloWeb.java and Server.java
  • The client part contains all generated files under package com.mycompany.service.client and the Client.java file.

Thursday, December 20, 2012

Auto Backup for PostgreSQL

Introduction
In this article, I would like to show you how to create a Windows batch file to take backups from a PostgreSQL database.

Background

When I was working with a PostgreSQL database for one of my projects I needed an auto system for taking backups daily. After some research I came up with this idea to create a Windows batch file and put it under the Windows Scheduler.
To prepare for a chart use these steps given below:

How to configure

Step 1:

Download the batch file.

Step 2:

You can start the Task Scheduler MMC snap-in by using a single command from the command line or by using the Windows interface. Task Scheduler can also be started by double-clicking the Taskschd.msc file in the %SYSTEMROOT%\System32 folder.

To run Task Scheduler using the Windows interface

Click the Start button. Click Control Panel. Click System and Maintenance. Click Administrative Tools. Double-click Task Scheduler.

To run Task Scheduler from the command line

Open a command prompt. To open a command prompt, click Start, click All Programs, click Accessories, and then click Command Prompt. At the command prompt, type Taskschd.msc. The Schtasks.exe command line tool enables a user to complete many of the same operations that they can complete using the Task Scheduler MMC snap-in. This tool enables a user to create, delete, query, change, run, and end scheduled tasks on a local or remote computer. This tool is located in the %SYSTEMROOT%\System32 folder. Type Schtasks.exe /? from a command prompt window to view the help for the tool.

Step 3:

You can schedule a task by either creating a basic task using the Create Basic Task Wizard or by creating a task without the wizard and supplying task information in the Create Task dialog box. The procedures below describe how to create a task using either method. If you create a basic task using the Create Basic Task Wizard, most of the task properties will be set to their default values, and you choose a trigger for the task from the most commonly used triggers. For more information about triggers, see Triggers.
You can import a task that is defined in an XML file. For more information, see Import a Task. For information on creating a task on a remote computer, see Manage or Create a Task on a Remote Computer.

To create a basic task by using the Windows interface

If Task Scheduler is not open, start Task Scheduler. For more information, see Start Task Scheduler. Find and click the task folder in the console tree that you want to create the task in. For more information about how to create the task in a new task folder, see Create a New Task Folder. In the Actions Pane, click Create Basic Task. Follow the instructions in the Create Basic Task Wizard.

To create a task by using the Windows interface

If Task Scheduler is not open, start Task Scheduler. For more information, see Start Task Scheduler. Find and click the task folder in the console tree that you want to create the task in. If you want to create the task in a new task folder, see Create a New Task Folder to create the folder. In the Actions Pane, click Create Task. On the General tab of the Create Task dialog box, enter a name for the task. Fill in or change any of the other properties on the General tab. For more information about these properties, see General Task Properties.
On the Triggers tab of the Create Task dialog box, click the New… button to create a trigger for the task, and supply information about the trigger in the New Trigger dialog box. For more information about triggers, see Triggers. On the Actions tab of the Create Task dialog box, click the New… button to create an action for the task, and supply information about the action in the New Action dialog box. For more information about actions, see Actions.
(Optional) On the Conditions tab of the Create Task dialog box, supply conditions for the task. For more information about the conditions, see Task Conditions.
(Optional) On the Settings tab of the Create Task dialog box, change the settings for the task. For more information about the settings, see Task Settings.
Click the OK button on the Create Task dialog box.

To create a task by using a command line

Open a command prompt. To open a command prompt, click Start, click All Programs, click Accessories, and then click Command Prompt.
Type:
schtasks /Create [/S <system> [/U <username> [/P [<password>]]]]
    [/RU <username> [/RP <password>]] /SC <schedule> [/MO <modifier>] [/D <day>]
    [/M <months>] [/I <idletime>] /TN <taskname> /TR <taskrun> [/ST <starttime>]
    [/RI <interval>] [ {/ET <endtime> | /DU <duration>} [/K] [/XML <xmlfile>] [/V1]]
    [/SD <startdate>] [/ED <enddate>] [/IT] [/Z] [/F]
To view the help for this command, type:
schtasks /Create /?
Additional Considerations
If the Remote Scheduled Tasks Management exception is disabled and the File and Printer Sharing exception is enabled in the Windows Firewall settings, and the Remote Registry service is running, a V1 task will be created on the remote computer even when the V1 parameter is not specified. The V1 parameter specifies that a task is visible to down-level systems.

Using the code

Script


@ECHO OFF
@setlocal enableextensions
@cd /d "%~dp0"SET PGPATH=C:\"Program Files"\PostgreSQL\9.1\bin\
SET SVPATH=f:\
SET PRJDB=demo
SET DBUSR=postgresFOR /F "TOKENS=1,2,3 DELIMS=/ " %%i IN ('DATE /T') DO SET d=%%i-%%j-%%k
FOR /F "TOKENS=1,2,3 DELIMS=: " %%i IN ('TIME /T') DO SET t=%%i%%j%%k

SET DBDUMP=%PRJDB%_%d%_%t%.sql
@ECHO OFF
%PGPATH%pg_dump -h localhost -p 5432 -U postgres %PRJDB% > %SVPATH%%DBDUMP%

echo Backup Taken Complete %SVPATH%%DBDUMP%

Initial value

  • PGPATH - PostgreSQL path
  • SVPATH - Backup File path
  • PRJDB - Name of the Database which will be backup
  • DBUSR - Database user name

References

restore a postgres backup file using the command line

There are two tools to look at, depending on how you created the dump file.
Your first source of reference should be the man page pg_dump(1) as that is what creates the dump itself. It says:
Dumps can be output in script or archive file formats. Script dumps are plain-text files containing the SQL commands required to reconstruct the database to the state it was in at the time it was saved. To restore from such a script, feed it to psql(1). Script files can be used to reconstruct the database even on other machines and other architectures; with some modifications even on other SQL database products.
The alternative archive file formats must be used with pg_restore(1) to rebuild the database. They allow pg_restore to be selective about what is restored, or even to reorder the items prior to being restored. The archive file formats are designed to be portable across architectures.
So depends on the way it was dumped out. You can probably figure it out using the excellent file(1) command - if it mentions ASCII text and/or SQL, it should be restored with psql otherwise you should probably use pg_restore
Restoring is pretty easy:
psql -U <username> -d <dbname> -1 -f <filename>.sql
or
pg_restore -U <username> -d <dbname> -1 -f <filename>.dump
Check out their respective manpages - there's quite a few options that affect how the restore works. You may have to clean out your "live" databases or recreate them from template0 (as pointed out in a comment) before restoring, depending on how the dumps were generated.



Step to do:

create backup
pg_dump -i -h localhost -p 5432 -U postgres -F c -b -v -f 
"/usr/local/backup/10.70.0.61.backup" old_db
restore from backup
pg_restore -i -h localhost -p 5432 -U postgres -d old_db -v 
"/usr/local/backup/10.70.0.61.backup"
important to set -h localhost - option

Daily Postgresql Backup by Batch File

Recently I installed PostgreSQL on a Windows 2003 server. I also wanted to back up one of the PostgreSQL databases to a folder on the server on a daily basis as an extra precautionary measure. PostgreSQL comes with a program called pg_dump which can be used to create a back up of a database. You give it the database to back up, the file to back up to and it does all the work for you.
The extra work needed here is to back up to a file name that differs each day so that you can have a folder of back ups per day. It would be handy for pg_dump to generate a file name based on date but it doesn’t. So I created a batch file to do the job in one go including a file name based on the date.
@echo off
set date=%date:/=_%
set BACKUP_FILE=D:\PostgreSQL_Backups\DBName\DBName_%date%.backup
pg_dump -h localhost -p 5432 -U postgres -F p -b -v -f %BACKUP_FILE% DBName
Then I created a Windows task scheduled to run daily which just runs the above batch file.

Saturday, December 15, 2012

Open Source Tutorial

Hi all! This is a tutorial : http://theopentutorials.com/tutorials/web-services/web-services-platform/

Friday, December 14, 2012

Importing Word document data in Excel

Sub ImportWordTable2()
'Import all tables to separate sheets
Dim wdDoc As Object
Dim wdFileName As Variant
Dim TableNo As Integer 'table number in Word
Dim iRow As Long 'row index in Excel
Dim iCol As Integer 'column index in Excel
wdFileName = Application.GetOpenFilename("Word files (*.doc),*.doc", , _
"Browse for file containing table to be imported")
If wdFileName = False Then Exit Sub '(user cancelled import file browser)
Set wdDoc = GetObject(wdFileName) 'open Word file
With wdDoc
    If wdDoc.tables.Count = 0 Then
        MsgBox "This document contains no tables", _
            vbExclamation, "Import Word Table"
    Else
        For TableNo = 1 To wdDoc.tables.Count
            With .tables(TableNo)
                Sheets.Add after:=Sheets(Worksheets.Count)
'copy cell contents from Word table cells to Excel cells
                For iRow = 1 To .Rows.Count
                    For iCol = 1 To .Columns.Count
                        On Error Resume Next
                        ActiveSheet.Cells(iRow, iCol) = 
                         WorksheetFunction.Clean(.cell(iRow, iCol).Range.Text)
                        On Error GoTo 0
                    Next iCol
                Next iRow
            End With
        Next TableNo
    End If
End With
Set wdDoc = Nothing
End Sub

Wednesday, December 12, 2012

Enterprise Application Integration - Tutorial

Installing and Configuring JBoss AS and JBoss Tools

Contents

  1. Installing the latest JDK
  2. Installing JBoss AS 6
  3. Installing Eclipse 3.6.2
  4. Installing JBoss Tools 3.2

Installing the latest JDK

  1. Make sure that the latest version of the Java Development Kit (JDK 6 Update 24 or later) is installed on your computer. If the JDK is properly installed on your computer, you can jump to step 4 of this section, otherwise continue with the next step.
  2. Go to http://www.oracle.com/technetwork/java/javase/downloads/index.html and follow the instructions on Oracle's website to download the latest version of the JDK (Java SE 6 Update 24 or later) for the operating system of your computer.
  3. Install the JDK to a directory on your computer, e.g. C:\Java\jdk1.6.0_24.
  4. Create an environment variable called JAVA_HOME that points to the JDK installation directory, for example C:\Java\jdk1.6.0_24.

Installing JBoss AS 6

  1. Get the latest stable version of the JBoss Application Server (6.0.0.Final) from http://sourceforge.net/projects/jboss/files/JBoss/JBoss-6.0.0.Final/ (jboss-as-distribution-6.0.0.Final.zip).
  2. Extract the zip archive to a directory on your computer, e.g. C:\EAI. The path must not contain any spaces. A new directory, e.g. C:\EAI\jboss-6.0.0.Final, containing the JBoss AS files will be created.
  3. Use the script <JBoss directory>\bin\run.bat to start the JBoss server and check the installation. After startup, you should be able to access the web server at http://localhost:8080.
  4. In order to stop the server, press CTRL-C in the console window that was opened during step 3.

Installing Eclipse 3.6.2

  1. Download the Eclipse IDE for Java EE Developers for your operating system (version 3.6.2, Helios SR2) from http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/heliossr2.
  2. Extract the downloaded archive, e.g. eclipse-jee-helios-SR2-win32.zip, to a directory on your computer, e.g. C:\EAI. This will create a sub directory, like C:\EAI\eclipse.
  3. Start Eclipse. The eclipse.exe is located in the installation directory. Wait for the "Workspace Launcher" window to pop up and select a workspace directory, for example C:\EAI\projects. This path must not contain any spaces either. The workspace directory is where all your projects will be stored. You may check the "Use this as the default and do not ask again" box to avoid this dialog from appearing on the next start. Click "OK" to close the dialog and get to the workbench window.

Installing JBoss Tools 3.2 for Eclipse

  1. Select "Help->Eclipse Marketplace..." from the Eclipse menu bar. Choose "Eclipse Marketplace" if prompted for a marketplace catalog.
  2. Search for "JBoss Tools" and install JBoss Tools (Helios), version 3.2.x.
  3. Wait until "Calculating requirements..." has finished and make sure that all features are checked, then click "Next".
  4. Accept the license agreements and click "Finish".
  5. When the download is complete, a security warning regarding "Unsigned content" will appear. Accept with "OK" to begin with the installation.
  6. When prompted to do so, "Restart Now".
  7. After closing the "Welcome" window you will see the "Java EE" perspective. The selected perspective is indicated in the upper right corner as shown in the following figure:

    If the Java EE button is not visible you can change to the Java EE perspective via "Window->Open Perspective->Other..." . In the "Open Perspective" dialog double click the Java EE entry.
  8. Activate the "Servers" view tab in the lower right of the window. Right-click the empty area and select "New->Server" as shown in this screenshot:

  9. In the "New Server" window select "JBoss AS 6.0" (from the JBoss Community category) as server type and click "Next".

    Set the "Home Directory" entry to the installation directory of the JBoss AS, e.g. C:\EAI\jboss-6.0.0.Final, and click "Finish".
  10. In the "Servers" view select the newly created server and click the green start button.

    A new "Console" view will open showing the startup logs of the JBoss AS.
Congratulations, you have successfully installed JBoss AS and JBoss Tools!
Continue with the setup of your first Java EE project.

Please send questions and comments regarding this tutorial to Henning Heitkötter.

How To Set Environment Variables

  • Windows XP: Open the Control Panel (Systemsteuerung) from the Start Menu, switch to Classic View (Klassische Ansicht) if necessary, open the System Control Panel applet (System), select the Advanced tab (Erweitert), and click on the Environment Variables button (Umgebungsvariablen).
  • Windows 7: Control Panel (Systemsteuerung) - System - choose Advanced System Settings (Erweiterte Systemeinstellungen) on the left - Advanced tab (Erweitert) - Environment Variables button (Umgebungsvariablen)
Link Source: http://www.wi.uni-muenster.de/pi/lehre/ss11/EAI/tutorials/tutorial_jboss_setup.html

Enterprise Application Integration - Tutorial


Creating Java EE projects with JBoss Tools

Contents

  1. Preconditions
  2. Importing the Example Application into Eclipse
  3. Creating an Enterprise Application from scratch

Preconditions

  • Make sure JBoss AS and Eclipse with JBoss Tools Plug-in are properly installed and configured (tutorial).
  • Start Eclipse with JBoss Tools Plug-in and make sure the Java EE perspective is opened.
  • Make sure that a JBoss 6.0 Runtime Server is configured in Eclipse as outlined in the first tutorial.

Importing the Example Application into Eclipse

This tutorial will show how to import a Java EE application using the example of a library application. It allows you to quickly get started with Eclipse, Java EE and JBoss Tools. The next section, "Creating an Enterprise Application from scratch", will show how you can create your own Java EE projects.
  1. Download the library application source files to a temporary folder.
  2. Select "File->Import..." from the Eclipse menu bar.
  3. Choose "General > Existing Projects into Workspace" and click next.
  4. Choose "Select archive file" and browse to the archive from step 1.
  5. Four projects called Library, Library-EJB, Library-Persistence and Library-Web should appear under "Projects". Make sure all four are selected and "Finish".
  6. The project explorer should now contain the four projects. Eclipse will automatically validate and build the projects.
  7. In the "Servers" tab, right-click on your JBoss 6.0 server and select "Add and Remove...".
  8. Select the library application and click "Add >", then "Finish.
  9. Start the server and wait until the application has been deployed.
  10. The Library web application is accessible under http://localhost:8080/Library-Web/.

Creating an Enterprise Application from scratch

The following instructions show how to create an enterprise application from scratch, without importing existing projects. It may be helpful when you start developing your own application, for example during the practical course.
An enterprise application consists of several projects. In the following, the application is made up of four projects:
  1. Enterprise Application Project: a container project that packages the other projects into an .ear file for deployment purposes.
  2. JPA Project: the data model of your application, contains mostly Entities.
  3. EJB Project: the business logic of your application, contains mostly Session Beans.
  4. Web Project: the web presentation layer of your application, implemented using JSF technology, contains web pages and Java classes as backing beans.
This tutorial uses "Test" and variations thereof as project names. Of course, you are free to choose your own names.

New Enterprise Application Project

  1. Select "File->New->Enterprise Application Project" from the menu bar.
  2. In the "New EAR Application Project" dialog, enter "Test"as project name, makesure that JBoss 6.0 is the target runtime and click "Finish".

New JPA Project

  1. Select "File->New->JPA Project" from the menu bar.
  2. In the "New JPA Project" dialog, enter "Test-Persistence" as project name. Again, the target runtime should be JBoss 6.0. "Minimal JPA 2.0 Configuration" should be selected as "Configuration".
  3. As we want this project to be part of the enterprise application, we select "Add project to an EAR" and choose our Test project from the "EAR Project Name" menu.
  4. Click "Finish". (Do not switch to the JPA perspective if asked to do so.)
  5. Open the file "persistence.xml" (under "JPA Content" or under src/META-INF/) and switch to the "Source" tab. Modify the node persistence-unit to match the following snippet:
    <persistence-unit name="Test-Persistence">
      <jta-data-source>java:/DefaultDS</jta-data-source>
      <properties>
        <property name="hibernate.hbm2ddl.auto"
          value="create-drop"/>
      </properties>
    </persistence-unit>
    This defines the data source to use ("java:/DefaultDS" is the JNDI address of the built-in HSQL database of  JBoss AS) and ensures that you always start with a fresh database after deployment. When you've reached a stable data schema, you can use "validate" or "update" instead of "create-drop".
  6. To create your first Entity, right-click on the project, select "New->Entity" and follow the wizard.

New EJB Project

  1. Select "File->New->EJB Project" from the menu bar.
  2. In the "New EJB Project" dialog, enter "Test-EJB"as project name. The "EJB module version" should be set to 3.1.
  3. As we want this project to be part of the enterprise application, we select "Add project to an EAR" and choose our Test project from the "EAR Project Name" menu.
  4. After clicking "Next" twice we disable the "Create an EJB Client Jar..." check box. For the moment we do not need a separate EJB client jar file.
  5. A click on "Finish" will create a new library-ejb project.
  6. To create a Session Bean, right-click on the project, select "New->Session Bean (EJB 3.x)" and follow the wizard.

New Web Project

  1. Select "File->New->Dynamic Web Project" from the menu bar.
  2. In the "New Dynamic Web Project" dialog, enter "Test-Web"as project name. The "Dynamic web module version" should be set to 3.0.
  3. Under "Configuration", select "JavaServer Faces v2.0 Project" from the drop-down menu.
  4. As we want this project to be part of the enterprise application, we select "Add project to an EAR" and choose our Test project from the "EAR Project Name" menu.
  5. A click on "Finish" will create a new library-web project.
  6. XHTML Pages with Facelets markup go into the WebContent folder ("New->Other..."). Backing beans should be created as Java classes under JavaResources/src.
Please refer to steps 7-9 of the section "Importing the Example Application into Eclipse" in order to learn how to deploy your project.

Tuesday, December 11, 2012

Add auto increment column in PostgreSQL

In PostgreSQL, we cannot just add an column and mark it as auto increment like in MySQL or SQL Server. Instead, we have to create an sequence and link it to the specified column.
1. Assume that we have a table called [testtbl] with an unique column called [id]
2. Generate sequence

1CREATE SEQUENCE <Sequence name>

==>

1CREATE SEQUENCE <testtbl_id_seq>

※After the sequence’s already created, we can call NEXTVAL(‘<Sequence name>’) to generate a new value automatically.

3. Link the sequence to the unique column 

 

1ALTER TABLE <Table name>
2ALTER COLUMN <Column name>
3SET DEFAULT NEXTVAL(<Created sequence name>);     ==> 
1ALTER TABLE testtbl
2ALTER COLUMN id
3SET DEFAULT NEXTVAL('testtbl_id_seq');
 

NVL() function in Postgre SQL

Do Postgre have any function that equals to NVL() of Oracle? of course, it do have the same function but with different name. Below is the systax:


coalesce(expr1, expr2, expr3,....)
 this function’ll returns the first non-null expression that is passed to it.

1Ex: 
2SELECT coalesce(<column name 1>, <New value>), <Column name 2>
3FROM <Table name>
4WHERE <Some Condition>

If <Column name 1> is NULL, it’ll be replaced by <New value>

Oracle/PLSQL: NVL Function

Oracle/PLSQL: NVL Function

In Oracle/PLSQL, the NVL function lets you substitute a value when a null value is encountered.

Syntax

The syntax for the NVL function is:
NVL( string1, replace_with )
string1 is the string to test for a null value.
replace_with is the value returned if string1 is null.

Applies To

  • Oracle 11g, Oracle 10g, Oracle 9i, Oracle 8i

Example #1

select NVL(supplier_city, 'n/a')
from suppliers;
The SQL statement above would return 'n/a' if the supplier_city field contained a null value. Otherwise, it would return the supplier_city value.

Example #2

select supplier_id,
NVL(supplier_desc, supplier_name)
from suppliers;
This SQL statement would return the supplier_name field if the supplier_desc contained a null value. Otherwise, it would return the supplier_desc.

Example #3

select NVL(commission, 0)
from sales;
This SQL statement would return 0 if the commission field contained a null value. Otherwise, it would return the commission field.

Frequently Asked Questions


Question: I tried to use the NVL function through VB to access Oracle DB.
To be precise,
select NVL(Distinct (emp_name),'AAA'),................ from.................
I got an oracle error when I use distinct clause with NVL, but when I remove distinct it works fine.
Answer: It is possible to the use the DISTINCT clause with the NVL function. However, the DISTINCT must come before the use of the NVL function. For example:
select distinct NVL(emp_name, 'AAA')
from employees;
Hope this helps!

Question: Is it possible to use the NVL function with more than one column with the same function call? To be clear, if i need to apply this NVL function to more than one column like this:
NVL(column1;column2 ...... , here is the default value for all )
Answer: You will need to make separate NVL function calls for each column. For example:
select NVL(table_name, 'not found'), NVL(owner, 'not found')
from all_tables;

Monday, December 3, 2012

octal to decimal conversion Java

import java.util.Scanner;



public class OctalConversion {



    // simple main method for static Java little job

    public static void main(String[] arg) {

        // Scanner to read user input

       Scanner scan = new Scanner(System.in);

        // prompt for String

        System.out.print("Enter octal number: ");

        // read it back

        String octalStr = scan.nextLine();

        // convert to int

        int dec = convertToDecimal(octalStr);

        // if not -1 conversion was OK

        if(dec != -1)

            System.out.println("Octal: " + octalStr + " is in decimal " + dec);

    }

     

    static int convertToDecimal(String octo) {

        int number = 0;      // init result

        for(int i = 0; i < octo.length(); i++) { // pass through all input characters

            char digit = octo.charAt(i);            // fetch octal digit

            digit -= '0';                           // translate to number (integer)

            if(digit < 0 || digit > 7) {          // validate user inpu

                System.out.println("Your number is NOT a valid Octal number");

                return -1;

            }

            number *= 8;                            // shift to left what I already ahve

            number += digit;                        // add new number

        }

        return number;

    }

}

JDBC Get Row Count

The JDBC Get Row Count enables you to return the row count of a query. JDBC Get Row Count  provides you the name of the field, total number of row and data type of the column  to be retrieved from the table.
Understand with Example
In this Tutorial we want to describe a code that make you to understand in JDBC Get Row Count. The code help you to understand how to count the number of field and field name. The metadata in this code  provide you the property of the retrieved column. For this, Program include a class name JdbcGetRowCount, Inside this class we have a main method that include list of following steps -
 Import a package java.sql*,enables you to provide a network interface that help in communicating between the front end and the backend.
 Loading a driver is the next step to be followed by calling a class.forName( ),that accept driver class as argument.
The DriverManager.getConnection ( ) return you a connection object, the get Connection ( ) built a connection between url and database. The create Statement ( ) is used to create sql object. An object of connection is used to send and execute query in the database.
.execute query ( )  -   This is used to retrieve the record set from a table in the database and the record set from the table is stored in Result Set.   The select statement is used to retrieve the  record set from table.
 rs.get Metadata ( ) - This is used to return an object that can be used further to get information about the types and properties of the columns in a ResultSetMetaData object. The meta data call a getColumnCount ( ) return you the number of column in the table.
Finally the println print the Table Name, number of field and the field name.
Incase the exception occurred in the try block, subsequent the catch block check and handle the exception.
JdbcGetRowCount.java
import java.sql.*;

public class JdbcGetRowCount {

    public static void main(String args[]) {

        Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        String url = "jdbc:mysql://localhost:3306/";
        String db = "komal";
        String driver = "com.mysql.jdbc.Driver";
        String user = "root";
        String pass = "root";

        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url + db, user, pass);
            st = con.createStatement();

            String sql = "select * from person";
            rs = st.executeQuery(sql);
            ResultSetMetaData metaData = rs.getMetaData();

            int rowCount = metaData.getColumnCount();

            System.out.println("Table Name : " + 
            metaData.getTableName(rowCount));
            System.out.println("No of Field : " + rowCount);
            System.out.print("Field Name :");
            for (int i = 0; i < rowCount; i++) {
                System.out.print("  " + metaData.getColumnLabel(i+1));
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
Output
Table Name : person
No of Field : 3
Field Name :  id  cname  dob

How to Convert Decimal to Binary Number in Java


Firstly, we have to draw control as Capture and set Variable for this control:










1/. Create a function name ReturnString:
    String ReturnString(String st)
    {
        String s="";
        char[] ch=st.toCharArray();
        for(int i=ch.length-1;i>=0;i--)
            s+=ch[i];
        return s;
    }
2/. In button Convert Number:

     private void btnConvertActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        long value;
        value=Long.valueOf(txtDecimail.getText());
        String st="";
        do
        {
            st+=value%2;
            value/=2;
        }while(value>0);
        txtBinary.setText(ReturnString(st));
    }