Tuesday, December 20, 2016

SOAP and REST.

Web Services
  • Transport Protocols : SOAP, REST
  • Respective registries to shared data.
  • Message integrity and non-repudiation
  • Reliable messaging
  • Business process flow
  • Protocol negotiation
  • Security
  • Transactions and process flow
  • Data independence for programming languages, middle-ware systems and DBMS
    • typing
    • structure
    • semantic information associated with data (mapping, transformation, creation)

Components for Web Services
  • XML: Extensible Markup Language
  • WSDL : fundamental abstraction of Web services as interface to underlying software
  • SOAP/REST : communication protocol over internet and networks
  • UDDI : Providing registry and repository services for storing and retrieving Web services interfaces

WSDL : Web Services Description Language
  • A mechanism to describe Web Services
    • data types
    • data structures
    • define interfaces
    • associate services with underlying implementations in each interface
      • how to map the types and structures into the messages to be exchanged
      • how to tie the messages to underlying implementations
  • A definition of service to map to communication protocols and transports such as SOAP messages.
    • both parties interact by sharing a common WSDL file.
    • sender uses the WSDL file to generate the messages.
    • receiver uses the WSDL file to parse the message and map it to underlying program.
  • The goal is that the parts can be developed separately and integrated as a comprehensive WSDL file.

UDDI : Universal Description, Discovery, and Integration

SOAP : Simple object Access Protocol

  • Understanding SOAP from IBM
  • Defines a common format for XML messages over HTTP and other protocols.
  • SOAP is designed so that it can be extended to additional features and functions.
  • SOAP is a one-way asynchronous messaging technology.
  • SOAP can be used in various messaging styles, from RPC (remote procedure calls) to document oriented publishing and subscription.
  • Minimum criterion for a Web service must support SOAP.

Example of Simple SOAP Envelope
<?xml version='1.0' ?>
<env:envelope xmlns:env="http://www.w3.org/2003/05/SOAP-envelope"> 
  <env:header>
  </env:header>
  <env:body>
  </env:body>
</env:Envelope>
Example of SOAP Header with Routing Information
<?xml version='1.0' ?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/SOAP-envelope"> 
  <env:header>
    <wsa:ReplyTo xmlns:wsa=
        "http://schemas.xmlSOAP.org/ws/2004/08/addressing">
      <wsa:Address>
         http://schemas.xmlSOAP.org/ws/2004/08/addressing/role/anonymous
      </wsa:Address>
    </wsa:ReplyTo>
  </env:header>
  <env:body>
  </env:body>
</env:Envelope>

REST, RESTlet, RESTful : REpresentation State Transfer



Wednesday, December 7, 2016

Software Terms.

Framework and Software Testing
  • A framework is a semi-complete application that provides a reusable and common structure to share among developers who can incorporate it into their own application and extend it to their specific needs. 
  • A framework has a more coherent structure than a toolkits with a set of utility classes.
  • For example, JUnit (www.junit.org) is a framework created by Erich Gamma and Kent Beck in 1997, following an earlier work called SUnit.
  • Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides wrote the classic "Design Patterns : Elements of Reusable Object-Oriented Software" book in 1995 and the four authors are often referred to as the Gang of Four (GoF).
  • Kent Beck's software discipline: Extreme Programming

Types of Testing
  • Programmer Test or customer test
  • Unit test: confirms the method (or a unit of work) accepts the expected range of input and returns the expected output value for each input.
    • API contract provides a view of expected behavior by method signature.
    • Notion of API contract
    • An exception should be thrown if the method cannot fulfill the contract.
  • Integration tests
  • Acceptance tests
  • Functional tests / Behavioral tests
    • web page links
    • database connection
    • forms
    • cookies
  • Usability tests
    • efficiency
    • navigation
    • UI
    • content checking
    • visual style
  • Compatibility tests
    • browser compatibility
    • OS
    • mobile browser
    • printing options
  • Performance tests
    • traffic
    • loads
    • stress testing
  • Security tests
    • authentication and authorization
    • session management
    • cryptography and SSL
    • data validation
    • denial of service
    • risky activities



