Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, February 14, 2011

java SQL basics 3 : Understanding JDBC Drivers


JDBC drivers are divided into four types or levels. 

The different types of jdbc drivers are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)

Type 1 JDBC Driver

JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.



Type 1: JDBC-ODBC Bridge
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
let us learn more..

Java SQL basics 2 : Working with ResultSet Objects in JDBC.


IF you come here directly- you are suggested to read the article http://codingbasics.blogspot.com/2011/02/java-sql-basics-1-processing-sql.html

Updating Rows in ResultSet Objects

You cannot update a default ResultSet object, and you can only move its cursor forward.
However, you can create ResultSet objects that can be scrolled (the cursor can move backwards or move to an absolute position) and updated.

The following method, multiplies the PRICE column of each row by the argument percentage:

  public void modifyPrices(float percentage) throws SQLException {
    Statement stmt = null;
    try {
      stmt = con.createStatement();
      stmt = con.createStatement(
        ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
      ResultSet uprs = stmt.executeQuery(
        "SELECT * FROM " + dbName + ".COFFEES");


      while (uprs.next()) {
        float f = uprs.getFloat("PRICE");
        uprs.updateFloat("PRICE", f * percentage);
        uprs.updateRow();
      }


    } catch (SQLException e ) {
      JDBCTutorialUtilities.printSQLException(e);
    } finally {
      stmt.close();
    }
  }
The field ResultSet.TYPE_SCROLL_SENSITIVE creates a ResultSet object whose cursor can move both forward and backward relative to the current position
 and to an absolute position. The field ResultSet.CONCUR_UPDATABLE creates a ResultSet object that can be updated.

The method ResultSet.updateFloat updates the specified column (in this example, PRICE with the specified float value in the row where the cursor is positioned.
ResultSet contains various updater methods that enable you to update column values of various data types.
However, none of these updater methods modifies the database; you must call the method ResultSet.updateRow to update the database.
Learn about Batch Updates using Statement Objects

Java SQL basics 1 : Processing SQL statements with JDBC


In general, to process any SQL statement with JDBC, you follow these steps:

  • Establishing a connection.
  • Create a statement.
  • Execute the query.
  • Process the ResultSet object.
  • Close the connection.

  public static void viewTable(Connection con, String dbName) throws SQLException {
    Statement stmt = null;
    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from " + dbName + ".COFFEES";
    try {
      stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(query);
      while (rs.next()) {
        String coffeeName = rs.getString("COF_NAME");
        int supplierID = rs.getInt("SUP_ID");
        float price = rs.getFloat("PRICE");
        int sales = rs.getInt("SALES");
        int total = rs.getInt("TOTAL");
        System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
      }
    } catch (SQLException e ) {
      JDBCTutorialUtilities.printSQLException(e);
    } finally {
      stmt.close();
    }


Lets break each step and understand the code

Thursday, January 27, 2011

Most frequently used Regular Expressions in Java.


Username :
------------


 ^[a-z0-9_-]{3,15}$

Notes :

 ^             Start of the line
[a-z0-9_-]   supported chars and symbols in the list:  a-z, 0-9 , underscore ,hyphen
{3,15}         Length at least 3 characters and maximum length of 15
$         End of the line.


Password :
----------

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})

Notes :

  (?=.*\d)  must contains one digit from 0-9
  (?=.*[a-z])  must contains one lowercase characters
  (?=.*[@#$%])  must contains one special symbols in the list "@#$%"

Let us see more

Thursday, January 13, 2011

Parse XML with Java - SAX and DOM parser

Parsing XML Documents

To process the data contained in XML documents, you need to write a application program (in a programming language such as Java, JavaScript). The program makes use of an XML parser to tokenize and retrieve the data/objects in the XML documents. An XML parser is the software that sits between the application and the XML documents to shield the application developer from the intricacies of the XML syntax. The parser reads a raw XML document, ensures that is well-formed, and may validate the document against a DTD or schema.
There are two standard APIs for parsing XML documents:
  1. SAX (Simple API for XML)
  2. DOM (Document Object Model)
SAX is an event-driven API. The SAX API defines a number of callback methods, which will be called when events occur during parsing. The SAX parser reads an XML document and generate events as it finds elements, attributes, or data in the document. There are events for document start, document end, element start-tags, element end-tags, attributes, text context, entities, processing instructions, comments and others.

DOM is an object-oriented API. The DOM parser explicitly builds an object model, in the form of a tree structure, to represent an XML document. Your application can then manipulate the nodes in the tree. DOM is a platform- and language-independent interface for processing XML documents. The DOM API defines the mechanism for querying, traversing and manipulating the object model built.

The JAXP (Java APIs for XML Processing) provides a common interface for creating, parsing and manipulating XML documents using the standard SAX, DOM and XSLTs.
More Information with a  detailed example

Friday, January 7, 2011

Log4j Implmentation with an example.

Article discusses the following
-------------------------------------------------


What is Log4j.
Example Implementation 
About Log level , appender, Layout in Log4j

Log4j is an OpenSource logging API developed under the Jakarta Apache project.Log4j allows developers to insert log statements in their code and configure them externally.

Logically, log4j can be viewed as being comprised of three main components: logger, appender, and layout namely. The functionalities of each of these components are accessible through Java classes of the same name. Users can extend these basic classes to create their own loggers, appenders, and layouts. 

You can download the current version of log4j from the project home page.
http://logging.apache.org/log4j/

Log4j can be configured with two ways : log4j.properties(tradtional way)  , Log4j.xml( More and more applications are adopting to this now).

Log4j.properties example
-------------------------
--------

  • Create a Java project.
  • Add the log4j.jar to the build path of the project.
  • Create a file named log4j.properties in the src folder with the following content.
          ### direct log messages to stdout ###
          log4j.appender.stdout=org.apache.log4j.ConsoleAppender
         log4j.appender.stdout.Target=System.out
        log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
        log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
        log4j.rootLogger=debug, stdout

------  click below to read More ( no need to click in case of a full page view) ---

Thursday, January 6, 2011

Aspect Oriented Programming - What is it , Why is it for me and How to do it



Enough of the Jargons ... Procedure Oriented, Object Oriented....and now
 what is Aspect Oriented Programming ?




What is Aspect Oriented Programming ?
Just imagine you have system for which you need add a set of  log statements
at the run-time. and say you should not modify the sources. How do you do it ?

OR put it in other way , say your application which is in execution needs
to be audited -say how many lines code is modified by each test case ?
This can be done by an adding a  counter in you testcase for each line
it accesses. Easy to do it at source if there are say, 10 test cases.
But , just imagine doing it for some 10000 test cases. We can simply forget
doing anything at the source level in these scenarios since this book- keeping
activity will consume lot of man-days and we would be more than happy if
we can hook something to our tests at the time of execution rather
than doing this at source level.This is exactly what AOP does for us.

AOP is very useful in cases of  are like  auditing, logging, security,
exception handling without having to modify the original business logic sources.
( Let us understand  each of these issues as "concerns" that are cross-cutting
 the breadth of the application )

---------click below on "more" for a detailed complete application --------

Tuesday, January 4, 2011

Invoke a java webservice from browser using javascript ( xmlhttp)

Have you felt tired of seeing pages of matter on invoking a webservice from browser without much understanding . Let us try our way.

The tutorial will have two sections :
1. A simple java method exposed as a webservice ( using java embedded webserver. No need of axis, tomcat etc.,)
2. A simple html page which will invoke the webservice ( no need of php , jsp etc., ) with a simple xmlhttp request / reposnse.

Two steps for Creating and Publishing Webservice using jax-ws:


1) create a java class and add methods which will be exposed as webservices. To make normal java methods as webservices we have to annotate the methods using @WebMethod annotaiion. Java class must be annotated with @WebService annotation. To Customize the parameter names in the request use @WebParam annotation

Example: This example exposes the webservices to calculate the area of suare and rectangle.

package com.example.ws;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;

@WebService
public class Area {

@WebMethod
public double square(@WebParam(name="side") double side)
{
return side * side;
}

@WebMethod
public double rectangle(@WebParam(name="length") double length,@WebParam(name="breadth") double breadth)
{
return length * breadth;
}

public static void main(String[] args) {
Area area = new Area();
String url = "http://localhost:8090/area"; // end point of webservice.
System.out.println(url+"?wsdl");
Endpoint.publish(url, area); // publishing the webservice
}
}

2) Run the below command from source location
apt -d . com\example\ws\Area.java
This command will generate the required wrapper classes one correspoding to request and other corresponding to response.

Now your webservice is ready to use. Just run the class com.example.ws.Area

you can view the wsdl of the service using url http://localhost:8090/area?wsdl

Hope you are getting it running.

Calling webservice from browser using XMLHttpRequest
The webserive exposed can be accessed using soap request sending from browser


<html>
<head>
<script language="javascript">
function call()
{
var side = sideid.value;
var req = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://ws.example.com/\"><soapenv:Body><web:square><side>" + side+ "</side></web:square></soapenv:Body></soapenv:Envelope>";
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var reqXML = xmlDoc.loadXML(req);
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response = xmlhttp.responseXML;
alert(response.selectSingleNode(".//return").text);
}
}
var soapaction = "http://ws.example.com/square";
xmlhttp.open("POST","http://localhost:8090/area?wsdl",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.setRequestHeader("SOAPAction", soapaction);
xmlhttp.send(req);
}
</script>
</head>
<body>
Side Length: <input type="text" id="sideid"></input>
<button onclick="call();">area of square</button>
</body>
</html>



Donot forget to give your comments /suggestions and refer to your friends.

Welcome to the world of real world programming- Java , JavaScript, .Net, webservices , XML, JQuery etc.,

Hi Folks..

Thank you for visiting this blog.
We are senior pros in IT coming together to post interesting programming fragments which come in handy for day-to-day help for developers.

Your suggestions / any specific help that is needed for you  with coding will be welcome by us and we will do our best to post solutions.

At present we will focus on Java , JavaScript, .Net, webservices , XML, SOA, JQuery
Going forward we will extend this to other areas of programming as well.
In this Journey, most of the articles - will be our own implementations since the theme is to present to the readers a code that is running well - that is simple and well understood. But, we also get inspired by few articles on the web and bring them here for the best of interest reaching out the best to everyone.

subversion video