Advance Java Unit - 4

 Unit4 java Beans & JDBC 

Introduction & Advantages of javaBeans 

avaBeans is one of the reusable class code element often applied on java  based software application programming. Here, Beans can be defined as a way  of encompassing multiple objects beneath a single object. The JavaBeans class  components can be labelled as methods, events, properties and persistence.  This type of class is advantageous over others due to its notable reusability  characteristics, enables object communication, platform-independent, shorter  time consumption, requires lesser manual efforts, etc. 

Understanding JavaBeans 

As stated, JavaBeans helps in reusing software components in developing an  application. With the help of JavaBeans, one can reuse software components  that other developers write. This eliminates the need for understanding inner  workings. As Beans consists of numerous objects into a single object, one can  

directly access this object from various places. Its maintenance is easy. The  software component model deals with the creation and reuse of the software  components to build an application. With the help of the builder tool, one can  develop new beans or use existing beans to create an application. One can  directly use these beans in the software. 

If you are still confused, then consider the example of a worker assembling a  car, and the radio is one of the components. Instead of manufacturing the  radio from scratch, a worker can directly assemble the radio to the car. This  eliminates the need for manufacturing a radio for assembly. Components of JavaBeans 

Components of Java Beams are nothing but the class that contains the  definition of beans. These classes have specific design convections. It consists  of events, methods, persistence, properties. Non-GUI based and GUI based  components are the two types of components. The classes are discussed  below: 

Properties: This attribute consists of a label, font, color, size, display  size, etc. It determines behavior, appearance, and the state of Beam. Methods: Methods in JavaBeans are similar to the normal Java methods.  It does have any specific naming convention.

Events: Events in JavaBeans is similar to Swing event handling. Advantages of JavaBeans 

1. Run anywhere; write once- Java Beans eliminates the need for writing  2. One can work with JavaBeans on Numerous local platforms, which make it  valuable in the global market. 

3. JavaBeans can capture the events that are sent by other objects. It enables  object communication. 

4. An application developer is able to control Methods, events, and the  properties of any Java beans. 

5. Zero hassle at run time with auxiliary software; one can configure beans  during design time. 

6. Reusable: One can make a persistence configuration setting in JavaBeans.  Persistent storage and restoration later can save the configuration setting of  the bean. 

Using JavaBeans in the Java program allows us to encapsulate many objects into  a single object called a bean. Java is an object-oriented programming language  that makes the develop once, run and reuse the program everywhere most  important. 

However, JavaBeans add reusability into the Java program by maintaining a  single object encapsulating many data members and member functions. In  other words, we can say that a JavaBean 

is a platform-independent component that allows us to reuse the class object  in our Java 

Application Building Tools 

The purpose of these software is to automate some tasks associated with building  software. For example, a build automation software can help you to compile an app  source code, run tests of the app, create an installer and even install the app on a  remote server. 

Build tools are an essential part of the DevOps process. They help to save time,  highlight potential issues, and ease the work of developers. There are scores of build  automation software on the market, so how do you know which ones to choose? Well,  that’s the purpose of this article. We’ve compiled a list of the top 10 build automation  software in 2019. 

1. Jenkins

This is a Java-based open-source build automation server. Jenkins has been around for  over a decade and is used by many developers. It features up to 1,400 plugins which  broaden the list of what it can do. Jenkins can be used to compile the source code, test,  and deploy an app among other things. You can run Jenkins as a servlet in a Java app  server like Apache Tomcat, or it can be launched as a standalone app. Jenkins can  even be used to share your app with different devices. 

2. Apache Ant 

This is another Java-based, open source build tool. Ant has been around for nearly two  decades now. Although it is considered “old,” it is still very useful. Apache Ant is very  flexible. You can customize it based on the tasks you need this software to perform.  Like other build automation software, Apache Ant can be used to compile the source  code of an app, and run it. Ant writes codes in XML – this is one of the reasons why it is  preferred by some developers. 

