Search This Blog

Tuesday, December 10, 2019

Web Services in Java


Web Service:
·         Web services are client and server applications that communicate over the World Wide Web’s (WWW) HyperText Transfer Protocol (HTTP).
·         As described by the World Wide Web Consortium (W3C), web services provide a standard means of interoperating between software applications running on a variety of platforms and frameworks.
·         Web services are characterized by their great interoperability and extensibility, as well as their machine-processable descriptions, thanks to the use of XML.
·         Web services can be combined in a loosely coupled way to achieve complex operations. Programs providing simple services can interact with each other to deliver sophisticated added-value services.

Loosely Coupled:

In computing and systems design a loosely coupled system is one in which each of its components has, or makes use of, little or no knowledge of the definitions of other separate components.
Subareas include the coupling of classes, interfaces, data, and services.[1] Loose coupling is the opposite of tight coupling.

Types of Web Services in Java

1.       Java API for XML Web Services (JAX-WS)
·         Big web services use XML messages that follow the Simple Object Access Protocol (SOAP) standard, an XML language defining a message architecture and message formats.
·         systems often contain a machine-readable description of the operations offered by the service, written in the Web Services Description Language (WSDL), an XML language for defining interfaces syntactically.
A SOAP-based design must include the following elements.
·         A formal contract must be established to describe the interface that the web service offers.
·         WSDL can be used to describe the details of the contract, which may include messages, operations, bindings, and the location of the web service
·         The architecture must address complex nonfunctional requirements.  Examples include transactions, security, addressing, trust, coordination, and so on.
·         The architecture needs to handle asynchronous processing and invocation.

1.       Java API for RESTful Web Services (JAX-RS).

In Java EE 6, JAX-RS provides the functionality for Representational State Transfer (RESTful) web services. 
RESTful web services, often better integrated with HTTP than SOAP-based services are, do not require XML messages or WSDL service–API definitions.
                A RESTful design may be appropriate when the following conditions are met.
·         The web services are completely stateless. A good test is to consider whether the interaction can survive a restart of the server
·         A caching infrastructure can be leveraged for performance. If the data that the web service returns is not dynamically generated and can be cached, the caching infrastructure that web servers and other intermediaries inherently provide can be leveraged to improve performance.
·         The service producer and service consumer have a mutual understanding of the context and content being passed along.
·         Bandwidth is particularly important and needs to be limited.
·         Web service delivery or aggregation into existing web sites can be enabled easily with a RESTful style
·         Developers can use such technologies as JAX-RS and Asynchronous JavaScript with XML (AJAX) and such toolkits as Direct Web Remoting (DWR) to consume the services in their web applications.


Saturday, May 17, 2014

Simulate Java StackOverFlow Exception



Stack memory:
  Let me describe  high level detail of stack memory, To execute any program we need to allocate two type of memory in processor(RAM).
     One is stack Memory -  The memory used for executing the program in processor.
   Second is Heap Memory- This memory is nothing but to Store the data(Object) in processor.


Stack Memory  will be start used, when program start from main method to the other  method execution.

Example :
Start using stack memory:  main-> method1-> Method 2->..... > Method N
Release stack memory :Method N (execution Over) -> Method N-1 ->  .............. > Method1->main

Below Program  stack memory are not released due to recursive   call of method1(). So it will throw stack over flow exception.




package com.blogspot.microtechinfo;

public class JavaStackOverFlow {

          private static int count=0;
         
          /**
           * @param args
           */
          public static void main(String[] args) {
                   // TODO Auto-generated method stub
                  
                             method1();
                  
          }
          private static void method1()
          {
                  
                   try{
                            
                             System.out.println("count="+ ++count);
                  method1();
                   }
                   catch (Exception e) {
                             // TODO: handle exception
                             e.printStackTrace();
                             System.exit(1);
                   }
                  
                  
          }
         
}


 Output:
  count=4484
count=4485
count=4486
count=4487
count=4488
count=4489
count=4490
Exception in thread "main" java.lang.StackOverflowError
          at sun.nio.cs.SingleByteEncoder.encodeArrayLoop(Unknown Source)
          at sun.nio.cs.SingleByteEncoder.encodeLoop(Unknown Source)
          at java.nio.charset.CharsetEncoder.encode(Unknown Source)
          at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
          at sun.nio.cs.StreamEncoder.write(Unknown Source)
          at java.io.OutputStreamWriter.write(Unknown Source)
          at java.io.BufferedWriter.flushBuffer(Unknown Source)
          at java.io.PrintStream.write(Unknown Source)
          at java.io.PrintStream.print(Unknown Source)
          at java.io.PrintStream.println(Unknown Source)

          at com.blogspot.microtechinfo.JavaStackOverFlow.method1(JavaStackOverFlow.java:21)