Tuesday, December 6, 2016

Java Interface and Exception.

Understanding Interfaces and Abstract Methods
  • To define what a class must do but not how to do it until later in specific application.
    • An abstract class define its signature and return types, namely, its interface for multiple processes or methods without implementations.
  • How? Specify methods with no body ({}).
  • Actions are defined in a class that implements the interface.
  • One interface, multiple methods is the essence of polymorphism.
  • Prior to JDK 8, interfaces could not define any implementation whatsoever. JDK 8 changes the rule so that default implementation to an interface method is allowed.
  • The original intent behind interface/abstract class remains. and default implementation in essence is a special use feature.
  • JDK 8 also added the ability to define static methods in interfaces.
    • Same as static methods in a class, static methods in interfaces can be called independently of any object created from it.
    • Yes, no implementation or instance of the interface is required to call a static method.
    • To call, specify the interface name, a period and the method name.
    • Static interface methods are not inherited by implementing class or a sub-interface extended from the parent interface.

Using Interface References
  • You can create an interface reference variable and use it to refer to any object that implements its interface. 
  • When you call a method on an object through an interface reference, you are calling the version of the method implemented by the object that is executed at runtime. 
  • This is similar as using a superclass reference to access a child class's methods on its objects. 

Using Interface to Share Constants
  • Though controversial, one usage of interface is to share constants among multiple classes.
  • Variables in interfaces are implicitly public, static and final and these are the characteristics of constants.
  • Examples of applications includes array size, various limits, special values and the like.

Extending Interface
  • An interface can inherit another interface by extending. 
  • When a class implements the derived interface, it must implement all methods in the inheritance chain.
interface X {
   void method1 ();
   void method2 ();
}

interface Y extends X {
   void method3 ();
}

class Z implements Y {
   public void method1 () {
      // do something...
   }
   public void method2 () {
      // do something...
   }
   public void method3 () {
      // do something...
   }
}

class Z2 implements Y {
   // implements all three methods
}

// Using Interface References
class Demo {
   public static void main (String args[]) {
   Z  obz  = new Z();
   Z2 obz2 = new Z2();
   X  obx  = new X();
   obx = obz;
   System.out.println ("Class z attribute is " + obx.getAttribute());
   obx = obz2;
   System.out.println ("Class z2 attribute is " + obx.getAttribute());
}


Exceptions
  • All exceptions are represented by classes.
  • All exceptions are derived from "Throwable" class.
  • When an exception occurs, an object of some exception class is generated.
  • Two direct subclasses of Throwable: Exception and Error.
    • Class Error exceptions are those occur in JVM, not in the program.
    • Class Error exceptions are usually beyond programmer's control.
    • Class Exception exceptions are those from program activity, such as divide-by-zero, array out-of-boundary and file-not-found errors. These are called standard exceptions.
    • Class Exception exceptions should be handled in the program.
      • RuntimeException is an important subclass of Exception class and is used to represent various common types of runt-time errors.
  • Another type of exceptions are those thrown manually by using throw statement.

Exceptions Handling
  • try
    • If an exception occurs within the try block, it is thrown.
  • catch
    • If an exception is thrown by try block, it will be handled here in a predictable way.
  • throw
    • Use throw to manually throw an exception.
  • throws
    • Use throws clause in the declaration of a method to specify an exception could be thrown out of a method.
  • finally
    • Use finally block to specify any activity that must be executed upon exiting from a try block.


Monday, December 5, 2016

JAVA Tips and Gotchas.