3. Gradle 

If you want a modern version of Apache Ant, I recommend Gradle. One of the main  differences between the two is that instead of XML, Gradle uses Apache Groove,  domain-specific language (DSL). Gradle is useful for every step in the app development  process. It can do everything that Ant can do, and much more, and it also supports  incremental builds. 

4. TeamCity 

This Java-based build automation software was released by JetBrains in 2006. This is a  commercial software. However, you can request a free license if you are working on an  open source project. TeamCity has the same features as other build tools. In addition, it  

has up to 100 build configurations, and you can run up to three builds simultaneously.  This is a powerful tool, and it produces sleek, modern apps. 

5. Maven 

This app from the Apache Software Foundation has been around since 2004. Maven  has been described as a modern version of Apache Ant. Although this is a Java-based  build tool, it supports projects built written in other programming languages. It uses  conventions for building, and you only need to write exceptions. With Maven, you can  easily write plugins for a specific task. Also, you can use it for multiple projects  concurrently. Maven depends on XML. 

6. Travis CI 

This is an open source continuous integration service. It is used to build and test  projects hosted on GitHub. This service comes with a vast library of pre-installed 

database and services. Also, it tests Pull Requests before merging to avoid potential  issues. Travis CI is written in Ruby but supports different programming languages. 

7. CMake 

This open source build automation software was released in 2000. You can use CMake  to compile, test, and package a cross-platform code. This is a versatile app. It can be  linked with third-party libraries and works with your native build environment. It is perfect  for working on large C++ projects and can be used for apps that are sourced from  different libraries. It creates a directory tree for your app. 

8. sbt 

This is an interaction build tool released in 2008. sbt stands for Scala Build Tool.  Although it is mainly used for Scala projects, it also supports Java. sbt provides all the  standard tools that you will find in the standard build automation software and more, but  it is specifically for Scala projects. It also manages dependencies. sbt comes with  several plugins, and you can add other features to the software. 

9. MSBuild 

This build automation software from Microsoft that works with XML code. Ir was  released in 2003 as a free, open-source build tool. MSBuild is part of the .NET  Framework. You can configure the build process to perform specific tasks. MSBuild is  similar to Ant in many ways, and many believe it is better. Although you can generate  files to use on MSBuild from Visual Studio, it is not compulsory. 

10. Bamboo 

This build too and continuous deployment server is written in Java and was released in  2007. Although it may not be as popular as some of the top build automation software, it  is equally good. It can run multiple builds concurrently. It also provides an in-depth  analysis of the problems with your software if bugs are found. It can be used to import  data from Jenkins and can be integrated with other software from Atlassian. This is a  premium software, and it is not open source. 

These are some of the top build automation tools on the market. Although these are  some of the best build tools out there, there are many others that may be equally good.  When choosing which build automation software to use, you must analyze the  requirements of your project and the features that each tool provides. Some of the build  tools highlighted above are more suited for teamwork than others. Also, some can be  integrated with other apps. These are the things to consider when choosing which build  automation tool to use. Ultimately, there is “no” best build tool – it all depends on which  particular tool suits the project that you’re working on 

Bean Development kit

JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software  development environment which is used to develop java applications and applets. It  physically exists. It contains JRE + development tools. 

JDK is an implementation of any one of the below given Java Platforms released by Oracle  corporation: 

o Standard Edition Java Platform 

o Enterprise Edition Java Platform 

o Micro Edition Java Platform 

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as  an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation  generator (Javadoc) etc. to complete the development of a Java Application. Components of JDK 

Following is a list of primary components of JDK: 

51.7M 

832

appletviewer: 

This tool is used to run and debug Java applets without a web browser.

apt: 

It is an annotation-processing tool.

extcheck: 

it is a utility that detects JAR file conflicts.

idlj: 

An IDL-to-Java compiler. This utility generates Java bindings from a given Java IDL  file.

jabswitch: 