Simulate Java OutOfMemoryError

Simulate Java OutOfMemoryError
Here am simulating java OutOfMemoryError, lets discuss brief details about OutOfMemoryError.

Why OutOfMemoryError error will arise?
          OutOfMemoryError will arise when allotted Heap size of the Java virtual will be exceeds during runtime.

Where object will be saved in Java?
          Basically all java class objects will be saved during runtime in HeapMemory.

Sample Java Program to simulate OutOfMemoryError

In below program name is object of String, so name value will be saved to Heap space of JVM.
          Calling method1 infinite time will cause java.lang.OutOfMemoryError: Java heap space error, because below line in method1 is causing this error. If you comments below line you don’t get this error.
                         name+=";"+name;


package com.blogspot.microtechinfo;

public class JavaOutOfMemory {

            private static String  name="Marimuthu Rajagopal";
          private static int count=0;
         
          /**
           * @param args
           */
          public static void main(String[] args) {
                   // TODO Auto-generated method stub
                        while(true)
                   {
                             method1();
                   }
          }
          private static void method1()
          {
                  
                         name+=";"+name;
                   System.out.println("count="+ ++count);
                  
          }
         
}

 Output:
  
when count is 20 i will be getting  java.lang.OutOfMemoryError: Java heap space,It will vary based on machine.

count=1
count=2
count=3
count=4
count=5
count=6
count=7
count=8
count=9
count=10
count=11
count=12
count=13
count=14
count=15
count=16
count=17
count=18
count=19
count=20
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
          at java.util.Arrays.copyOfRange(Unknown Source)
          at java.lang.String.(Unknown Source)
          at java.lang.StringBuilder.toString(Unknown Source)
          at com.blogspot.microtechinfo.JavaOutOfMemory.method1(JavaOutOfMemory.java:21)
          at com.blogspot.microtechinfo.JavaOutOfMemory.main(JavaOutOfMemory.java:15)





Sunday, November 4, 2012

startsWith,endsWith Methods of String Class in Java


In this article, I am going to explains about endsWith,startsWith method in java String Class.
Let start explain about the two methods functionality.

startsWith(String arg)
                true, when the argument string is  matched with the “Prefix” of the another String, Otherwise false.
                Example :
                                String dbValue="s";
            boolean startValue="start".startsWith(dbValue);
            if(startValue)
            {
                  System.out.println("execute block of statement");
            }
            Here the value of variable startValue is “true”. So if statement will be executed and print as execute block of statement.

In real time variable dbvalue we used to get from the database/User interface. If we get the “empty” string value from the DB/UI than wired behavior will start.

I.e. we think that variable startValue is false and if statement won’t get executed, but variable  startValue will be  true and if statement get executed.


String dbValue="";
            boolean startValue="start".startsWith(dbValue);
            if(startValue)
            {
                  System.out.println("execute block of statement");
            }
Reason:
      The reason for return value true is comparison will be taken care by character sequence.so first character is consider as “empty character”.

endsWith(String arg)
true, when the argument string is  matched with the “Suffix” of the another String, Otherwise false.

            String dbValue="";
            boolean endValue="end".endsWith(dbValue);
if(endValue)
            {
                  System.out.println("execute block of statement");
            }
As same as the startsWith method variable  endValue will be  true and if statement get executed.

Saturday, July 9, 2011

Java 7 Presentation (Project Coin)

My presentation was Java 7 launched event in Java User Group Chennai at 9-July-2011



Covered topic in Java 7 Presentation (Project Coin):

· Java Language enhancement history from version JDK 1.1 to Java 7

· Definition of Java7 Project Coin from JSR 334 Lead Joseph D.Darcy’s

  • Java 7 Language enhancement

1. String in Switch(alternative for if else statement with String)

2. Binary Literal(0B) and Underscore in literal for more readability (int binary=10_1)

3. Multi catch and more precious rethrow

4. Try with resource statement(Automatic resource management)

5. Diamond Operator(Generics)

6. Improved Compiler warning for varargs.


Wednesday, July 6, 2011

Moving Java Forward: A Video Discussion about Java 7

Discussion in this video:
  • Java SE 7 invoke dynamic
  • Java SE 7 Project Coin
  • Java SE 8 Closure(Lambda expression)





Sunday, June 26, 2011

Product development

In this article i am registering my software product development and maintains experience of last 4 years of journey.