  • Overloading - if the number of parameters are different, the return type can be different. But the return type cannot be used to differentiate the methods.
  • Static blocks is executed when the class is first loaded before the class can be used anywhere else, and thus can be used to initialize members before the class is constructed.
  • Recursive versions of many routines may execute a bit more slowly than their iterative equivalents because of the additional overhead of the additional method calls.
  • Inner class - a class inside a class but outside of any method.
  • Nested class - a class inside a method.
  • Autoboxing - occurs when a primitive type must be converted into an object. Vice versa, auto-unboxing happens whenever an object must be converted into a primitive type. (Say, between int and Integer)
  • Use 'import static' - called static import - to refer to static members of a class directly by their names, without  having to qualify them with the class name.
  • @Annotation (Metadata) - used by frameworks in development and deployment.
    • @Retention
    • @Target
    • @Inherited
    • @Override
    • @Deprecated
    • @SafeVarargs
    • @SuppressWarnings
    • @FunctionalInterface
  • In Java 8, you can specify a variable-length argument (varargs) by three periods (...)
Example
// If mixing normal and varargs parameters, the variable-length
// parameter must be the only and the last one.
static void myVarMethod (int a, double b, String c, int ... v) {
   for ( int i=0; i < v.length; i++ ) {
      system.out.println ("index-" + i + " = " + v[i]);
   }
}

public void main (String args[]) {
   myVarMethod (5, 1, 3);
   myVarMethod (2);
   myVarMethod ();
}


import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
// Not a good practice as out.println is now ambiguous
import static java.lang.System.out;

// Now you can call these methods directly
double x = sqrt (pow(a, 4) - b*c);
double x = (-b + sqrt (pow(b, 2) - 4*a*c)) / (2*a);
out.println ("The solution is ", + x);


Java Generics
class ClassGeneric  {
   T obj;

   ClassGeneric (T o) {
      this.obj = o;
   }

   T getObj() {
      return obj;
   }

   void printType () {
      System.out.println ("Type of this object is " + 
         obj.getclass().getName() );
   }
}

// To use ClassGeneric
class Demo {
   public static void main (String args[]) {
      ClassGeneric  instanceOfT;
      instanceOfT = new ClassGeneric  (23);
      instanceOfT.printType();

      ClassGeneric  instanceOfStr = new ClassGeneric ("My String");
      instanceOfT.printType();
   }
}



Friday, December 2, 2016

JDBC demystified.


JDBC (Java DabaBase Connectivity) is an API interface for relational databases connections, such as Oracle RDBMS, SQL Server, MySQL, and Microsoft SQL DB.

In Java 7 includes JDBC 4.1 reduces the amounts of code required to work with databases. It is most commonly used as in web-based applications hosted in J2EE servers, including JBOSS, Tomcat, WebSphere.

Android has its own API SQLite to work with local database. Calls can be made from Android application to access larger databases through web services hosted by middleware servers.

The Spring application framework includes something called JDBC Template. It simplifies the amount of code using JDBC to talk to the database. Hibernate is the most popular data mapping APIs using an object-relational mapping mechanism. It represents the database structure with Java classes and objects. In the background it's still using JDBC to communicate with the database.

Applications that use the JDBC API require drivers. A JDBC driver is a software library that encapsulates the logic required to communicate between the application and the database management system. JDBC driver rules are defined in Java Standard Edition.

A driver library package will contain specific implementations of these Java interfaces.
  • Connection - which lets you connect to the database, 
  • ResultSet - which encapsulates data returned from the database, 
  • Statement - requests to the database
  • PreparedStatement - represent requests to the database
  • CallableStatement - represent requests to the database

Typically, a driver package can be downloaded from the database vendors themselves, a MySQL driver from MySQL an Oracle driver for Oracle, et cetera. Most of JDBC drivers will support these five interfaces.

There are four distinct types of drivers, distinguished by their architecture.

Type 1 JDBC Driver
  • JDBC-ODBC bridge driver + ODBC driver
    • it is the oldest type. 
    • Installed on the client system.
    • Started in the mid to late '90s when JDBC got started, ODBC or the Open Database Connectivity protocol was the dominant model for communicating with the database. 
    • At runtime, requests go from the application through the JDBC API to the Bridge driver from there to the ODBC driver and then to the database. 
  • Not fast, but it is dependable, 
  • Can work with any database for which an ODBC driver existed (pretty much every RDBMS) 
  • Cons: 
    • the ODBC Bridge driver is not 100% Java and therefore not portable between operating systems. 
    • working with two drivers and both have to be on the same computer as the application, so you have increased maintenance.
    • the ODBC driver has to match the database version, and so if database on the server, is updated, all the client applications have to be updated as well. 

Type 2 JDBC Driver
  • Native protocol API driver + Java driver
    • Both are installed on the client system just like the Bridge driver and ODBC driver.
  • Fast - because primarily working with native APIs, you get the best performance.