It is a Java Access Bridge. Exposes assistive technologies on Microsoft Windows  systems.

java: 

The loader for Java applications. This tool is an interpreter and can interpret the class  files generated by the javac compiler. Now a single launcher is used for both  development and deployment. The old deployment launcher, jre, no longer comes  with Sun JDK, and instead it has been replaced by this new java loader.



javac: 

It specifies the Java compiler, which converts source code into Java bytecode.

javadoc: 

The documentation generator, which automatically generates documentation from  source code comments

jar: 

The specifies the archiver, which packages related class libraries into a single JAR file.  This tool also helps manage JAR files.

javafxpackager: 

It is a tool to package and sign JavaFX applications.

jarsigner: 

the jar signing and verification tool.

javah: 

the C header and stub generator, used to write native methods.

javap: 

the class file disassembler.

javaws: 

the Java Web Start launcher for JNLP applications.

JConsole: 

Java Monitoring and Management Console.

jdb: 

the debugger.

jhat: 

Java Heap Analysis Tool (experimental).

jinfo: 

This utility gets configuration information from a running Java process or crash  dump.

jmap: 

Oracle jmap - Memory Map- This utility outputs the memory map for Java and can  print shared object memory maps or heap memory details of a given process or core  dump.



jmc: 

Java Mission Control

jps: 

Java Virtual Machine Process Status Tool lists the instrumented HotSpot Java Virtual  Machines (JVMs) on the target system.

jrunscript: 

Java command-line script shell.

jstack: 

It is a utility that prints Java stack traces of Java threads (experimental).

jstat: 

Java Virtual Machine statistics monitoring tool (experimental).

jstatd: 

jstat daemon (experimental).

keytool: 

It is a tool for manipulating the keystore.

pack200: 

JAR compression tool.

Policytool: 

It specifies the policy creation and management tool, which can determine policy for  a Java runtime, specifying which permissions are available for code from various  sources.

VisualVM: 

It is a visual tool integrating several command-line JDK tools and lightweight  [clarification needed] performance and memory profiling capabilities

wsimport: 

It generates portable JAX-WS artifacts for invoking a web service.

xjc: 

It is the part of the Java API for XML Binding (JAXB) API. It accepts an XML schema  and generates Java classes.



JAR Files

A JAR (Java Archive) is a package file format typically used to aggregate many  Java class files and associated metadata and resources (text, images, etc.) into  one file to distribute application software or libraries on the Java platform. In simple words, a JAR file is a file that contains a compressed version of .class  files, audio files, image files, or directories. We can imagine a .jar file as a  zipped file(.zip) that is created by using WinZip software. Even, WinZip software  can be used to extract the contents of a .jar . So you can use them for tasks  such as lossless data compression, archiving, decompression, and archive  unpacking. 

Let us see how to create a .jar file and related commands which help us to work  with .jar files 

1.1 Create a JAR file 

In order to create a .jar file, we can use jar cf command in the following ways  as discussed below: 

Syntax: 

jar cf jarfilename inputfiles 

Here, cf represents to create the file. For example , assuming our package pack  is available in C:\directory , to convert it into a jar file into the pack.jar , we can  give the command as: 

C:\> jar cf pack.jar pack 

1. 2 View a JAR file 

Now, pack.jar file is created. In order to view a JAR file ‘.jar’ files, we can use  the command as: 

Syntax: 

jar tf jarfilename 

Here, tf represents the table view of file contents. For example, to view the  contents of our pack.jar file, we can give the command: 

C:/> jar tf pack.jar 

Now, the contents of pack.jar are displayed as follows: 

META-INF/ 

META-INF/MANIFEST.MF 

pack/ 

pack/class1.class 

pack/class2.class 

.. 

.. 

Here class1, class2, etc are the classes in the package pack. The first two  entries represent that there is a manifest file created and added to pack.jar. The  third entry represents the sub-directory with the name pack and the last two  represent the files name in the directory pack.