As per my product development experience we should consider both the technology,business domain specific challenges and changes.

Here are the points we have to consider when start design and develop the product

  1. Choosing right technology and Architecture.

  2. Product specific database design(like Menu creation based on User Type,Page wise privileges )

  3. Business Domain specific database design(static business rules and dynamic business rules)

  4. Include Innovate ideas in Product.

  5. Product should open in smart phone and other devices too.

Choosing Right technology and Architecture:

Based on the software product we have to choose technology and technique.

    1. Embedded software product development-C,C++ based framework and technology

    2. Enterprise based product-Java,J2EE,.Net,Asp.Net

    3. Mobile based apps-J2ME,Android etc.,

    4. Social apps – Scala,Phyton,PHP

Role of architect is design the database and use the efficient Programming language/API to fetch the data and display the same to end user in an efficient manner.

Architect should design the software such a way that design should be understandable by developer and also accommodate the future enhancement and design.


Product specific database design:

Product specific database design are more important. if any design went wrong over here entire product we have to redo.

Product specific rules designs are

  1. User Type Identification

  2. Mapping User type to Page wise Permission

  3. Mapping Users to User Type.

  4. Region Identification

  5. mapping Users with Regions


Business Domain Specific Database design:

Here only most of the architect lack including me, because with out understanding business domain and business rules we can't design the tables and other relation.

But we can design table in two way:

  1. Static business rules(does not change any business rules example is accounts(credit and debit))

  2. Dynamic business rules(For example car rental amount vary based on no.of kilo meter travel,no of day travels,driver and cleaner bata if any dependency comes in future like fuel hike should be included and calculate amount based on that) so we have to design tables to accommodate all dynamic business rules.

Include Innovative Idea In product:

As per my point of view innovative idea is nothing but make application very user friendly using latest technology and technique.

Product should open in smart phone and other devices too

    If we work for enterprise based product development we only do the web based product but now days we should concentrate on mobile based application development too.

Friday, March 18, 2011

Servlet 2.4 Specification Notes

Note while reading servlet 2.4 specification.

SRV.1.1 What is a Servlet?
A servlet is a JavaTM technology-based Web component, managed by a container,
that generates dynamic content. Like other Java technology-based components,
servlets are platform-independent Java classes that are compiled to platform-neutral
byte code that can be loaded dynamically into and run by a Java technology-enabled
Web server. Containers, sometimes called servlet engines, are Web server extensions
that provide servlet functionality. Servlets interact with Web clients via a
request/response paradigm implemented by the servlet container.

SRV.1.2 What is a Servlet Container?
The servlet container is a part of aWeb server or application server that provides the
network services over which requests and responses are sent, decodes MIME-based
requests, and formats MIME-based responses. A servlet container also contains and
manages servlets through their lifecycle.

All servlet containers must support HTTP as a protocol for requests and
responses, but additional request/response-based protocols such as HTTPS
(HTTP over SSL) may be supported.

Sequence of Servlet Request & Response
The following is a typical sequence of events:
1. A client (e.g., a Web browser) accesses a Web server and makes an HTTP request.
2. The request is received by the Web server and handed off to the servlet container.
The servlet container can be running in the same process as the host
Web server, in a different process on the same host, or on a different host from
the Web server for which it processes requests.
3. The servlet container determines which servlet to invoke based on the configuration
of its servlets, and calls it with objects representing the request and response.
4. The servlet uses the request object to find out who the remote user is, what
HTTP POST parameters may have been sent as part of this request, and other
relevant data. The servlet performs whatever logic it was programmed with,
and generates data to send back to the client. It sends this data back to the client
via the response object.
5. Once the servlet has finished processing the request, the servlet container ensures
that the response is properly flushed, and returns control back to the host
Web server.

Comparing Servlets with Other Technologies
In functionality, servlets lie somewhere between Common Gateway Interface (CGI)
programs and proprietary server extensions such as the Netscape Server API
(NSAPI) or Apache Modules.
Servlets have the following advantages over other server extension mechanisms:
• They are generally much faster than CGI scripts because a different process
model is used.
• They use a standard API that is supported by many Web servers.
• They have all the advantages of the Java programming language, including
ease of development and platform independence.
• They can access the large set of APIs available for the Java platform.

Servlet Interface

The Servlet interface is the central abstraction of the Java Servlet API. All servlets
implement this interface either directly, or more commonly, by extending a class
that implements the interface. The two classes in the Java Servlet API that implement
the Servlet interface are GenericServlet and HttpServlet. For most purposes,
Developers will extend HttpServlet to implement their servlets.