  • Not 100% Java so it's not portable between operating systems.
  • The native API driver has to be installed on the application client and maintained, and once again, if the database is updated, the client software has to be updated as well.

Type 3 JDBC Driver
  • Net protocol + Java driver
    • installed in multiple locations
    • 100% Java driver that's installed in the client along with the application
    • a middleware server which hosts its own application
  • requests go at runtime from the application to the Type 3 driver that's installed on the client, to the network to the middleware server and then to the database.
  • The middleware driver can be native, and so the communication between the middleware and the database can be very fast.
    • but at the cost of the maintenance challenges with more than one driver to maintain. 

Type 4 JDBC Driver
  • All 100% Java thin driver + 100% Java driver
    • the most common.
    • Only one driver package with Java application itself.
    • Can be on a client computer, in a web environment on J2EE server.
  • Requests go from the application to the driver that's on the client and then through JDBC through the thin driver to the database server if it's out on the web, or to the database file if it's on the local hard disk. 
  • With the Java thin driver, you're communicating directly from the application to the database. No additional layers to install or maintain so maintenance is greatly simplified. 
  • Cons: a different driver package is needed for each database to work with.

Working with Multiple Database Types in Single Application
  • Most applications will only use a single database type, but if you're working with more than one database management system, you'll need to provide multiple drivers. 
  • For example, you may have one MySQL database server hosted in the Cloud that is accessible over the web and an Apache Derby SQL Database that is initialized with local files and runs in the same Java process of the application.
  • Use Type 4 pure Java drivers to make the code as portable as possible. That's the idea of encapsulated applications.

Simple Type 4 Java driver example
private Connection getConnection (String dbName) {
    Connection connection = null;
    try {
        String dbDirectory = "./Resources";
        System.setProperty("derby.system.home", dbDirectory);
        String dbUrl = "jdbc:derby:" + dbName + ";create=true";

        connection = DriverManager.getConnection (dbUrl);
        return connection;
    }
    catch (SQLException e) {
        for (Throwable t : e) t.printStackTrace();
        System.err.println(e);
        return null;
    }
}

private void getResultSet (Connection cn) {
    String sql  = "SELECT * FROM Runners ";
        try ( PreparedStatement ps = cn.prepareStatement(sql);
              ResultSet rs = ps.executeQuery();
        ) {
              readRS(rs);
              disconnect();
        }
        catch (SQLException e) {
              System.err.println(e);
        }
}

private void readRS (ResultSet rs) {
    try {
        while (rs.next()) {
            ThreadRunner t = new ThreadRunner 
                (rs.getString(1), rs.getInt(2), rs.getInt(3));
            t.setName(rs.getString(1));
            runners.add( t );
         }
     }
     catch (SQLException e) {
         System.err.println(e);
     }
}

private boolean disconnect () {
    try {
        String shutdownURL = "jdbc:derby:;shutdown=true";
        DriverManager.getConnection(shutdownURL);
    }
    catch (SQLException e) {
        if (e.getMessage().equals(
             "Derby system shutdown."))
        return true;
    }
    return false;
}