Note: When we create .jar files, it automatically receives the default manifest  file. There can be only one manifest file in an archive, and it always has the  pathname. 

META-INF/MANIFEST.MF 

This manifest file is useful to specify the information about other files which are  packaged. 

1.3 Extracting a JAR file 

In order to extract the files from a .jar file, we can use the commands below  listed: 

jar xf jarfilename 

Here, xf represents extract files from the jar files. For example, to extract the  contents of our pack.jar file, we can write: 

C:\> jar xf pack.jar 

This will create the following directories in C:\ 

META-INF 

In this directory, we can see class1.class and class2.class. 

pack  

1.4 Updating a JAR File 

The Jar tool provides a ‘u’ option that you can use to update the contents of an  existing JAR file by modifying its manifest or by adding files. The basic  command for adding files has this format as shown below: 

Syntax: 

jar uf jar-file input-file(s) 

Here ‘uf’ represents the updated jar file. For example, to update the contents of  our pack.jar file, we can write: 

C:\>jar uf pack.jar 

1.5 Running a JAR file 

In order to run an application packaged as a JAR file (requires the Main-class  manifest header), the following command can be used as listed: Syntax: 

C:\>java -jar pack.jar 

Developing Simple Bean Using the BDK The Bean Developer Kit (BDK) 

The Bean Developer Kit (BDK), available from the Java Soft site, is a simple example of a tool that  enables you to create, configure, and connect a set of Beans. There is also a set of sample Beans  with their source code. This section provides-step-by-step instructions for installing and using this tool. ‘In this chapter, instructions are provided for a Windows 95/98/NT environment. The procedure» for  a.UNIX platform are similar, some of the commands arc different. 

Installing the BDK