SRV.2.1 Request Handling Methods
The basic Servlet interface defines a service method for handling client requests.
This method is called for each request that the servlet container routes to an instance
of a servlet.
The handling of concurrent requests to a Web application generally requires
that the Web Developer design servlets that can deal with multiple threads executing
within the service method at a particular time.
Generally the Web container handles concurrent requests to the same servlet
by concurrent execution of the service method on different threads.

SRV.2.1.1 HTTP Specific Request Handling Methods
The HttpServlet abstract subclass adds additional methods beyond the basic
Servlet interface that are automatically called by the service method in the
HttpServlet class to aid in processing HTTP-based requests. These methods are:
• doGet for handling HTTP GET requests
• doPost for handling HTTP POST requests
• doPut for handling HTTP PUT requests
• doDelete for handling HTTP DELETE requests
• doHead for handling HTTP HEAD requests
• doOptions for handling HTTP OPTIONS requests
• doTrace for handling HTTP TRACE requests
Typically when developing HTTP-based servlets, a Servlet Developer will
only concern himself with the doGet and doPost methods. The other methods are
considered to be methods for use by programmers very familiar with HTTP programming.

SRV.2.1.2 Additional Methods
The doPut and doDelete methods allow Servlet Developers to support HTTP/1.1
clients that employ these features. The doHead method in HttpServlet is a specialized
form of the doGet method that returns only the headers produced by the doGet
method. The doOptions method responds with which HTTP methods are supported
by the servlet. The doTrace method generates a response containing all instances of
the headers sent in the TRACE request.

SRV.2.1.3 Conditional GET Support
The HttpServlet interface defines the getLastModified method to support conditional
GET operations. A conditional GET operation requests a resource be sent only if
it has been modified since a specified time. In appropriate situations, implementation
of this method may aid efficient utilization of network resources.

Monday, March 14, 2011

this Keyword In Java

All java developer aware role of 'this'. 'this' is a reference to the current object in constructor and instance methods.

In java we use 'this' in different place are:

  1. Using 'this field' inside constructor/non-static method.

  2. Using 'this field' inside static method.

  3. Using this() method inside constructor

  4. Using this() method inside static/non-static methods.

  5. Recursive constructor invocation using this().


S.No.



Place
of 'this'



Description



When
executes



Where
Not Include



Sample
Code



1



Using
'this field' inside constructor/non-static method



'this'
act as the reference to the current object, So using 'this' we can
access the class instance variable and methods(static/no-static).


Most
of the case we use in POJO class setter & getter method.



We
can use to refer the current object instance variable inside the
constructor/non-static methods.



Its should
be used anywhere in inside constructor/non-static method.



package
thispck;


public
class
SampleThis


{ int
intvalue;


public
SampleThis(
int
intvalue)


{


this.intvalue=intvalue;


}


public
static
void
main(String arg[])


{


SampleThis
sampleThis=
new
SampleThis(10);


System.out.println("Int
Value::"
+sampleThis.intvalue);


}


}


Output:


Int
Value::10



2



Using
'this field' inside static method.



Not
possible to use this.



-



Compile
time error.


Error:


cannot use
this in a static context.



-



3



Using
'this() method' inside constructor



This()
method used for calling the default constructor and parameter
constructor in a class.






While
object creation using new keyword.



'this()'
declaration should be first statement in constructor.


Otherwise
compile time Error:


Constructor
call must be first statement in constructor






package
thispck;


public
class
SampleThis


{ int
intvalue;


public
SampleThis(
int
intvalue)


{


this.intvalue=intvalue;


}


public
SampleThis()


{


this(0);


}


public
static
void
main(String arg[])


{


SampleThis
sampleThis=
new
SampleThis(10);


System.out.println("Int
Value::"
+sampleThis.intvalue);


}


}


output:


Int
Value::10



4



Using
this() method inside static/non-static methods.



Compile
time error



-



Error:


Constructor
call must be the first statement in a constructor



-



5




Recursive constructor
invocation


using
this()



Compile
time error



-




Compile
time error.



public
SampleThis(int intvalue)



{



this();



this.intvalue=intvalue;



}







public
SampleThis()



{



this(0);



}



package
thispck;


public
class
SampleThis


{ int
intvalue;


public
SampleThis(
int
intvalue)


{


this();


this.intvalue=intvalue;


}


public
SampleThis()


{


this(0);


}


public
static
void
main(String arg[])


{


SampleThis
sampleThis=
new
SampleThis(10);


System.out.println("Int
Value::"
+sampleThis.intvalue);


}


}