The JDK must be installed on your machine for the DDKto work. Confirm that the JOK tools are  accessible from your environment. The’BDK can then be downloaded from the Java Soft site’  (http://java.sun.com).Itis packaged as one file that is a self-extracting archive. Follow the instructions  to install it on tour machine. 

Starting the BDK 

To start the DDK, follow these steps: 1. Change to the directory c:\bdk\beanbox. 2. Execute the batcl(·file called run.bat. This causes the BDK to display the three windows  shown Toolbox lists allof the different Beans that have been included with the BDK. Bean Box  provides an area to layout and connect the Beans selected from the Too Box. Properties . 

Using the BDK 

This section describes how to create an application by using some of the Beans provided with the BDK. First, the Molecule Bean displays at three-dimensional view of a molecule. It  may be configured to present one of the following molecules: hy ironical. acid, benzene,  counterintelligence, anticyclone, ethane, or water. This compos net also has methods that allow the  molecule to be rotated in space along its X or Y axis. -Second, the Our Bean provides a push-button  functionality. We will have one. 

Create and Configure an Instance of the ,Molecule Bean Follow these steps to create o,.md configu.re an instance of the Molecule Bean. 1. Position the cursor on ‘the Tool Box entry labeled Molecule and click the left mouse button. You should see the cursor change to a cross. 

2. Move the cursor to the Bean Box display area and click the left mouse button in approximately the area where you wish the Bean to be displayed. You should see a rectangular region appear that contains a display of a molecule. This areas surrounded by a hatched. border, indicating that it is currently selected. 3. You can preposition the Molecule Bean by positioning the cursor over one of the hatched borders and dragging the Bean. 4. You can change the molecule that is displayed by changing the selection in the Properties window. Notice that the Bean display changes immediately when you change the selected molecule. 

The java bean API 

The JSP API 

The JSP API consists of two packages: 

1. javax.servlet.jsp 

2. javax.servlet.jsp.tagext 

javax.servlet.jsp package 

The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as  follows:

1. JspPage 

2. HttpJspPage 

The classes are as follows: 

o JspWriter 

o PageContext 

o JspFactory 

o JspEngineInfo 

o JspException 

o JspError 

The JspPage interface 

According to the JSP specification, all the generated servlet classes must implement the  JspPage inter\\face. It extends the Servlet interface. It provides two life cycle methods.Stock  Purchase 

Methods of JspPage interface 

1. public void jspInit(): It is invoked only once during the life cycle of the JSP when JSP page  is requested firstly. It is used to perform initialization. It is same as the init() method of  Servlet interface. 

2. public void jspDestroy(): It is invoked only once during the life cycle of the JSP before  the JSP page is destroyed. It can be used to perform some clean up operation. 

The HttpJspPage interface 

The HttpJspPage interface provides the one life cycle method of JSP. It extends the  JspPage interface. 

Method of HttpJspPage interface: 

1. public void _jspService(): It is invoked each time when request for the JSP page comes  to the container. It is used to process the request. The underscore _ signifies that you  cannot override this method.

We will learn all other classes and interfaces later. 

Advantages 

Beans are persistable and can be stored and retrieved back from permanent storage. A bean can be customized and manipulated by some auxiliary software. We can control what properties, methods, and events are to be exposed to the  application that wants to use it. 

A bean can not only be registered to receive events send by another object, but also  generate events. 

Disadvantages 

The benefits of immutable objects are absent in beans because they are by default  mutable. 

Because every Java bean must have a no-argument constructor (nullary constructor),  this may lead to an object being instantiated in an invalid state. 

Bean classes contain much boilerplate code because, as per specification, most or all  private properties must be exposed through public getters and setters. This often leads  to writing many unnecessary codes. 

Introduction to JDBC  

What is JDBC? 

JDBC stands for Java Database Connectivity, which is a standard Java API for database independent connectivity between the Java programming language and a wide range of  databases. 

The JDBC library includes APIs for each of the tasks mentioned below that are commonly  associated with database usage. 

Making a connection to a database. 

Creating SQL or MySQL statements. 

Executing SQL or MySQL queries in the database. 

Viewing & Modifying the resulting records. 

Fundamentally, JDBC is a specification that provides a complete set of interfaces that  allows for portable access to an underlying database. Java can be used to write different  types of executables, such as − 

Java Applications 

Java Applets 

Java Servlets 

Java ServerPages (JSPs) 

Enterprise JavaBeans (EJBs).

All of these different executables are able to use a JDBC driver to access a database,  and take advantage of the stored data. 

JDBC provides the same capabilities as ODBC, allowing Java programs to contain  database-independent code. 

Pre-Requisite 

Before moving further, you need to have a good understanding of the following two  subjects − 

Core JAVA Programming 

SQL or MySQL Database 

JDBC Architecture 

The JDBC API supports both two-tier and three-tier processing models for database  access but in general, JDBC Architecture consists of two layers − 

JDBC API − This provides the application-to-JDBC Manager connection. JDBC Driver API − This supports the JDBC Manager-to-Driver Connection. 

The JDBC API uses a driver manager and database-specific drivers to provide  transparent connectivity to heterogeneous databases. 

The JDBC driver manager ensures that the correct driver is used to access each data  source. The driver manager is capable of supporting multiple concurrent drivers  connected to multiple heterogeneous databases. 

Following is the architectural diagram, which shows the location of the driver manager  with respect to the JDBC drivers and the Java application − 

Common JDBC Components 

The JDBC API provides the following interfaces and classes −

DriverManager − This class manages a list of database drivers. Matches  connection requests from the java application with the proper database driver using  communication sub protocol. The first driver that recognizes a certain subprotocol  under JDBC will be used to establish a database Connection. 

Driver − This interface handles the communications with the database server. You  will interact directly with Driver objects very rarely. Instead, you use DriverManager  objects, which manages objects of this type. It also abstracts the details associated  with working with Driver objects. 

Connection − This interface with all methods for contacting a database. The  connection object represents communication context, i.e., all communication with  database is through connection object only. 

Statement − You use objects created from this interface to submit the SQL  statements to the database. Some derived interfaces accept parameters in addition  to executing stored procedures. 

ResultSet − These objects hold data retrieved from a database after you execute  an SQL query using Statement objects. It acts as an iterator to allow you to move  through its data. 

SQLException − This class handles any errors that occur in a database  application. 

The JDBC 4.0 Packages 

The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC  version at the time of writing this tutorial. It offers the main classes for interacting with  your data sources. 

The new features in these packages include changes in the following areas − Automatic database driver loading. 

Exception handling improvements. 

Enhanced BLOB/CLOB functionality. 

Connection and statement interface enhancements. 

National character set support. 

SQL ROWID access. 

SQL 2003 XML data type support. 

Annotations. 

Types of JDBC Connectivit(Accessing Relation  Database from java programs) 

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute  the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses  JDBC drivers to connect with the database. There are four types of JDBC drivers: o JDBC-ODBC Bridge Driver, 

o Native Driver, 

o Network Protocol Driver, and

o Thin Driver 

We have discussed the above four drivers in the next chapter. 

We can use JDBC API to access tabular data stored in any relational database. By the help  of JDBC API, we can save, update, delete and fetch data from the database. It is like Open  Database Connectivity (ODBC) provided by Microsoft. 

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is  based on the X/Open SQL Call Level Interface. The java.sql package contains classes and  interfaces for JDBC API. A list of popular interfaces of JDBC API are given below: 41.8M 

781 

HTML Tutorial 

o Driver interface 

o Connection interface 

o Statement interface 

o PreparedStatement interface 

o CallableStatement interface 

o ResultSet interface 

o ResultSetMetaData interface 

o DatabaseMetaData interface 

o RowSet interface 

A list of popular classes of JDBC API are given below: 

o DriverManager class 

o Blob class 

o Clob class 

o Types class 

Why Should We Use JDBC 

Before JDBC, ODBC API was the database API to connect and execute the query with the  database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform  dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses  JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform the  following activities: 

1. Connect to the database 

2. Execute queries and update statements to the database 

3. Retrieve the result received from the database. 

Establishing database connection 

There are 5 steps to connect any java application with the database using JDBC. These steps are as follows: o Register the Driver class 

o Create connection 

o Create statement 

o Execute queries 

o Close connection 

1) Register the driver class 

The forName() method of Class class is used to register the driver class. This method is used to dynamicallydriver class. 

Syntax of forName() method 

Example to register the OracleDriver class 

Here, Java program is loading oracle driver to esteblish database connection. 

1. Class.forName("oracle.jdbc.driver.OracleDriver"); 

2) Create the connection object 

The getConnection() method of DriverManager class is used to establish connection with the database. 

Syntax of getConnection() method 

1. 1) public static Connection getConnection(String url)throws SQLException  

2. 2) public static Connection getConnection(String url,String name,String password)  3. throws SQLException  

Example to establish connection with the Oracle database 1. Connection con=DriverManager.getConnection(  

2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");  

3) Create the Statement object 

The createStatement() method of Connection interface is used to create statement. The object of statement is reto execute queries with the database. 

Syntax of createStatement() method 

1. public Statement createStatement()throws SQLException  

Example to create the statement object 

1. Statement stmt=con.createStatement();  

4) Execute the query 

The executeQuery() method of Statement interface is used to execute queries to the database. This method reobject of ResultSet that can be used to get all the records of a table. 

Syntax of executeQuery() method 

1. public ResultSet executeQuery(String sql)throws SQLException  

Example to execute query 

1. ResultSet rs=stmt.executeQuery("select * from emp");  

2.  

3. while(rs.next()){  

4. System.out.println(rs.getInt(1)+" "+rs.getString(2));  

5. } 

5) Close the connection object 

By closing connection object statement and ResultSet will be closed automatically. The close() method of Cointerface is used to close the connection. 

Syntax of close() method 

1. public void close()throws SQLException 


No comments:

Post a Comment